* textmodes/css-mode.el (css-indent-offset, css-electric-keys):
[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 ;; This code supports Emacs 21.1 and later
15 ;; And XEmacs 21.1 and later
16 ;; Please do not make changes that break Emacs 21. Thanks!
17 ;;
18 ;;
19
20 ;; This file is part of GNU Emacs.
21
22 ;; GNU Emacs is free software; you can redistribute it and/or modify
23 ;; it under the terms of the GNU General Public License as published by
24 ;; the Free Software Foundation; either version 3, or (at your option)
25 ;; any later version.
26
27 ;; GNU Emacs is distributed in the hope that it will be useful,
28 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
29 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30 ;; GNU General Public License for more details.
31
32 ;; You should have received a copy of the GNU General Public License
33 ;; along with GNU Emacs; see the file COPYING. If not, write to the
34 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
35 ;; Boston, MA 02110-1301, USA.
36
37 ;;; Commentary:
38
39 ;; This mode borrows heavily from the Pascal-mode and the cc-mode of Emacs
40
41 ;; USAGE
42 ;; =====
43
44 ;; A major mode for editing Verilog HDL source code. When you have
45 ;; entered Verilog mode, you may get more info by pressing C-h m. You
46 ;; may also get online help describing various functions by: C-h f
47 ;; <Name of function you want described>
48
49 ;; KNOWN BUGS / BUG REPORTS
50 ;; =======================
51
52 ;; Verilog is a rapidly evolving language, and hence this mode is
53 ;; under continuous development. Hence this is beta code, and likely
54 ;; has bugs. Please report any and all bugs to me at mac@verilog.com.
55 ;; Please use verilog-submit-bug-report to submit a report; type C-c
56 ;; C-b to invoke this and as a result I will have a much easier time
57 ;; of reproducing the bug you find, and hence fixing it.
58
59 ;; INSTALLING THE MODE
60 ;; ===================
61
62 ;; An older version of this mode may be already installed as a part of
63 ;; your environment, and one method of updating would be to update
64 ;; your Emacs environment. Sometimes this is difficult for local
65 ;; political/control reasons, and hence you can always install a
66 ;; private copy (or even a shared copy) which overrides the system
67 ;; default.
68
69 ;; You can get step by step help in installing this file by going to
70 ;; <http://www.verilog.com/emacs_install.html>
71
72 ;; The short list of installation instructions are: To set up
73 ;; automatic Verilog mode, put this file in your load path, and put
74 ;; the following in code (please un comment it first!) in your
75 ;; .emacs, or in your site's site-load.el
76
77 ; (autoload 'verilog-mode "verilog-mode" "Verilog mode" t )
78 ; (setq auto-mode-alist (cons '("\\.v\\'" . verilog-mode) auto-mode-alist))
79 ; (setq auto-mode-alist (cons '("\\.dv\\'" . verilog-mode) auto-mode-alist))
80
81 ;; If you want to customize Verilog mode to fit your needs better,
82 ;; you may add these lines (the values of the variables presented
83 ;; here are the defaults). Note also that if you use an Emacs that
84 ;; supports custom, it's probably better to use the custom menu to
85 ;; edit these.
86 ;;
87 ;; Be sure to examine at the help for verilog-auto, and the other
88 ;; verilog-auto-* functions for some major coding time savers.
89 ;;
90 ; ;; User customization for Verilog mode
91 ; (setq verilog-indent-level 3
92 ; verilog-indent-level-module 3
93 ; verilog-indent-level-declaration 3
94 ; verilog-indent-level-behavioral 3
95 ; verilog-indent-level-directive 1
96 ; verilog-case-indent 2
97 ; verilog-auto-newline t
98 ; verilog-auto-indent-on-newline t
99 ; verilog-tab-always-indent t
100 ; verilog-auto-endcomments t
101 ; verilog-minimum-comment-distance 40
102 ; verilog-indent-begin-after-if t
103 ; verilog-auto-lineup '(all)
104 ; verilog-highlight-p1800-keywords nil
105 ; verilog-linter "my_lint_shell_command"
106 ; )
107
108 ;; \f
109
110 ;;; History:
111 ;;
112 ;; See commit history at http://www.veripool.com/verilog-mode.html
113 ;; (This section is required to appease checkdoc.)
114
115 ;;; Code:
116
117 ;; This variable will always hold the version number of the mode
118 (defconst verilog-mode-version "399"
119 "Version of this Verilog mode.")
120 (defconst verilog-mode-release-date "2008-02-19-GNU"
121 "Release date of this Verilog mode.")
122 (defconst verilog-mode-release-emacs t
123 "If non-nil, this version of Verilog mode was released with Emacs itself.")
124
125 (defun verilog-version ()
126 "Inform caller of the version of this file."
127 (interactive)
128 (message "Using verilog-mode version %s" verilog-mode-version))
129
130 ;; Insure we have certain packages, and deal with it if we don't
131 ;; Be sure to note which Emacs flavor and version added each feature.
132 (eval-when-compile
133 ;; The below were disabled when GNU Emacs 22 was released;
134 ;; perhaps some still need to be there to support Emacs 21.
135 (when (featurep 'xemacs)
136 (condition-case nil
137 (require 'easymenu)
138 (error nil))
139 (condition-case nil
140 (require 'regexp-opt)
141 (error nil))
142 ;; Bug in 19.28 through 19.30 skeleton.el, not provided.
143 (condition-case nil
144 (load "skeleton")
145 (error nil))
146 (condition-case nil
147 (if (fboundp 'when)
148 nil ;; fab
149 (defmacro when (cond &rest body)
150 (list 'if cond (cons 'progn body))))
151 (error nil))
152 (condition-case nil
153 (if (fboundp 'unless)
154 nil ;; fab
155 (defmacro unless (cond &rest body)
156 (cons 'if (cons cond (cons nil body)))))
157 (error nil))
158 (condition-case nil
159 (if (fboundp 'store-match-data)
160 nil ;; fab
161 (defmacro store-match-data (&rest args) nil))
162 (error nil))
163 (condition-case nil
164 (if (fboundp 'char-before)
165 nil ;; great
166 (defmacro char-before (&rest body)
167 (char-after (1- (point)))))
168 (error nil))
169 (condition-case nil
170 (require 'custom)
171 (error nil))
172 (condition-case nil
173 (if (fboundp 'match-string-no-properties)
174 nil ;; great
175 (defsubst match-string-no-properties (num &optional string)
176 "Return string of text matched by last search, without text properties.
177 NUM specifies which parenthesized expression in the last regexp.
178 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
179 Zero means the entire text matched by the whole regexp or whole string.
180 STRING should be given if the last search was by `string-match' on STRING."
181 (if (match-beginning num)
182 (if string
183 (let ((result
184 (substring string
185 (match-beginning num) (match-end num))))
186 (set-text-properties 0 (length result) nil result)
187 result)
188 (buffer-substring-no-properties (match-beginning num)
189 (match-end num)
190 (current-buffer)))))
191 )
192 (error nil))
193 (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
194 nil ;; We've got what we needed
195 ;; We have the old custom-library, hack around it!
196 (defmacro defgroup (&rest args) nil)
197 (defmacro customize (&rest args)
198 (message
199 "Sorry, Customize is not available with this version of Emacs"))
200 (defmacro defcustom (var value doc &rest args)
201 `(defvar ,var ,value ,doc))
202 )
203 (if (fboundp 'defface)
204 nil ; great!
205 (defmacro defface (var values doc &rest args)
206 `(make-face ,var))
207 )
208
209 (if (and (featurep 'custom) (fboundp 'customize-group))
210 nil ;; We've got what we needed
211 ;; We have an intermediate custom-library, hack around it!
212 (defmacro customize-group (var &rest args)
213 `(customize ,var))
214 )))
215
216 ;; Provide a regular expression optimization routine, using regexp-opt
217 ;; if provided by the user's elisp libraries
218 (eval-and-compile
219 ;; The below were disabled when GNU Emacs 22 was released;
220 ;; perhaps some still need to be there to support Emacs 21.
221 (if (featurep 'xemacs)
222 (if (fboundp 'regexp-opt)
223 ;; regexp-opt is defined, does it take 3 or 2 arguments?
224 (if (fboundp 'function-max-args)
225 (let ((args (function-max-args `regexp-opt)))
226 (cond
227 ((eq args 3) ;; It takes 3
228 (condition-case nil ; Hide this defun from emacses
229 ;with just a two input regexp
230 (defun verilog-regexp-opt (a b)
231 "Deal with differing number of required arguments for `regexp-opt'.
232 Call 'regexp-opt' on A and B."
233 (regexp-opt a b 't))
234 (error nil))
235 )
236 ((eq args 2) ;; It takes 2
237 (defun verilog-regexp-opt (a b)
238 "Call 'regexp-opt' on A and B."
239 (regexp-opt a b))
240 )
241 (t nil)))
242 ;; We can't tell; assume it takes 2
243 (defun verilog-regexp-opt (a b)
244 "Call 'regexp-opt' on A and B."
245 (regexp-opt a b))
246 )
247 ;; There is no regexp-opt, provide our own
248 (defun verilog-regexp-opt (strings &optional paren shy)
249 (let ((open (if paren "\\(" "")) (close (if paren "\\)" "")))
250 (concat open (mapconcat 'regexp-quote strings "\\|") close)))
251 )
252 ;; Emacs.
253 (defalias 'verilog-regexp-opt 'regexp-opt)))
254
255 (eval-when-compile
256 (defun verilog-regexp-words (a)
257 "Call 'regexp-opt' with word delimiters for the words A."
258 (concat "\\<" (verilog-regexp-opt a t) "\\>")))
259
260 (defun verilog-customize ()
261 "Link to customize screen for Verilog."
262 (interactive)
263 (customize-group 'verilog-mode))
264
265 (defun verilog-font-customize ()
266 "Link to customize fonts used for Verilog."
267 (interactive)
268 (if (fboundp 'customize-apropos)
269 (customize-apropos "font-lock-*" 'faces)))
270
271 (defun verilog-booleanp (value)
272 "Return t if VALUE is boolean.
273 This implements GNU Emacs 22.1's `booleanp' function in earlier Emacs.
274 This function may be removed when Emacs 21 is no longer supported."
275 (or (equal value t) (equal value nil)))
276
277 (defgroup verilog-mode nil
278 "Facilitates easy editing of Verilog source text."
279 :version "22.2"
280 :group 'languages)
281
282 ; (defgroup verilog-mode-fonts nil
283 ; "Facilitates easy customization fonts used in Verilog source text"
284 ; :link '(customize-apropos "font-lock-*" 'faces)
285 ; :group 'verilog-mode)
286
287 (defgroup verilog-mode-indent nil
288 "Customize indentation and highlighting of Verilog source text."
289 :group 'verilog-mode)
290
291 (defgroup verilog-mode-actions nil
292 "Customize actions on Verilog source text."
293 :group 'verilog-mode)
294
295 (defgroup verilog-mode-auto nil
296 "Customize AUTO actions when expanding Verilog source text."
297 :group 'verilog-mode)
298
299 (defcustom verilog-linter
300 "echo 'No verilog-linter set, see \"M-x describe-variable verilog-linter\"'"
301 "*Unix program and arguments to call to run a lint checker on Verilog source.
302 Depending on the `verilog-set-compile-command', this may be invoked when
303 you type \\[compile]. When the compile completes, \\[next-error] will take
304 you to the next lint error."
305 :type 'string
306 :group 'verilog-mode-actions)
307 ;; We don't mark it safe, as it's used as a shell command
308
309 (defcustom verilog-coverage
310 "echo 'No verilog-coverage set, see \"M-x describe-variable verilog-coverage\"'"
311 "*Program and arguments to use to annotate for coverage Verilog source.
312 Depending on the `verilog-set-compile-command', this may be invoked when
313 you type \\[compile]. When the compile completes, \\[next-error] will take
314 you to the next lint error."
315 :type 'string
316 :group 'verilog-mode-actions)
317 ;; We don't mark it safe, as it's used as a shell command
318
319 (defcustom verilog-simulator
320 "echo 'No verilog-simulator set, see \"M-x describe-variable verilog-simulator\"'"
321 "*Program and arguments to use to interpret Verilog source.
322 Depending on the `verilog-set-compile-command', this may be invoked when
323 you type \\[compile]. When the compile completes, \\[next-error] will take
324 you to the next lint error."
325 :type 'string
326 :group 'verilog-mode-actions)
327 ;; We don't mark it safe, as it's used as a shell command
328
329 (defcustom verilog-compiler
330 "echo 'No verilog-compiler set, see \"M-x describe-variable verilog-compiler\"'"
331 "*Program and arguments to use to compile Verilog source.
332 Depending on the `verilog-set-compile-command', this may be invoked when
333 you type \\[compile]. When the compile completes, \\[next-error] will take
334 you to the next lint error."
335 :type 'string
336 :group 'verilog-mode-actions)
337 ;; We don't mark it safe, as it's used as a shell command
338
339 (defvar verilog-tool 'verilog-linter
340 "Which tool to use for building compiler-command.
341 Either nil, `verilog-linter, `verilog-coverage, `verilog-simulator, or
342 `verilog-compiler. Alternatively use the \"Choose Compilation Action\"
343 menu. See `verilog-set-compile-command' for more information.")
344
345 (defcustom verilog-highlight-translate-off nil
346 "*Non-nil means background-highlight code excluded from translation.
347 That is, all code between \"// synopsys translate_off\" and
348 \"// synopsys translate_on\" is highlighted using a different background color
349 \(face `verilog-font-lock-translate-off-face').
350
351 Note: This will slow down on-the-fly fontification (and thus editing).
352
353 Note: Activate the new setting in a Verilog buffer by re-fontifying it (menu
354 entry \"Fontify Buffer\"). XEmacs: turn off and on font locking."
355 :type 'boolean
356 :group 'verilog-mode-indent)
357 ;; Note we don't use :safe, as that would break on Emacsen before 22.0.
358 (put 'verilog-highlight-translate-off 'safe-local-variable 'verilog-booleanp)
359
360 (defcustom verilog-indent-level 3
361 "*Indentation of Verilog statements with respect to containing block."
362 :group 'verilog-mode-indent
363 :type 'integer)
364 (put 'verilog-indent-level 'safe-local-variable 'integerp)
365
366 (defcustom verilog-indent-level-module 3
367 "*Indentation of Module level Verilog statements (eg always, initial).
368 Set to 0 to get initial and always statements lined up on the left side of
369 your screen."
370 :group 'verilog-mode-indent
371 :type 'integer)
372 (put 'verilog-indent-level-module 'safe-local-variable 'integerp)
373
374 (defcustom verilog-indent-level-declaration 3
375 "*Indentation of declarations with respect to containing block.
376 Set to 0 to get them list right under containing block."
377 :group 'verilog-mode-indent
378 :type 'integer)
379 (put 'verilog-indent-level-declaration 'safe-local-variable 'integerp)
380
381 (defcustom verilog-indent-declaration-macros nil
382 "*How to treat macro expansions in a declaration.
383 If nil, indent as:
384 input [31:0] a;
385 input `CP;
386 output c;
387 If non nil, treat as:
388 input [31:0] a;
389 input `CP ;
390 output c;"
391 :group 'verilog-mode-indent
392 :type 'boolean)
393 (put 'verilog-indent-declaration-macros 'safe-local-variable 'verilog-booleanp)
394
395 (defcustom verilog-indent-lists t
396 "*How to treat indenting items in a list.
397 If t (the default), indent as:
398 always @( posedge a or
399 reset ) begin
400
401 If nil, treat as:
402 always @( posedge a or
403 reset ) begin"
404 :group 'verilog-mode-indent
405 :type 'boolean)
406 (put 'verilog-indent-lists 'safe-local-variable 'verilog-booleanp)
407
408 (defcustom verilog-indent-level-behavioral 3
409 "*Absolute indentation of first begin in a task or function block.
410 Set to 0 to get such code to start at the left side of the screen."
411 :group 'verilog-mode-indent
412 :type 'integer)
413 (put 'verilog-indent-level-behavioral 'safe-local-variable 'integerp)
414
415 (defcustom verilog-indent-level-directive 1
416 "*Indentation to add to each level of `ifdef declarations.
417 Set to 0 to have all directives start at the left side of the screen."
418 :group 'verilog-mode-indent
419 :type 'integer)
420 (put 'verilog-indent-level-directive 'safe-local-variable 'integerp)
421
422 (defcustom verilog-cexp-indent 2
423 "*Indentation of Verilog statements split across lines."
424 :group 'verilog-mode-indent
425 :type 'integer)
426 (put 'verilog-cexp-indent 'safe-local-variable 'integerp)
427
428 (defcustom verilog-case-indent 2
429 "*Indentation for case statements."
430 :group 'verilog-mode-indent
431 :type 'integer)
432 (put 'verilog-case-indent 'safe-local-variable 'integerp)
433
434 (defcustom verilog-auto-newline t
435 "*True means automatically newline after semicolons."
436 :group 'verilog-mode-indent
437 :type 'boolean)
438 (put 'verilog-auto-newline 'safe-local-variable 'verilog-booleanp)
439
440 (defcustom verilog-auto-indent-on-newline t
441 "*True means automatically indent line after newline."
442 :group 'verilog-mode-indent
443 :type 'boolean)
444 (put 'verilog-auto-indent-on-newline 'safe-local-variable 'verilog-booleanp)
445
446 (defcustom verilog-tab-always-indent t
447 "*True means TAB should always re-indent the current line.
448 A nil value means TAB will only reindent when at the beginning of the line."
449 :group 'verilog-mode-indent
450 :type 'boolean)
451 (put 'verilog-tab-always-indent 'safe-local-variable 'verilog-booleanp)
452
453 (defcustom verilog-tab-to-comment nil
454 "*True means TAB moves to the right hand column in preparation for a comment."
455 :group 'verilog-mode-actions
456 :type 'boolean)
457 (put 'verilog-tab-to-comment 'safe-local-variable 'verilog-booleanp)
458
459 (defcustom verilog-indent-begin-after-if t
460 "*If true, indent begin statements following if, else, while, for and repeat.
461 Otherwise, line them up."
462 :group 'verilog-mode-indent
463 :type 'boolean)
464 (put 'verilog-indent-begin-after-if 'safe-local-variable 'verilog-booleanp)
465
466
467 (defcustom verilog-align-ifelse nil
468 "*If true, align `else' under matching `if'.
469 Otherwise else is lined up with first character on line holding matching if."
470 :group 'verilog-mode-indent
471 :type 'boolean)
472 (put 'verilog-align-ifelse 'safe-local-variable 'verilog-booleanp)
473
474 (defcustom verilog-minimum-comment-distance 10
475 "*Minimum distance (in lines) between begin and end required before a comment.
476 Setting this variable to zero results in every end acquiring a comment; the
477 default avoids too many redundant comments in tight quarters."
478 :group 'verilog-mode-indent
479 :type 'integer)
480 (put 'verilog-minimum-comment-distance 'safe-local-variable 'integerp)
481
482 (defcustom verilog-auto-lineup '(declaration)
483 "*Algorithm for lining up statements on multiple lines.
484
485 If this list contains the symbol 'all', then all line ups described below
486 are done.
487
488 If this list contains the symbol 'declaration', then declarations are lined up
489 with any preceding declarations, taking into account widths and the like, so
490 for example the code:
491 reg [31:0] a;
492 reg b;
493 would become
494 reg [31:0] a;
495 reg b;
496
497 If this list contains the symbol 'assignment', then assignments are lined up
498 with any preceding assignments, so for example the code
499 a_long_variable = b + c;
500 d = e + f;
501 would become
502 a_long_variable = b + c;
503 d = e + f;"
504
505 ;; The following is not implemented:
506 ;If this list contains the symbol 'case', then case items are lined up
507 ;with any preceding case items, so for example the code
508 ; case (a) begin
509 ; a_long_state : a = 3;
510 ; b: a = 4;
511 ; endcase
512 ;would become
513 ; case (a) begin
514 ; a_long_state : a = 3;
515 ; b : a = 4;
516 ; endcase
517 ;
518
519 :group 'verilog-mode-indent
520 :type 'list)
521 (put 'verilog-auto-lineup 'safe-local-variable 'listp)
522
523 (defcustom verilog-highlight-p1800-keywords nil
524 "*True means highlight words newly reserved by IEEE-1800.
525 These will appear in `verilog-font-lock-p1800-face' in order to gently
526 suggest changing where these words are used as variables to something else.
527 A nil value means highlight these words as appropriate for the SystemVerilog
528 IEEE-1800 standard. Note that changing this will require restarting Emacs
529 to see the effect as font color choices are cached by Emacs."
530 :group 'verilog-mode-indent
531 :type 'boolean)
532 (put 'verilog-highlight-p1800-keywords 'safe-local-variable 'verilog-booleanp)
533
534 (defcustom verilog-auto-endcomments t
535 "*True means insert a comment /* ... */ after 'end's.
536 The name of the function or case will be set between the braces."
537 :group 'verilog-mode-actions
538 :type 'boolean)
539 (put 'verilog-auto-endcomments 'safe-local-variable 'verilog-booleanp)
540
541 (defcustom verilog-auto-read-includes nil
542 "*True means to automatically read includes before AUTOs.
543 This will do a `verilog-read-defines' and `verilog-read-includes' before
544 each AUTO expansion. This makes it easier to embed defines and includes,
545 but can result in very slow reading times if there are many or large
546 include files."
547 :group 'verilog-mode-actions
548 :type 'boolean)
549 (put 'verilog-auto-read-includes 'safe-local-variable 'verilog-booleanp)
550
551 (defcustom verilog-auto-save-policy nil
552 "*Non-nil indicates action to take when saving a Verilog buffer with AUTOs.
553 A value of `force' will always do a \\[verilog-auto] automatically if
554 needed on every save. A value of `detect' will do \\[verilog-auto]
555 automatically when it thinks necessary. A value of `ask' will query the
556 user when it thinks updating is needed.
557
558 You should not rely on the 'ask or 'detect policies, they are safeguards
559 only. They do not detect when AUTOINSTs need to be updated because a
560 sub-module's port list has changed."
561 :group 'verilog-mode-actions
562 :type '(choice (const nil) (const ask) (const detect) (const force)))
563
564 (defcustom verilog-auto-star-expand t
565 "*Non-nil indicates to expand a SystemVerilog .* instance ports.
566 They will be expanded in the same way as if there was a AUTOINST in the
567 instantiation. See also `verilog-auto-star' and `verilog-auto-star-save'."
568 :group 'verilog-mode-actions
569 :type 'boolean)
570 (put 'verilog-auto-star-expand 'safe-local-variable 'verilog-booleanp)
571
572 (defcustom verilog-auto-star-save nil
573 "*Non-nil indicates to save to disk SystemVerilog .* instance expansions.
574 A nil value indicates direct connections will be removed before saving.
575 Only meaningful to those created due to `verilog-auto-star-expand' being set.
576
577 Instead of setting this, you may want to use /*AUTOINST*/, which will
578 always be saved."
579 :group 'verilog-mode-actions
580 :type 'boolean)
581 (put 'verilog-auto-star-save 'safe-local-variable 'verilog-booleanp)
582
583 (defvar verilog-auto-update-tick nil
584 "Modification tick at which autos were last performed.")
585
586 (defvar verilog-auto-last-file-locals nil
587 "Text from file-local-variables during last evaluation.")
588
589 (defvar verilog-error-regexp-add-didit nil)
590 (defvar verilog-error-regexp nil)
591 (setq verilog-error-regexp-add-didit nil
592 verilog-error-regexp
593 '(
594 ; SureLint
595 ;; ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 2)
596 ; Most SureFire tools
597 ("\\(WARNING\\|ERROR\\|INFO\\)[^:]*: \\([^,]+\\), \\(line \\|\\)\\([0-9]+\\):" 2 4 )
598 ("\
599 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
600 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 2 5)
601 ; xsim
602 ; Error! in file /homes/mac/Axis/Xsim/test.v at line 13 [OBJ_NOT_DECLARED]
603 ("\\(Error\\|Warning\\).*in file (\\([^ \t]+\\) at line *\\([0-9]+\\))" 2 3)
604 ; vcs
605 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 3)
606 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 2)
607 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 3)
608 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 2)
609 ; Verilator
610 ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 4)
611 ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 4)
612 ; vxl
613 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 3)
614 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\([0-9]+\\):.*$" 1 2) ; vxl
615 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+line[ \t]+\\([0-9]+\\):.*$" 1 2)
616 ; nc-verilog
617 (".*\\*[WE],[0-9A-Z]+ (\\([^ \t,]+\\),\\([0-9]+\\)|" 1 2)
618 ; Leda
619 ("In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\[\\(Warning\\|Error\\|Failure\\)\\][^\n]*" 1 2)
620 )
621 ; "*List of regexps for Verilog compilers, like verilint. See compilation-error-regexp-alist for the formatting."
622 )
623
624 (defvar verilog-error-font-lock-keywords
625 '(
626 ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 bold t)
627 ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 2 bold t)
628
629 ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 2 bold t)
630 ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 3 bold t)
631
632 ("\
633 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
634 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
635 ("\
636 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
637 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
638
639 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 bold t)
640 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 3 bold t)
641
642 ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 bold t)
643 ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 4 bold t)
644
645 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
646 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
647
648 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
649 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 3 bold t)
650
651 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 bold t)
652 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
653 ; vxl
654 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
655 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
656
657 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\([0-9]+\\):.*$" 1 bold t)
658 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\([0-9]+\\):.*$" 2 bold t)
659
660 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+line[ \t]+\\([0-9]+\\):.*$" 1 bold t)
661 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+line[ \t]+\\([0-9]+\\):.*$" 2 bold t)
662 ; nc-verilog
663 (".*[WE],[0-9A-Z]+ (\\([^ \t,]+\\),\\([0-9]+\\)|" 1 bold t)
664 (".*[WE],[0-9A-Z]+ (\\([^ \t,]+\\),\\([0-9]+\\)|" 2 bold t)
665 ; Leda
666 ("In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\[\\(Warning\\|Error\\|Failure\\)\\][^\n]*" 1 bold t)
667 ("In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\[\\(Warning\\|Error\\|Failure\\)\\][^\n]*" 2 bold t)
668 )
669 "*Keywords to also highlight in Verilog *compilation* buffers.")
670
671 (defcustom verilog-library-flags '("")
672 "*List of standard Verilog arguments to use for /*AUTOINST*/.
673 These arguments are used to find files for `verilog-auto', and match
674 the flags accepted by a standard Verilog-XL simulator.
675
676 -f filename Reads more `verilog-library-flags' from the filename.
677 +incdir+dir Adds the directory to `verilog-library-directories'.
678 -Idir Adds the directory to `verilog-library-directories'.
679 -y dir Adds the directory to `verilog-library-directories'.
680 +libext+.v Adds the extensions to `verilog-library-extensions'.
681 -v filename Adds the filename to `verilog-library-files'.
682
683 filename Adds the filename to `verilog-library-files'.
684 This is not recommended, -v is a better choice.
685
686 You might want these defined in each file; put at the *END* of your file
687 something like:
688
689 // Local Variables:
690 // verilog-library-flags:(\"-y dir -y otherdir\")
691 // End:
692
693 Verilog-mode attempts to detect changes to this local variable, but they
694 are only insured to be correct when the file is first visited. Thus if you
695 have problems, use \\[find-alternate-file] RET to have these take effect.
696
697 See also the variables mentioned above."
698 :group 'verilog-mode-auto
699 :type '(repeat string))
700 (put 'verilog-library-flags 'safe-local-variable 'listp)
701
702 (defcustom verilog-library-directories '(".")
703 "*List of directories when looking for files for /*AUTOINST*/.
704 The directory may be relative to the current file, or absolute.
705 Environment variables are also expanded in the directory names.
706 Having at least the current directory is a good idea.
707
708 You might want these defined in each file; put at the *END* of your file
709 something like:
710
711 // Local Variables:
712 // verilog-library-directories:(\".\" \"subdir\" \"subdir2\")
713 // End:
714
715 Verilog-mode attempts to detect changes to this local variable, but they
716 are only insured to be correct when the file is first visited. Thus if you
717 have problems, use \\[find-alternate-file] RET to have these take effect.
718
719 See also `verilog-library-flags', `verilog-library-files'
720 and `verilog-library-extensions'."
721 :group 'verilog-mode-auto
722 :type '(repeat file))
723 (put 'verilog-library-directories 'safe-local-variable 'listp)
724
725 (defcustom verilog-library-files '()
726 "*List of files to search for modules.
727 AUTOINST will use this when it needs to resolve a module name.
728 This is a complete path, usually to a technology file with many standard
729 cells defined in it.
730
731 You might want these defined in each file; put at the *END* of your file
732 something like:
733
734 // Local Variables:
735 // verilog-library-files:(\"/some/path/technology.v\" \"/some/path/tech2.v\")
736 // End:
737
738 Verilog-mode attempts to detect changes to this local variable, but they
739 are only insured to be correct when the file is first visited. Thus if you
740 have problems, use \\[find-alternate-file] RET to have these take effect.
741
742 See also `verilog-library-flags', `verilog-library-directories'."
743 :group 'verilog-mode-auto
744 :type '(repeat directory))
745 (put 'verilog-library-files 'safe-local-variable 'listp)
746
747 (defcustom verilog-library-extensions '(".v")
748 "*List of extensions to use when looking for files for /*AUTOINST*/.
749 See also `verilog-library-flags', `verilog-library-directories'."
750 :type '(repeat string)
751 :group 'verilog-mode-auto)
752 (put 'verilog-library-extensions 'safe-local-variable 'listp)
753
754 (defcustom verilog-active-low-regexp nil
755 "*If set, treat signals matching this regexp as active low.
756 This is used for AUTORESET and AUTOTIEOFF. For proper behavior,
757 you will probably also need `verilog-auto-reset-widths' set."
758 :group 'verilog-mode-auto
759 :type 'string)
760 (put 'verilog-active-low-regexp 'safe-local-variable 'stringp)
761
762 (defcustom verilog-auto-sense-include-inputs nil
763 "*If true, AUTOSENSE should include all inputs.
764 If nil, only inputs that are NOT output signals in the same block are
765 included."
766 :group 'verilog-mode-auto
767 :type 'boolean)
768 (put 'verilog-auto-sense-include-inputs 'safe-local-variable 'verilog-booleanp)
769
770 (defcustom verilog-auto-sense-defines-constant nil
771 "*If true, AUTOSENSE should assume all defines represent constants.
772 When true, the defines will not be included in sensitivity lists. To
773 maintain compatibility with other sites, this should be set at the bottom
774 of each Verilog file that requires it, rather than being set globally."
775 :group 'verilog-mode-auto
776 :type 'boolean)
777 (put 'verilog-auto-sense-defines-constant 'safe-local-variable 'verilog-booleanp)
778
779 (defcustom verilog-auto-reset-widths t
780 "*If true, AUTORESET should determine the width of signals.
781 This is then used to set the width of the zero (32'h0 for example). This
782 is required by some lint tools that aren't smart enough to ignore widths of
783 the constant zero. This may result in ugly code when parameters determine
784 the MSB or LSB of a signal inside an AUTORESET."
785 :type 'boolean
786 :group 'verilog-mode-auto)
787 (put 'verilog-auto-reset-widths 'safe-local-variable 'verilog-booleanp)
788
789 (defcustom verilog-assignment-delay ""
790 "*Text used for delays in delayed assignments. Add a trailing space if set."
791 :group 'verilog-mode-auto
792 :type 'string)
793 (put 'verilog-assignment-delay 'safe-local-variable 'stringp)
794
795 (defcustom verilog-auto-inst-vector t
796 "*If true, when creating default ports with AUTOINST, use bus subscripts.
797 If nil, skip the subscript when it matches the entire bus as declared in
798 the module (AUTOWIRE signals always are subscripted, you must manually
799 declare the wire to have the subscripts removed.) Setting this to nil may
800 speed up some simulators, but is less general and harder to read, so avoid."
801 :group 'verilog-mode-auto
802 :type 'boolean)
803 (put 'verilog-auto-inst-vector 'safe-local-variable 'verilog-booleanp)
804
805 (defcustom verilog-auto-inst-template-numbers nil
806 "*If true, when creating templated ports with AUTOINST, add a comment.
807 The comment will add the line number of the template that was used for that
808 port declaration. Setting this aids in debugging, but nil is suggested for
809 regular use to prevent large numbers of merge conflicts."
810 :group 'verilog-mode-auto
811 :type 'boolean)
812 (put 'verilog-auto-inst-template-numbers 'safe-local-variable 'verilog-booleanp)
813
814 (defvar verilog-auto-inst-column 40
815 "Column number for first part of auto-inst.")
816
817 (defcustom verilog-auto-input-ignore-regexp nil
818 "*If set, when creating AUTOINPUT list, ignore signals matching this regexp.
819 See the \\[verilog-faq] for examples on using this."
820 :group 'verilog-mode-auto
821 :type 'string)
822 (put 'verilog-auto-input-ignore-regexp 'safe-local-variable 'stringp)
823
824 (defcustom verilog-auto-inout-ignore-regexp nil
825 "*If set, when creating AUTOINOUT list, ignore signals matching this regexp.
826 See the \\[verilog-faq] for examples on using this."
827 :group 'verilog-mode-auto
828 :type 'string)
829 (put 'verilog-auto-inout-ignore-regexp 'safe-local-variable 'stringp)
830
831 (defcustom verilog-auto-output-ignore-regexp nil
832 "*If set, when creating AUTOOUTPUT list, ignore signals matching this regexp.
833 See the \\[verilog-faq] for examples on using this."
834 :group 'verilog-mode-auto
835 :type 'string)
836 (put 'verilog-auto-output-ignore-regexp 'safe-local-variable 'stringp)
837
838 (defcustom verilog-auto-unused-ignore-regexp nil
839 "*If set, when creating AUTOUNUSED list, ignore signals matching this regexp.
840 See the \\[verilog-faq] for examples on using this."
841 :group 'verilog-mode-auto
842 :type 'string)
843 (put 'verilog-auto-unused-ignore-regexp 'safe-local-variable 'stringp)
844
845 (defcustom verilog-typedef-regexp nil
846 "*If non-nil, regular expression that matches Verilog-2001 typedef names.
847 For example, \"_t$\" matches typedefs named with _t, as in the C language."
848 :group 'verilog-mode-auto
849 :type 'string)
850 (put 'verilog-typedef-regexp 'safe-local-variable 'stringp)
851
852 (defcustom verilog-mode-hook 'verilog-set-compile-command
853 "*Hook run after Verilog mode is loaded."
854 :type 'hook
855 :group 'verilog-mode)
856
857 (defcustom verilog-auto-hook nil
858 "*Hook run after `verilog-mode' updates AUTOs."
859 :group 'verilog-mode-auto
860 :type 'hook)
861
862 (defcustom verilog-before-auto-hook nil
863 "*Hook run before `verilog-mode' updates AUTOs."
864 :group 'verilog-mode-auto
865 :type 'hook)
866
867 (defcustom verilog-delete-auto-hook nil
868 "*Hook run after `verilog-mode' deletes AUTOs."
869 :group 'verilog-mode-auto
870 :type 'hook)
871
872 (defcustom verilog-before-delete-auto-hook nil
873 "*Hook run before `verilog-mode' deletes AUTOs."
874 :group 'verilog-mode-auto
875 :type 'hook)
876
877 (defcustom verilog-getopt-flags-hook nil
878 "*Hook run after `verilog-getopt-flags' determines the Verilog option lists."
879 :group 'verilog-mode-auto
880 :type 'hook)
881
882 (defcustom verilog-before-getopt-flags-hook nil
883 "*Hook run before `verilog-getopt-flags' determines the Verilog option lists."
884 :group 'verilog-mode-auto
885 :type 'hook)
886
887 (defvar verilog-imenu-generic-expression
888 '((nil "^\\s-*\\(\\(m\\(odule\\|acromodule\\)\\)\\|primitive\\)\\s-+\\([a-zA-Z0-9_.:]+\\)" 4)
889 ("*Vars*" "^\\s-*\\(reg\\|wire\\)\\s-+\\(\\|\\[[^]]+\\]\\s-+\\)\\([A-Za-z0-9_]+\\)" 3))
890 "Imenu expression for Verilog mode. See `imenu-generic-expression'.")
891
892 ;;
893 ;; provide a verilog-header function.
894 ;; Customization variables:
895 ;;
896 (defvar verilog-date-scientific-format nil
897 "*If non-nil, dates are written in scientific format (e.g. 1997/09/17).
898 If nil, in European format (e.g. 17.09.1997). The brain-dead American
899 format (e.g. 09/17/1997) is not supported.")
900
901 (defvar verilog-company nil
902 "*Default name of Company for Verilog header.
903 If set will become buffer local.")
904 (make-variable-buffer-local 'verilog-company)
905
906 (defvar verilog-project nil
907 "*Default name of Project for Verilog header.
908 If set will become buffer local.")
909 (make-variable-buffer-local 'verilog-project)
910
911 (defvar verilog-mode-map
912 (let ((map (make-sparse-keymap)))
913 (define-key map ";" 'electric-verilog-semi)
914 (define-key map [(control 59)] 'electric-verilog-semi-with-comment)
915 (define-key map ":" 'electric-verilog-colon)
916 ;;(define-key map "=" 'electric-verilog-equal)
917 (define-key map "\`" 'electric-verilog-tick)
918 (define-key map "\t" 'electric-verilog-tab)
919 (define-key map "\r" 'electric-verilog-terminate-line)
920 ;; backspace/delete key bindings
921 (define-key map [backspace] 'backward-delete-char-untabify)
922 (unless (boundp 'delete-key-deletes-forward) ; XEmacs variable
923 (define-key map [delete] 'delete-char)
924 (define-key map [(meta delete)] 'kill-word))
925 (define-key map "\M-\C-b" 'electric-verilog-backward-sexp)
926 (define-key map "\M-\C-f" 'electric-verilog-forward-sexp)
927 (define-key map "\M-\r" `electric-verilog-terminate-and-indent)
928 (define-key map "\M-\t" 'verilog-complete-word)
929 (define-key map "\M-?" 'verilog-show-completions)
930 (define-key map "\C-c\`" 'verilog-lint-off)
931 (define-key map "\C-c\*" 'verilog-delete-auto-star-implicit)
932 (define-key map "\C-c\C-r" 'verilog-label-be)
933 (define-key map "\C-c\C-i" 'verilog-pretty-declarations)
934 (define-key map "\C-c=" 'verilog-pretty-expr)
935 (define-key map "\C-c\C-b" 'verilog-submit-bug-report)
936 (define-key map "\M-*" 'verilog-star-comment)
937 (define-key map "\C-c\C-c" 'verilog-comment-region)
938 (define-key map "\C-c\C-u" 'verilog-uncomment-region)
939 (when (featurep 'xemacs)
940 (define-key map [(meta control h)] 'verilog-mark-defun)
941 (define-key map "\M-\C-a" 'verilog-beg-of-defun)
942 (define-key map "\M-\C-e" 'verilog-end-of-defun))
943 (define-key map "\C-c\C-d" 'verilog-goto-defun)
944 (define-key map "\C-c\C-k" 'verilog-delete-auto)
945 (define-key map "\C-c\C-a" 'verilog-auto)
946 (define-key map "\C-c\C-s" 'verilog-auto-save-compile)
947 (define-key map "\C-c\C-z" 'verilog-inject-auto)
948 (define-key map "\C-c\C-e" 'verilog-expand-vector)
949 (define-key map "\C-c\C-h" 'verilog-header)
950 map)
951 "Keymap used in Verilog mode.")
952
953 ;; menus
954 (easy-menu-define
955 verilog-menu verilog-mode-map "Menu for Verilog mode"
956 `("Verilog"
957 ("Choose Compilation Action"
958 ["None"
959 (progn
960 (setq verilog-tool nil)
961 (verilog-set-compile-command))
962 :style radio
963 :selected (equal verilog-tool nil)]
964 ["Lint"
965 (progn
966 (setq verilog-tool 'verilog-linter)
967 (verilog-set-compile-command))
968 :style radio
969 :selected (equal verilog-tool `verilog-linter)]
970 ["Coverage"
971 (progn
972 (setq verilog-tool 'verilog-coverage)
973 (verilog-set-compile-command))
974 :style radio
975 :selected (equal verilog-tool `verilog-coverage)]
976 ["Simulator"
977 (progn
978 (setq verilog-tool 'verilog-simulator)
979 (verilog-set-compile-command))
980 :style radio
981 :selected (equal verilog-tool `verilog-simulator)]
982 ["Compiler"
983 (progn
984 (setq verilog-tool 'verilog-compiler)
985 (verilog-set-compile-command))
986 :style radio
987 :selected (equal verilog-tool `verilog-compiler)]
988 )
989 ("Move"
990 ["Beginning of function" verilog-beg-of-defun
991 :keys "C-M-a"]
992 ["End of function" verilog-end-of-defun
993 :keys "C-M-e"]
994 ["Mark function" verilog-mark-defun
995 :keys "C-M-h"]
996 ["Goto function/module" verilog-goto-defun t]
997 ["Move to beginning of block" electric-verilog-backward-sexp t]
998 ["Move to end of block" electric-verilog-forward-sexp t]
999 )
1000 ("Comments"
1001 ["Comment Region" verilog-comment-region t]
1002 ["UnComment Region" verilog-uncomment-region t]
1003 ["Multi-line comment insert" verilog-star-comment t]
1004 ["Lint error to comment" verilog-lint-off t]
1005 )
1006 "----"
1007 ["Compile" compile t]
1008 ["AUTO, Save, Compile" verilog-auto-save-compile t]
1009 ["Next Compile Error" next-error t]
1010 ["Ignore Lint Warning at point" verilog-lint-off t]
1011 "----"
1012 ["Line up declarations around point" verilog-pretty-declarations t]
1013 ["Line up equations around point" verilog-pretty-expr t]
1014 ["Redo/insert comments on every end" verilog-label-be t]
1015 ["Expand [x:y] vector line" verilog-expand-vector t]
1016 ["Insert begin-end block" verilog-insert-block t]
1017 ["Complete word" verilog-complete-word t]
1018 "----"
1019 ["Recompute AUTOs" verilog-auto t]
1020 ["Kill AUTOs" verilog-delete-auto t]
1021 ["Inject AUTOs" verilog-inject-auto t]
1022 ("AUTO Help..."
1023 ["AUTO General" (describe-function 'verilog-auto) t]
1024 ["AUTO Library Flags" (describe-variable 'verilog-library-flags) t]
1025 ["AUTO Library Path" (describe-variable 'verilog-library-directories) t]
1026 ["AUTO Library Files" (describe-variable 'verilog-library-files) t]
1027 ["AUTO Library Extensions" (describe-variable 'verilog-library-extensions) t]
1028 ["AUTO `define Reading" (describe-function 'verilog-read-defines) t]
1029 ["AUTO `include Reading" (describe-function 'verilog-read-includes) t]
1030 ["AUTOARG" (describe-function 'verilog-auto-arg) t]
1031 ["AUTOASCIIENUM" (describe-function 'verilog-auto-ascii-enum) t]
1032 ["AUTOINOUTMODULE" (describe-function 'verilog-auto-inout-module) t]
1033 ["AUTOINOUT" (describe-function 'verilog-auto-inout) t]
1034 ["AUTOINPUT" (describe-function 'verilog-auto-input) t]
1035 ["AUTOINST" (describe-function 'verilog-auto-inst) t]
1036 ["AUTOINST (.*)" (describe-function 'verilog-auto-star) t]
1037 ["AUTOINSTPARAM" (describe-function 'verilog-auto-inst-param) t]
1038 ["AUTOOUTPUT" (describe-function 'verilog-auto-output) t]
1039 ["AUTOOUTPUTEVERY" (describe-function 'verilog-auto-output-every) t]
1040 ["AUTOREG" (describe-function 'verilog-auto-reg) t]
1041 ["AUTOREGINPUT" (describe-function 'verilog-auto-reg-input) t]
1042 ["AUTORESET" (describe-function 'verilog-auto-reset) t]
1043 ["AUTOSENSE" (describe-function 'verilog-auto-sense) t]
1044 ["AUTOTIEOFF" (describe-function 'verilog-auto-tieoff) t]
1045 ["AUTOUNUSED" (describe-function 'verilog-auto-unused) t]
1046 ["AUTOWIRE" (describe-function 'verilog-auto-wire) t]
1047 )
1048 "----"
1049 ["Submit bug report" verilog-submit-bug-report t]
1050 ["Version and FAQ" verilog-faq t]
1051 ["Customize Verilog Mode..." verilog-customize t]
1052 ["Customize Verilog Fonts & Colors" verilog-font-customize t]))
1053
1054 (easy-menu-define
1055 verilog-stmt-menu verilog-mode-map "Menu for statement templates in Verilog."
1056 '("Statements"
1057 ["Header" verilog-sk-header t]
1058 ["Comment" verilog-sk-comment t]
1059 "----"
1060 ["Module" verilog-sk-module t]
1061 ["Primitive" verilog-sk-primitive t]
1062 "----"
1063 ["Input" verilog-sk-input t]
1064 ["Output" verilog-sk-output t]
1065 ["Inout" verilog-sk-inout t]
1066 ["Wire" verilog-sk-wire t]
1067 ["Reg" verilog-sk-reg t]
1068 ["Define thing under point as a register" verilog-sk-define-signal t]
1069 "----"
1070 ["Initial" verilog-sk-initial t]
1071 ["Always" verilog-sk-always t]
1072 ["Function" verilog-sk-function t]
1073 ["Task" verilog-sk-task t]
1074 ["Specify" verilog-sk-specify t]
1075 ["Generate" verilog-sk-generate t]
1076 "----"
1077 ["Begin" verilog-sk-begin t]
1078 ["If" verilog-sk-if t]
1079 ["(if) else" verilog-sk-else-if t]
1080 ["For" verilog-sk-for t]
1081 ["While" verilog-sk-while t]
1082 ["Fork" verilog-sk-fork t]
1083 ["Repeat" verilog-sk-repeat t]
1084 ["Case" verilog-sk-case t]
1085 ["Casex" verilog-sk-casex t]
1086 ["Casez" verilog-sk-casez t]))
1087
1088 (defvar verilog-mode-abbrev-table nil
1089 "Abbrev table in use in Verilog-mode buffers.")
1090
1091 (define-abbrev-table 'verilog-mode-abbrev-table ())
1092
1093 ;;
1094 ;; Macros
1095 ;;
1096
1097 (defsubst verilog-string-replace-matches (from-string to-string fixedcase literal string)
1098 "Replace occurrences of FROM-STRING with TO-STRING.
1099 FIXEDCASE and LITERAL as in `replace-match`. STRING is what to replace.
1100 The case (verilog-string-replace-matches \"o\" \"oo\" nil nil \"foobar\")
1101 will break, as the o's continuously replace. xa -> x works ok though."
1102 ;; Hopefully soon to a emacs built-in
1103 (let ((start 0))
1104 (while (string-match from-string string start)
1105 (setq string (replace-match to-string fixedcase literal string)
1106 start (min (length string) (match-end 0))))
1107 string))
1108
1109 (defsubst verilog-string-remove-spaces (string)
1110 "Remove spaces surrounding STRING."
1111 (save-match-data
1112 (setq string (verilog-string-replace-matches "^\\s-+" "" nil nil string))
1113 (setq string (verilog-string-replace-matches "\\s-+$" "" nil nil string))
1114 string))
1115
1116 (defsubst verilog-re-search-forward (REGEXP BOUND NOERROR)
1117 ; checkdoc-params: (REGEXP BOUND NOERROR)
1118 "Like `re-search-forward', but skips over match in comments or strings."
1119 (store-match-data '(nil nil))
1120 (while (and
1121 (re-search-forward REGEXP BOUND NOERROR)
1122 (and (verilog-skip-forward-comment-or-string)
1123 (progn
1124 (store-match-data '(nil nil))
1125 (if BOUND
1126 (< (point) BOUND)
1127 t)))))
1128 (match-end 0))
1129
1130 (defsubst verilog-re-search-backward (REGEXP BOUND NOERROR)
1131 ; checkdoc-params: (REGEXP BOUND NOERROR)
1132 "Like `re-search-backward', but skips over match in comments or strings."
1133 (store-match-data '(nil nil))
1134 (while (and
1135 (re-search-backward REGEXP BOUND NOERROR)
1136 (and (verilog-skip-backward-comment-or-string)
1137 (progn
1138 (store-match-data '(nil nil))
1139 (if BOUND
1140 (> (point) BOUND)
1141 t)))))
1142 (match-end 0))
1143
1144 (defsubst verilog-re-search-forward-quick (regexp bound noerror)
1145 "Like `verilog-re-search-forward', including use of REGEXP BOUND and NOERROR,
1146 but trashes match data and is faster for REGEXP that doesn't match often.
1147 This may at some point use text properties to ignore comments,
1148 so there may be a large up front penalty for the first search."
1149 (let (pt)
1150 (while (and (not pt)
1151 (re-search-forward regexp bound noerror))
1152 (if (not (verilog-inside-comment-p))
1153 (setq pt (match-end 0))))
1154 pt))
1155
1156 (defsubst verilog-re-search-backward-quick (regexp bound noerror)
1157 ; checkdoc-params: (REGEXP BOUND NOERROR)
1158 "Like `verilog-re-search-backward', including use of REGEXP BOUND and NOERROR,
1159 but trashes match data and is faster for REGEXP that doesn't match often.
1160 This may at some point use text properties to ignore comments,
1161 so there may be a large up front penalty for the first search."
1162 (let (pt)
1163 (while (and (not pt)
1164 (re-search-backward regexp bound noerror))
1165 (if (not (verilog-inside-comment-p))
1166 (setq pt (match-end 0))))
1167 pt))
1168
1169 (defsubst verilog-get-beg-of-line (&optional arg)
1170 (save-excursion
1171 (beginning-of-line arg)
1172 (point)))
1173
1174 (defsubst verilog-get-end-of-line (&optional arg)
1175 (save-excursion
1176 (end-of-line arg)
1177 (point)))
1178
1179 (defsubst verilog-within-string ()
1180 (save-excursion
1181 (nth 3 (parse-partial-sexp (verilog-get-beg-of-line) (point)))))
1182
1183 (defvar compile-command)
1184
1185 ;; compilation program
1186 (defun verilog-set-compile-command ()
1187 "Function to compute shell command to compile Verilog.
1188
1189 This reads `verilog-tool' and sets `compile-command'. This specifies the
1190 program that executes when you type \\[compile] or
1191 \\[verilog-auto-save-compile].
1192
1193 By default `verilog-tool' uses a Makefile if one exists in the current
1194 directory. If not, it is set to the `verilog-linter', `verilog-coverage',
1195 `verilog-simulator', or `verilog-compiler' variables, as selected with the
1196 Verilog -> \"Choose Compilation Action\" menu.
1197
1198 You should set `verilog-tool' or the other variables to the path and
1199 arguments for your Verilog simulator. For example:
1200 \"vcs -p123 -O\"
1201 or a string like:
1202 \"(cd /tmp; surecov %s)\".
1203
1204 In the former case, the path to the current buffer is concat'ed to the
1205 value of `verilog-tool'; in the later, the path to the current buffer is
1206 substituted for the %s.
1207
1208 Where __FILE__ appears in the string, the `buffer-file-name' of the
1209 current buffer, without the directory portion, will be substituted."
1210 (interactive)
1211 (cond
1212 ((or (file-exists-p "makefile") ;If there is a makefile, use it
1213 (file-exists-p "Makefile"))
1214 (make-local-variable 'compile-command)
1215 (setq compile-command "make "))
1216 (t
1217 (make-local-variable 'compile-command)
1218 (setq compile-command
1219 (if verilog-tool
1220 (if (string-match "%s" (eval verilog-tool))
1221 (format (eval verilog-tool) (or buffer-file-name ""))
1222 (concat (eval verilog-tool) " " (or buffer-file-name "")))
1223 ""))))
1224 (verilog-modify-compile-command))
1225
1226 (defun verilog-modify-compile-command ()
1227 "Replace meta-information in `compile-command'.
1228 Where __FILE__ appears in the string, the current buffer's file-name,
1229 without the directory portion, will be substituted."
1230 (when (and
1231 (stringp compile-command)
1232 (string-match "\\b__FILE__\\b" compile-command))
1233 (make-local-variable 'compile-command)
1234 (setq compile-command
1235 (verilog-string-replace-matches
1236 "\\b__FILE__\\b" (file-name-nondirectory (buffer-file-name))
1237 t t compile-command))))
1238
1239 ;; Following code only gets called from compilation-mode-hook.
1240 (defvar compilation-error-regexp-alist)
1241
1242 (defun verilog-error-regexp-add ()
1243 "Add the messages to the `compilation-error-regexp-alist'.
1244 Called by `compilation-mode-hook'. This allows \\[next-error] to
1245 find the errors."
1246 (if (not verilog-error-regexp-add-didit)
1247 (progn
1248 (setq verilog-error-regexp-add-didit t)
1249 (setq-default compilation-error-regexp-alist
1250 (append verilog-error-regexp
1251 (default-value 'compilation-error-regexp-alist)))
1252 ;; Could be buffer local at this point; maybe also in let; change all three
1253 (setq compilation-error-regexp-alist
1254 (default-value 'compilation-error-regexp-alist))
1255 (set (make-local-variable 'compilation-error-regexp-alist)
1256 (default-value 'compilation-error-regexp-alist)))))
1257
1258 (add-hook 'compilation-mode-hook 'verilog-error-regexp-add)
1259
1260 (defconst verilog-directive-re
1261 ;; "`case" "`default" "`define" "`define" "`else" "`endfor" "`endif"
1262 ;; "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
1263 ;; "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
1264 ;; "`time_scale" "`undef" "`while"
1265 "\\<`\\(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\\)\\>")
1266
1267 (defconst verilog-directive-begin
1268 "\\<`\\(for\\|i\\(f\\|fdef\\|fndef\\)\\|switch\\|while\\)\\>")
1269
1270 (defconst verilog-directive-middle
1271 "\\<`\\(else\\|default\\|case\\)\\>")
1272
1273 (defconst verilog-directive-end
1274 "`\\(endfor\\|endif\\|endswitch\\|endwhile\\)\\>")
1275
1276 (defconst verilog-directive-re-1
1277 (concat "[ \t]*" verilog-directive-re))
1278
1279 ;;
1280 ;; Regular expressions used to calculate indent, etc.
1281 ;;
1282 (defconst verilog-symbol-re "\\<[a-zA-Z_][a-zA-Z_0-9.]*\\>")
1283 (defconst verilog-case-re "\\(\\<case[xz]?\\>\\|\\<randcase\\>\\)")
1284 ;; Want to match
1285 ;; aa :
1286 ;; aa,bb :
1287 ;; a[34:32] :
1288 ;; a,
1289 ;; b :
1290
1291 (defconst verilog-no-indent-begin-re
1292 "\\<\\(if\\|else\\|while\\|for\\|repeat\\|always\\|always_comb\\|always_ff\\|always_latch\\)\\>")
1293
1294 (defconst verilog-ends-re
1295 ;; Parenthesis indicate type of keyword found
1296 (concat
1297 "\\(\\<else\\>\\)\\|" ; 1
1298 "\\(\\<if\\>\\)\\|" ; 2
1299 "\\(\\<end\\>\\)\\|" ; 3
1300 "\\(\\<endcase\\>\\)\\|" ; 4
1301 "\\(\\<endfunction\\>\\)\\|" ; 5
1302 "\\(\\<endtask\\>\\)\\|" ; 6
1303 "\\(\\<endspecify\\>\\)\\|" ; 7
1304 "\\(\\<endtable\\>\\)\\|" ; 8
1305 "\\(\\<endgenerate\\>\\)\\|" ; 9
1306 "\\(\\<join\\(_any\\|_none\\)?\\>\\)\\|" ; 10
1307 "\\(\\<endclass\\>\\)\\|" ; 11
1308 "\\(\\<endgroup\\>\\)" ; 12
1309 ))
1310
1311 (defconst verilog-auto-end-comment-lines-re
1312 ;; Matches to names in this list cause auto-end-commentation
1313 (concat "\\("
1314 verilog-directive-re "\\)\\|\\("
1315 (eval-when-compile
1316 (verilog-regexp-words
1317 `( "begin"
1318 "else"
1319 "end"
1320 "endcase"
1321 "endclass"
1322 "endclocking"
1323 "endgroup"
1324 "endfunction"
1325 "endmodule"
1326 "endprogram"
1327 "endprimitive"
1328 "endinterface"
1329 "endpackage"
1330 "endsequence"
1331 "endspecify"
1332 "endtable"
1333 "endtask"
1334 "join"
1335 "join_any"
1336 "join_none"
1337 "module"
1338 "macromodule"
1339 "primitive"
1340 "interface"
1341 "package")))
1342 "\\)"))
1343
1344 ;;; NOTE: verilog-leap-to-head expects that verilog-end-block-re and
1345 ;;; verilog-end-block-ordered-re matches exactly the same strings.
1346 (defconst verilog-end-block-ordered-re
1347 ;; Parenthesis indicate type of keyword found
1348 (concat "\\(\\<endcase\\>\\)\\|" ; 1
1349 "\\(\\<end\\>\\)\\|" ; 2
1350 "\\(\\<end" ; 3, but not used
1351 "\\(" ; 4, but not used
1352 "\\(function\\)\\|" ; 5
1353 "\\(task\\)\\|" ; 6
1354 "\\(module\\)\\|" ; 7
1355 "\\(primitive\\)\\|" ; 8
1356 "\\(interface\\)\\|" ; 9
1357 "\\(package\\)\\|" ; 10
1358 "\\(class\\)\\|" ; 11
1359 "\\(group\\)\\|" ; 12
1360 "\\(program\\)\\|" ; 13
1361 "\\(sequence\\)\\|" ; 14
1362 "\\(clocking\\)\\|" ; 15
1363 "\\)\\>\\)"))
1364 (defconst verilog-end-block-re
1365 (eval-when-compile
1366 (verilog-regexp-words
1367
1368 `("end" ;; closes begin
1369 "endcase" ;; closes any of case, casex casez or randcase
1370 "join" "join_any" "join_none" ;; closes fork
1371 "endclass"
1372 "endtable"
1373 "endspecify"
1374 "endfunction"
1375 "endgenerate"
1376 "endtask"
1377 "endgroup"
1378 "endproperty"
1379 "endinterface"
1380 "endpackage"
1381 "endprogram"
1382 "endsequence"
1383 "endclocking"
1384 ))))
1385
1386
1387 (defconst verilog-endcomment-reason-re
1388 ;; Parenthesis indicate type of keyword found
1389 (concat
1390 "\\(\\<fork\\>\\)\\|"
1391 "\\(\\<begin\\>\\)\\|"
1392 "\\(\\<if\\>\\)\\|"
1393 "\\(\\<clocking\\>\\)\\|"
1394 "\\(\\<else\\>\\)\\|"
1395 "\\(\\<end\\>.*\\<else\\>\\)\\|"
1396 "\\(\\<task\\>\\)\\|"
1397 "\\(\\<function\\>\\)\\|"
1398 "\\(\\<initial\\>\\)\\|"
1399 "\\(\\<interface\\>\\)\\|"
1400 "\\(\\<package\\>\\)\\|"
1401 "\\(\\<final\\>\\)\\|"
1402 "\\(\\<always\\>\\(\[ \t\]*@\\)?\\)\\|"
1403 "\\(\\<always_comb\\>\\(\[ \t\]*@\\)?\\)\\|"
1404 "\\(\\<always_ff\\>\\(\[ \t\]*@\\)?\\)\\|"
1405 "\\(\\<always_latch\\>\\(\[ \t\]*@\\)?\\)\\|"
1406 "\\(@\\)\\|"
1407 "\\(\\<while\\>\\)\\|"
1408 "\\(\\<for\\(ever\\|each\\)?\\>\\)\\|"
1409 "\\(\\<repeat\\>\\)\\|\\(\\<wait\\>\\)\\|"
1410 "#"))
1411
1412 (defconst verilog-named-block-re "begin[ \t]*:")
1413
1414 ;; These words begin a block which can occur inside a module which should be indented,
1415 ;; and closed with the respective word from the end-block list
1416
1417 (defconst verilog-beg-block-re
1418 (eval-when-compile
1419 (verilog-regexp-words
1420 `("begin"
1421 "case" "casex" "casez" "randcase"
1422 "clocking"
1423 "generate"
1424 "fork"
1425 "function"
1426 "property"
1427 "specify"
1428 "table"
1429 "task"
1430 ))))
1431 ;; These are the same words, in a specific order in the regular
1432 ;; expression so that matching will work nicely for
1433 ;; verilog-forward-sexp and verilog-calc-indent
1434
1435 (defconst verilog-beg-block-re-ordered
1436 ( concat "\\<"
1437 "\\(begin\\)" ;1
1438 "\\|\\(randcase\\|\\(unique\\s-+\\|priority\\s-+\\)?case[xz]?\\)" ; 2,3
1439 "\\|\\(\\(disable\\s-+\\)?fork\\)" ;4
1440 "\\|\\(class\\)" ;5
1441 "\\|\\(table\\)" ;6
1442 "\\|\\(specify\\)" ;7
1443 "\\|\\(function\\)" ;8
1444 "\\|\\(task\\)" ;9
1445 "\\|\\(generate\\)" ;10
1446 "\\|\\(covergroup\\)" ;11
1447 "\\|\\(property\\)" ;12
1448 "\\|\\(\\(rand\\)?sequence\\)" ;13
1449 "\\|\\(clocking\\)" ;14
1450 "\\>"))
1451
1452 (defconst verilog-end-block-ordered-rry
1453 [ "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
1454 "\\(\\<randcase\\>\\|\\<case[xz]?\\>\\)\\|\\(\\<endcase\\>\\)"
1455 "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
1456 "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)"
1457 "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)"
1458 "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)"
1459 "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)"
1460 "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)"
1461 "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)"
1462 "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)"
1463 "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)"
1464 "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)"
1465 "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)"
1466 ] )
1467
1468 (defconst verilog-nameable-item-re
1469 (eval-when-compile
1470 (verilog-regexp-words
1471 `("begin"
1472 "fork"
1473 "join" "join_any" "join_none"
1474 "end"
1475 "endcase"
1476 "endconfig"
1477 "endclass"
1478 "endclocking"
1479 "endfunction"
1480 "endgenerate"
1481 "endmodule"
1482 "endprimative"
1483 "endinterface"
1484 "endpackage"
1485 "endspecify"
1486 "endtable"
1487 "endtask" )
1488 )))
1489
1490 (defconst verilog-declaration-opener
1491 (eval-when-compile
1492 (verilog-regexp-words
1493 `("module" "begin" "task" "function"))))
1494
1495 (defconst verilog-declaration-prefix-re
1496 (eval-when-compile
1497 (verilog-regexp-words
1498 `(
1499 ;; port direction
1500 "inout" "input" "output" "ref"
1501 ;; changeableness
1502 "const" "static" "protected" "local"
1503 ;; parameters
1504 "localparam" "parameter" "var"
1505 ;; type creation
1506 "typedef"
1507 ))))
1508 (defconst verilog-declaration-core-re
1509 (eval-when-compile
1510 (verilog-regexp-words
1511 `(
1512 ;; port direction (by themselves)
1513 "inout" "input" "output"
1514 ;; integer_atom_type
1515 "byte" "shortint" "int" "longint" "integer" "time"
1516 ;; integer_vector_type
1517 "bit" "logic" "reg"
1518 ;; non_integer_type
1519 "shortreal" "real" "realtime"
1520 ;; net_type
1521 "supply0" "supply1" "tri" "triand" "trior" "trireg" "tri0" "tri1" "uwire" "wire" "wand" "wor"
1522 ;; misc
1523 "string" "event" "chandle" "virtual" "enum" "genvar"
1524 "struct" "union"
1525 ;; builtin classes
1526 "mailbox" "semaphore"
1527 ))))
1528 (defconst verilog-declaration-re
1529 (concat "\\(" verilog-declaration-prefix-re "\\s-*\\)?" verilog-declaration-core-re))
1530 (defconst verilog-range-re "\\(\\[[^]]*\\]\\s-*\\)+")
1531 (defconst verilog-optional-signed-re "\\s-*\\(signed\\)?")
1532 (defconst verilog-optional-signed-range-re
1533 (concat
1534 "\\s-*\\(\\<\\(reg\\|wire\\)\\>\\s-*\\)?\\(\\<signed\\>\\s-*\\)?\\(" verilog-range-re "\\)?"))
1535 (defconst verilog-macroexp-re "`\\sw+")
1536
1537 (defconst verilog-delay-re "#\\s-*\\(\\([0-9_]+\\('s?[hdxbo][0-9a-fA-F_xz]+\\)?\\)\\|\\(([^()]*)\\)\\|\\(\\sw+\\)\\)")
1538 (defconst verilog-declaration-re-2-no-macro
1539 (concat "\\s-*" verilog-declaration-re
1540 "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
1541 "\\)?"))
1542 (defconst verilog-declaration-re-2-macro
1543 (concat "\\s-*" verilog-declaration-re
1544 "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
1545 "\\|\\(" verilog-macroexp-re "\\)"
1546 "\\)?"))
1547 (defconst verilog-declaration-re-1-macro
1548 (concat "^" verilog-declaration-re-2-macro))
1549
1550 (defconst verilog-declaration-re-1-no-macro (concat "^" verilog-declaration-re-2-no-macro))
1551
1552 (defconst verilog-defun-re
1553 (eval-when-compile (verilog-regexp-words `("macromodule" "module" "class" "program" "interface" "package" "primitive" "config"))))
1554 (defconst verilog-end-defun-re
1555 (eval-when-compile (verilog-regexp-words `("endmodule" "endclass" "endprogram" "endinterface" "endpackage" "endprimitive" "endconfig"))))
1556 (defconst verilog-zero-indent-re
1557 (concat verilog-defun-re "\\|" verilog-end-defun-re))
1558
1559 (defconst verilog-behavioral-block-beg-re
1560 (eval-when-compile (verilog-regexp-words `("initial" "final" "always" "always_comb" "always_latch" "always_ff"
1561 "function" "task"))))
1562
1563 (defconst verilog-indent-re
1564 (eval-when-compile
1565 (verilog-regexp-words
1566 `(
1567 "{"
1568 "always" "always_latch" "always_ff" "always_comb"
1569 "begin" "end"
1570 ; "unique" "priority"
1571 "case" "casex" "casez" "randcase" "endcase"
1572 "class" "endclass"
1573 "clocking" "endclocking"
1574 "config" "endconfig"
1575 "covergroup" "endgroup"
1576 "fork" "join" "join_any" "join_none"
1577 "function" "endfunction"
1578 "final"
1579 "generate" "endgenerate"
1580 "initial"
1581 "interface" "endinterface"
1582 "module" "macromodule" "endmodule"
1583 "package" "endpackage"
1584 "primitive" "endprimative"
1585 "program" "endprogram"
1586 "property" "endproperty"
1587 "sequence" "randsequence" "endsequence"
1588 "specify" "endspecify"
1589 "table" "endtable"
1590 "task" "endtask"
1591 "`case"
1592 "`default"
1593 "`define" "`undef"
1594 "`if" "`ifdef" "`ifndef" "`else" "`endif"
1595 "`while" "`endwhile"
1596 "`for" "`endfor"
1597 "`format"
1598 "`include"
1599 "`let"
1600 "`protect" "`endprotect"
1601 "`switch" "`endswitch"
1602 "`timescale"
1603 "`time_scale"
1604 ))))
1605
1606 (defconst verilog-defun-level-re
1607 (eval-when-compile
1608 (verilog-regexp-words
1609 `(
1610 "module" "macromodule" "primitive" "class" "program" "initial" "final" "always" "always_comb"
1611 "always_ff" "always_latch" "endtask" "endfunction" "interface" "package"
1612 "config"))))
1613
1614 (defconst verilog-defun-level-not-generate-re
1615 (eval-when-compile
1616 (verilog-regexp-words
1617 `(
1618 "module" "macromodule" "primitive" "class" "program" "interface" "package" "config"))))
1619
1620 (defconst verilog-cpp-level-re
1621 (eval-when-compile
1622 (verilog-regexp-words
1623 `(
1624 "endmodule" "endprimitive" "endinterface" "endpackage" "endprogram" "endclass"
1625 ))))
1626 (defconst verilog-disable-fork-re "disable\\s-+fork")
1627 (defconst verilog-extended-case-re "\\(unique\\s-+\\|priority\\s-+\\)?case[xz]?")
1628 (defconst verilog-extended-complete-re
1629 (concat "\\(\\<extern\\s-+\\|\\<virtual\\s-+\\|\\<protected\\s-+\\)*\\(\\<function\\>\\|\\<task\\>\\)"
1630 "\\|\\(\\<typedef\\>\\s-+\\)*\\(\\<struct\\>\\|\\<union\\>\\|\\<class\\>\\)"
1631 "\\|" verilog-extended-case-re ))
1632 (defconst verilog-basic-complete-re
1633 (eval-when-compile
1634 (verilog-regexp-words
1635 `(
1636 "always" "assign" "always_latch" "always_ff" "always_comb" "constraint"
1637 "import" "initial" "final" "module" "macromodule" "repeat" "randcase" "while"
1638 "if" "for" "forever" "foreach" "else" "parameter" "do"
1639 ))))
1640 (defconst verilog-complete-reg
1641 (concat
1642 verilog-extended-complete-re
1643 "\\|"
1644 verilog-basic-complete-re))
1645
1646 (defconst verilog-end-statement-re
1647 (concat "\\(" verilog-beg-block-re "\\)\\|\\("
1648 verilog-end-block-re "\\)"))
1649
1650 (defconst verilog-endcase-re
1651 (concat verilog-case-re "\\|"
1652 "\\(endcase\\)\\|"
1653 verilog-defun-re
1654 ))
1655
1656 (defconst verilog-exclude-str-start "/* -----\\/----- EXCLUDED -----\\/-----"
1657 "String used to mark beginning of excluded text.")
1658 (defconst verilog-exclude-str-end " -----/\\----- EXCLUDED -----/\\----- */"
1659 "String used to mark end of excluded text.")
1660 (defconst verilog-preprocessor-re
1661 (eval-when-compile
1662 (verilog-regexp-words
1663 `(
1664 "`define" "`include" "`ifdef" "`ifndef" "`if" "`endif" "`else"
1665 ))))
1666
1667 (defconst verilog-keywords
1668 '( "`case" "`default" "`define" "`else" "`endfor" "`endif"
1669 "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
1670 "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
1671 "`time_scale" "`undef" "`while"
1672
1673 "after" "alias" "always" "always_comb" "always_ff" "always_latch" "and"
1674 "assert" "assign" "assume" "automatic" "before" "begin" "bind"
1675 "bins" "binsof" "bit" "break" "buf" "bufif0" "bufif1" "byte"
1676 "case" "casex" "casez" "cell" "chandle" "class" "clocking" "cmos"
1677 "config" "const" "constraint" "context" "continue" "cover"
1678 "covergroup" "coverpoint" "cross" "deassign" "default" "defparam"
1679 "design" "disable" "dist" "do" "edge" "else" "end" "endcase"
1680 "endclass" "endclocking" "endconfig" "endfunction" "endgenerate"
1681 "endgroup" "endinterface" "endmodule" "endpackage" "endprimitive"
1682 "endprogram" "endproperty" "endspecify" "endsequence" "endtable"
1683 "endtask" "enum" "event" "expect" "export" "extends" "extern"
1684 "final" "first_match" "for" "force" "foreach" "forever" "fork"
1685 "forkjoin" "function" "generate" "genvar" "highz0" "highz1" "if"
1686 "iff" "ifnone" "ignore_bins" "illegal_bins" "import" "incdir"
1687 "include" "initial" "inout" "input" "inside" "instance" "int"
1688 "integer" "interface" "intersect" "join" "join_any" "join_none"
1689 "large" "liblist" "library" "local" "localparam" "logic"
1690 "longint" "macromodule" "mailbox" "matches" "medium" "modport" "module"
1691 "nand" "negedge" "new" "nmos" "nor" "noshowcancelled" "not"
1692 "notif0" "notif1" "null" "or" "output" "package" "packed"
1693 "parameter" "pmos" "posedge" "primitive" "priority" "program"
1694 "property" "protected" "pull0" "pull1" "pulldown" "pullup"
1695 "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
1696 "randcase" "randsequence" "rcmos" "real" "realtime" "ref" "reg"
1697 "release" "repeat" "return" "rnmos" "rpmos" "rtran" "rtranif0"
1698 "rtranif1" "scalared" "semaphore" "sequence" "shortint" "shortreal"
1699 "showcancelled" "signed" "small" "solve" "specify" "specparam"
1700 "static" "string" "strong0" "strong1" "struct" "super" "supply0"
1701 "supply1" "table" "tagged" "task" "this" "throughout" "time"
1702 "timeprecision" "timeunit" "tran" "tranif0" "tranif1" "tri"
1703 "tri0" "tri1" "triand" "trior" "trireg" "type" "typedef" "union"
1704 "unique" "unsigned" "use" "uwire" "var" "vectored" "virtual" "void"
1705 "wait" "wait_order" "wand" "weak0" "weak1" "while" "wildcard"
1706 "wire" "with" "within" "wor" "xnor" "xor"
1707 )
1708 "List of Verilog keywords.")
1709
1710 (defconst verilog-comment-start-regexp "//\\|/\\*"
1711 "Dual comment value for `comment-start-regexp'.")
1712
1713 (defvar verilog-mode-syntax-table
1714 (let ((table (make-syntax-table)))
1715 ;; Populate the syntax TABLE.
1716 (modify-syntax-entry ?\\ "\\" table)
1717 (modify-syntax-entry ?+ "." table)
1718 (modify-syntax-entry ?- "." table)
1719 (modify-syntax-entry ?= "." table)
1720 (modify-syntax-entry ?% "." table)
1721 (modify-syntax-entry ?< "." table)
1722 (modify-syntax-entry ?> "." table)
1723 (modify-syntax-entry ?& "." table)
1724 (modify-syntax-entry ?| "." table)
1725 (modify-syntax-entry ?` "w" table)
1726 (modify-syntax-entry ?_ "w" table)
1727 (modify-syntax-entry ?\' "." table)
1728
1729 ;; Set up TABLE to handle block and line style comments.
1730 (if (featurep 'xemacs)
1731 (progn
1732 ;; XEmacs (formerly Lucid) has the best implementation
1733 (modify-syntax-entry ?/ ". 1456" table)
1734 (modify-syntax-entry ?* ". 23" table)
1735 (modify-syntax-entry ?\n "> b" table))
1736 ;; Emacs 19 does things differently, but we can work with it
1737 (modify-syntax-entry ?/ ". 124b" table)
1738 (modify-syntax-entry ?* ". 23" table)
1739 (modify-syntax-entry ?\n "> b" table))
1740 table)
1741 "Syntax table used in Verilog mode buffers.")
1742
1743 (defvar verilog-font-lock-keywords nil
1744 "Default highlighting for Verilog mode.")
1745
1746 (defvar verilog-font-lock-keywords-1 nil
1747 "Subdued level highlighting for Verilog mode.")
1748
1749 (defvar verilog-font-lock-keywords-2 nil
1750 "Medium level highlighting for Verilog mode.
1751 See also `verilog-font-lock-extra-types'.")
1752
1753 (defvar verilog-font-lock-keywords-3 nil
1754 "Gaudy level highlighting for Verilog mode.
1755 See also `verilog-font-lock-extra-types'.")
1756 (defvar verilog-font-lock-translate-off-face
1757 'verilog-font-lock-translate-off-face
1758 "Font to use for translated off regions.")
1759 (defface verilog-font-lock-translate-off-face
1760 '((((class color)
1761 (background light))
1762 (:background "gray90" :italic t ))
1763 (((class color)
1764 (background dark))
1765 (:background "gray10" :italic t ))
1766 (((class grayscale) (background light))
1767 (:foreground "DimGray" :italic t))
1768 (((class grayscale) (background dark))
1769 (:foreground "LightGray" :italic t))
1770 (t (:italis t)))
1771 "Font lock mode face used to background highlight translate-off regions."
1772 :group 'font-lock-highlighting-faces)
1773
1774 (defvar verilog-font-lock-p1800-face
1775 'verilog-font-lock-p1800-face
1776 "Font to use for p1800 keywords.")
1777 (defface verilog-font-lock-p1800-face
1778 '((((class color)
1779 (background light))
1780 (:foreground "DarkOrange3" :bold t ))
1781 (((class color)
1782 (background dark))
1783 (:foreground "orange1" :bold t ))
1784 (t (:italic t)))
1785 "Font lock mode face used to highlight P1800 keywords."
1786 :group 'font-lock-highlighting-faces)
1787
1788 (defvar verilog-font-lock-ams-face
1789 'verilog-font-lock-ams-face
1790 "Font to use for Analog/Mixed Signal keywords.")
1791 (defface verilog-font-lock-ams-face
1792 '((((class color)
1793 (background light))
1794 (:foreground "Purple" :bold t ))
1795 (((class color)
1796 (background dark))
1797 (:foreground "orange1" :bold t ))
1798 (t (:italic t)))
1799 "Font lock mode face used to highlight AMS keywords."
1800 :group 'font-lock-highlighting-faces)
1801
1802 (defvar verilog-font-grouping-keywords-face
1803 'verilog-font-lock-grouping-keywords-face
1804 "Font to use for Verilog Grouping Keywords (such as begin..end).")
1805 (defface verilog-font-lock-grouping-keywords-face
1806 '((((class color)
1807 (background light))
1808 (:foreground "red4" :bold t ))
1809 (((class color)
1810 (background dark))
1811 (:foreground "red4" :bold t ))
1812 (t (:italic t)))
1813 "Font lock mode face used to highlight verilog grouping keywords."
1814 :group 'font-lock-highlighting-faces)
1815
1816 (let* ((verilog-type-font-keywords
1817 (eval-when-compile
1818 (verilog-regexp-opt
1819 '(
1820 "and" "bit" "buf" "bufif0" "bufif1" "cmos" "defparam"
1821 "event" "genvar" "inout" "input" "integer" "localparam"
1822 "logic" "mailbox" "nand" "nmos" "not" "notif0" "notif1" "or"
1823 "output" "parameter" "pmos" "pull0" "pull1" "pullup"
1824 "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran"
1825 "rtranif0" "rtranif1" "semaphore" "signed" "struct" "supply"
1826 "supply0" "supply1" "time" "tran" "tranif0" "tranif1"
1827 "tri" "tri0" "tri1" "triand" "trior" "trireg" "typedef"
1828 "uwire" "vectored" "wand" "wire" "wor" "xnor" "xor"
1829 ) nil )))
1830
1831 (verilog-pragma-keywords
1832 (eval-when-compile
1833 (verilog-regexp-opt
1834 '("surefire" "synopsys" "rtl_synthesis" "verilint" ) nil
1835 )))
1836
1837 (verilog-p1800-keywords
1838 (eval-when-compile
1839 (verilog-regexp-opt
1840 '("alias" "assert" "assume" "automatic" "before" "bind"
1841 "bins" "binsof" "break" "byte" "cell" "chandle" "class"
1842 "clocking" "config" "const" "constraint" "context" "continue"
1843 "cover" "covergroup" "coverpoint" "cross" "deassign" "design"
1844 "dist" "do" "edge" "endclass" "endclocking" "endconfig"
1845 "endgroup" "endprogram" "endproperty" "endsequence" "enum"
1846 "expect" "export" "extends" "extern" "first_match" "foreach"
1847 "forkjoin" "genvar" "highz0" "highz1" "ifnone" "ignore_bins"
1848 "illegal_bins" "import" "incdir" "include" "inside" "instance"
1849 "int" "intersect" "large" "liblist" "library" "local" "longint"
1850 "matches" "medium" "modport" "new" "noshowcancelled" "null"
1851 "packed" "program" "property" "protected" "pull0" "pull1"
1852 "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
1853 "randcase" "randsequence" "ref" "release" "return" "scalared"
1854 "sequence" "shortint" "shortreal" "showcancelled" "small" "solve"
1855 "specparam" "static" "string" "strong0" "strong1" "struct"
1856 "super" "tagged" "this" "throughout" "timeprecision" "timeunit"
1857 "type" "union" "unsigned" "use" "var" "virtual" "void"
1858 "wait_order" "weak0" "weak1" "wildcard" "with" "within"
1859 ) nil )))
1860
1861 (verilog-ams-keywords
1862 (eval-when-compile
1863 (verilog-regexp-opt
1864 '("above" "abs" "absdelay" "acos" "acosh" "ac_stim"
1865 "aliasparam" "analog" "analysis" "asin" "asinh" "atan" "atan2" "atanh"
1866 "branch" "ceil" "connectmodule" "connectrules" "cos" "cosh" "ddt"
1867 "ddx" "discipline" "driver_update" "enddiscipline" "endconnectrules"
1868 "endnature" "endparamset" "exclude" "exp" "final_step" "flicker_noise"
1869 "floor" "flow" "from" "ground" "hypot" "idt" "idtmod" "inf"
1870 "initial_step" "laplace_nd" "laplace_np" "laplace_zd" "laplace_zp"
1871 "last_crossing" "limexp" "ln" "log" "max" "min" "nature"
1872 "net_resolution" "noise_table" "paramset" "potential" "pow" "sin"
1873 "sinh" "slew" "sqrt" "tan" "tanh" "timer" "transition" "white_noise"
1874 "wreal" "zi_nd" "zi_np" "zi_zd" ) nil )))
1875
1876 (verilog-font-keywords
1877 (eval-when-compile
1878 (verilog-regexp-opt
1879 '(
1880 "assign" "case" "casex" "casez" "randcase" "deassign"
1881 "default" "disable" "else" "endcase" "endfunction"
1882 "endgenerate" "endinterface" "endmodule" "endprimitive"
1883 "endspecify" "endtable" "endtask" "final" "for" "force" "return" "break"
1884 "continue" "forever" "fork" "function" "generate" "if" "iff" "initial"
1885 "interface" "join" "join_any" "join_none" "macromodule" "module" "negedge"
1886 "package" "endpackage" "always" "always_comb" "always_ff"
1887 "always_latch" "posedge" "primitive" "priority" "release"
1888 "repeat" "specify" "table" "task" "unique" "wait" "while"
1889 "class" "program" "endclass" "endprogram"
1890 ) nil )))
1891
1892 (verilog-font-grouping-keywords
1893 (eval-when-compile
1894 (verilog-regexp-opt
1895 '( "begin" "end" ) nil ))))
1896
1897 (setq verilog-font-lock-keywords
1898 (list
1899 ;; Fontify all builtin keywords
1900 (concat "\\<\\(" verilog-font-keywords "\\|"
1901 ;; And user/system tasks and functions
1902 "\\$[a-zA-Z][a-zA-Z0-9_\\$]*"
1903 "\\)\\>")
1904 ;; Fontify all types
1905 (cons (concat "\\(\\<" verilog-font-grouping-keywords "\\)\\>")
1906 'verilog-font-lock-ams-face)
1907 (cons (concat "\\<\\(" verilog-type-font-keywords "\\)\\>")
1908 'font-lock-type-face)
1909 ;; Fontify IEEE-P1800 keywords appropriately
1910 (if verilog-highlight-p1800-keywords
1911 (cons (concat "\\<\\(" verilog-p1800-keywords "\\)\\>")
1912 'verilog-font-lock-p1800-face)
1913 (cons (concat "\\<\\(" verilog-p1800-keywords "\\)\\>")
1914 'font-lock-type-face))
1915 ;; Fontify Verilog-AMS keywords
1916 (cons (concat "\\<\\(" verilog-ams-keywords "\\)\\>")
1917 'verilog-font-lock-ams-face)))
1918
1919 (setq verilog-font-lock-keywords-1
1920 (append verilog-font-lock-keywords
1921 (list
1922 ;; Fontify module definitions
1923 (list
1924 "\\<\\(\\(macro\\)?module\\|primitive\\|class\\|program\\|interface\\|package\\|task\\)\\>\\s-*\\(\\sw+\\)"
1925 '(1 font-lock-keyword-face)
1926 '(3 font-lock-function-name-face 'prepend))
1927 ;; Fontify function definitions
1928 (list
1929 (concat "\\<function\\>\\s-+\\(integer\\|real\\(time\\)?\\|time\\)\\s-+\\(\\sw+\\)" )
1930 '(1 font-lock-keyword-face)
1931 '(3 font-lock-reference-face prepend))
1932 '("\\<function\\>\\s-+\\(\\[[^]]+\\]\\)\\s-+\\(\\sw+\\)"
1933 (1 font-lock-keyword-face)
1934 (2 font-lock-reference-face append))
1935 '("\\<function\\>\\s-+\\(\\sw+\\)"
1936 1 'font-lock-reference-face append))))
1937
1938 (setq verilog-font-lock-keywords-2
1939 (append verilog-font-lock-keywords-1
1940 (list
1941 ;; Fontify pragmas
1942 (concat "\\(//\\s-*" verilog-pragma-keywords "\\s-.*\\)")
1943 ;; Fontify escaped names
1944 '("\\(\\\\\\S-*\\s-\\)" 0 font-lock-function-name-face)
1945 ;; Fontify macro definitions/ uses
1946 '("`\\s-*[A-Za-z][A-Za-z0-9_]*" 0 (if (boundp 'font-lock-preprocessor-face)
1947 'font-lock-preprocessor-face
1948 'font-lock-type-face))
1949 ;; Fontify delays/numbers
1950 '("\\(@\\)\\|\\(#\\s-*\\(\\(\[0-9_.\]+\\('s?[hdxbo][0-9a-fA-F_xz]*\\)?\\)\\|\\(([^()]+)\\|\\sw+\\)\\)\\)"
1951 0 font-lock-type-face append)
1952 ;; Fontify instantiation names
1953 '("\\([A-Za-z][A-Za-z0-9_]+\\)\\s-*(" 1 font-lock-function-name-face)
1954 )))
1955
1956 (setq verilog-font-lock-keywords-3
1957 (append verilog-font-lock-keywords-2
1958 (when verilog-highlight-translate-off
1959 (list
1960 ;; Fontify things in translate off regions
1961 '(verilog-match-translate-off
1962 (0 'verilog-font-lock-translate-off-face prepend))
1963 )))))
1964
1965
1966 (defun verilog-inside-comment-p ()
1967 "Check if point inside a nested comment."
1968 (save-excursion
1969 (let ((st-point (point)) hitbeg)
1970 (or (search-backward "//" (verilog-get-beg-of-line) t)
1971 (if (progn
1972 ;; This is for tricky case //*, we keep searching if /*
1973 ;; is proceeded by // on same line.
1974 (while
1975 (and (setq hitbeg (search-backward "/*" nil t))
1976 (progn
1977 (forward-char 1)
1978 (search-backward "//" (verilog-get-beg-of-line) t))))
1979 hitbeg)
1980 (not (search-forward "*/" st-point t)))))))
1981
1982 (defun verilog-declaration-end ()
1983 (search-forward ";"))
1984
1985 (defun verilog-point-text (&optional pointnum)
1986 "Return text describing where POINTNUM or current point is (for errors).
1987 Use filename, if current buffer being edited shorten to just buffer name."
1988 (concat (or (and (equal (window-buffer (selected-window)) (current-buffer))
1989 (buffer-name))
1990 buffer-file-name
1991 (buffer-name))
1992 ":" (int-to-string (count-lines (point-min) (or pointnum (point))))))
1993
1994 (defun electric-verilog-backward-sexp ()
1995 "Move backward over a sexp."
1996 (interactive)
1997 ;; before that see if we are in a comment
1998 (verilog-backward-sexp))
1999
2000 (defun electric-verilog-forward-sexp ()
2001 "Move forward over a sexp."
2002 (interactive)
2003 ;; before that see if we are in a comment
2004 (verilog-forward-sexp))
2005
2006 ;;;used by hs-minor-mode
2007 (defun verilog-forward-sexp-function (arg)
2008 (if (< arg 0)
2009 (verilog-backward-sexp)
2010 (verilog-forward-sexp)))
2011
2012
2013 (defun verilog-backward-sexp ()
2014 (let ((reg)
2015 (elsec 1)
2016 (found nil)
2017 (st (point)))
2018 (if (not (looking-at "\\<"))
2019 (forward-word -1))
2020 (cond
2021 ((verilog-skip-backward-comment-or-string))
2022 ((looking-at "\\<else\\>")
2023 (setq reg (concat
2024 verilog-end-block-re
2025 "\\|\\(\\<else\\>\\)"
2026 "\\|\\(\\<if\\>\\)"))
2027 (while (and (not found)
2028 (verilog-re-search-backward reg nil 'move))
2029 (cond
2030 ((match-end 1) ; matched verilog-end-block-re
2031 ; try to leap back to matching outward block by striding across
2032 ; indent level changing tokens then immediately
2033 ; previous line governs indentation.
2034 (verilog-leap-to-head))
2035 ((match-end 2) ; else, we're in deep
2036 (setq elsec (1+ elsec)))
2037 ((match-end 3) ; found it
2038 (setq elsec (1- elsec))
2039 (if (= 0 elsec)
2040 ;; Now previous line describes syntax
2041 (setq found 't))))))
2042 ((looking-at verilog-end-block-re)
2043 (verilog-leap-to-head))
2044 ((looking-at "\\(endmodule\\>\\)\\|\\(\\<endprimitive\\>\\)\\|\\(\\<endclass\\>\\)\\|\\(\\<endprogram\\>\\)\\|\\(\\<endinterface\\>\\)\\|\\(\\<endpackage\\>\\)")
2045 (cond
2046 ((match-end 1)
2047 (verilog-re-search-backward "\\<\\(macro\\)?module\\>" nil 'move))
2048 ((match-end 2)
2049 (verilog-re-search-backward "\\<primitive\\>" nil 'move))
2050 ((match-end 3)
2051 (verilog-re-search-backward "\\<class\\>" nil 'move))
2052 ((match-end 4)
2053 (verilog-re-search-backward "\\<program\\>" nil 'move))
2054 ((match-end 5)
2055 (verilog-re-search-backward "\\<interface\\>" nil 'move))
2056 ((match-end 6)
2057 (verilog-re-search-backward "\\<package\\>" nil 'move))
2058 (t
2059 (goto-char st)
2060 (backward-sexp 1))))
2061 (t
2062 (goto-char st)
2063 (backward-sexp)))))
2064
2065 (defun verilog-forward-sexp ()
2066 (let ((reg)
2067 (md 2)
2068 (st (point)))
2069 (if (not (looking-at "\\<"))
2070 (forward-word -1))
2071 (cond
2072 ((verilog-skip-forward-comment-or-string)
2073 (verilog-forward-syntactic-ws))
2074 ((looking-at verilog-beg-block-re-ordered) ;; begin|(case)|xx|(fork)|class|table|specify|function|task|generate|covergroup|property|sequence|clocking
2075 (cond
2076 ((match-end 1) ; end
2077 ;; Search forward for matching begin
2078 (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
2079 ((match-end 2) ; endcase
2080 ;; Search forward for matching case
2081 (setq reg "\\(\\<randcase\\>\\|\\(\\<unique\\>\\s-+\\|\\<priority\\>\\s-+\\)?\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" )
2082 (setq md 3) ;; ender is third item in regexp
2083 )
2084 ((match-end 4) ; join
2085 ;; might be "disable fork"
2086 (if (or
2087 (looking-at verilog-disable-fork-re)
2088 (and (looking-at "fork")
2089 (progn
2090 (forward-word -1)
2091 (looking-at verilog-disable-fork-re))))
2092 (progn
2093 (goto-char (match-end 0))
2094 (forward-word)
2095 (setq reg nil))
2096 (progn
2097 ;; Search forward for matching fork
2098 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))))
2099 ((match-end 5) ; endclass
2100 ;; Search forward for matching class
2101 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
2102 ((match-end 6) ; endtable
2103 ;; Search forward for matching table
2104 (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
2105 ((match-end 7) ; endspecify
2106 ;; Search forward for matching specify
2107 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
2108 ((match-end 8) ; endfunction
2109 ;; Search forward for matching function
2110 (setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
2111 ((match-end 9) ; endtask
2112 ;; Search forward for matching task
2113 (setq reg "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)" ))
2114 ((match-end 10) ; endgenerate
2115 ;; Search forward for matching generate
2116 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
2117 ((match-end 11) ; endgroup
2118 ;; Search forward for matching covergroup
2119 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
2120 ((match-end 12) ; endproperty
2121 ;; Search forward for matching property
2122 (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
2123 ((match-end 13) ; endsequence
2124 ;; Search forward for matching sequence
2125 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" )
2126 (setq md 3)) ; 3 to get to endsequence in the reg above
2127 ((match-end 14) ; endclocking
2128 ;; Search forward for matching clocking
2129 (setq reg "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)" )))
2130 (if (and reg
2131 (forward-word 1))
2132 (catch 'skip
2133 (let ((nest 1))
2134 (while (verilog-re-search-forward reg nil 'move)
2135 (cond
2136 ((match-end md) ; the closer in reg, so we are climbing out
2137 (setq nest (1- nest))
2138 (if (= 0 nest) ; we are out!
2139 (throw 'skip 1)))
2140 ((match-end 1) ; the opener in reg, so we are deeper now
2141 (setq nest (1+ nest)))))))))
2142 ((looking-at (concat
2143 "\\(\\<\\(macro\\)?module\\>\\)\\|"
2144 "\\(\\<primitive\\>\\)\\|"
2145 "\\(\\<class\\>\\)\\|"
2146 "\\(\\<program\\>\\)\\|"
2147 "\\(\\<interface\\>\\)\\|"
2148 "\\(\\<package\\>\\)"))
2149 (cond
2150 ((match-end 1)
2151 (verilog-re-search-forward "\\<endmodule\\>" nil 'move))
2152 ((match-end 2)
2153 (verilog-re-search-forward "\\<endprimitive\\>" nil 'move))
2154 ((match-end 3)
2155 (verilog-re-search-forward "\\<endclass\\>" nil 'move))
2156 ((match-end 4)
2157 (verilog-re-search-forward "\\<endprogram\\>" nil 'move))
2158 ((match-end 5)
2159 (verilog-re-search-forward "\\<endinterface\\>" nil 'move))
2160 ((match-end 6)
2161 (verilog-re-search-forward "\\<endpackage\\>" nil 'move))
2162 (t
2163 (goto-char st)
2164 (if (= (following-char) ?\) )
2165 (forward-char 1)
2166 (forward-sexp 1)))))
2167 (t
2168 (goto-char st)
2169 (if (= (following-char) ?\) )
2170 (forward-char 1)
2171 (forward-sexp 1))))))
2172
2173 (defun verilog-declaration-beg ()
2174 (verilog-re-search-backward verilog-declaration-re (bobp) t))
2175
2176 (defun verilog-font-lock-init ()
2177 "Initialize fontification."
2178 ;; highlight keywords and standardized types, attributes, enumeration
2179 ;; values, and subprograms
2180 (setq verilog-font-lock-keywords-3
2181 (append verilog-font-lock-keywords-2
2182 (when verilog-highlight-translate-off
2183 (list
2184 ;; Fontify things in translate off regions
2185 '(verilog-match-translate-off
2186 (0 'verilog-font-lock-translate-off-face prepend))))))
2187 (put 'verilog-mode 'font-lock-defaults
2188 '((verilog-font-lock-keywords
2189 verilog-font-lock-keywords-1
2190 verilog-font-lock-keywords-2
2191 verilog-font-lock-keywords-3)
2192 nil ; nil means highlight strings & comments as well as keywords
2193 nil ; nil means keywords must match case
2194 nil ; syntax table handled elsewhere
2195 ;; Function to move to beginning of reasonable region to highlight
2196 verilog-beg-of-defun)))
2197
2198 ;; initialize fontification for Verilog Mode
2199 (verilog-font-lock-init)
2200
2201 ;;
2202 ;;
2203 ;; Mode
2204 ;;
2205 (defvar verilog-which-tool 1)
2206 ;;;###autoload
2207 (defun verilog-mode ()
2208 "Major mode for editing Verilog code.
2209 \\<verilog-mode-map>
2210 See \\[describe-function] verilog-auto (\\[verilog-auto]) for details on how
2211 AUTOs can improve coding efficiency.
2212
2213 Use \\[verilog-faq] for a pointer to frequently asked questions.
2214
2215 NEWLINE, TAB indents for Verilog code.
2216 Delete converts tabs to spaces as it moves back.
2217
2218 Supports highlighting.
2219
2220 Turning on Verilog mode calls the value of the variable `verilog-mode-hook'
2221 with no args, if that value is non-nil.
2222
2223 Variables controlling indentation/edit style:
2224
2225 variable `verilog-indent-level' (default 3)
2226 Indentation of Verilog statements with respect to containing block.
2227 `verilog-indent-level-module' (default 3)
2228 Absolute indentation of Module level Verilog statements.
2229 Set to 0 to get initial and always statements lined up
2230 on the left side of your screen.
2231 `verilog-indent-level-declaration' (default 3)
2232 Indentation of declarations with respect to containing block.
2233 Set to 0 to get them list right under containing block.
2234 `verilog-indent-level-behavioral' (default 3)
2235 Indentation of first begin in a task or function block
2236 Set to 0 to get such code to lined up underneath the task or
2237 function keyword.
2238 `verilog-indent-level-directive' (default 1)
2239 Indentation of `ifdef/`endif blocks.
2240 `verilog-cexp-indent' (default 1)
2241 Indentation of Verilog statements broken across lines i.e.:
2242 if (a)
2243 begin
2244 `verilog-case-indent' (default 2)
2245 Indentation for case statements.
2246 `verilog-auto-newline' (default nil)
2247 Non-nil means automatically newline after semicolons and the punctuation
2248 mark after an end.
2249 `verilog-auto-indent-on-newline' (default t)
2250 Non-nil means automatically indent line after newline.
2251 `verilog-tab-always-indent' (default t)
2252 Non-nil means TAB in Verilog mode should always reindent the current line,
2253 regardless of where in the line point is when the TAB command is used.
2254 `verilog-indent-begin-after-if' (default t)
2255 Non-nil means to indent begin statements following a preceding
2256 if, else, while, for and repeat statements, if any. Otherwise,
2257 the begin is lined up with the preceding token. If t, you get:
2258 if (a)
2259 begin // amount of indent based on `verilog-cexp-indent'
2260 otherwise you get:
2261 if (a)
2262 begin
2263 `verilog-auto-endcomments' (default t)
2264 Non-nil means a comment /* ... */ is set after the ends which ends
2265 cases, tasks, functions and modules.
2266 The type and name of the object will be set between the braces.
2267 `verilog-minimum-comment-distance' (default 10)
2268 Minimum distance (in lines) between begin and end required before a comment
2269 will be inserted. Setting this variable to zero results in every
2270 end acquiring a comment; the default avoids too many redundant
2271 comments in tight quarters.
2272 `verilog-auto-lineup' (default `(all))
2273 List of contexts where auto lineup of code should be done.
2274
2275 Variables controlling other actions:
2276
2277 `verilog-linter' (default surelint)
2278 Unix program to call to run the lint checker. This is the default
2279 command for \\[compile-command] and \\[verilog-auto-save-compile].
2280
2281 See \\[customize] for the complete list of variables.
2282
2283 AUTO expansion functions are, in part:
2284
2285 \\[verilog-auto] Expand AUTO statements.
2286 \\[verilog-delete-auto] Remove the AUTOs.
2287 \\[verilog-inject-auto] Insert AUTOs for the first time.
2288
2289 Some other functions are:
2290
2291 \\[verilog-complete-word] Complete word with appropriate possibilities.
2292 \\[verilog-mark-defun] Mark function.
2293 \\[verilog-beg-of-defun] Move to beginning of current function.
2294 \\[verilog-end-of-defun] Move to end of current function.
2295 \\[verilog-label-be] Label matching begin ... end, fork ... join, etc statements.
2296
2297 \\[verilog-comment-region] Put marked area in a comment.
2298 \\[verilog-uncomment-region] Uncomment an area commented with \\[verilog-comment-region].
2299 \\[verilog-insert-block] Insert begin ... end;.
2300 \\[verilog-star-comment] Insert /* ... */.
2301
2302 \\[verilog-sk-always] Insert a always @(AS) begin .. end block.
2303 \\[verilog-sk-begin] Insert a begin .. end block.
2304 \\[verilog-sk-case] Insert a case block, prompting for details.
2305 \\[verilog-sk-for] Insert a for (...) begin .. end block, prompting for details.
2306 \\[verilog-sk-generate] Insert a generate .. endgenerate block.
2307 \\[verilog-sk-header] Insert a nice header block at the top of file.
2308 \\[verilog-sk-initial] Insert an initial begin .. end block.
2309 \\[verilog-sk-fork] Insert a fork begin .. end .. join block.
2310 \\[verilog-sk-module] Insert a module .. (/*AUTOARG*/);.. endmodule block.
2311 \\[verilog-sk-primitive] Insert a primitive .. (.. );.. endprimitive block.
2312 \\[verilog-sk-repeat] Insert a repeat (..) begin .. end block.
2313 \\[verilog-sk-specify] Insert a specify .. endspecify block.
2314 \\[verilog-sk-task] Insert a task .. begin .. end endtask block.
2315 \\[verilog-sk-while] Insert a while (...) begin .. end block, prompting for details.
2316 \\[verilog-sk-casex] Insert a casex (...) item: begin.. end endcase block, prompting for details.
2317 \\[verilog-sk-casez] Insert a casez (...) item: begin.. end endcase block, prompting for details.
2318 \\[verilog-sk-if] Insert an if (..) begin .. end block.
2319 \\[verilog-sk-else-if] Insert an else if (..) begin .. end block.
2320 \\[verilog-sk-comment] Insert a comment block.
2321 \\[verilog-sk-assign] Insert an assign .. = ..; statement.
2322 \\[verilog-sk-function] Insert a function .. begin .. end endfunction block.
2323 \\[verilog-sk-input] Insert an input declaration, prompting for details.
2324 \\[verilog-sk-output] Insert an output declaration, prompting for details.
2325 \\[verilog-sk-state-machine] Insert a state machine definition, prompting for details.
2326 \\[verilog-sk-inout] Insert an inout declaration, prompting for details.
2327 \\[verilog-sk-wire] Insert a wire declaration, prompting for details.
2328 \\[verilog-sk-reg] Insert a register declaration, prompting for details.
2329 \\[verilog-sk-define-signal] Define signal under point as a register at the top of the module.
2330
2331 All key bindings can be seen in a Verilog-buffer with \\[describe-bindings].
2332 Key bindings specific to `verilog-mode-map' are:
2333
2334 \\{verilog-mode-map}"
2335 (interactive)
2336 (kill-all-local-variables)
2337 (use-local-map verilog-mode-map)
2338 (setq major-mode 'verilog-mode)
2339 (setq mode-name "Verilog")
2340 (setq local-abbrev-table verilog-mode-abbrev-table)
2341 (set (make-local-variable 'beginning-of-defun-function)
2342 'verilog-beg-of-defun)
2343 (set (make-local-variable 'end-of-defun-function)
2344 'verilog-end-of-defun)
2345 (set-syntax-table verilog-mode-syntax-table)
2346 (make-local-variable 'indent-line-function)
2347 (setq indent-line-function 'verilog-indent-line-relative)
2348 (setq comment-indent-function 'verilog-comment-indent)
2349 (make-local-variable 'parse-sexp-ignore-comments)
2350 (setq parse-sexp-ignore-comments nil)
2351 (make-local-variable 'comment-start)
2352 (make-local-variable 'comment-end)
2353 (make-local-variable 'comment-multi-line)
2354 (make-local-variable 'comment-start-skip)
2355 (setq comment-start "// "
2356 comment-end ""
2357 comment-start-skip "/\\*+ *\\|// *"
2358 comment-multi-line nil)
2359 ;; Set up for compilation
2360 (setq verilog-which-tool 1)
2361 (setq verilog-tool 'verilog-linter)
2362 (verilog-set-compile-command)
2363 (when (boundp 'hack-local-variables-hook) ;; Also modify any file-local-variables
2364 (add-hook 'hack-local-variables-hook 'verilog-modify-compile-command t))
2365
2366 ;; Setting up menus
2367 (when (featurep 'xemacs)
2368 (easy-menu-add verilog-stmt-menu)
2369 (easy-menu-add verilog-menu)
2370 (setq mode-popup-menu (cons "Verilog Mode" verilog-stmt-menu)))
2371
2372 ;; Stuff for GNU emacs
2373 (set (make-local-variable 'font-lock-defaults)
2374 '((verilog-font-lock-keywords verilog-font-lock-keywords-1
2375 verilog-font-lock-keywords-2
2376 verilog-font-lock-keywords-3)
2377 nil nil nil verilog-beg-of-defun))
2378 ;;------------------------------------------------------------
2379 ;; now hook in 'verilog-colorize-include-files (eldo-mode.el&spice-mode.el)
2380 ;; all buffer local:
2381 (when (featurep 'xemacs)
2382 (make-local-hook 'font-lock-mode-hook)
2383 (make-local-hook 'font-lock-after-fontify-buffer-hook); doesn't exist in emacs 20
2384 (make-local-hook 'after-change-functions))
2385 (add-hook 'font-lock-mode-hook 'verilog-colorize-include-files-buffer t t)
2386 (add-hook 'font-lock-after-fontify-buffer-hook 'verilog-colorize-include-files-buffer t t) ; not in emacs 20
2387 (add-hook 'after-change-functions 'verilog-colorize-include-files t t)
2388
2389 ;; Tell imenu how to handle Verilog.
2390 (make-local-variable 'imenu-generic-expression)
2391 (setq imenu-generic-expression verilog-imenu-generic-expression)
2392 ;; hideshow support
2393 (unless (assq 'verilog-mode hs-special-modes-alist)
2394 (setq hs-special-modes-alist
2395 (cons '(verilog-mode-mode "\\<begin\\>" "\\<end\\>" nil
2396 verilog-forward-sexp-function)
2397 hs-special-modes-alist)))
2398
2399 ;; Stuff for autos
2400 (add-hook 'write-contents-hooks 'verilog-auto-save-check) ; already local
2401 ;; (verilog-auto-reeval-locals t) ; Save locals in case user changes them
2402 ;; (verilog-getopt-flags)
2403 (run-hooks 'verilog-mode-hook))
2404 \f
2405
2406 ;;
2407 ;; Electric functions
2408 ;;
2409 (defun electric-verilog-terminate-line (&optional arg)
2410 "Terminate line and indent next line.
2411 With optional ARG, remove existing end of line comments."
2412 (interactive)
2413 ;; before that see if we are in a comment
2414 (let ((state
2415 (save-excursion
2416 (parse-partial-sexp (point-min) (point)))))
2417 (cond
2418 ((nth 7 state) ; Inside // comment
2419 (if (eolp)
2420 (progn
2421 (delete-horizontal-space)
2422 (newline))
2423 (progn
2424 (newline)
2425 (insert "// ")
2426 (beginning-of-line)))
2427 (verilog-indent-line))
2428 ((nth 4 state) ; Inside any comment (hence /**/)
2429 (newline)
2430 (verilog-more-comment))
2431 ((eolp)
2432 ;; First, check if current line should be indented
2433 (if (save-excursion
2434 (delete-horizontal-space)
2435 (beginning-of-line)
2436 (skip-chars-forward " \t")
2437 (if (looking-at verilog-auto-end-comment-lines-re)
2438 (let ((indent-str (verilog-indent-line)))
2439 ;; Maybe we should set some endcomments
2440 (if verilog-auto-endcomments
2441 (verilog-set-auto-endcomments indent-str arg))
2442 (end-of-line)
2443 (delete-horizontal-space)
2444 (if arg
2445 ()
2446 (newline))
2447 nil)
2448 (progn
2449 (end-of-line)
2450 (delete-horizontal-space)
2451 't)))
2452 ;; see if we should line up assignments
2453 (progn
2454 (if (or (memq 'all verilog-auto-lineup)
2455 (memq 'assignments verilog-auto-lineup))
2456 (verilog-pretty-expr))
2457 (newline))
2458 (forward-line 1))
2459 ;; Indent next line
2460 (if verilog-auto-indent-on-newline
2461 (verilog-indent-line)))
2462 (t
2463 (newline)))))
2464
2465 (defun electric-verilog-terminate-and-indent ()
2466 "Insert a newline and indent for the next statement."
2467 (interactive)
2468 (electric-verilog-terminate-line 1))
2469
2470 (defun electric-verilog-semi ()
2471 "Insert `;' character and reindent the line."
2472 (interactive)
2473 (insert last-command-char)
2474
2475 (if (or (verilog-in-comment-or-string-p)
2476 (verilog-in-escaped-name-p))
2477 ()
2478 (save-excursion
2479 (beginning-of-line)
2480 (verilog-forward-ws&directives)
2481 (verilog-indent-line))
2482 (if (and verilog-auto-newline
2483 (not (verilog-parenthesis-depth)))
2484 (electric-verilog-terminate-line))))
2485
2486 (defun electric-verilog-semi-with-comment ()
2487 "Insert `;' character, reindent the line and indent for comment."
2488 (interactive)
2489 (insert "\;")
2490 (save-excursion
2491 (beginning-of-line)
2492 (verilog-indent-line))
2493 (indent-for-comment))
2494
2495 (defun electric-verilog-colon ()
2496 "Insert `:' and do all indentations except line indent on this line."
2497 (interactive)
2498 (insert last-command-char)
2499 ;; Do nothing if within string.
2500 (if (or
2501 (verilog-within-string)
2502 (not (verilog-in-case-region-p)))
2503 ()
2504 (save-excursion
2505 (let ((p (point))
2506 (lim (progn (verilog-beg-of-statement) (point))))
2507 (goto-char p)
2508 (verilog-backward-case-item lim)
2509 (verilog-indent-line)))
2510 ;; (let ((verilog-tab-always-indent nil))
2511 ;; (verilog-indent-line))
2512 ))
2513
2514 ;;(defun electric-verilog-equal ()
2515 ;; "Insert `=', and do indentation if within block."
2516 ;; (interactive)
2517 ;; (insert last-command-char)
2518 ;; Could auto line up expressions, but not yet
2519 ;; (if (eq (car (verilog-calculate-indent)) 'block)
2520 ;; (let ((verilog-tab-always-indent nil))
2521 ;; (verilog-indent-command)))
2522 ;; )
2523
2524 (defun electric-verilog-tick ()
2525 "Insert back-tick, and indent to column 0 if this is a CPP directive."
2526 (interactive)
2527 (insert last-command-char)
2528 (save-excursion
2529 (if (progn
2530 (beginning-of-line)
2531 (looking-at verilog-directive-re-1))
2532 (verilog-indent-line))))
2533
2534 (defun electric-verilog-tab ()
2535 "Function called when TAB is pressed in Verilog mode."
2536 (interactive)
2537 ;; If verilog-tab-always-indent, indent the beginning of the line.
2538 (if (or verilog-tab-always-indent
2539 (save-excursion
2540 (skip-chars-backward " \t")
2541 (bolp)))
2542 (let* ((oldpnt (point))
2543 (boi-point
2544 (save-excursion
2545 (beginning-of-line)
2546 (skip-chars-forward " \t")
2547 (verilog-indent-line)
2548 (back-to-indentation)
2549 (point))))
2550 (if (< (point) boi-point)
2551 (back-to-indentation)
2552 (cond ((not verilog-tab-to-comment))
2553 ((not (eolp))
2554 (end-of-line))
2555 (t
2556 (indent-for-comment)
2557 (when (and (eolp) (= oldpnt (point)))
2558 ; kill existing comment
2559 (beginning-of-line)
2560 (re-search-forward comment-start-skip oldpnt 'move)
2561 (goto-char (match-beginning 0))
2562 (skip-chars-backward " \t")
2563 (kill-region (point) oldpnt))))))
2564 (progn (insert "\t"))))
2565
2566 \f
2567
2568 ;;
2569 ;; Interactive functions
2570 ;;
2571
2572 (defun verilog-indent-buffer ()
2573 "Indent-region the entire buffer as Verilog code.
2574 To call this from the command line, see \\[verilog-batch-indent]."
2575 (interactive)
2576 (verilog-mode)
2577 (indent-region (point-min) (point-max) nil))
2578
2579 (defun verilog-insert-block ()
2580 "Insert Verilog begin ... end; block in the code with right indentation."
2581 (interactive)
2582 (verilog-indent-line)
2583 (insert "begin")
2584 (electric-verilog-terminate-line)
2585 (save-excursion
2586 (electric-verilog-terminate-line)
2587 (insert "end")
2588 (beginning-of-line)
2589 (verilog-indent-line)))
2590
2591 (defun verilog-star-comment ()
2592 "Insert Verilog star comment at point."
2593 (interactive)
2594 (verilog-indent-line)
2595 (insert "/*")
2596 (save-excursion
2597 (newline)
2598 (insert " */"))
2599 (newline)
2600 (insert " * "))
2601
2602 (defun verilog-insert-1 (fmt max)
2603 "Use format string FMT to insert integers 0 to MAX - 1.
2604 Inserts one integer per line, at the current column. Stops early
2605 if it reaches the end of the buffer."
2606 (let ((col (current-column))
2607 (n 0))
2608 (save-excursion
2609 (while (< n max)
2610 (insert (format fmt n))
2611 (forward-line 1)
2612 ;; Note that this function does not bother to check for lines
2613 ;; shorter than col.
2614 (if (eobp)
2615 (setq n max)
2616 (setq n (1+ n))
2617 (move-to-column col))))))
2618
2619 (defun verilog-insert-indices (max)
2620 "Insert a set of indices into a rectangle.
2621 The upper left corner is defined by point. Indices begin with 0
2622 and extend to the MAX - 1. If no prefix arg is given, the user
2623 is prompted for a value. The indices are surrounded by square
2624 brackets \[]. For example, the following code with the point
2625 located after the first 'a' gives:
2626
2627 a = b a[ 0] = b
2628 a = b a[ 1] = b
2629 a = b a[ 2] = b
2630 a = b a[ 3] = b
2631 a = b ==> insert-indices ==> a[ 4] = b
2632 a = b a[ 5] = b
2633 a = b a[ 6] = b
2634 a = b a[ 7] = b
2635 a = b a[ 8] = b"
2636
2637 (interactive "NMAX: ")
2638 (verilog-insert-1 "[%3d]" max))
2639
2640 (defun verilog-generate-numbers (max)
2641 "Insert a set of generated numbers into a rectangle.
2642 The upper left corner is defined by point. The numbers are padded to three
2643 digits, starting with 000 and extending to (MAX - 1). If no prefix argument
2644 is supplied, then the user is prompted for the MAX number. Consider the
2645 following code fragment:
2646
2647 buf buf buf buf000
2648 buf buf buf buf001
2649 buf buf buf buf002
2650 buf buf buf buf003
2651 buf buf ==> generate-numbers ==> buf buf004
2652 buf buf buf buf005
2653 buf buf buf buf006
2654 buf buf buf buf007
2655 buf buf buf buf008"
2656
2657 (interactive "NMAX: ")
2658 (verilog-insert-1 "%3.3d" max))
2659
2660 (defun verilog-mark-defun ()
2661 "Mark the current Verilog function (or procedure).
2662 This puts the mark at the end, and point at the beginning."
2663 (interactive)
2664 (if (featurep 'xemacs)
2665 (progn
2666 (push-mark (point))
2667 (verilog-end-of-defun)
2668 (push-mark (point))
2669 (verilog-beg-of-defun)
2670 (if (fboundp 'zmacs-activate-region)
2671 (zmacs-activate-region)))
2672 (mark-defun)))
2673
2674 (defun verilog-comment-region (start end)
2675 ; checkdoc-params: (start end)
2676 "Put the region into a Verilog comment.
2677 The comments that are in this area are \"deformed\":
2678 `*)' becomes `!(*' and `}' becomes `!{'.
2679 These deformed comments are returned to normal if you use
2680 \\[verilog-uncomment-region] to undo the commenting.
2681
2682 The commented area starts with `verilog-exclude-str-start', and ends with
2683 `verilog-exclude-str-end'. But if you change these variables,
2684 \\[verilog-uncomment-region] won't recognize the comments."
2685 (interactive "r")
2686 (save-excursion
2687 ;; Insert start and endcomments
2688 (goto-char end)
2689 (if (and (save-excursion (skip-chars-forward " \t") (eolp))
2690 (not (save-excursion (skip-chars-backward " \t") (bolp))))
2691 (forward-line 1)
2692 (beginning-of-line))
2693 (insert verilog-exclude-str-end)
2694 (setq end (point))
2695 (newline)
2696 (goto-char start)
2697 (beginning-of-line)
2698 (insert verilog-exclude-str-start)
2699 (newline)
2700 ;; Replace end-comments within commented area
2701 (goto-char end)
2702 (save-excursion
2703 (while (re-search-backward "\\*/" start t)
2704 (replace-match "*-/" t t)))
2705 (save-excursion
2706 (let ((s+1 (1+ start)))
2707 (while (re-search-backward "/\\*" s+1 t)
2708 (replace-match "/-*" t t))))))
2709
2710 (defun verilog-uncomment-region ()
2711 "Uncomment a commented area; change deformed comments back to normal.
2712 This command does nothing if the pointer is not in a commented
2713 area. See also `verilog-comment-region'."
2714 (interactive)
2715 (save-excursion
2716 (let ((start (point))
2717 (end (point)))
2718 ;; Find the boundaries of the comment
2719 (save-excursion
2720 (setq start (progn (search-backward verilog-exclude-str-start nil t)
2721 (point)))
2722 (setq end (progn (search-forward verilog-exclude-str-end nil t)
2723 (point))))
2724 ;; Check if we're really inside a comment
2725 (if (or (equal start (point)) (<= end (point)))
2726 (message "Not standing within commented area.")
2727 (progn
2728 ;; Remove endcomment
2729 (goto-char end)
2730 (beginning-of-line)
2731 (let ((pos (point)))
2732 (end-of-line)
2733 (delete-region pos (1+ (point))))
2734 ;; Change comments back to normal
2735 (save-excursion
2736 (while (re-search-backward "\\*-/" start t)
2737 (replace-match "*/" t t)))
2738 (save-excursion
2739 (while (re-search-backward "/-\\*" start t)
2740 (replace-match "/*" t t)))
2741 ;; Remove start comment
2742 (goto-char start)
2743 (beginning-of-line)
2744 (let ((pos (point)))
2745 (end-of-line)
2746 (delete-region pos (1+ (point)))))))))
2747
2748 (defun verilog-beg-of-defun ()
2749 "Move backward to the beginning of the current function or procedure."
2750 (interactive)
2751 (verilog-re-search-backward verilog-defun-re nil 'move))
2752
2753 (defun verilog-end-of-defun ()
2754 "Move forward to the end of the current function or procedure."
2755 (interactive)
2756 (verilog-re-search-forward verilog-end-defun-re nil 'move))
2757
2758 (defun verilog-get-beg-of-defun (&optional warn)
2759 (save-excursion
2760 (cond ((verilog-re-search-forward-quick verilog-defun-re nil t)
2761 (point))
2762 (t
2763 (error "%s: Can't find module beginning" (verilog-point-text))
2764 (point-max)))))
2765 (defun verilog-get-end-of-defun (&optional warn)
2766 (save-excursion
2767 (cond ((verilog-re-search-forward-quick verilog-end-defun-re nil t)
2768 (point))
2769 (t
2770 (error "%s: Can't find endmodule" (verilog-point-text))
2771 (point-max)))))
2772
2773 (defun verilog-label-be (&optional arg)
2774 "Label matching begin ... end, fork ... join and case ... endcase statements.
2775 With ARG, first kill any existing labels."
2776 (interactive)
2777 (let ((cnt 0)
2778 (oldpos (point))
2779 (b (progn
2780 (verilog-beg-of-defun)
2781 (point-marker)))
2782 (e (progn
2783 (verilog-end-of-defun)
2784 (point-marker))))
2785 (goto-char (marker-position b))
2786 (if (> (- e b) 200)
2787 (message "Relabeling module..."))
2788 (while (and
2789 (> (marker-position e) (point))
2790 (verilog-re-search-forward
2791 (concat
2792 "\\<end\\(\\(function\\)\\|\\(task\\)\\|\\(module\\)\\|\\(primitive\\)\\|\\(interface\\)\\|\\(package\\)\\|\\(case\\)\\)?\\>"
2793 "\\|\\(`endif\\)\\|\\(`else\\)")
2794 nil 'move))
2795 (goto-char (match-beginning 0))
2796 (let ((indent-str (verilog-indent-line)))
2797 (verilog-set-auto-endcomments indent-str 't)
2798 (end-of-line)
2799 (delete-horizontal-space))
2800 (setq cnt (1+ cnt))
2801 (if (= 9 (% cnt 10))
2802 (message "%d..." cnt)))
2803 (goto-char oldpos)
2804 (if (or
2805 (> (- e b) 200)
2806 (> cnt 20))
2807 (message "%d lines auto commented" cnt))))
2808
2809 (defun verilog-beg-of-statement ()
2810 "Move backward to beginning of statement."
2811 (interactive)
2812 ;; Move back token by token until we see the end
2813 ;; of some ealier line.
2814 (while
2815 ;; If the current point does not begin a new
2816 ;; statement, as in the character ahead of us is a ';', or SOF
2817 ;; or the string after us unambiguosly starts a statement,
2818 ;; or the token before us unambiguously ends a statement,
2819 ;; then move back a token and test again.
2820 (not (or
2821 (bolp)
2822 (= (preceding-char) ?\;)
2823 (not (or
2824 (looking-at "\\<")
2825 (forward-word -1)))
2826 (and
2827 (looking-at verilog-extended-complete-re)
2828 (not (save-excursion
2829 (verilog-backward-token)
2830 (looking-at verilog-extended-complete-re))))
2831 (looking-at verilog-basic-complete-re)
2832 (save-excursion
2833 (verilog-backward-token)
2834 (or
2835 (looking-at verilog-end-block-re)
2836 (looking-at verilog-preprocessor-re)))))
2837 (verilog-backward-syntactic-ws)
2838 (verilog-backward-token))
2839 ;; Now point is where the previous line ended.
2840 (verilog-forward-syntactic-ws))
2841
2842 (defun verilog-beg-of-statement-1 ()
2843 "Move backward to beginning of statement."
2844 (interactive)
2845 (let ((pt (point)))
2846
2847 (while (and (not (looking-at verilog-complete-reg))
2848 (setq pt (point))
2849 (verilog-backward-token)
2850 (not (looking-at verilog-complete-reg))
2851 (verilog-backward-syntactic-ws)
2852 (setq pt (point))
2853 (not (bolp))
2854 (not (= (preceding-char) ?\;))))
2855 (goto-char pt)
2856 (verilog-forward-ws&directives)))
2857
2858 (defun verilog-end-of-statement ()
2859 "Move forward to end of current statement."
2860 (interactive)
2861 (let ((nest 0) pos)
2862 (or (looking-at verilog-beg-block-re)
2863 ;; Skip to end of statement
2864 (setq pos (catch 'found
2865 (while t
2866 (forward-sexp 1)
2867 (verilog-skip-forward-comment-or-string)
2868 (cond ((looking-at "[ \t]*;")
2869 (skip-chars-forward "^;")
2870 (forward-char 1)
2871 (throw 'found (point)))
2872 ((save-excursion
2873 (forward-sexp -1)
2874 (looking-at verilog-beg-block-re))
2875 (goto-char (match-beginning 0))
2876 (throw 'found nil))
2877 ((looking-at "[ \t]*)")
2878 (throw 'found (point)))
2879 ((eobp)
2880 (throw 'found (point))))))))
2881 (if (not pos)
2882 ;; Skip a whole block
2883 (catch 'found
2884 (while t
2885 (verilog-re-search-forward verilog-end-statement-re nil 'move)
2886 (setq nest (if (match-end 1)
2887 (1+ nest)
2888 (1- nest)))
2889 (cond ((eobp)
2890 (throw 'found (point)))
2891 ((= 0 nest)
2892 (throw 'found (verilog-end-of-statement))))))
2893 pos)))
2894
2895 (defun verilog-in-case-region-p ()
2896 "Return true if in a case region.
2897 More specifically, point @ in the line foo : @ begin"
2898 (interactive)
2899 (save-excursion
2900 (if (and
2901 (progn (verilog-forward-syntactic-ws)
2902 (looking-at "\\<begin\\>"))
2903 (progn (verilog-backward-syntactic-ws)
2904 (= (preceding-char) ?\:)))
2905 (catch 'found
2906 (let ((nest 1))
2907 (while t
2908 (verilog-re-search-backward
2909 (concat "\\(\\<module\\>\\)\\|\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|"
2910 "\\(\\<endcase\\>\\)\\>")
2911 nil 'move)
2912 (cond
2913 ((match-end 3)
2914 (setq nest (1+ nest)))
2915 ((match-end 2)
2916 (if (= nest 1)
2917 (throw 'found 1))
2918 (setq nest (1- nest)))
2919 (t
2920 (throw 'found (= nest 0)))))))
2921 nil)))
2922 (defun verilog-in-struct-region-p ()
2923 "Return true if in a struct region.
2924 More specifically, in a list after a struct|union keyword."
2925 (interactive)
2926 (save-excursion
2927 (let* ((state (parse-partial-sexp (point-min) (point)))
2928 (depth (nth 0 state)))
2929 (if depth
2930 (progn (backward-up-list depth)
2931 (verilog-beg-of-statement)
2932 (looking-at "\\<typedef\\>?\\s-*\\<struct\\|union\\>"))))))
2933
2934 (defun verilog-in-generate-region-p ()
2935 "Return true if in a generate region.
2936 More specifically, after a generate and before an endgenerate."
2937 (interactive)
2938 (let ((lim (save-excursion (verilog-beg-of-defun) (point)))
2939 (nest 1))
2940 (save-excursion
2941 (while (and
2942 (/= nest 0)
2943 (verilog-re-search-backward "\\<\\(generate\\)\\|\\(endgenerate\\)\\>" lim 'move)
2944 (cond
2945 ((match-end 1) ; generate
2946 (setq nest (1- nest)))
2947 ((match-end 2) ; endgenerate
2948 (setq nest (1+ nest)))))))
2949 (= nest 0) )) ; return nest
2950
2951 (defun verilog-in-fork-region-p ()
2952 "Return true if between a fork and join."
2953 (interactive)
2954 (let ((lim (save-excursion (verilog-beg-of-defun) (point)))
2955 (nest 1))
2956 (save-excursion
2957 (while (and
2958 (/= nest 0)
2959 (verilog-re-search-backward "\\<\\(fork\\)\\|\\(join\\(_any\\|_none\\)?\\)\\>" lim 'move)
2960 (cond
2961 ((match-end 1) ; fork
2962 (setq nest (1- nest)))
2963 ((match-end 2) ; join
2964 (setq nest (1+ nest)))))))
2965 (= nest 0) )) ; return nest
2966
2967 (defun verilog-backward-case-item (lim)
2968 "Skip backward to nearest enclosing case item.
2969 Limit search to point LIM."
2970 (interactive)
2971 (let ((str 'nil)
2972 (lim1
2973 (progn
2974 (save-excursion
2975 (verilog-re-search-backward verilog-endcomment-reason-re
2976 lim 'move)
2977 (point)))))
2978 ;; Try to find the real :
2979 (if (save-excursion (search-backward ":" lim1 t))
2980 (let ((colon 0)
2981 b e )
2982 (while
2983 (and
2984 (< colon 1)
2985 (verilog-re-search-backward "\\(\\[\\)\\|\\(\\]\\)\\|\\(:\\)"
2986 lim1 'move))
2987 (cond
2988 ((match-end 1) ;; [
2989 (setq colon (1+ colon))
2990 (if (>= colon 0)
2991 (error "%s: unbalanced [" (verilog-point-text))))
2992 ((match-end 2) ;; ]
2993 (setq colon (1- colon)))
2994
2995 ((match-end 3) ;; :
2996 (setq colon (1+ colon)))))
2997 ;; Skip back to beginning of case item
2998 (skip-chars-backward "\t ")
2999 (verilog-skip-backward-comment-or-string)
3000 (setq e (point))
3001 (setq b
3002 (progn
3003 (if
3004 (verilog-re-search-backward
3005 "\\<\\(case[zx]?\\)\\>\\|;\\|\\<end\\>" nil 'move)
3006 (progn
3007 (cond
3008 ((match-end 1)
3009 (goto-char (match-end 1))
3010 (verilog-forward-ws&directives)
3011 (if (looking-at "(")
3012 (progn
3013 (forward-sexp)
3014 (verilog-forward-ws&directives)))
3015 (point))
3016 (t
3017 (goto-char (match-end 0))
3018 (verilog-forward-ws&directives)
3019 (point))))
3020 (error "Malformed case item"))))
3021 (setq str (buffer-substring b e))
3022 (if
3023 (setq e
3024 (string-match
3025 "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
3026 (setq str (concat (substring str 0 e) "...")))
3027 str)
3028 'nil)))
3029 \f
3030
3031 ;;
3032 ;; Other functions
3033 ;;
3034
3035 (defun verilog-kill-existing-comment ()
3036 "Kill auto comment on this line."
3037 (save-excursion
3038 (let* (
3039 (e (progn
3040 (end-of-line)
3041 (point)))
3042 (b (progn
3043 (beginning-of-line)
3044 (search-forward "//" e t))))
3045 (if b
3046 (delete-region (- b 2) e)))))
3047
3048 (defconst verilog-directive-nest-re
3049 (concat "\\(`else\\>\\)\\|"
3050 "\\(`endif\\>\\)\\|"
3051 "\\(`if\\>\\)\\|"
3052 "\\(`ifdef\\>\\)\\|"
3053 "\\(`ifndef\\>\\)"))
3054 (defun verilog-set-auto-endcomments (indent-str kill-existing-comment)
3055 "Add ending comment with given INDENT-STR.
3056 With KILL-EXISTING-COMMENT, remove what was there before.
3057 Insert `// case: 7 ' or `// NAME ' on this line if appropriate.
3058 Insert `// case expr ' if this line ends a case block.
3059 Insert `// ifdef FOO ' if this line ends code conditional on FOO.
3060 Insert `// NAME ' if this line ends a function, task, module,
3061 primitive or interface named NAME."
3062 (save-excursion
3063 (cond
3064 (; Comment close preprocessor directives
3065 (and
3066 (looking-at "\\(`endif\\)\\|\\(`else\\)")
3067 (or kill-existing-comment
3068 (not (save-excursion
3069 (end-of-line)
3070 (search-backward "//" (verilog-get-beg-of-line) t)))))
3071 (let ((nest 1) b e
3072 m
3073 (else (if (match-end 2) "!" " ")))
3074 (end-of-line)
3075 (if kill-existing-comment
3076 (verilog-kill-existing-comment))
3077 (delete-horizontal-space)
3078 (save-excursion
3079 (backward-sexp 1)
3080 (while (and (/= nest 0)
3081 (verilog-re-search-backward verilog-directive-nest-re nil 'move))
3082 (cond
3083 ((match-end 1) ; `else
3084 (if (= nest 1)
3085 (setq else "!")))
3086 ((match-end 2) ; `endif
3087 (setq nest (1+ nest)))
3088 ((match-end 3) ; `if
3089 (setq nest (1- nest)))
3090 ((match-end 4) ; `ifdef
3091 (setq nest (1- nest)))
3092 ((match-end 5) ; `ifndef
3093 (setq nest (1- nest)))))
3094 (if (match-end 0)
3095 (setq
3096 m (buffer-substring
3097 (match-beginning 0)
3098 (match-end 0))
3099 b (progn
3100 (skip-chars-forward "^ \t")
3101 (verilog-forward-syntactic-ws)
3102 (point))
3103 e (progn
3104 (skip-chars-forward "a-zA-Z0-9_")
3105 (point)))))
3106 (if b
3107 (if (> (count-lines (point) b) verilog-minimum-comment-distance)
3108 (insert (concat " // " else m " " (buffer-substring b e))))
3109 (progn
3110 (insert " // unmatched `else or `endif")
3111 (ding 't)))))
3112
3113 (; Comment close case/class/function/task/module and named block
3114 (and (looking-at "\\<end")
3115 (or kill-existing-comment
3116 (not (save-excursion
3117 (end-of-line)
3118 (search-backward "//" (verilog-get-beg-of-line) t)))))
3119 (let ((type (car indent-str)))
3120 (unless (eq type 'declaration)
3121 (unless (looking-at (concat "\\(" verilog-end-block-ordered-re "\\)[ \t]*:")) ;; ignore named ends
3122 (if (looking-at verilog-end-block-ordered-re)
3123 (cond
3124 (;- This is a case block; search back for the start of this case
3125 (match-end 1) ;; of verilog-end-block-ordered-re
3126
3127 (let ((err 't)
3128 (str "UNMATCHED!!"))
3129 (save-excursion
3130 (verilog-leap-to-head)
3131 (cond
3132 ((looking-at "\\<randcase\\>")
3133 (setq str "randcase")
3134 (setq err nil))
3135 ((match-end 0)
3136 (goto-char (match-end 1))
3137 (if nil
3138 (let (s f)
3139 (setq s (match-beginning 1))
3140 (setq f (progn (end-of-line)
3141 (point)))
3142 (setq str (buffer-substring s f)))
3143 (setq err nil))
3144 (setq str (concat (buffer-substring (match-beginning 1) (match-end 1))
3145 " "
3146 (verilog-get-expr))))))
3147 (end-of-line)
3148 (if kill-existing-comment
3149 (verilog-kill-existing-comment))
3150 (delete-horizontal-space)
3151 (insert (concat " // " str ))
3152 (if err (ding 't))))
3153
3154 (;- This is a begin..end block
3155 (match-end 2) ;; of verilog-end-block-ordered-re
3156 (let ((str " // UNMATCHED !!")
3157 (err 't)
3158 (here (point))
3159 there
3160 cntx)
3161 (save-excursion
3162 (verilog-leap-to-head)
3163 (setq there (point))
3164 (if (not (match-end 0))
3165 (progn
3166 (goto-char here)
3167 (end-of-line)
3168 (if kill-existing-comment
3169 (verilog-kill-existing-comment))
3170 (delete-horizontal-space)
3171 (insert str)
3172 (ding 't))
3173 (let ((lim
3174 (save-excursion (verilog-beg-of-defun) (point)))
3175 (here (point)))
3176 (cond
3177 (;-- handle named block differently
3178 (looking-at verilog-named-block-re)
3179 (search-forward ":")
3180 (setq there (point))
3181 (setq str (verilog-get-expr))
3182 (setq err nil)
3183 (setq str (concat " // block: " str )))
3184
3185 ((verilog-in-case-region-p) ;-- handle case item differently
3186 (goto-char here)
3187 (setq str (verilog-backward-case-item lim))
3188 (setq there (point))
3189 (setq err nil)
3190 (setq str (concat " // case: " str )))
3191
3192 (;- try to find "reason" for this begin
3193 (cond
3194 (;
3195 (eq here (progn
3196 (verilog-backward-token)
3197 (verilog-beg-of-statement-1)
3198 (point)))
3199 (setq err nil)
3200 (setq str ""))
3201 ((looking-at verilog-endcomment-reason-re)
3202 (setq there (match-end 0))
3203 (setq cntx (concat
3204 (buffer-substring (match-beginning 0) (match-end 0)) " "))
3205 (cond
3206 (;- begin
3207 (match-end 2)
3208 (setq err nil)
3209 (save-excursion
3210 (if (and (verilog-continued-line)
3211 (looking-at "\\<repeat\\>\\|\\<wait\\>\\|\\<always\\>"))
3212 (progn
3213 (goto-char (match-end 0))
3214 (setq there (point))
3215 (setq str
3216 (concat " // "
3217 (buffer-substring (match-beginning 0) (match-end 0)) " "
3218 (verilog-get-expr))))
3219 (setq str ""))))
3220
3221 (;- else
3222 (match-end 4)
3223 (let ((nest 0)
3224 ( reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)"))
3225 (catch 'skip
3226 (while (verilog-re-search-backward reg nil 'move)
3227 (cond
3228 ((match-end 1) ; begin
3229 (setq nest (1- nest)))
3230 ((match-end 2) ; end
3231 (setq nest (1+ nest)))
3232 ((match-end 3)
3233 (if (= 0 nest)
3234 (progn
3235 (goto-char (match-end 0))
3236 (setq there (point))
3237 (setq err nil)
3238 (setq str (verilog-get-expr))
3239 (setq str (concat " // else: !if" str ))
3240 (throw 'skip 1)))))))))
3241
3242 (;- end else
3243 (match-end 5)
3244 (goto-char there)
3245 (let ((nest 0)
3246 (reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)"))
3247 (catch 'skip
3248 (while (verilog-re-search-backward reg nil 'move)
3249 (cond
3250 ((match-end 1) ; begin
3251 (setq nest (1- nest)))
3252 ((match-end 2) ; end
3253 (setq nest (1+ nest)))
3254 ((match-end 3)
3255 (if (= 0 nest)
3256 (progn
3257 (goto-char (match-end 0))
3258 (setq there (point))
3259 (setq err nil)
3260 (setq str (verilog-get-expr))
3261 (setq str (concat " // else: !if" str ))
3262 (throw 'skip 1)))))))))
3263
3264 (;- task/function/initial et cetera
3265 t
3266 (match-end 0)
3267 (goto-char (match-end 0))
3268 (setq there (point))
3269 (setq err nil)
3270 (setq str (verilog-get-expr))
3271 (setq str (concat " // " cntx str )))
3272
3273 (;-- otherwise...
3274 (setq str " // auto-endcomment confused "))))
3275
3276 ((and
3277 (verilog-in-case-region-p) ;-- handle case item differently
3278 (progn
3279 (setq there (point))
3280 (goto-char here)
3281 (setq str (verilog-backward-case-item lim))))
3282 (setq err nil)
3283 (setq str (concat " // case: " str )))
3284
3285 ((verilog-in-fork-region-p)
3286 (setq err nil)
3287 (setq str " // fork branch" ))
3288
3289 ((looking-at "\\<end\\>")
3290 ;; HERE
3291 (forward-word 1)
3292 (verilog-forward-syntactic-ws)
3293 (setq err nil)
3294 (setq str (verilog-get-expr))
3295 (setq str (concat " // " cntx str )))
3296
3297 ))))
3298 (goto-char here)
3299 (end-of-line)
3300 (if kill-existing-comment
3301 (verilog-kill-existing-comment))
3302 (delete-horizontal-space)
3303 (if (or err
3304 (> (count-lines here there) verilog-minimum-comment-distance))
3305 (insert str))
3306 (if err (ding 't))
3307 ))))
3308 (;- this is endclass, which can be nested
3309 (match-end 11) ;; of verilog-end-block-ordered-re
3310 ;;(goto-char there)
3311 (let ((nest 0)
3312 (reg "\\<\\(class\\)\\|\\(endclass\\)\\|\\(package\\|primitive\\|\\(macro\\)?module\\)\\>")
3313 string)
3314 (save-excursion
3315 (catch 'skip
3316 (while (verilog-re-search-backward reg nil 'move)
3317 (cond
3318 ((match-end 3) ; endclass
3319 (ding 't)
3320 (setq string "unmatched endclass")
3321 (throw 'skip 1))
3322
3323 ((match-end 2) ; endclass
3324 (setq nest (1+ nest)))
3325
3326 ((match-end 1) ; class
3327 (setq nest (1- nest))
3328 (if (< nest 0)
3329 (progn
3330 (goto-char (match-end 0))
3331 (let (b e)
3332 (setq b (progn
3333 (skip-chars-forward "^ \t")
3334 (verilog-forward-ws&directives)
3335 (point))
3336 e (progn
3337 (skip-chars-forward "a-zA-Z0-9_")
3338 (point)))
3339 (setq string (buffer-substring b e)))
3340 (throw 'skip 1))))
3341 ))))
3342 (end-of-line)
3343 (insert (concat " // " string ))))
3344
3345 (;- this is end{function,generate,task,module,primitive,table,generate}
3346 ;- which can not be nested.
3347 t
3348 (let (string reg (width nil))
3349 (end-of-line)
3350 (if kill-existing-comment
3351 (save-match-data
3352 (verilog-kill-existing-comment)))
3353 (delete-horizontal-space)
3354 (backward-sexp)
3355 (cond
3356 ((match-end 5) ;; of verilog-end-block-ordered-re
3357 (setq reg "\\(\\<function\\>\\)\\|\\(\\<\\(endfunction\\|task\\|\\(macro\\)?module\\|primitive\\)\\>\\)")
3358 (setq width "\\(\\s-*\\(\\[[^]]*\\]\\)\\|\\(real\\(time\\)?\\)\\|\\(integer\\)\\|\\(time\\)\\)?"))
3359 ((match-end 6) ;; of verilog-end-block-ordered-re
3360 (setq reg "\\(\\<task\\>\\)\\|\\(\\<\\(endtask\\|function\\|\\(macro\\)?module\\|primitive\\)\\>\\)"))
3361 ((match-end 7) ;; of verilog-end-block-ordered-re
3362 (setq reg "\\(\\<\\(macro\\)?module\\>\\)\\|\\<endmodule\\>"))
3363 ((match-end 8) ;; of verilog-end-block-ordered-re
3364 (setq reg "\\(\\<primitive\\>\\)\\|\\(\\<\\(endprimitive\\|package\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3365 ((match-end 9) ;; of verilog-end-block-ordered-re
3366 (setq reg "\\(\\<interface\\>\\)\\|\\(\\<\\(endinterface\\|package\\|primitive\\|\\(macro\\)?module\\)\\>\\)"))
3367 ((match-end 10) ;; of verilog-end-block-ordered-re
3368 (setq reg "\\(\\<package\\>\\)\\|\\(\\<\\(endpackage\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3369 ((match-end 11) ;; of verilog-end-block-ordered-re
3370 (setq reg "\\(\\<class\\>\\)\\|\\(\\<\\(endclass\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3371 ((match-end 12) ;; of verilog-end-block-ordered-re
3372 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<\\(endcovergroup\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3373 ((match-end 13) ;; of verilog-end-block-ordered-re
3374 (setq reg "\\(\\<program\\>\\)\\|\\(\\<\\(endprogram\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3375 ((match-end 14) ;; of verilog-end-block-ordered-re
3376 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<\\(endsequence\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3377 ((match-end 15) ;; of verilog-end-block-ordered-re
3378 (setq reg "\\(\\<clocking\\>\\)\\|\\<endclocking\\>"))
3379
3380 (t (error "Problem in verilog-set-auto-endcomments")))
3381 (let (b e)
3382 (save-excursion
3383 (verilog-re-search-backward reg nil 'move)
3384 (cond
3385 ((match-end 1)
3386 (setq b (progn
3387 (skip-chars-forward "^ \t")
3388 (verilog-forward-ws&directives)
3389 (if (and width (looking-at width))
3390 (progn
3391 (goto-char (match-end 0))
3392 (verilog-forward-ws&directives)))
3393 (point))
3394 e (progn
3395 (skip-chars-forward "a-zA-Z0-9_")
3396 (point)))
3397 (setq string (buffer-substring b e)))
3398 (t
3399 (ding 't)
3400 (setq string "unmatched end(function|task|module|primitive|interface|package|class|clocking)")))))
3401 (end-of-line)
3402 (insert (concat " // " string )))
3403 ))))))))))
3404
3405 (defun verilog-get-expr()
3406 "Grab expression at point, e.g, case ( a | b & (c ^d))."
3407 (let* ((b (progn
3408 (verilog-forward-syntactic-ws)
3409 (skip-chars-forward " \t")
3410 (point)))
3411 (e (let ((par 1))
3412 (cond
3413 ((looking-at "@")
3414 (forward-char 1)
3415 (verilog-forward-syntactic-ws)
3416 (if (looking-at "(")
3417 (progn
3418 (forward-char 1)
3419 (while (and (/= par 0)
3420 (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
3421 (cond
3422 ((match-end 1)
3423 (setq par (1+ par)))
3424 ((match-end 2)
3425 (setq par (1- par)))))))
3426 (point))
3427 ((looking-at "(")
3428 (forward-char 1)
3429 (while (and (/= par 0)
3430 (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
3431 (cond
3432 ((match-end 1)
3433 (setq par (1+ par)))
3434 ((match-end 2)
3435 (setq par (1- par)))))
3436 (point))
3437 ((looking-at "\\[")
3438 (forward-char 1)
3439 (while (and (/= par 0)
3440 (verilog-re-search-forward "\\(\\[\\)\\|\\(\\]\\)" nil 'move))
3441 (cond
3442 ((match-end 1)
3443 (setq par (1+ par)))
3444 ((match-end 2)
3445 (setq par (1- par)))))
3446 (verilog-forward-syntactic-ws)
3447 (skip-chars-forward "^ \t\n\f")
3448 (point))
3449 ((looking-at "/[/\\*]")
3450 b)
3451 ('t
3452 (skip-chars-forward "^: \t\n\f")
3453 (point)))))
3454 (str (buffer-substring b e)))
3455 (if (setq e (string-match "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
3456 (setq str (concat (substring str 0 e) "...")))
3457 str))
3458
3459 (defun verilog-expand-vector ()
3460 "Take a signal vector on the current line and expand it to multiple lines.
3461 Useful for creating tri's and other expanded fields."
3462 (interactive)
3463 (verilog-expand-vector-internal "[" "]"))
3464
3465 (defun verilog-expand-vector-internal (bra ket)
3466 "Given BRA, the start brace and KET, the end brace, expand one line into many lines."
3467 (save-excursion
3468 (forward-line 0)
3469 (let ((signal-string (buffer-substring (point)
3470 (progn
3471 (end-of-line) (point)))))
3472 (if (string-match
3473 (concat "\\(.*\\)"
3474 (regexp-quote bra)
3475 "\\([0-9]*\\)\\(:[0-9]*\\|\\)\\(::[0-9---]*\\|\\)"
3476 (regexp-quote ket)
3477 "\\(.*\\)$") signal-string)
3478 (let* ((sig-head (match-string 1 signal-string))
3479 (vec-start (string-to-number (match-string 2 signal-string)))
3480 (vec-end (if (= (match-beginning 3) (match-end 3))
3481 vec-start
3482 (string-to-number
3483 (substring signal-string (1+ (match-beginning 3))
3484 (match-end 3)))))
3485 (vec-range
3486 (if (= (match-beginning 4) (match-end 4))
3487 1
3488 (string-to-number
3489 (substring signal-string (+ 2 (match-beginning 4))
3490 (match-end 4)))))
3491 (sig-tail (match-string 5 signal-string))
3492 vec)
3493 ;; Decode vectors
3494 (setq vec nil)
3495 (if (< vec-range 0)
3496 (let ((tmp vec-start))
3497 (setq vec-start vec-end
3498 vec-end tmp
3499 vec-range (- vec-range))))
3500 (if (< vec-end vec-start)
3501 (while (<= vec-end vec-start)
3502 (setq vec (append vec (list vec-start)))
3503 (setq vec-start (- vec-start vec-range)))
3504 (while (<= vec-start vec-end)
3505 (setq vec (append vec (list vec-start)))
3506 (setq vec-start (+ vec-start vec-range))))
3507 ;;
3508 ;; Delete current line
3509 (delete-region (point) (progn (forward-line 0) (point)))
3510 ;;
3511 ;; Expand vector
3512 (while vec
3513 (insert (concat sig-head bra
3514 (int-to-string (car vec)) ket sig-tail "\n"))
3515 (setq vec (cdr vec)))
3516 (delete-char -1)
3517 ;;
3518 )))))
3519
3520 (defun verilog-strip-comments ()
3521 "Strip all comments from the Verilog code."
3522 (interactive)
3523 (goto-char (point-min))
3524 (while (re-search-forward "//" nil t)
3525 (if (verilog-within-string)
3526 (re-search-forward "\"" nil t)
3527 (if (verilog-in-star-comment-p)
3528 (re-search-forward "\*/" nil t)
3529 (let ((bpt (- (point) 2)))
3530 (end-of-line)
3531 (delete-region bpt (point))))))
3532 ;;
3533 (goto-char (point-min))
3534 (while (re-search-forward "/\\*" nil t)
3535 (if (verilog-within-string)
3536 (re-search-forward "\"" nil t)
3537 (let ((bpt (- (point) 2)))
3538 (re-search-forward "\\*/")
3539 (delete-region bpt (point))))))
3540
3541 (defun verilog-one-line ()
3542 "Convert structural Verilog instances to occupy one line."
3543 (interactive)
3544 (goto-char (point-min))
3545 (while (re-search-forward "\\([^;]\\)[ \t]*\n[ \t]*" nil t)
3546 (replace-match "\\1 " nil nil)))
3547
3548 (defun verilog-linter-name ()
3549 "Return name of linter, either surelint or verilint."
3550 (let ((compile-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
3551 compile-command))
3552 (lint-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
3553 verilog-linter)))
3554 (cond ((equal compile-word1 "surelint") `surelint)
3555 ((equal compile-word1 "verilint") `verilint)
3556 ((equal lint-word1 "surelint") `surelint)
3557 ((equal lint-word1 "verilint") `verilint)
3558 (t `surelint)))) ;; back compatibility
3559
3560 (defun verilog-lint-off ()
3561 "Convert a Verilog linter warning line into a disable statement.
3562 For example:
3563 pci_bfm_null.v, line 46: Unused input: pci_rst_
3564 becomes a comment for the appropriate tool.
3565
3566 The first word of the `compile-command' or `verilog-linter'
3567 variables is used to determine which product is being used.
3568
3569 See \\[verilog-surelint-off] and \\[verilog-verilint-off]."
3570 (interactive)
3571 (let ((linter (verilog-linter-name)))
3572 (cond ((equal linter `surelint)
3573 (verilog-surelint-off))
3574 ((equal linter `verilint)
3575 (verilog-verilint-off))
3576 (t (error "Linter name not set")))))
3577
3578 (defvar compilation-last-buffer)
3579
3580 (defun verilog-surelint-off ()
3581 "Convert a SureLint warning line into a disable statement.
3582 Run from Verilog source window; assumes there is a *compile* buffer
3583 with point set appropriately.
3584
3585 For example:
3586 WARNING [STD-UDDONX]: xx.v, line 8: output out is never assigned.
3587 becomes:
3588 // surefire lint_line_off UDDONX"
3589 (interactive)
3590 (let ((buff (if (boundp 'next-error-last-buffer)
3591 next-error-last-buffer
3592 compilation-last-buffer)))
3593 (when (buffer-live-p buff)
3594 ;; FIXME with-current-buffer?
3595 (save-excursion
3596 (switch-to-buffer buff)
3597 (beginning-of-line)
3598 (when
3599 (looking-at "\\(INFO\\|WARNING\\|ERROR\\) \\[[^-]+-\\([^]]+\\)\\]: \\([^,]+\\), line \\([0-9]+\\): \\(.*\\)$")
3600 (let* ((code (match-string 2))
3601 (file (match-string 3))
3602 (line (match-string 4))
3603 (buffer (get-file-buffer file))
3604 dir filename)
3605 (unless buffer
3606 (progn
3607 (setq buffer
3608 (and (file-exists-p file)
3609 (find-file-noselect file)))
3610 (or buffer
3611 (let* ((pop-up-windows t))
3612 (let ((name (expand-file-name
3613 (read-file-name
3614 (format "Find this error in: (default %s) "
3615 file)
3616 dir file t))))
3617 (if (file-directory-p name)
3618 (setq name (expand-file-name filename name)))
3619 (setq buffer
3620 (and (file-exists-p name)
3621 (find-file-noselect name))))))))
3622 (switch-to-buffer buffer)
3623 (goto-line (string-to-number line))
3624 (end-of-line)
3625 (catch 'already
3626 (cond
3627 ((verilog-in-slash-comment-p)
3628 (re-search-backward "//")
3629 (cond
3630 ((looking-at "// surefire lint_off_line ")
3631 (goto-char (match-end 0))
3632 (let ((lim (save-excursion (end-of-line) (point))))
3633 (if (re-search-forward code lim 'move)
3634 (throw 'already t)
3635 (insert (concat " " code)))))
3636 (t
3637 )))
3638 ((verilog-in-star-comment-p)
3639 (re-search-backward "/\*")
3640 (insert (format " // surefire lint_off_line %6s" code )))
3641 (t
3642 (insert (format " // surefire lint_off_line %6s" code ))
3643 )))))))))
3644
3645 (defun verilog-verilint-off ()
3646 "Convert a Verilint warning line into a disable statement.
3647
3648 For example:
3649 (W240) pci_bfm_null.v, line 46: Unused input: pci_rst_
3650 becomes:
3651 //Verilint 240 off // WARNING: Unused input"
3652 (interactive)
3653 (save-excursion
3654 (beginning-of-line)
3655 (when (looking-at "\\(.*\\)([WE]\\([0-9A-Z]+\\)).*,\\s +line\\s +[0-9]+:\\s +\\([^:\n]+\\):?.*$")
3656 (replace-match (format
3657 ;; %3s makes numbers 1-999 line up nicely
3658 "\\1//Verilint %3s off // WARNING: \\3"
3659 (match-string 2)))
3660 (beginning-of-line)
3661 (verilog-indent-line))))
3662
3663 (defun verilog-auto-save-compile ()
3664 "Update automatics with \\[verilog-auto], save the buffer, and compile."
3665 (interactive)
3666 (verilog-auto) ; Always do it for safety
3667 (save-buffer)
3668 (compile compile-command))
3669
3670 \f
3671
3672 ;;
3673 ;; Batch
3674 ;;
3675
3676 (defmacro verilog-batch-error-wrapper (&rest body)
3677 "Execute BODY and add error prefix to any errors found.
3678 This lets programs calling batch mode to easily extract error messages."
3679 `(condition-case err
3680 (progn ,@body)
3681 (error
3682 (error "%%Error: %s%s" (error-message-string err)
3683 (if (featurep 'xemacs) "\n" ""))))) ;; xemacs forgets to add a newline
3684
3685 (defun verilog-batch-execute-func (funref)
3686 "Internal processing of a batch command, running FUNREF on all command arguments."
3687 (verilog-batch-error-wrapper
3688 ;; General globals needed
3689 (setq make-backup-files nil)
3690 (setq-default make-backup-files nil)
3691 (setq enable-local-variables t)
3692 (setq enable-local-eval t)
3693 ;; Make sure any sub-files we read get proper mode
3694 (setq default-major-mode `verilog-mode)
3695 ;; Ditto files already read in
3696 (mapc (lambda (buf)
3697 (when (buffer-file-name buf)
3698 (save-excursion
3699 (set-buffer buf)
3700 (verilog-mode))))
3701 (buffer-list))
3702 ;; Process the files
3703 (mapcar '(lambda (buf)
3704 (when (buffer-file-name buf)
3705 (save-excursion
3706 (if (not (file-exists-p (buffer-file-name buf)))
3707 (error
3708 (concat "File not found: " (buffer-file-name buf))))
3709 (message (concat "Processing " (buffer-file-name buf)))
3710 (set-buffer buf)
3711 (funcall funref)
3712 (save-buffer))))
3713 (buffer-list))))
3714
3715 (defun verilog-batch-auto ()
3716 "For use with --batch, perform automatic expansions as a stand-alone tool.
3717 This sets up the appropriate Verilog mode environment, updates automatics
3718 with \\[verilog-auto] on all command-line files, and saves the buffers.
3719 For proper results, multiple filenames need to be passed on the command
3720 line in bottom-up order."
3721 (unless noninteractive
3722 (error "Use verilog-batch-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
3723 (verilog-batch-execute-func `verilog-auto))
3724
3725 (defun verilog-batch-delete-auto ()
3726 "For use with --batch, perform automatic deletion as a stand-alone tool.
3727 This sets up the appropriate Verilog mode environment, deletes automatics
3728 with \\[verilog-delete-auto] on all command-line files, and saves the buffers."
3729 (unless noninteractive
3730 (error "Use verilog-batch-delete-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
3731 (verilog-batch-execute-func `verilog-delete-auto))
3732
3733 (defun verilog-batch-inject-auto ()
3734 "For use with --batch, perform automatic injection as a stand-alone tool.
3735 This sets up the appropriate Verilog mode environment, injects new automatics
3736 with \\[verilog-inject-auto] on all command-line files, and saves the buffers.
3737 For proper results, multiple filenames need to be passed on the command
3738 line in bottom-up order."
3739 (unless noninteractive
3740 (error "Use verilog-batch-inject-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
3741 (verilog-batch-execute-func `verilog-inject-auto))
3742
3743 (defun verilog-batch-indent ()
3744 "For use with --batch, reindent an a entire file as a stand-alone tool.
3745 This sets up the appropriate Verilog mode environment, calls
3746 \\[verilog-indent-buffer] on all command-line files, and saves the buffers."
3747 (unless noninteractive
3748 (error "Use verilog-batch-indent only with --batch")) ;; Otherwise we'd mess up buffer modes
3749 (verilog-batch-execute-func `verilog-indent-buffer))
3750 \f
3751
3752 ;;
3753 ;; Indentation
3754 ;;
3755 (defconst verilog-indent-alist
3756 '((block . (+ ind verilog-indent-level))
3757 (case . (+ ind verilog-case-indent))
3758 (cparenexp . (+ ind verilog-indent-level))
3759 (cexp . (+ ind verilog-cexp-indent))
3760 (defun . verilog-indent-level-module)
3761 (declaration . verilog-indent-level-declaration)
3762 (directive . (verilog-calculate-indent-directive))
3763 (tf . verilog-indent-level)
3764 (behavioral . (+ verilog-indent-level-behavioral verilog-indent-level-module))
3765 (statement . ind)
3766 (cpp . 0)
3767 (comment . (verilog-comment-indent))
3768 (unknown . 3)
3769 (string . 0)))
3770
3771 (defun verilog-continued-line-1 (lim)
3772 "Return true if this is a continued line.
3773 Set point to where line starts. Limit search to point LIM."
3774 (let ((continued 't))
3775 (if (eq 0 (forward-line -1))
3776 (progn
3777 (end-of-line)
3778 (verilog-backward-ws&directives lim)
3779 (if (bobp)
3780 (setq continued nil)
3781 (setq continued (verilog-backward-token))))
3782 (setq continued nil))
3783 continued))
3784
3785 (defun verilog-calculate-indent ()
3786 "Calculate the indent of the current Verilog line.
3787 Examine previous lines. Once a line is found that is definitive as to the
3788 type of the current line, return that lines' indent level and its type.
3789 Return a list of two elements: (INDENT-TYPE INDENT-LEVEL)."
3790 (save-excursion
3791 (let* ((starting_position (point))
3792 (par 0)
3793 (begin (looking-at "[ \t]*begin\\>"))
3794 (lim (save-excursion (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)" nil t)))
3795 (type (catch 'nesting
3796 ;; Keep working backwards until we can figure out
3797 ;; what type of statement this is.
3798 ;; Basically we need to figure out
3799 ;; 1) if this is a continuation of the previous line;
3800 ;; 2) are we in a block scope (begin..end)
3801
3802 ;; if we are in a comment, done.
3803 (if (verilog-in-star-comment-p)
3804 (throw 'nesting 'comment))
3805
3806 ;; if we have a directive, done.
3807 (if (save-excursion (beginning-of-line) (looking-at verilog-directive-re-1))
3808 (throw 'nesting 'directive))
3809
3810 ;; unless we are in the newfangled coverpoint or constraint blocks
3811 ;; if we are in a parenthesized list, and the user likes to indent these, return.
3812 (if (and
3813 verilog-indent-lists
3814 (not (verilog-in-coverage))
3815 (verilog-in-paren))
3816 (progn (setq par 1)
3817 (throw 'nesting 'block)))
3818
3819 ;; See if we are continuing a previous line
3820 (while t
3821 ;; trap out if we crawl off the top of the buffer
3822 (if (bobp) (throw 'nesting 'cpp))
3823
3824 (if (verilog-continued-line-1 lim)
3825 (let ((sp (point)))
3826 (if (and
3827 (not (looking-at verilog-complete-reg))
3828 (verilog-continued-line-1 lim))
3829 (progn (goto-char sp)
3830 (throw 'nesting 'cexp))
3831
3832 (goto-char sp))
3833
3834 (if (and begin
3835 (not verilog-indent-begin-after-if)
3836 (looking-at verilog-no-indent-begin-re))
3837 (progn
3838 (beginning-of-line)
3839 (skip-chars-forward " \t")
3840 (throw 'nesting 'statement))
3841 (progn
3842 (throw 'nesting 'cexp))))
3843 ;; not a continued line
3844 (goto-char starting_position))
3845
3846 (if (looking-at "\\<else\\>")
3847 ;; search back for governing if, striding across begin..end pairs
3848 ;; appropriately
3849 (let ((elsec 1))
3850 (while (verilog-re-search-backward verilog-ends-re nil 'move)
3851 (cond
3852 ((match-end 1) ; else, we're in deep
3853 (setq elsec (1+ elsec)))
3854 ((match-end 2) ; if
3855 (setq elsec (1- elsec))
3856 (if (= 0 elsec)
3857 (if verilog-align-ifelse
3858 (throw 'nesting 'statement)
3859 (progn ;; back up to first word on this line
3860 (beginning-of-line)
3861 (verilog-forward-syntactic-ws)
3862 (throw 'nesting 'statement)))))
3863 (t ; endblock
3864 ; try to leap back to matching outward block by striding across
3865 ; indent level changing tokens then immediately
3866 ; previous line governs indentation.
3867 (let (( reg) (nest 1))
3868 ;; verilog-ends => else|if|end|join(_any|_none|)|endcase|endclass|endtable|endspecify|endfunction|endtask|endgenerate|endgroup
3869 (cond
3870 ((match-end 3) ; end
3871 ;; Search back for matching begin
3872 (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
3873 ((match-end 4) ; endcase
3874 ;; Search back for matching case
3875 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
3876 ((match-end 5) ; endfunction
3877 ;; Search back for matching function
3878 (setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
3879 ((match-end 6) ; endtask
3880 ;; Search back for matching task
3881 (setq reg "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)" ))
3882 ((match-end 7) ; endspecify
3883 ;; Search back for matching specify
3884 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
3885 ((match-end 8) ; endtable
3886 ;; Search back for matching table
3887 (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
3888 ((match-end 9) ; endgenerate
3889 ;; Search back for matching generate
3890 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
3891 ((match-end 10) ; joins
3892 ;; Search back for matching fork
3893 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|none\\)?\\>\\)" ))
3894 ((match-end 11) ; class
3895 ;; Search back for matching class
3896 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
3897 ((match-end 12) ; covergroup
3898 ;; Search back for matching covergroup
3899 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" )))
3900 (catch 'skip
3901 (while (verilog-re-search-backward reg nil 'move)
3902 (cond
3903 ((match-end 1) ; begin
3904 (setq nest (1- nest))
3905 (if (= 0 nest)
3906 (throw 'skip 1)))
3907 ((match-end 2) ; end
3908 (setq nest (1+ nest)))))
3909 )))))))
3910 (throw 'nesting (verilog-calc-1)))
3911 );; catch nesting
3912 );; type
3913 )
3914 ;; Return type of block and indent level.
3915 (if (not type)
3916 (setq type 'cpp))
3917 (if (> par 0) ; Unclosed Parenthesis
3918 (list 'cparenexp par)
3919 (cond
3920 ((eq type 'case)
3921 (list type (verilog-case-indent-level)))
3922 ((eq type 'statement)
3923 (list type (current-column)))
3924 ((eq type 'defun)
3925 (list type 0))
3926 (t
3927 (list type (verilog-current-indent-level))))))))
3928
3929 (defun verilog-wai ()
3930 "Show matching nesting block for debugging."
3931 (interactive)
3932 (save-excursion
3933 (let ((nesting (verilog-calc-1)))
3934 (message "You are at nesting %s" nesting))))
3935
3936 (defun verilog-calc-1 ()
3937 (catch 'nesting
3938 (while (verilog-re-search-backward (concat "\\({\\|}\\|" verilog-indent-re "\\)") nil 'move)
3939 (cond
3940 ((equal (char-after) ?\{)
3941 (if (verilog-at-constraint-p)
3942 (throw 'nesting 'block)))
3943 ((equal (char-after) ?\})
3944
3945 (let ((there (verilog-at-close-constraint-p)))
3946 (if there (goto-char there))))
3947
3948 ((looking-at verilog-beg-block-re-ordered)
3949 (cond
3950 ((match-end 2) ; *sigh* could be "unique case" or "priority casex"
3951 (let ((here (point)))
3952 (verilog-beg-of-statement)
3953 (if (looking-at verilog-extended-case-re)
3954 (throw 'nesting 'case)
3955 (goto-char here)))
3956 (throw 'nesting 'case))
3957
3958 ((match-end 4) ; *sigh* could be "disable fork"
3959 (let ((here (point)))
3960 (verilog-beg-of-statement)
3961 (if (looking-at verilog-disable-fork-re)
3962 t ; is disable fork, this is a normal statement
3963 (progn ; or is fork, starts a new block
3964 (goto-char here)
3965 (throw 'nesting 'block)))))
3966
3967
3968 ;; need to consider typedef struct here...
3969 ((looking-at "\\<class\\|struct\\|function\\|task\\|property\\>")
3970 ; *sigh* These words have an optional prefix:
3971 ; extern {virtual|protected}? function a();
3972 ; assert property (p_1);
3973 ; typedef class foo;
3974 ; and we don't want to confuse this with
3975 ; function a();
3976 ; property
3977 ; ...
3978 ; endfunction
3979 (let ((here (point)))
3980 (save-excursion
3981 (verilog-beg-of-statement)
3982 (if (= (point) here)
3983 (throw 'nesting 'block)))))
3984 (t (throw 'nesting 'block))))
3985
3986 ((looking-at verilog-end-block-re)
3987 (verilog-leap-to-head)
3988 (if (verilog-in-case-region-p)
3989 (progn
3990 (verilog-leap-to-case-head)
3991 (if (looking-at verilog-case-re)
3992 (throw 'nesting 'case)))))
3993
3994 ((looking-at (if (verilog-in-generate-region-p)
3995 verilog-defun-level-not-generate-re
3996 verilog-defun-level-re))
3997 (throw 'nesting 'defun))
3998
3999 ((looking-at verilog-cpp-level-re)
4000 (throw 'nesting 'cpp))
4001
4002 ((bobp)
4003 (throw 'nesting 'cpp))))
4004 (throw 'nesting 'cpp)))
4005
4006 (defun verilog-calculate-indent-directive ()
4007 "Return indentation level for directive.
4008 For speed, the searcher looks at the last directive, not the indent
4009 of the appropriate enclosing block."
4010 (let ((base -1) ;; Indent of the line that determines our indentation
4011 (ind 0)) ;; Relative offset caused by other directives (like `endif on same line as `else)
4012 ;; Start at current location, scan back for another directive
4013
4014 (save-excursion
4015 (beginning-of-line)
4016 (while (and (< base 0)
4017 (verilog-re-search-backward verilog-directive-re nil t))
4018 (cond ((save-excursion (skip-chars-backward " \t") (bolp))
4019 (setq base (current-indentation))))
4020 (cond ((and (looking-at verilog-directive-end) (< base 0)) ;; Only matters when not at BOL
4021 (setq ind (- ind verilog-indent-level-directive)))
4022 ((and (looking-at verilog-directive-middle) (>= base 0)) ;; Only matters when at BOL
4023 (setq ind (+ ind verilog-indent-level-directive)))
4024 ((looking-at verilog-directive-begin)
4025 (setq ind (+ ind verilog-indent-level-directive)))))
4026 ;; Adjust indent to starting indent of critical line
4027 (setq ind (max 0 (+ ind base))))
4028
4029 (save-excursion
4030 (beginning-of-line)
4031 (skip-chars-forward " \t")
4032 (cond ((or (looking-at verilog-directive-middle)
4033 (looking-at verilog-directive-end))
4034 (setq ind (max 0 (- ind verilog-indent-level-directive))))))
4035 ind))
4036
4037 (defun verilog-leap-to-case-head ()
4038 (let ((nest 1))
4039 (while (/= 0 nest)
4040 (verilog-re-search-backward "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" nil 'move)
4041 (cond
4042 ((match-end 1)
4043 (setq nest (1- nest)))
4044 ((match-end 2)
4045 (setq nest (1+ nest)))
4046 ((bobp)
4047 (ding 't)
4048 (setq nest 0))))))
4049
4050 (defun verilog-leap-to-head ()
4051 "Move point to the head of this block.
4052 Jump from end to matching begin, from endcase to matching case, and so on."
4053 (let ((reg nil)
4054 snest
4055 (nest 1))
4056 (cond
4057 ((looking-at "\\<end\\>")
4058 ;; 1: Search back for matching begin
4059 (setq reg (concat "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|"
4060 "\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" )))
4061 ((looking-at "\\<endcase\\>")
4062 ;; 2: Search back for matching case
4063 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>\\)\\|\\(\\<endcase\\>\\)" ))
4064 ((looking-at "\\<join\\(_any\\|_none\\)?\\>")
4065 ;; 3: Search back for matching fork
4066 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
4067 ((looking-at "\\<endclass\\>")
4068 ;; 4: Search back for matching class
4069 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
4070 ((looking-at "\\<endtable\\>")
4071 ;; 5: Search back for matching table
4072 (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
4073 ((looking-at "\\<endspecify\\>")
4074 ;; 6: Search back for matching specify
4075 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
4076 ((looking-at "\\<endfunction\\>")
4077 ;; 7: Search back for matching function
4078 (setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
4079 ((looking-at "\\<endgenerate\\>")
4080 ;; 8: Search back for matching generate
4081 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
4082 ((looking-at "\\<endtask\\>")
4083 ;; 9: Search back for matching task
4084 (setq reg "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)" ))
4085 ((looking-at "\\<endgroup\\>")
4086 ;; 10: Search back for matching covergroup
4087 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
4088 ((looking-at "\\<endproperty\\>")
4089 ;; 11: Search back for matching property
4090 (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
4091 ((looking-at "\\<endinterface\\>")
4092 ;; 12: Search back for matching interface
4093 (setq reg "\\(\\<interface\\>\\)\\|\\(\\<endinterface\\>\\)" ))
4094 ((looking-at "\\<endsequence\\>")
4095 ;; 12: Search back for matching sequence
4096 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" ))
4097 ((looking-at "\\<endclocking\\>")
4098 ;; 12: Search back for matching clocking
4099 (setq reg "\\(\\<clocking\\)\\|\\(\\<endclocking\\>\\)" )))
4100 (if reg
4101 (catch 'skip
4102 (let (sreg)
4103 (while (verilog-re-search-backward reg nil 'move)
4104 (cond
4105 ((match-end 1) ; begin
4106 (setq nest (1- nest))
4107 (if (= 0 nest)
4108 ;; Now previous line describes syntax
4109 (throw 'skip 1))
4110 (if (and snest
4111 (= snest nest))
4112 (setq reg sreg)))
4113 ((match-end 2) ; end
4114 (setq nest (1+ nest)))
4115 ((match-end 3)
4116 ;; endcase, jump to case
4117 (setq snest nest)
4118 (setq nest (1+ nest))
4119 (setq sreg reg)
4120 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
4121 ((match-end 4)
4122 ;; join, jump to fork
4123 (setq snest nest)
4124 (setq nest (1+ nest))
4125 (setq sreg reg)
4126 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
4127 )))))))
4128
4129 (defun verilog-continued-line ()
4130 "Return true if this is a continued line.
4131 Set point to where line starts."
4132 (let ((continued 't))
4133 (if (eq 0 (forward-line -1))
4134 (progn
4135 (end-of-line)
4136 (verilog-backward-ws&directives)
4137 (if (bobp)
4138 (setq continued nil)
4139 (while (and continued
4140 (save-excursion
4141 (skip-chars-backward " \t")
4142 (not (bolp))))
4143 (setq continued (verilog-backward-token)))))
4144 (setq continued nil))
4145 continued))
4146
4147 (defun verilog-backward-token ()
4148 "Step backward token, returning true if we are now at an end of line token."
4149 (interactive)
4150 (verilog-backward-syntactic-ws)
4151 (cond
4152 ((bolp)
4153 nil)
4154 (;-- Anything ending in a ; is complete
4155 (= (preceding-char) ?\;)
4156 nil)
4157 (; If a "}" is prefixed by a ";", then this is a complete statement
4158 ; i.e.: constraint foo { a = b; }
4159 (= (preceding-char) ?\})
4160 (progn
4161 (backward-char)
4162 (verilog-at-close-constraint-p)))
4163 (;-- constraint foo { a = b }
4164 ; is a complete statement. *sigh*
4165 (= (preceding-char) ?\{)
4166 (progn
4167 (backward-char)
4168 (not (verilog-at-constraint-p))))
4169 (;-- Could be 'case (foo)' or 'always @(bar)' which is complete
4170 ; also could be simply '@(foo)'
4171 ; or foo u1 #(a=8)
4172 ; (b, ... which ISN'T complete
4173 ;;;; Do we need this???
4174 (= (preceding-char) ?\))
4175 (progn
4176 (backward-char)
4177 (backward-up-list 1)
4178 (verilog-backward-syntactic-ws)
4179 (let ((back (point)))
4180 (forward-word -1)
4181 (cond
4182 ((looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|case\\(\\|[xz]\\)\\|for\\(\\|each\\|ever\\)\\|i\\(f\\|nitial\\)\\|repeat\\|while\\)\\>")
4183 (not (looking-at "\\<randcase\\>\\|\\<case[xz]?\\>[^:]")))
4184 (t
4185 (goto-char back)
4186 (cond
4187 ((= (preceding-char) ?\@)
4188 (backward-char)
4189 (save-excursion
4190 (verilog-backward-token)
4191 (not (looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|initial\\|while\\)\\>"))))
4192 ((= (preceding-char) ?\#)
4193 (backward-char))
4194 (t t)))))))
4195
4196 (;-- any of begin|initial|while are complete statements; 'begin : foo' is also complete
4197 t
4198 (forward-word -1)
4199 (cond
4200 ((looking-at "\\<else\\>")
4201 t)
4202 ((looking-at verilog-behavioral-block-beg-re)
4203 t)
4204 ((looking-at verilog-indent-re)
4205 nil)
4206 (t
4207 (let
4208 ((back (point)))
4209 (verilog-backward-syntactic-ws)
4210 (cond
4211 ((= (preceding-char) ?\:)
4212 (backward-char)
4213 (verilog-backward-syntactic-ws)
4214 (backward-sexp)
4215 (if (looking-at verilog-nameable-item-re )
4216 nil
4217 t))
4218 ((= (preceding-char) ?\#)
4219 (backward-char)
4220 t)
4221 ((= (preceding-char) ?\`)
4222 (backward-char)
4223 t)
4224
4225 (t
4226 (goto-char back)
4227 t))))))))
4228
4229 (defun verilog-backward-syntactic-ws (&optional bound)
4230 "Backward skip over syntactic whitespace for Emacs 19.
4231 Optional BOUND limits search."
4232 (save-restriction
4233 (let* ((bound (or bound (point-min))) (here bound) )
4234 (if (< bound (point))
4235 (progn
4236 (narrow-to-region bound (point))
4237 (while (/= here (point))
4238 (setq here (point))
4239 (verilog-skip-backward-comments))))))
4240 t)
4241
4242 (defun verilog-forward-syntactic-ws (&optional bound)
4243 "Forward skip over syntactic whitespace for Emacs 19.
4244 Optional BOUND limits search."
4245 (save-restriction
4246 (let* ((bound (or bound (point-max)))
4247 (here bound))
4248 (if (> bound (point))
4249 (progn
4250 (narrow-to-region (point) bound)
4251 (while (/= here (point))
4252 (setq here (point))
4253 (forward-comment (buffer-size))))))))
4254
4255 (defun verilog-backward-ws&directives (&optional bound)
4256 "Backward skip over syntactic whitespace and compiler directives for Emacs 19.
4257 Optional BOUND limits search."
4258 (save-restriction
4259 (let* ((bound (or bound (point-min)))
4260 (here bound)
4261 (p nil) )
4262 (if (< bound (point))
4263 (progn
4264 (let ((state
4265 (save-excursion
4266 (parse-partial-sexp (point-min) (point)))))
4267 (cond
4268 ((nth 7 state) ;; in // comment
4269 (verilog-re-search-backward "//" nil 'move)
4270 (skip-chars-backward "/"))
4271 ((nth 4 state) ;; in /* */ comment
4272 (verilog-re-search-backward "/\*" nil 'move))))
4273 (narrow-to-region bound (point))
4274 (while (/= here (point))
4275 (setq here (point))
4276 (verilog-skip-backward-comments)
4277 (setq p
4278 (save-excursion
4279 (beginning-of-line)
4280 (cond
4281 ((verilog-within-translate-off)
4282 (verilog-back-to-start-translate-off (point-min)))
4283 ((looking-at verilog-directive-re-1)
4284 (point))
4285 (t
4286 nil))))
4287 (if p (goto-char p))))))))
4288
4289 (defun verilog-forward-ws&directives (&optional bound)
4290 "Forward skip over syntactic whitespace and compiler directives for Emacs 19.
4291 Optional BOUND limits search."
4292 (save-restriction
4293 (let* ((bound (or bound (point-max)))
4294 (here bound)
4295 jump)
4296 (if (> bound (point))
4297 (progn
4298 (let ((state
4299 (save-excursion
4300 (parse-partial-sexp (point-min) (point)))))
4301 (cond
4302 ((nth 7 state) ;; in // comment
4303 (verilog-re-search-forward "//" nil 'move))
4304 ((nth 4 state) ;; in /* */ comment
4305 (verilog-re-search-forward "/\*" nil 'move))))
4306 (narrow-to-region (point) bound)
4307 (while (/= here (point))
4308 (setq here (point)
4309 jump nil)
4310 (forward-comment (buffer-size))
4311 (save-excursion
4312 (beginning-of-line)
4313 (if (looking-at verilog-directive-re-1)
4314 (setq jump t)))
4315 (if jump
4316 (beginning-of-line 2))))))))
4317
4318 (defun verilog-in-comment-p ()
4319 "Return true if in a star or // comment."
4320 (let ((state
4321 (save-excursion
4322 (parse-partial-sexp (point-min) (point)))))
4323 (or (nth 4 state) (nth 7 state))))
4324
4325 (defun verilog-in-star-comment-p ()
4326 "Return true if in a star comment."
4327 (let ((state
4328 (save-excursion
4329 (parse-partial-sexp (point-min) (point)))))
4330 (and
4331 (nth 4 state) ; t if in a comment of style a // or b /**/
4332 (not
4333 (nth 7 state) ; t if in a comment of style b /**/
4334 ))))
4335
4336 (defun verilog-in-slash-comment-p ()
4337 "Return true if in a slash comment."
4338 (let ((state
4339 (save-excursion
4340 (parse-partial-sexp (point-min) (point)))))
4341 (nth 7 state)))
4342
4343 (defun verilog-in-comment-or-string-p ()
4344 "Return true if in a string or comment."
4345 (let ((state
4346 (save-excursion
4347 (parse-partial-sexp (point-min) (point)))))
4348 (or (nth 3 state) (nth 4 state) (nth 7 state)))) ; Inside string or comment)
4349
4350 (defun verilog-in-escaped-name-p ()
4351 "Return true if in an escaped name."
4352 (save-excursion
4353 (backward-char)
4354 (skip-chars-backward "^ \t\n\f")
4355 (if (equal (char-after (point) ) ?\\ )
4356 t
4357 nil)))
4358
4359 (defun verilog-in-paren ()
4360 "Return true if in a parenthetical expression."
4361 (let ((state
4362 (save-excursion
4363 (parse-partial-sexp (point-min) (point)))))
4364 (> (nth 0 state) 0 )))
4365
4366 (defun verilog-in-coverage ()
4367 "Return true if in a constraint or coverpoint expression."
4368 (interactive)
4369 (save-excursion
4370 (if (verilog-in-paren)
4371 (progn
4372 (backward-up-list 1)
4373 (verilog-at-constraint-p)
4374 )
4375 nil)))
4376 (defun verilog-at-close-constraint-p ()
4377 "If at the } that closes a constraint or covergroup, return true."
4378 (if (and
4379 (equal (char-after) ?\})
4380 (verilog-in-paren))
4381
4382 (save-excursion
4383 (verilog-backward-ws&directives)
4384 (if (equal (char-before) ?\;)
4385 (point)
4386 nil))))
4387
4388 (defun verilog-at-constraint-p ()
4389 "If at the { of a constraint or coverpoint definition, return true, moving point to constraint."
4390 (if (save-excursion
4391 (and
4392 (equal (char-after) ?\{)
4393 (forward-list)
4394 (progn (backward-char 1)
4395 (verilog-backward-ws&directives)
4396 (equal (char-before) ?\;))))
4397 ;; maybe
4398 (verilog-re-search-backward "\\<constraint\\|coverpoint\\|cross\\>" nil 'move)
4399 ;; not
4400 nil))
4401
4402 (defun verilog-parenthesis-depth ()
4403 "Return non zero if in parenthetical-expression."
4404 (save-excursion
4405 (nth 1 (parse-partial-sexp (point-min) (point)))))
4406
4407
4408 (defun verilog-skip-forward-comment-or-string ()
4409 "Return true if in a string or comment."
4410 (let ((state
4411 (save-excursion
4412 (parse-partial-sexp (point-min) (point)))))
4413 (cond
4414 ((nth 3 state) ;Inside string
4415 (goto-char (nth 3 state))
4416 t)
4417 ((nth 7 state) ;Inside // comment
4418 (forward-line 1)
4419 t)
4420 ((nth 4 state) ;Inside any comment (hence /**/)
4421 (search-forward "*/"))
4422 (t
4423 nil))))
4424
4425 (defun verilog-skip-backward-comment-or-string ()
4426 "Return true if in a string or comment."
4427 (let ((state
4428 (save-excursion
4429 (parse-partial-sexp (point-min) (point)))))
4430 (cond
4431 ((nth 3 state) ;Inside string
4432 (search-backward "\"")
4433 t)
4434 ((nth 7 state) ;Inside // comment
4435 (search-backward "//")
4436 (skip-chars-backward "/")
4437 t)
4438 ((nth 4 state) ;Inside /* */ comment
4439 (search-backward "/*")
4440 t)
4441 (t
4442 nil))))
4443
4444 (defun verilog-skip-backward-comments ()
4445 "Return true if a comment was skipped."
4446 (let ((more t))
4447 (while more
4448 (setq more
4449 (let ((state
4450 (save-excursion
4451 (parse-partial-sexp (point-min) (point)))))
4452 (cond
4453 ((nth 7 state) ;Inside // comment
4454 (search-backward "//")
4455 (skip-chars-backward "/")
4456 (skip-chars-backward " \t\n\f")
4457 t)
4458 ((nth 4 state) ;Inside /* */ comment
4459 (search-backward "/*")
4460 (skip-chars-backward " \t\n\f")
4461 t)
4462 ((and (not (bobp))
4463 (= (char-before) ?\/)
4464 (= (char-before (1- (point))) ?\*))
4465 (goto-char (- (point) 2))
4466 t)
4467 (t
4468 (skip-chars-backward " \t\n\f")
4469 nil)))))))
4470
4471 (defun verilog-skip-forward-comment-p ()
4472 "If in comment, move to end and return true."
4473 (let (state)
4474 (progn
4475 (setq state
4476 (save-excursion
4477 (parse-partial-sexp (point-min) (point))))
4478 (cond
4479 ((nth 3 state)
4480 t)
4481 ((nth 7 state) ;Inside // comment
4482 (end-of-line)
4483 (forward-char 1)
4484 t)
4485 ((nth 4 state) ;Inside any comment
4486 t)
4487 (t
4488 nil)))))
4489
4490 (defun verilog-indent-line-relative ()
4491 "Cheap version of indent line.
4492 Only look at a few lines to determine indent level."
4493 (interactive)
4494 (let ((indent-str)
4495 (sp (point)))
4496 (if (looking-at "^[ \t]*$")
4497 (cond ;- A blank line; No need to be too smart.
4498 ((bobp)
4499 (setq indent-str (list 'cpp 0)))
4500 ((verilog-continued-line)
4501 (let ((sp1 (point)))
4502 (if (verilog-continued-line)
4503 (progn
4504 (goto-char sp)
4505 (setq indent-str
4506 (list 'statement (verilog-current-indent-level))))
4507 (goto-char sp1)
4508 (setq indent-str (list 'block (verilog-current-indent-level)))))
4509 (goto-char sp))
4510 ((goto-char sp)
4511 (setq indent-str (verilog-calculate-indent))))
4512 (progn (skip-chars-forward " \t")
4513 (setq indent-str (verilog-calculate-indent))))
4514 (verilog-do-indent indent-str)))
4515
4516 (defun verilog-indent-line ()
4517 "Indent for special part of code."
4518 (verilog-do-indent (verilog-calculate-indent)))
4519
4520 (defun verilog-do-indent (indent-str)
4521 (let ((type (car indent-str))
4522 (ind (car (cdr indent-str))))
4523 (cond
4524 (; handle continued exp
4525 (eq type 'cexp)
4526 (let ((here (point)))
4527 (verilog-backward-syntactic-ws)
4528 (cond
4529 ((or
4530 (= (preceding-char) ?\,)
4531 (= (preceding-char) ?\])
4532 (save-excursion
4533 (verilog-beg-of-statement-1)
4534 (looking-at verilog-declaration-re)))
4535 (let* ( fst
4536 (val
4537 (save-excursion
4538 (backward-char 1)
4539 (verilog-beg-of-statement-1)
4540 (setq fst (point))
4541 (if (looking-at verilog-declaration-re)
4542 (progn ;; we have multiple words
4543 (goto-char (match-end 0))
4544 (skip-chars-forward " \t")
4545 (cond
4546 ((and verilog-indent-declaration-macros
4547 (= (following-char) ?\`))
4548 (progn
4549 (forward-char 1)
4550 (forward-word 1)
4551 (skip-chars-forward " \t")))
4552 ((= (following-char) ?\[)
4553 (progn
4554 (forward-char 1)
4555 (backward-up-list -1)
4556 (skip-chars-forward " \t"))))
4557 (current-column))
4558 (progn
4559 (goto-char fst)
4560 (+ (current-column) verilog-cexp-indent))))))
4561 (goto-char here)
4562 (indent-line-to val)))
4563 ((= (preceding-char) ?\) )
4564 (goto-char here)
4565 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
4566 (indent-line-to val)))
4567 (t
4568 (goto-char here)
4569 (let ((val))
4570 (verilog-beg-of-statement-1)
4571 (if (and (< (point) here)
4572 (verilog-re-search-forward "=[ \\t]*" here 'move))
4573 (setq val (current-column))
4574 (setq val (eval (cdr (assoc type verilog-indent-alist)))))
4575 (goto-char here)
4576 (indent-line-to val))))))
4577
4578 (; handle inside parenthetical expressions
4579 (eq type 'cparenexp)
4580 (let ((val (save-excursion
4581 (backward-up-list 1)
4582 (forward-char 1)
4583 (skip-chars-forward " \t")
4584 (current-column))))
4585 (indent-line-to val)
4586 (if (and (not (verilog-in-struct-region-p))
4587 (looking-at verilog-declaration-re))
4588 (verilog-indent-declaration ind))))
4589
4590 (;-- Handle the ends
4591 (or
4592 (looking-at verilog-end-block-re )
4593 (verilog-at-close-constraint-p))
4594 (let ((val (if (eq type 'statement)
4595 (- ind verilog-indent-level)
4596 ind)))
4597 (indent-line-to val)))
4598
4599 (;-- Case -- maybe line 'em up
4600 (and (eq type 'case) (not (looking-at "^[ \t]*$")))
4601 (progn
4602 (cond
4603 ((looking-at "\\<endcase\\>")
4604 (indent-line-to ind))
4605 (t
4606 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
4607 (indent-line-to val))))))
4608
4609 (;-- defun
4610 (and (eq type 'defun)
4611 (looking-at verilog-zero-indent-re))
4612 (indent-line-to 0))
4613
4614 (;-- declaration
4615 (and (or
4616 (eq type 'defun)
4617 (eq type 'block))
4618 (looking-at verilog-declaration-re))
4619 (verilog-indent-declaration ind))
4620
4621 (;-- Everything else
4622 t
4623 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
4624 (indent-line-to val))))
4625
4626 (if (looking-at "[ \t]+$")
4627 (skip-chars-forward " \t"))
4628 indent-str ; Return indent data
4629 ))
4630
4631 (defun verilog-current-indent-level ()
4632 "Return the indent-level of the current statement."
4633 (save-excursion
4634 (let (par-pos)
4635 (beginning-of-line)
4636 (setq par-pos (verilog-parenthesis-depth))
4637 (while par-pos
4638 (goto-char par-pos)
4639 (beginning-of-line)
4640 (setq par-pos (verilog-parenthesis-depth)))
4641 (skip-chars-forward " \t")
4642 (current-column))))
4643
4644 (defun verilog-case-indent-level ()
4645 "Return the indent-level of the current statement.
4646 Do not count named blocks or case-statements."
4647 (save-excursion
4648 (skip-chars-forward " \t")
4649 (cond
4650 ((looking-at verilog-named-block-re)
4651 (current-column))
4652 ((and (not (looking-at verilog-case-re))
4653 (looking-at "^[^:;]+[ \t]*:"))
4654 (verilog-re-search-forward ":" nil t)
4655 (skip-chars-forward " \t")
4656 (current-column))
4657 (t
4658 (current-column)))))
4659
4660 (defun verilog-indent-comment ()
4661 "Indent current line as comment."
4662 (let* ((stcol
4663 (cond
4664 ((verilog-in-star-comment-p)
4665 (save-excursion
4666 (re-search-backward "/\\*" nil t)
4667 (1+(current-column))))
4668 (comment-column
4669 comment-column )
4670 (t
4671 (save-excursion
4672 (re-search-backward "//" nil t)
4673 (current-column))))))
4674 (indent-line-to stcol)
4675 stcol))
4676
4677 (defun verilog-more-comment ()
4678 "Make more comment lines like the previous."
4679 (let* ((star 0)
4680 (stcol
4681 (cond
4682 ((verilog-in-star-comment-p)
4683 (save-excursion
4684 (setq star 1)
4685 (re-search-backward "/\\*" nil t)
4686 (1+(current-column))))
4687 (comment-column
4688 comment-column )
4689 (t
4690 (save-excursion
4691 (re-search-backward "//" nil t)
4692 (current-column))))))
4693 (progn
4694 (indent-to stcol)
4695 (if (and star
4696 (save-excursion
4697 (forward-line -1)
4698 (skip-chars-forward " \t")
4699 (looking-at "\*")))
4700 (insert "* ")))))
4701
4702 (defun verilog-comment-indent (&optional arg)
4703 "Return the column number the line should be indented to.
4704 ARG is ignored, for `comment-indent-function' compatibility."
4705 (cond
4706 ((verilog-in-star-comment-p)
4707 (save-excursion
4708 (re-search-backward "/\\*" nil t)
4709 (1+(current-column))))
4710 ( comment-column
4711 comment-column )
4712 (t
4713 (save-excursion
4714 (re-search-backward "//" nil t)
4715 (current-column)))))
4716
4717 ;;
4718
4719 (defun verilog-pretty-declarations (&optional quiet)
4720 "Line up declarations around point."
4721 (interactive)
4722 (save-excursion
4723 (if (progn
4724 (verilog-beg-of-statement-1)
4725 (looking-at verilog-declaration-re))
4726 (let* ((m1 (make-marker))
4727 (e) (r)
4728 (here (point))
4729 ;; Start of declaration range
4730 (start
4731 (progn
4732 (verilog-beg-of-statement-1)
4733 (while (looking-at verilog-declaration-re)
4734 (beginning-of-line)
4735 (setq e (point))
4736 (verilog-backward-syntactic-ws)
4737 (backward-char)
4738 (verilog-beg-of-statement-1)) ;Ack, need to grok `define
4739 e))
4740 ;; End of declaration range
4741 (end
4742 (progn
4743 (goto-char here)
4744 (verilog-end-of-statement)
4745 (setq e (point)) ;Might be on last line
4746 (verilog-forward-syntactic-ws)
4747 (while (looking-at verilog-declaration-re)
4748 (beginning-of-line)
4749 (verilog-end-of-statement)
4750 (setq e (point))
4751 (verilog-forward-syntactic-ws))
4752 e))
4753 (edpos (set-marker (make-marker) end))
4754 (ind)
4755 (base-ind
4756 (progn
4757 (goto-char start)
4758 (verilog-do-indent (verilog-calculate-indent))
4759 (verilog-forward-ws&directives)
4760 (current-column))))
4761 (goto-char end)
4762 (goto-char start)
4763 (if (and (not quiet)
4764 (> (- end start) 100))
4765 (message "Lining up declarations..(please stand by)"))
4766 ;; Get the beginning of line indent first
4767 (while (progn (setq e (marker-position edpos))
4768 (< (point) e))
4769 (cond
4770 ( (save-excursion (skip-chars-backward " \t")
4771 (bolp))
4772 (verilog-forward-ws&directives)
4773 (indent-line-to base-ind)
4774 (verilog-forward-ws&directives)
4775 (verilog-re-search-forward "[ \t\n\f]" e 'move))
4776 (t
4777 (just-one-space)
4778 (verilog-re-search-forward "[ \t\n\f]" e 'move)))
4779 ;;(forward-line)
4780 )
4781 ;; Now find biggest prefix
4782 (setq ind (verilog-get-lineup-indent start edpos))
4783 ;; Now indent each line.
4784 (goto-char start)
4785 (while (progn (setq e (marker-position edpos))
4786 (setq r (- e (point)))
4787 (> r 0))
4788 (setq e (point))
4789 (unless quiet (message "%d" r))
4790 (cond
4791 ((or (and verilog-indent-declaration-macros
4792 (looking-at verilog-declaration-re-1-macro))
4793 (looking-at verilog-declaration-re-1-no-macro))
4794 (let ((p (match-end 0)))
4795 (set-marker m1 p)
4796 (if (verilog-re-search-forward "[[#`]" p 'move)
4797 (progn
4798 (forward-char -1)
4799 (just-one-space)
4800 (goto-char (marker-position m1))
4801 (just-one-space)
4802 (indent-to ind))
4803 (progn
4804 (just-one-space)
4805 (indent-to ind)))))
4806 ((verilog-continued-line-1 start)
4807 (goto-char e)
4808 (indent-line-to ind))
4809 (t ; Must be comment or white space
4810 (goto-char e)
4811 (verilog-forward-ws&directives)
4812 (forward-line -1)))
4813 (forward-line 1))
4814 (unless quiet (message ""))))))
4815
4816 (defun verilog-pretty-expr (&optional quiet myre)
4817 "Line up expressions around point, or optional regexp MYRE."
4818 (interactive "sRegular Expression: ((<|:)?=) ")
4819 (save-excursion
4820 (if (or (eq myre nil)
4821 (string-equal myre ""))
4822 (setq myre "\\(<\\|:\\)?="))
4823 (setq myre (concat "\\(^[^;#:<=>]*\\)\\(" myre "\\)"))
4824 (let ((rexp(concat "^\\s-*" verilog-complete-reg)))
4825 (beginning-of-line)
4826 (if (and (not (looking-at rexp ))
4827 (looking-at myre))
4828 (let* ((here (point))
4829 (e) (r)
4830 (start
4831 (progn
4832 (beginning-of-line)
4833 (setq e (point))
4834 (verilog-backward-syntactic-ws)
4835 (beginning-of-line)
4836 (while (and (not (looking-at rexp ))
4837 (looking-at myre)
4838 (not (bobp))
4839 )
4840 (setq e (point))
4841 (verilog-backward-syntactic-ws)
4842 (beginning-of-line)
4843 ) ;Ack, need to grok `define
4844 e))
4845 (end
4846 (progn
4847 (goto-char here)
4848 (end-of-line)
4849 (setq e (point)) ;Might be on last line
4850 (verilog-forward-syntactic-ws)
4851 (beginning-of-line)
4852 (while (and (not (looking-at rexp ))
4853 (looking-at myre))
4854 (end-of-line)
4855 (setq e (point))
4856 (verilog-forward-syntactic-ws)
4857 (beginning-of-line)
4858 )
4859 e))
4860 (edpos (set-marker (make-marker) end))
4861 (ind)
4862 )
4863 (goto-char start)
4864 (verilog-do-indent (verilog-calculate-indent))
4865 (if (and (not quiet)
4866 (> (- end start) 100))
4867 (message "Lining up expressions..(please stand by)"))
4868
4869 ;; Set indent to minimum throughout region
4870 (while (< (point) (marker-position edpos))
4871 (beginning-of-line)
4872 (verilog-just-one-space myre)
4873 (end-of-line)
4874 (verilog-forward-syntactic-ws)
4875 )
4876
4877 ;; Now find biggest prefix
4878 (setq ind (verilog-get-lineup-indent-2 myre start edpos))
4879
4880 ;; Now indent each line.
4881 (goto-char start)
4882 (while (progn (setq e (marker-position edpos))
4883 (setq r (- e (point)))
4884 (> r 0))
4885 (setq e (point))
4886 (if (not quiet) (message "%d" r))
4887 (cond
4888 ((looking-at myre)
4889 (goto-char (match-end 1))
4890 (if (not (verilog-parenthesis-depth)) ;; ignore parenthsized exprs
4891 (if (eq (char-after) ?=)
4892 (indent-to (1+ ind)) ; line up the = of the <= with surrounding =
4893 (indent-to ind)
4894 )))
4895 ((verilog-continued-line-1 start)
4896 (goto-char e)
4897 (indent-line-to ind))
4898 (t ; Must be comment or white space
4899 (goto-char e)
4900 (verilog-forward-ws&directives)
4901 (forward-line -1))
4902 )
4903 (forward-line 1))
4904 (unless quiet (message ""))
4905 )))))
4906
4907 (defun verilog-just-one-space (myre)
4908 "Remove extra spaces around regular expression MYRE."
4909 (interactive)
4910 (if (and (not(looking-at verilog-complete-reg))
4911 (looking-at myre))
4912 (let ((p1 (match-end 1))
4913 (p2 (match-end 2)))
4914 (progn
4915 (goto-char p2)
4916 (if (looking-at "\\s-") (just-one-space))
4917 (goto-char p1)
4918 (forward-char -1)
4919 (if (looking-at "\\s-") (just-one-space))
4920 ))))
4921
4922 (defun verilog-indent-declaration (baseind)
4923 "Indent current lines as declaration.
4924 Line up the variable names based on previous declaration's indentation.
4925 BASEIND is the base indent to offset everything."
4926 (interactive)
4927 (let ((pos (point-marker))
4928 (lim (save-excursion
4929 ;; (verilog-re-search-backward verilog-declaration-opener nil 'move)
4930 (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)\\|\\(\\<task\\>\\)" nil 'move)
4931 (point)))
4932 (ind)
4933 (val)
4934 (m1 (make-marker)))
4935 (setq val
4936 (+ baseind (eval (cdr (assoc 'declaration verilog-indent-alist)))))
4937 (indent-line-to val)
4938
4939 ;; Use previous declaration (in this module) as template.
4940 (if (or (memq 'all verilog-auto-lineup)
4941 (memq 'declaration verilog-auto-lineup))
4942 (if (verilog-re-search-backward
4943 (or (and verilog-indent-declaration-macros
4944 verilog-declaration-re-1-macro)
4945 verilog-declaration-re-1-no-macro) lim t)
4946 (progn
4947 (goto-char (match-end 0))
4948 (skip-chars-forward " \t")
4949 (setq ind (current-column))
4950 (goto-char pos)
4951 (setq val
4952 (+ baseind
4953 (eval (cdr (assoc 'declaration verilog-indent-alist)))))
4954 (indent-line-to val)
4955 (if (and verilog-indent-declaration-macros
4956 (looking-at verilog-declaration-re-2-macro))
4957 (let ((p (match-end 0)))
4958 (set-marker m1 p)
4959 (if (verilog-re-search-forward "[[#`]" p 'move)
4960 (progn
4961 (forward-char -1)
4962 (just-one-space)
4963 (goto-char (marker-position m1))
4964 (just-one-space)
4965 (indent-to ind))
4966 (if (/= (current-column) ind)
4967 (progn
4968 (just-one-space)
4969 (indent-to ind)))))
4970 (if (looking-at verilog-declaration-re-2-no-macro)
4971 (let ((p (match-end 0)))
4972 (set-marker m1 p)
4973 (if (verilog-re-search-forward "[[`#]" p 'move)
4974 (progn
4975 (forward-char -1)
4976 (just-one-space)
4977 (goto-char (marker-position m1))
4978 (just-one-space)
4979 (indent-to ind))
4980 (if (/= (current-column) ind)
4981 (progn
4982 (just-one-space)
4983 (indent-to ind))))))))))
4984 (goto-char pos)))
4985
4986 (defun verilog-get-lineup-indent (b edpos)
4987 "Return the indent level that will line up several lines within the region.
4988 Region is defined by B and EDPOS."
4989 (save-excursion
4990 (let ((ind 0) e)
4991 (goto-char b)
4992 ;; Get rightmost position
4993 (while (progn (setq e (marker-position edpos))
4994 (< (point) e))
4995 (if (verilog-re-search-forward
4996 (or (and verilog-indent-declaration-macros
4997 verilog-declaration-re-1-macro)
4998 verilog-declaration-re-1-no-macro) e 'move)
4999 (progn
5000 (goto-char (match-end 0))
5001 (verilog-backward-syntactic-ws)
5002 (if (> (current-column) ind)
5003 (setq ind (current-column)))
5004 (goto-char (match-end 0)))))
5005 (if (> ind 0)
5006 (1+ ind)
5007 ;; No lineup-string found
5008 (goto-char b)
5009 (end-of-line)
5010 (skip-chars-backward " \t")
5011 (1+ (current-column))))))
5012
5013 (defun verilog-get-lineup-indent-2 (myre b edpos)
5014 "Return the indent level that will line up several lines within the region."
5015 (save-excursion
5016 (let ((ind 0) e)
5017 (goto-char b)
5018 ;; Get rightmost position
5019 (while (progn (setq e (marker-position edpos))
5020 (< (point) e))
5021 (if (and (verilog-re-search-forward myre e 'move)
5022 (not (verilog-parenthesis-depth))) ;; skip parenthsized exprs
5023 (progn
5024 (goto-char (match-beginning 2))
5025 (verilog-backward-syntactic-ws)
5026 (if (> (current-column) ind)
5027 (setq ind (current-column)))
5028 (goto-char (match-end 0)))
5029 ))
5030 (if (> ind 0)
5031 (1+ ind)
5032 ;; No lineup-string found
5033 (goto-char b)
5034 (end-of-line)
5035 (skip-chars-backward " \t")
5036 (1+ (current-column))))))
5037
5038 (defun verilog-comment-depth (type val)
5039 "A useful mode debugging aide. TYPE and VAL are comments for insertion."
5040 (save-excursion
5041 (let
5042 ((b (prog2
5043 (beginning-of-line)
5044 (point-marker)
5045 (end-of-line)))
5046 (e (point-marker)))
5047 (if (re-search-backward " /\\* \[#-\]# \[a-zA-Z\]+ \[0-9\]+ ## \\*/" b t)
5048 (progn
5049 (replace-match " /* -# ## */")
5050 (end-of-line))
5051 (progn
5052 (end-of-line)
5053 (insert " /* ## ## */"))))
5054 (backward-char 6)
5055 (insert
5056 (format "%s %d" type val))))
5057
5058 ;; \f
5059 ;;
5060 ;; Completion
5061 ;;
5062 (defvar verilog-str nil)
5063 (defvar verilog-all nil)
5064 (defvar verilog-pred nil)
5065 (defvar verilog-buffer-to-use nil)
5066 (defvar verilog-flag nil)
5067 (defvar verilog-toggle-completions nil
5068 "*True means \\<verilog-mode-map>\\[verilog-complete-word] should try all possible completions one by one.
5069 Repeated use of \\[verilog-complete-word] will show you all of them.
5070 Normally, when there is more than one possible completion,
5071 it displays a list of all possible completions.")
5072
5073
5074 (defvar verilog-type-keywords
5075 '(
5076 "and" "buf" "bufif0" "bufif1" "cmos" "defparam" "inout" "input"
5077 "integer" "localparam" "logic" "mailbox" "nand" "nmos" "nor" "not" "notif0"
5078 "notif1" "or" "output" "parameter" "pmos" "pull0" "pull1" "pullup"
5079 "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran" "rtranif0"
5080 "rtranif1" "semaphore" "time" "tran" "tranif0" "tranif1" "tri" "tri0" "tri1"
5081 "triand" "trior" "trireg" "wand" "wire" "wor" "xnor" "xor"
5082 )
5083 "*Keywords for types used when completing a word in a declaration or parmlist.
5084 \(Eg. integer, real, reg...)")
5085
5086 (defvar verilog-cpp-keywords
5087 '("module" "macromodule" "primitive" "timescale" "define" "ifdef" "ifndef" "else"
5088 "endif")
5089 "*Keywords to complete when at first word of a line in declarative scope.
5090 \(Eg. initial, always, begin, assign.)
5091 The procedures and variables defined within the Verilog program
5092 will be completed at runtime and should not be added to this list.")
5093
5094 (defvar verilog-defun-keywords
5095 (append
5096 '(
5097 "always" "always_comb" "always_ff" "always_latch" "assign"
5098 "begin" "end" "generate" "endgenerate" "module" "endmodule"
5099 "specify" "endspecify" "function" "endfunction" "initial" "final"
5100 "task" "endtask" "primitive" "endprimitive"
5101 )
5102 verilog-type-keywords)
5103 "*Keywords to complete when at first word of a line in declarative scope.
5104 \(Eg. initial, always, begin, assign.)
5105 The procedures and variables defined within the Verilog program
5106 will be completed at runtime and should not be added to this list.")
5107
5108 (defvar verilog-block-keywords
5109 '(
5110 "begin" "break" "case" "continue" "else" "end" "endfunction"
5111 "endgenerate" "endinterface" "endpackage" "endspecify" "endtask"
5112 "for" "fork" "if" "join" "join_any" "join_none" "repeat" "return"
5113 "while")
5114 "*Keywords to complete when at first word of a line in behavioral scope.
5115 \(Eg. begin, if, then, else, for, fork.)
5116 The procedures and variables defined within the Verilog program
5117 will be completed at runtime and should not be added to this list.")
5118
5119 (defvar verilog-tf-keywords
5120 '("begin" "break" "fork" "join" "join_any" "join_none" "case" "end" "endtask" "endfunction" "if" "else" "for" "while" "repeat")
5121 "*Keywords to complete when at first word of a line in a task or function.
5122 \(Eg. begin, if, then, else, for, fork.)
5123 The procedures and variables defined within the Verilog program
5124 will be completed at runtime and should not be added to this list.")
5125
5126 (defvar verilog-case-keywords
5127 '("begin" "fork" "join" "join_any" "join_none" "case" "end" "endcase" "if" "else" "for" "repeat")
5128 "*Keywords to complete when at first word of a line in case scope.
5129 \(Eg. begin, if, then, else, for, fork.)
5130 The procedures and variables defined within the Verilog program
5131 will be completed at runtime and should not be added to this list.")
5132
5133 (defvar verilog-separator-keywords
5134 '("else" "then" "begin")
5135 "*Keywords to complete when NOT standing at the first word of a statement.
5136 \(Eg. else, then.)
5137 Variables and function names defined within the Verilog program
5138 will be completed at runtime and should not be added to this list.")
5139
5140 (defun verilog-string-diff (str1 str2)
5141 "Return index of first letter where STR1 and STR2 differs."
5142 (catch 'done
5143 (let ((diff 0))
5144 (while t
5145 (if (or (> (1+ diff) (length str1))
5146 (> (1+ diff) (length str2)))
5147 (throw 'done diff))
5148 (or (equal (aref str1 diff) (aref str2 diff))
5149 (throw 'done diff))
5150 (setq diff (1+ diff))))))
5151
5152 ;; Calculate all possible completions for functions if argument is `function',
5153 ;; completions for procedures if argument is `procedure' or both functions and
5154 ;; procedures otherwise.
5155
5156 (defun verilog-func-completion (type)
5157 "Build regular expression for module/task/function names.
5158 TYPE is 'module, 'tf for task or function, or t if unknown."
5159 (if (string= verilog-str "")
5160 (setq verilog-str "[a-zA-Z_]"))
5161 (let ((verilog-str (concat (cond
5162 ((eq type 'module) "\\<\\(module\\)\\s +")
5163 ((eq type 'tf) "\\<\\(task\\|function\\)\\s +")
5164 (t "\\<\\(task\\|function\\|module\\)\\s +"))
5165 "\\<\\(" verilog-str "[a-zA-Z0-9_.]*\\)\\>"))
5166 match)
5167
5168 (if (not (looking-at verilog-defun-re))
5169 (verilog-re-search-backward verilog-defun-re nil t))
5170 (forward-char 1)
5171
5172 ;; Search through all reachable functions
5173 (goto-char (point-min))
5174 (while (verilog-re-search-forward verilog-str (point-max) t)
5175 (progn (setq match (buffer-substring (match-beginning 2)
5176 (match-end 2)))
5177 (if (or (null verilog-pred)
5178 (funcall verilog-pred match))
5179 (setq verilog-all (cons match verilog-all)))))
5180 (if (match-beginning 0)
5181 (goto-char (match-beginning 0)))))
5182
5183 (defun verilog-get-completion-decl (end)
5184 "Macro for searching through current declaration (var, type or const)
5185 for matches of `str' and adding the occurrence tp `all' through point END."
5186 (let ((re (or (and verilog-indent-declaration-macros
5187 verilog-declaration-re-2-macro)
5188 verilog-declaration-re-2-no-macro))
5189 decl-end match)
5190 ;; Traverse lines
5191 (while (and (< (point) end)
5192 (verilog-re-search-forward re end t))
5193 ;; Traverse current line
5194 (setq decl-end (save-excursion (verilog-declaration-end)))
5195 (while (and (verilog-re-search-forward verilog-symbol-re decl-end t)
5196 (not (match-end 1)))
5197 (setq match (buffer-substring (match-beginning 0) (match-end 0)))
5198 (if (string-match (concat "\\<" verilog-str) match)
5199 (if (or (null verilog-pred)
5200 (funcall verilog-pred match))
5201 (setq verilog-all (cons match verilog-all)))))
5202 (forward-line 1)))
5203 verilog-all)
5204
5205 (defun verilog-type-completion ()
5206 "Calculate all possible completions for types."
5207 (let ((start (point))
5208 goon)
5209 ;; Search for all reachable type declarations
5210 (while (or (verilog-beg-of-defun)
5211 (setq goon (not goon)))
5212 (save-excursion
5213 (if (and (< start (prog1 (save-excursion (verilog-end-of-defun)
5214 (point))
5215 (forward-char 1)))
5216 (verilog-re-search-forward
5217 "\\<type\\>\\|\\<\\(begin\\|function\\|procedure\\)\\>"
5218 start t)
5219 (not (match-end 1)))
5220 ;; Check current type declaration
5221 (verilog-get-completion-decl start))))))
5222
5223 (defun verilog-var-completion ()
5224 "Calculate all possible completions for variables (or constants)."
5225 (let ((start (point)))
5226 ;; Search for all reachable var declarations
5227 (verilog-beg-of-defun)
5228 (save-excursion
5229 ;; Check var declarations
5230 (verilog-get-completion-decl start))))
5231
5232 (defun verilog-keyword-completion (keyword-list)
5233 "Give list of all possible completions of keywords in KEYWORD-LIST."
5234 (mapcar '(lambda (s)
5235 (if (string-match (concat "\\<" verilog-str) s)
5236 (if (or (null verilog-pred)
5237 (funcall verilog-pred s))
5238 (setq verilog-all (cons s verilog-all)))))
5239 keyword-list))
5240
5241
5242 (defun verilog-completion (verilog-str verilog-pred verilog-flag)
5243 "Function passed to `completing-read', `try-completion' or `all-completions'.
5244 Called to get completion on VERILOG-STR. If VERILOG-PRED is non-nil, it
5245 must be a function to be called for every match to check if this should
5246 really be a match. If VERILOG-FLAG is t, the function returns a list of
5247 all possible completions. If VERILOG-FLAG is nil it returns a string,
5248 the longest possible completion, or t if VERILOG-STR is an exact match.
5249 If VERILOG-FLAG is 'lambda, the function returns t if VERILOG-STR is an
5250 exact match, nil otherwise."
5251 (save-excursion
5252 (let ((verilog-all nil))
5253 ;; Set buffer to use for searching labels. This should be set
5254 ;; within functions which use verilog-completions
5255 (set-buffer verilog-buffer-to-use)
5256
5257 ;; Determine what should be completed
5258 (let ((state (car (verilog-calculate-indent))))
5259 (cond ((eq state 'defun)
5260 (save-excursion (verilog-var-completion))
5261 (verilog-func-completion 'module)
5262 (verilog-keyword-completion verilog-defun-keywords))
5263
5264 ((eq state 'behavioral)
5265 (save-excursion (verilog-var-completion))
5266 (verilog-func-completion 'module)
5267 (verilog-keyword-completion verilog-defun-keywords))
5268
5269 ((eq state 'block)
5270 (save-excursion (verilog-var-completion))
5271 (verilog-func-completion 'tf)
5272 (verilog-keyword-completion verilog-block-keywords))
5273
5274 ((eq state 'case)
5275 (save-excursion (verilog-var-completion))
5276 (verilog-func-completion 'tf)
5277 (verilog-keyword-completion verilog-case-keywords))
5278
5279 ((eq state 'tf)
5280 (save-excursion (verilog-var-completion))
5281 (verilog-func-completion 'tf)
5282 (verilog-keyword-completion verilog-tf-keywords))
5283
5284 ((eq state 'cpp)
5285 (save-excursion (verilog-var-completion))
5286 (verilog-keyword-completion verilog-cpp-keywords))
5287
5288 ((eq state 'cparenexp)
5289 (save-excursion (verilog-var-completion)))
5290
5291 (t;--Anywhere else
5292 (save-excursion (verilog-var-completion))
5293 (verilog-func-completion 'both)
5294 (verilog-keyword-completion verilog-separator-keywords))))
5295
5296 ;; Now we have built a list of all matches. Give response to caller
5297 (verilog-completion-response))))
5298
5299 (defun verilog-completion-response ()
5300 (cond ((or (equal verilog-flag 'lambda) (null verilog-flag))
5301 ;; This was not called by all-completions
5302 (if (null verilog-all)
5303 ;; Return nil if there was no matching label
5304 nil
5305 ;; Get longest string common in the labels
5306 (let* ((elm (cdr verilog-all))
5307 (match (car verilog-all))
5308 (min (length match))
5309 tmp)
5310 (if (string= match verilog-str)
5311 ;; Return t if first match was an exact match
5312 (setq match t)
5313 (while (not (null elm))
5314 ;; Find longest common string
5315 (if (< (setq tmp (verilog-string-diff match (car elm))) min)
5316 (progn
5317 (setq min tmp)
5318 (setq match (substring match 0 min))))
5319 ;; Terminate with match=t if this is an exact match
5320 (if (string= (car elm) verilog-str)
5321 (progn
5322 (setq match t)
5323 (setq elm nil))
5324 (setq elm (cdr elm)))))
5325 ;; If this is a test just for exact match, return nil ot t
5326 (if (and (equal verilog-flag 'lambda) (not (equal match 't)))
5327 nil
5328 match))))
5329 ;; If flag is t, this was called by all-completions. Return
5330 ;; list of all possible completions
5331 (verilog-flag
5332 verilog-all)))
5333
5334 (defvar verilog-last-word-numb 0)
5335 (defvar verilog-last-word-shown nil)
5336 (defvar verilog-last-completions nil)
5337
5338 (defun verilog-complete-word ()
5339 "Complete word at current point.
5340 \(See also `verilog-toggle-completions', `verilog-type-keywords',
5341 and `verilog-separator-keywords'.)"
5342 (interactive)
5343 (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
5344 (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
5345 (verilog-str (buffer-substring b e))
5346 ;; The following variable is used in verilog-completion
5347 (verilog-buffer-to-use (current-buffer))
5348 (allcomp (if (and verilog-toggle-completions
5349 (string= verilog-last-word-shown verilog-str))
5350 verilog-last-completions
5351 (all-completions verilog-str 'verilog-completion)))
5352 (match (if verilog-toggle-completions
5353 "" (try-completion
5354 verilog-str (mapcar '(lambda (elm)
5355 (cons elm 0)) allcomp)))))
5356 ;; Delete old string
5357 (delete-region b e)
5358
5359 ;; Toggle-completions inserts whole labels
5360 (if verilog-toggle-completions
5361 (progn
5362 ;; Update entry number in list
5363 (setq verilog-last-completions allcomp
5364 verilog-last-word-numb
5365 (if (>= verilog-last-word-numb (1- (length allcomp)))
5366 0
5367 (1+ verilog-last-word-numb)))
5368 (setq verilog-last-word-shown (elt allcomp verilog-last-word-numb))
5369 ;; Display next match or same string if no match was found
5370 (if (not (null allcomp))
5371 (insert "" verilog-last-word-shown)
5372 (insert "" verilog-str)
5373 (message "(No match)")))
5374 ;; The other form of completion does not necessarily do that.
5375
5376 ;; Insert match if found, or the original string if no match
5377 (if (or (null match) (equal match 't))
5378 (progn (insert "" verilog-str)
5379 (message "(No match)"))
5380 (insert "" match))
5381 ;; Give message about current status of completion
5382 (cond ((equal match 't)
5383 (if (not (null (cdr allcomp)))
5384 (message "(Complete but not unique)")
5385 (message "(Sole completion)")))
5386 ;; Display buffer if the current completion didn't help
5387 ;; on completing the label.
5388 ((and (not (null (cdr allcomp))) (= (length verilog-str)
5389 (length match)))
5390 (with-output-to-temp-buffer "*Completions*"
5391 (display-completion-list allcomp))
5392 ;; Wait for a key press. Then delete *Completion* window
5393 (momentary-string-display "" (point))
5394 (delete-window (get-buffer-window (get-buffer "*Completions*")))
5395 )))))
5396
5397 (defun verilog-show-completions ()
5398 "Show all possible completions at current point."
5399 (interactive)
5400 (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
5401 (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
5402 (verilog-str (buffer-substring b e))
5403 ;; The following variable is used in verilog-completion
5404 (verilog-buffer-to-use (current-buffer))
5405 (allcomp (if (and verilog-toggle-completions
5406 (string= verilog-last-word-shown verilog-str))
5407 verilog-last-completions
5408 (all-completions verilog-str 'verilog-completion))))
5409 ;; Show possible completions in a temporary buffer.
5410 (with-output-to-temp-buffer "*Completions*"
5411 (display-completion-list allcomp))
5412 ;; Wait for a key press. Then delete *Completion* window
5413 (momentary-string-display "" (point))
5414 (delete-window (get-buffer-window (get-buffer "*Completions*")))))
5415
5416
5417 (defun verilog-get-default-symbol ()
5418 "Return symbol around current point as a string."
5419 (save-excursion
5420 (buffer-substring (progn
5421 (skip-chars-backward " \t")
5422 (skip-chars-backward "a-zA-Z0-9_")
5423 (point))
5424 (progn
5425 (skip-chars-forward "a-zA-Z0-9_")
5426 (point)))))
5427
5428 (defun verilog-build-defun-re (str &optional arg)
5429 "Return function/task/module starting with STR as regular expression.
5430 With optional second ARG non-nil, STR is the complete name of the instruction."
5431 (if arg
5432 (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "\\)\\>")
5433 (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "[a-zA-Z0-9_]*\\)\\>")))
5434
5435 (defun verilog-comp-defun (verilog-str verilog-pred verilog-flag)
5436 "Function passed to `completing-read', `try-completion' or `all-completions'.
5437 Returns a completion on any function name based on VERILOG-STR prefix. If
5438 VERILOG-PRED is non-nil, it must be a function to be called for every match
5439 to check if this should really be a match. If VERILOG-FLAG is t, the
5440 function returns a list of all possible completions. If it is nil it
5441 returns a string, the longest possible completion, or t if VERILOG-STR is
5442 an exact match. If VERILOG-FLAG is 'lambda, the function returns t if
5443 VERILOG-STR is an exact match, nil otherwise."
5444 (save-excursion
5445 (let ((verilog-all nil)
5446 match)
5447
5448 ;; Set buffer to use for searching labels. This should be set
5449 ;; within functions which use verilog-completions
5450 (set-buffer verilog-buffer-to-use)
5451
5452 (let ((verilog-str verilog-str))
5453 ;; Build regular expression for functions
5454 (if (string= verilog-str "")
5455 (setq verilog-str (verilog-build-defun-re "[a-zA-Z_]"))
5456 (setq verilog-str (verilog-build-defun-re verilog-str)))
5457 (goto-char (point-min))
5458
5459 ;; Build a list of all possible completions
5460 (while (verilog-re-search-forward verilog-str nil t)
5461 (setq match (buffer-substring (match-beginning 2) (match-end 2)))
5462 (if (or (null verilog-pred)
5463 (funcall verilog-pred match))
5464 (setq verilog-all (cons match verilog-all)))))
5465
5466 ;; Now we have built a list of all matches. Give response to caller
5467 (verilog-completion-response))))
5468
5469 (defun verilog-goto-defun ()
5470 "Move to specified Verilog module/task/function.
5471 The default is a name found in the buffer around point.
5472 If search fails, other files are checked based on
5473 `verilog-library-flags'."
5474 (interactive)
5475 (let* ((default (verilog-get-default-symbol))
5476 ;; The following variable is used in verilog-comp-function
5477 (verilog-buffer-to-use (current-buffer))
5478 (label (if (not (string= default ""))
5479 ;; Do completion with default
5480 (completing-read (concat "Label: (default " default ") ")
5481 'verilog-comp-defun nil nil "")
5482 ;; There is no default value. Complete without it
5483 (completing-read "Label: "
5484 'verilog-comp-defun nil nil "")))
5485 pt)
5486 ;; If there was no response on prompt, use default value
5487 (if (string= label "")
5488 (setq label default))
5489 ;; Goto right place in buffer if label is not an empty string
5490 (or (string= label "")
5491 (progn
5492 (save-excursion
5493 (goto-char (point-min))
5494 (setq pt
5495 (re-search-forward (verilog-build-defun-re label t) nil t)))
5496 (when pt
5497 (goto-char pt)
5498 (beginning-of-line))
5499 pt)
5500 (verilog-goto-defun-file label))))
5501
5502 ;; Eliminate compile warning
5503 (defvar occur-pos-list)
5504
5505 (defun verilog-showscopes ()
5506 "List all scopes in this module."
5507 (interactive)
5508 (let ((buffer (current-buffer))
5509 (linenum 1)
5510 (nlines 0)
5511 (first 1)
5512 (prevpos (point-min))
5513 (final-context-start (make-marker))
5514 (regexp "\\(module\\s-+\\w+\\s-*(\\)\\|\\(\\w+\\s-+\\w+\\s-*(\\)"))
5515 (with-output-to-temp-buffer "*Occur*"
5516 (save-excursion
5517 (message (format "Searching for %s ..." regexp))
5518 ;; Find next match, but give up if prev match was at end of buffer.
5519 (while (and (not (= prevpos (point-max)))
5520 (verilog-re-search-forward regexp nil t))
5521 (goto-char (match-beginning 0))
5522 (beginning-of-line)
5523 (save-match-data
5524 (setq linenum (+ linenum (count-lines prevpos (point)))))
5525 (setq prevpos (point))
5526 (goto-char (match-end 0))
5527 (let* ((start (save-excursion
5528 (goto-char (match-beginning 0))
5529 (forward-line (if (< nlines 0) nlines (- nlines)))
5530 (point)))
5531 (end (save-excursion
5532 (goto-char (match-end 0))
5533 (if (> nlines 0)
5534 (forward-line (1+ nlines))
5535 (forward-line 1))
5536 (point)))
5537 (tag (format "%3d" linenum))
5538 (empty (make-string (length tag) ?\ ))
5539 tem)
5540 (save-excursion
5541 (setq tem (make-marker))
5542 (set-marker tem (point))
5543 (set-buffer standard-output)
5544 (setq occur-pos-list (cons tem occur-pos-list))
5545 (or first (zerop nlines)
5546 (insert "--------\n"))
5547 (setq first nil)
5548 (insert-buffer-substring buffer start end)
5549 (backward-char (- end start))
5550 (setq tem (if (< nlines 0) (- nlines) nlines))
5551 (while (> tem 0)
5552 (insert empty ?:)
5553 (forward-line 1)
5554 (setq tem (1- tem)))
5555 (let ((this-linenum linenum))
5556 (set-marker final-context-start
5557 (+ (point) (- (match-end 0) (match-beginning 0))))
5558 (while (< (point) final-context-start)
5559 (if (null tag)
5560 (setq tag (format "%3d" this-linenum)))
5561 (insert tag ?:)))))))
5562 (set-buffer-modified-p nil))))
5563
5564
5565 ;; Highlight helper functions
5566 (defconst verilog-directive-regexp "\\(translate\\|coverage\\|lint\\)_")
5567 (defun verilog-within-translate-off ()
5568 "Return point if within translate-off region, else nil."
5569 (and (save-excursion
5570 (re-search-backward
5571 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "\\(on\\|off\\)\\>")
5572 nil t))
5573 (equal "off" (match-string 2))
5574 (point)))
5575
5576 (defun verilog-start-translate-off (limit)
5577 "Return point before translate-off directive if before LIMIT, else nil."
5578 (when (re-search-forward
5579 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
5580 limit t)
5581 (match-beginning 0)))
5582
5583 (defun verilog-back-to-start-translate-off (limit)
5584 "Return point before translate-off directive if before LIMIT, else nil."
5585 (when (re-search-backward
5586 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
5587 limit t)
5588 (match-beginning 0)))
5589
5590 (defun verilog-end-translate-off (limit)
5591 "Return point after translate-on directive if before LIMIT, else nil."
5592
5593 (re-search-forward (concat
5594 "//\\s-*.*\\s-*" verilog-directive-regexp "on\\>") limit t))
5595
5596 (defun verilog-match-translate-off (limit)
5597 "Match a translate-off block, setting `match-data' and returning t, else nil.
5598 Bound search by LIMIT."
5599 (when (< (point) limit)
5600 (let ((start (or (verilog-within-translate-off)
5601 (verilog-start-translate-off limit)))
5602 (case-fold-search t))
5603 (when start
5604 (let ((end (or (verilog-end-translate-off limit) limit)))
5605 (set-match-data (list start end))
5606 (goto-char end))))))
5607
5608 (defun verilog-font-lock-match-item (limit)
5609 "Match, and move over, any declaration item after point.
5610 Bound search by LIMIT. Adapted from
5611 `font-lock-match-c-style-declaration-item-and-skip-to-next'."
5612 (condition-case nil
5613 (save-restriction
5614 (narrow-to-region (point-min) limit)
5615 ;; match item
5616 (when (looking-at "\\s-*\\([a-zA-Z]\\w*\\)")
5617 (save-match-data
5618 (goto-char (match-end 1))
5619 ;; move to next item
5620 (if (looking-at "\\(\\s-*,\\)")
5621 (goto-char (match-end 1))
5622 (end-of-line) t))))
5623 (error nil)))
5624
5625
5626 ;; Added by Subbu Meiyappan for Header
5627
5628 (defun verilog-header ()
5629 "Insert a standard Verilog file header."
5630 (interactive)
5631 (let ((start (point)))
5632 (insert "\
5633 //-----------------------------------------------------------------------------
5634 // Title : <title>
5635 // Project : <project>
5636 //-----------------------------------------------------------------------------
5637 // File : <filename>
5638 // Author : <author>
5639 // Created : <credate>
5640 // Last modified : <moddate>
5641 //-----------------------------------------------------------------------------
5642 // Description :
5643 // <description>
5644 //-----------------------------------------------------------------------------
5645 // Copyright (c) <copydate> by <company> This model is the confidential and
5646 // proprietary property of <company> and the possession or use of this
5647 // file requires a written license from <company>.
5648 //------------------------------------------------------------------------------
5649 // Modification history :
5650 // <modhist>
5651 //-----------------------------------------------------------------------------
5652
5653 ")
5654 (goto-char start)
5655 (search-forward "<filename>")
5656 (replace-match (buffer-name) t t)
5657 (search-forward "<author>") (replace-match "" t t)
5658 (insert (user-full-name))
5659 (insert " <" (user-login-name) "@" (system-name) ">")
5660 (search-forward "<credate>") (replace-match "" t t)
5661 (verilog-insert-date)
5662 (search-forward "<moddate>") (replace-match "" t t)
5663 (verilog-insert-date)
5664 (search-forward "<copydate>") (replace-match "" t t)
5665 (verilog-insert-year)
5666 (search-forward "<modhist>") (replace-match "" t t)
5667 (verilog-insert-date)
5668 (insert " : created")
5669 (goto-char start)
5670 (let (string)
5671 (setq string (read-string "title: "))
5672 (search-forward "<title>")
5673 (replace-match string t t)
5674 (setq string (read-string "project: " verilog-project))
5675 (setq verilog-project string)
5676 (search-forward "<project>")
5677 (replace-match string t t)
5678 (setq string (read-string "Company: " verilog-company))
5679 (setq verilog-company string)
5680 (search-forward "<company>")
5681 (replace-match string t t)
5682 (search-forward "<company>")
5683 (replace-match string t t)
5684 (search-forward "<company>")
5685 (replace-match string t t)
5686 (search-backward "<description>")
5687 (replace-match "" t t))))
5688
5689 ;; verilog-header Uses the verilog-insert-date function
5690
5691 (defun verilog-insert-date ()
5692 "Insert date from the system."
5693 (interactive)
5694 (let ((timpos))
5695 (setq timpos (point))
5696 (if verilog-date-scientific-format
5697 (shell-command "date \"+@%Y/%m/%d\"" t)
5698 (shell-command "date \"+@%d.%m.%Y\"" t))
5699 (search-forward "@")
5700 (delete-region timpos (point))
5701 (end-of-line))
5702 (delete-char 1))
5703
5704 (defun verilog-insert-year ()
5705 "Insert year from the system."
5706 (interactive)
5707 (let ((timpos))
5708 (setq timpos (point))
5709 (shell-command "date \"+@%Y\"" t)
5710 (search-forward "@")
5711 (delete-region timpos (point))
5712 (end-of-line))
5713 (delete-char 1))
5714
5715 \f
5716 ;;
5717 ;; Signal list parsing
5718 ;;
5719
5720 ;; Elements of a signal list
5721 (defsubst verilog-sig-name (sig)
5722 (car sig))
5723 (defsubst verilog-sig-bits (sig)
5724 (nth 1 sig))
5725 (defsubst verilog-sig-comment (sig)
5726 (nth 2 sig))
5727 (defsubst verilog-sig-memory (sig)
5728 (nth 3 sig))
5729 (defsubst verilog-sig-enum (sig)
5730 (nth 4 sig))
5731 (defsubst verilog-sig-signed (sig)
5732 (nth 5 sig))
5733 (defsubst verilog-sig-type (sig)
5734 (nth 6 sig))
5735 (defsubst verilog-sig-multidim (sig)
5736 (nth 7 sig))
5737 (defsubst verilog-sig-multidim-string (sig)
5738 (if (verilog-sig-multidim sig)
5739 (let ((str "") (args (verilog-sig-multidim sig)))
5740 (while args
5741 (setq str (concat str (car args)))
5742 (setq args (cdr args)))
5743 str)))
5744 (defsubst verilog-sig-width (sig)
5745 (verilog-make-width-expression (verilog-sig-bits sig)))
5746
5747 (defsubst verilog-alw-get-inputs (sigs)
5748 (nth 2 sigs))
5749 (defsubst verilog-alw-get-outputs (sigs)
5750 (nth 0 sigs))
5751 (defsubst verilog-alw-get-uses-delayed (sigs)
5752 (nth 3 sigs))
5753
5754 (defun verilog-signals-not-in (in-list not-list)
5755 "Return list of signals in IN-LIST that aren't also in NOT-LIST.
5756 Also remove any duplicates in IN-LIST.
5757 Signals must be in standard (base vector) form."
5758 (let (out-list)
5759 (while in-list
5760 (if (not (or (assoc (car (car in-list)) not-list)
5761 (assoc (car (car in-list)) out-list)))
5762 (setq out-list (cons (car in-list) out-list)))
5763 (setq in-list (cdr in-list)))
5764 (nreverse out-list)))
5765 ;;(verilog-signals-not-in '(("A" "") ("B" "") ("DEL" "[2:3]")) '(("DEL" "") ("EXT" "")))
5766
5767 (defun verilog-signals-in (in-list other-list)
5768 "Return list of signals in IN-LIST that are also in OTHER-LIST.
5769 Signals must be in standard (base vector) form."
5770 (let (out-list)
5771 (while in-list
5772 (if (assoc (car (car in-list)) other-list)
5773 (setq out-list (cons (car in-list) out-list)))
5774 (setq in-list (cdr in-list)))
5775 (nreverse out-list)))
5776 ;;(verilog-signals-in '(("A" "") ("B" "") ("DEL" "[2:3]")) '(("DEL" "") ("EXT" "")))
5777
5778 (defun verilog-signals-memory (in-list)
5779 "Return list of signals in IN-LIST that are memoried (multidimensional)."
5780 (let (out-list)
5781 (while in-list
5782 (if (nth 3 (car in-list))
5783 (setq out-list (cons (car in-list) out-list)))
5784 (setq in-list (cdr in-list)))
5785 out-list))
5786 ;;(verilog-signals-memory '(("A" nil nil "[3:0]")) '(("B" nil nil nil)))
5787
5788 (defun verilog-signals-sort-compare (a b)
5789 "Compare signal A and B for sorting."
5790 (string< (car a) (car b)))
5791
5792 (defun verilog-signals-not-params (in-list)
5793 "Return list of signals in IN-LIST that aren't parameters or numeric constants."
5794 (let (out-list)
5795 (while in-list
5796 (unless (boundp (intern (concat "vh-" (car (car in-list)))))
5797 (setq out-list (cons (car in-list) out-list)))
5798 (setq in-list (cdr in-list)))
5799 (nreverse out-list)))
5800
5801 (defun verilog-signals-combine-bus (in-list)
5802 "Return a list of signals in IN-LIST, with busses combined.
5803 Duplicate signals are also removed. For example A[2] and A[1] become A[2:1]."
5804 (let (combo buswarn
5805 out-list
5806 sig highbit lowbit ; Temp information about current signal
5807 sv-name sv-highbit sv-lowbit ; Details about signal we are forming
5808 sv-comment sv-memory sv-enum sv-signed sv-type sv-multidim sv-busstring
5809 bus)
5810 ;; Shove signals so duplicated signals will be adjacent
5811 (setq in-list (sort in-list `verilog-signals-sort-compare))
5812 (while in-list
5813 (setq sig (car in-list))
5814 ;; No current signal; form from existing details
5815 (unless sv-name
5816 (setq sv-name (verilog-sig-name sig)
5817 sv-highbit nil
5818 sv-busstring nil
5819 sv-comment (verilog-sig-comment sig)
5820 sv-memory (verilog-sig-memory sig)
5821 sv-enum (verilog-sig-enum sig)
5822 sv-signed (verilog-sig-signed sig)
5823 sv-type (verilog-sig-type sig)
5824 sv-multidim (verilog-sig-multidim sig)
5825 combo ""
5826 buswarn ""))
5827 ;; Extract bus details
5828 (setq bus (verilog-sig-bits sig))
5829 (cond ((and bus
5830 (or (and (string-match "\\[\\([0-9]+\\):\\([0-9]+\\)\\]" bus)
5831 (setq highbit (string-to-number (match-string 1 bus))
5832 lowbit (string-to-number
5833 (match-string 2 bus))))
5834 (and (string-match "\\[\\([0-9]+\\)\\]" bus)
5835 (setq highbit (string-to-number (match-string 1 bus))
5836 lowbit highbit))))
5837 ;; Combine bits in bus
5838 (if sv-highbit
5839 (setq sv-highbit (max highbit sv-highbit)
5840 sv-lowbit (min lowbit sv-lowbit))
5841 (setq sv-highbit highbit
5842 sv-lowbit lowbit)))
5843 (bus
5844 ;; String, probably something like `preproc:0
5845 (setq sv-busstring bus)))
5846 ;; Peek ahead to next signal
5847 (setq in-list (cdr in-list))
5848 (setq sig (car in-list))
5849 (cond ((and sig (equal sv-name (verilog-sig-name sig)))
5850 ;; Combine with this signal
5851 (when (and sv-busstring
5852 (not (equal sv-busstring (verilog-sig-bits sig))))
5853 (when nil ;; Debugging
5854 (message (concat "Warning, can't merge into single bus "
5855 sv-name bus
5856 ", the AUTOs may be wrong")))
5857 (setq buswarn ", Couldn't Merge"))
5858 (if (verilog-sig-comment sig) (setq combo ", ..."))
5859 (setq sv-memory (or sv-memory (verilog-sig-memory sig))
5860 sv-enum (or sv-enum (verilog-sig-enum sig))
5861 sv-signed (or sv-signed (verilog-sig-signed sig))
5862 sv-type (or sv-type (verilog-sig-type sig))
5863 sv-multidim (or sv-multidim (verilog-sig-multidim sig))))
5864 ;; Doesn't match next signal, add to queue, zero in prep for next
5865 ;; Note sig may also be nil for the last signal in the list
5866 (t
5867 (setq out-list
5868 (cons
5869 (list sv-name
5870 (or sv-busstring
5871 (if sv-highbit
5872 (concat "[" (int-to-string sv-highbit) ":"
5873 (int-to-string sv-lowbit) "]")))
5874 (concat sv-comment combo buswarn)
5875 sv-memory sv-enum sv-signed sv-type sv-multidim)
5876 out-list)
5877 sv-name nil))))
5878 ;;
5879 out-list))
5880
5881 (defun verilog-sig-tieoff (sig &optional no-width)
5882 "Return tieoff expression for given SIG, with appropriate width.
5883 Ignore width if optional NO-WIDTH is set."
5884 (let* ((width (if no-width nil (verilog-sig-width sig))))
5885 (concat
5886 (if (and verilog-active-low-regexp
5887 (string-match verilog-active-low-regexp (verilog-sig-name sig)))
5888 "~" "")
5889 (cond ((not width)
5890 "0")
5891 ((string-match "^[0-9]+$" width)
5892 (concat width (if (verilog-sig-signed sig) "'sh0" "'h0")))
5893 (t
5894 (concat "{" width "{1'b0}}"))))))
5895
5896 ;;
5897 ;; Port/Wire/Etc Reading
5898 ;;
5899
5900 (defun verilog-read-inst-backward-name ()
5901 "Internal. Move point back to beginning of inst-name."
5902 (verilog-backward-open-paren)
5903 (let (done)
5904 (while (not done)
5905 (verilog-re-search-backward-quick "\\()\\|\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil) ; ] isn't word boundary
5906 (cond ((looking-at ")")
5907 (verilog-backward-open-paren))
5908 (t (setq done t)))))
5909 (while (looking-at "\\]")
5910 (verilog-backward-open-bracket)
5911 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil))
5912 (skip-chars-backward "a-zA-Z0-9`_$"))
5913
5914 (defun verilog-read-inst-module ()
5915 "Return module_name when point is inside instantiation."
5916 (save-excursion
5917 (verilog-read-inst-backward-name)
5918 ;; Skip over instantiation name
5919 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil) ; ) isn't word boundary
5920 ;; Check for parameterized instantiations
5921 (when (looking-at ")")
5922 (verilog-backward-open-paren)
5923 (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil))
5924 (skip-chars-backward "a-zA-Z0-9'_$")
5925 (looking-at "[a-zA-Z0-9`_\$]+")
5926 ;; Important: don't use match string, this must work with emacs 19 font-lock on
5927 (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
5928
5929 (defun verilog-read-inst-name ()
5930 "Return instance_name when point is inside instantiation."
5931 (save-excursion
5932 (verilog-read-inst-backward-name)
5933 (looking-at "[a-zA-Z0-9`_\$]+")
5934 ;; Important: don't use match string, this must work with emacs 19 font-lock on
5935 (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
5936
5937 (defun verilog-read-module-name ()
5938 "Return module name when after its ( or ;."
5939 (save-excursion
5940 (re-search-backward "[(;]")
5941 (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil)
5942 (skip-chars-backward "a-zA-Z0-9`_$")
5943 (looking-at "[a-zA-Z0-9`_\$]+")
5944 ;; Important: don't use match string, this must work with emacs 19 font-lock on
5945 (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
5946
5947 (defun verilog-read-auto-params (num-param &optional max-param)
5948 "Return parameter list inside auto.
5949 Optional NUM-PARAM and MAX-PARAM check for a specific number of parameters."
5950 (let ((olist))
5951 (save-excursion
5952 ;; /*AUTOPUNT("parameter", "parameter")*/
5953 (search-backward "(")
5954 (while (looking-at "(?\\s *\"\\([^\"]*\\)\"\\s *,?")
5955 (setq olist (cons (match-string 1) olist))
5956 (goto-char (match-end 0))))
5957 (or (eq nil num-param)
5958 (<= num-param (length olist))
5959 (error "%s: Expected %d parameters" (verilog-point-text) num-param))
5960 (if (eq max-param nil) (setq max-param num-param))
5961 (or (eq nil max-param)
5962 (>= max-param (length olist))
5963 (error "%s: Expected <= %d parameters" (verilog-point-text) max-param))
5964 (nreverse olist)))
5965
5966 (defun verilog-read-decls ()
5967 "Compute signal declaration information for the current module at point.
5968 Return a array of [outputs inouts inputs wire reg assign const]."
5969 (let ((end-mod-point (or (verilog-get-end-of-defun t) (point-max)))
5970 (functask 0) (paren 0) (sig-paren 0)
5971 sigs-in sigs-out sigs-inout sigs-wire sigs-reg sigs-assign sigs-const sigs-gparam
5972 vec expect-signal keywd newsig rvalue enum io signed typedefed multidim)
5973 (save-excursion
5974 (verilog-beg-of-defun)
5975 (setq sigs-const (verilog-read-auto-constants (point) end-mod-point))
5976 (while (< (point) end-mod-point)
5977 ;;(if dbg (setq dbg (cons (format "Pt %s Vec %s Kwd'%s'\n" (point) vec keywd) dbg)))
5978 (cond
5979 ((looking-at "//")
5980 (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
5981 (setq enum (match-string 1)))
5982 (search-forward "\n"))
5983 ((looking-at "/\\*")
5984 (forward-char 2)
5985 (if (looking-at "[^*]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
5986 (setq enum (match-string 1)))
5987 (or (search-forward "*/")
5988 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
5989 ((looking-at "(\\*")
5990 (forward-char 2)
5991 (or (looking-at "\\s-*)") ; It's a "always @ (*)"
5992 (search-forward "*)")
5993 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
5994 ((eq ?\" (following-char))
5995 (or (re-search-forward "[^\\]\"" nil t) ;; don't forward-char first, since we look for a non backslash first
5996 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
5997 ((eq ?\; (following-char))
5998 (setq vec nil io nil expect-signal nil newsig nil paren 0 rvalue nil)
5999 (forward-char 1))
6000 ((eq ?= (following-char))
6001 (setq rvalue t newsig nil)
6002 (forward-char 1))
6003 ((and (or rvalue sig-paren)
6004 (cond ((and (eq ?, (following-char))
6005 (eq paren sig-paren))
6006 (setq rvalue nil)
6007 (forward-char 1)
6008 t)
6009 ;; ,'s can occur inside {} & funcs
6010 ((looking-at "[{(]")
6011 (setq paren (1+ paren))
6012 (forward-char 1)
6013 t)
6014 ((looking-at "[})]")
6015 (setq paren (1- paren))
6016 (forward-char 1)
6017 (when (< paren sig-paren)
6018 (setq expect-signal nil)) ; ) that ends variables inside v2k arg list
6019 t))))
6020 ((looking-at "\\s-*\\(\\[[^]]+\\]\\)")
6021 (goto-char (match-end 0))
6022 (cond (newsig ; Memory, not just width. Patch last signal added's memory (nth 3)
6023 (setcar (cdr (cdr (cdr newsig))) (match-string 1)))
6024 (vec ;; Multidimensional
6025 (setq multidim (cons vec multidim))
6026 (setq vec (verilog-string-replace-matches
6027 "\\s-+" "" nil nil (match-string 1))))
6028 (t ;; Bit width
6029 (setq vec (verilog-string-replace-matches
6030 "\\s-+" "" nil nil (match-string 1))))))
6031 ;; Normal or escaped identifier -- note we remember the \ if escaped
6032 ((looking-at "\\s-*\\([a-zA-Z0-9`_$]+\\|\\\\[^ \t\n\f]+\\)")
6033 (goto-char (match-end 0))
6034 (setq keywd (match-string 1))
6035 (when (string-match "^\\\\" keywd)
6036 (setq keywd (concat keywd " "))) ;; Escaped ID needs space at end
6037 (cond ((equal keywd "input")
6038 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
6039 expect-signal 'sigs-in io t))
6040 ((equal keywd "output")
6041 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
6042 expect-signal 'sigs-out io t))
6043 ((equal keywd "inout")
6044 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
6045 expect-signal 'sigs-inout io t))
6046 ((or (equal keywd "wire")
6047 (equal keywd "tri")
6048 (equal keywd "tri0")
6049 (equal keywd "tri1"))
6050 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
6051 expect-signal 'sigs-wire)))
6052 ((or (equal keywd "reg")
6053 (equal keywd "trireg"))
6054 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
6055 expect-signal 'sigs-reg)))
6056 ((equal keywd "assign")
6057 (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
6058 expect-signal 'sigs-assign))
6059 ((or (equal keywd "supply0")
6060 (equal keywd "supply1")
6061 (equal keywd "supply")
6062 (equal keywd "localparam"))
6063 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
6064 expect-signal 'sigs-const)))
6065 ((or (equal keywd "parameter"))
6066 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
6067 expect-signal 'sigs-gparam)))
6068 ((equal keywd "signed")
6069 (setq signed "signed"))
6070 ((or (equal keywd "function")
6071 (equal keywd "task"))
6072 (setq functask (1+ functask)))
6073 ((or (equal keywd "endfunction")
6074 (equal keywd "endtask"))
6075 (setq functask (1- functask)))
6076 ((or (equal keywd "`ifdef")
6077 (equal keywd "`ifndef"))
6078 (setq rvalue t))
6079 ((verilog-typedef-name-p keywd)
6080 (setq typedefed keywd))
6081 ((and expect-signal
6082 (eq functask 0)
6083 (not rvalue)
6084 (eq paren sig-paren)
6085 (not (member keywd verilog-keywords)))
6086 ;; Add new signal to expect-signal's variable
6087 (setq newsig (list keywd vec nil nil enum signed typedefed multidim))
6088 (set expect-signal (cons newsig
6089 (symbol-value expect-signal))))))
6090 (t
6091 (forward-char 1)))
6092 (skip-syntax-forward " "))
6093 ;; Return arguments
6094 (vector (nreverse sigs-out)
6095 (nreverse sigs-inout)
6096 (nreverse sigs-in)
6097 (nreverse sigs-wire)
6098 (nreverse sigs-reg)
6099 (nreverse sigs-assign)
6100 (nreverse sigs-const)
6101 (nreverse sigs-gparam)))))
6102
6103 (eval-when-compile
6104 ;; Prevent compile warnings; these are let's, not globals
6105 ;; Do not remove the eval-when-compile
6106 ;; - we want a error when we are debugging this code if they are refed.
6107 (defvar sigs-in)
6108 (defvar sigs-inout)
6109 (defvar sigs-out))
6110
6111
6112 (defsubst verilog-modi-get-decls (modi)
6113 (verilog-modi-cache-results modi 'verilog-read-decls))
6114
6115 (defsubst verilog-modi-get-sub-decls (modi)
6116 (verilog-modi-cache-results modi 'verilog-read-sub-decls))
6117
6118
6119 ;; Signal reading for given module
6120 ;; Note these all take modi's - as returned from the
6121 ;; verilog-modi-current function.
6122 (defsubst verilog-modi-get-outputs (modi)
6123 (aref (verilog-modi-get-decls modi) 0))
6124 (defsubst verilog-modi-get-inouts (modi)
6125 (aref (verilog-modi-get-decls modi) 1))
6126 (defsubst verilog-modi-get-inputs (modi)
6127 (aref (verilog-modi-get-decls modi) 2))
6128 (defsubst verilog-modi-get-wires (modi)
6129 (aref (verilog-modi-get-decls modi) 3))
6130 (defsubst verilog-modi-get-regs (modi)
6131 (aref (verilog-modi-get-decls modi) 4))
6132 (defsubst verilog-modi-get-assigns (modi)
6133 (aref (verilog-modi-get-decls modi) 5))
6134 (defsubst verilog-modi-get-consts (modi)
6135 (aref (verilog-modi-get-decls modi) 6))
6136 (defsubst verilog-modi-get-gparams (modi)
6137 (aref (verilog-modi-get-decls modi) 7))
6138 (defsubst verilog-modi-get-sub-outputs (modi)
6139 (aref (verilog-modi-get-sub-decls modi) 0))
6140 (defsubst verilog-modi-get-sub-inouts (modi)
6141 (aref (verilog-modi-get-sub-decls modi) 1))
6142 (defsubst verilog-modi-get-sub-inputs (modi)
6143 (aref (verilog-modi-get-sub-decls modi) 2))
6144
6145
6146 (defun verilog-read-sub-decls-sig (submodi comment port sig vec multidim)
6147 "For `verilog-read-sub-decls-line', add a signal."
6148 (let (portdata)
6149 (when sig
6150 (setq port (verilog-symbol-detick-denumber port))
6151 (setq sig (verilog-symbol-detick-denumber sig))
6152 (if sig (setq sig (verilog-string-replace-matches "^[---+~!|&]+" "" nil nil sig)))
6153 (if vec (setq vec (verilog-symbol-detick-denumber vec)))
6154 (if multidim (setq multidim (mapcar `verilog-symbol-detick-denumber multidim)))
6155 (unless (or (not sig)
6156 (equal sig "")) ;; Ignore .foo(1'b1) assignments
6157 (cond ((setq portdata (assoc port (verilog-modi-get-inouts submodi)))
6158 (setq sigs-inout (cons (list sig vec (concat "To/From " comment) nil nil
6159 (verilog-sig-signed portdata)
6160 (verilog-sig-type portdata)
6161 multidim)
6162 sigs-inout)))
6163 ((setq portdata (assoc port (verilog-modi-get-outputs submodi)))
6164 (setq sigs-out (cons (list sig vec (concat "From " comment) nil nil
6165 (verilog-sig-signed portdata)
6166 (verilog-sig-type portdata)
6167 multidim)
6168 sigs-out)))
6169 ((setq portdata (assoc port (verilog-modi-get-inputs submodi)))
6170 (setq sigs-in (cons (list sig vec (concat "To " comment) nil nil
6171 (verilog-sig-signed portdata)
6172 (verilog-sig-type portdata)
6173 multidim)
6174 sigs-in)))
6175 ;; (t -- warning pin isn't defined.) ; Leave for lint tool
6176 )))))
6177
6178 (defun verilog-read-sub-decls-line (submodi comment)
6179 "For `verilog-read-sub-decls', read lines of port defs until none match anymore.
6180 Return the list of signals found, using submodi to look up each port."
6181 (let (done port sig vec multidim)
6182 (save-excursion
6183 (forward-line 1)
6184 (while (not done)
6185 ;; Get port name
6186 (cond ((looking-at "\\s-*\\.\\s-*\\([a-zA-Z0-9`_$]*\\)\\s-*(\\s-*")
6187 (setq port (match-string 1))
6188 (goto-char (match-end 0)))
6189 ((looking-at "\\s-*\\.\\s-*\\(\\\\[^ \t\n\f]*\\)\\s-*(\\s-*")
6190 (setq port (concat (match-string 1) " ")) ;; escaped id's need trailing space
6191 (goto-char (match-end 0)))
6192 ((looking-at "\\s-*\\.[^(]*(")
6193 (setq port nil) ;; skip this line
6194 (goto-char (match-end 0)))
6195 (t
6196 (setq port nil done t))) ;; Unknown, ignore rest of line
6197 ;; Get signal name
6198 (when port
6199 (setq multidim nil)
6200 (cond ((looking-at "\\(\\\\[^ \t\n\f]*\\)\\s-*)")
6201 (setq sig (concat (match-string 1) " ") ;; escaped id's need trailing space
6202 vec nil))
6203 ; We intentionally ignore (non-escaped) signals with .s in them
6204 ; this prevents AUTOWIRE etc from noticing hierarchical sigs.
6205 ((looking-at "\\([^[({).]*\\)\\s-*)")
6206 (setq sig (verilog-string-remove-spaces (match-string 1))
6207 vec nil))
6208 ((looking-at "\\([^[({).]*\\)\\s-*\\(\\[[^]]+\\]\\)\\s-*)")
6209 (setq sig (verilog-string-remove-spaces (match-string 1))
6210 vec (match-string 2)))
6211 ((looking-at "\\([^[({).]*\\)\\s-*/\\*\\(\\[[^*]+\\]\\)\\*/\\s-*)")
6212 (setq sig (verilog-string-remove-spaces (match-string 1))
6213 vec nil)
6214 (let ((parse (match-string 2)))
6215 (while (string-match "^\\(\\[[^]]+\\]\\)\\(.*\\)$" parse)
6216 (when vec (setq multidim (cons vec multidim)))
6217 (setq vec (match-string 1 parse))
6218 (setq parse (match-string 2 parse)))))
6219 ((looking-at "{\\(.*\\)}.*\\s-*)")
6220 (let ((mlst (split-string (match-string 1) ","))
6221 mstr)
6222 (while (setq mstr (pop mlst))
6223 ;;(unless noninteractive (message "sig: %s " mstr))
6224 (cond
6225 ((string-match "\\(['`a-zA-Z0-9_$]+\\)\\s-*$" mstr)
6226 (setq sig (verilog-string-remove-spaces (match-string 1 mstr))
6227 vec nil)
6228 ;;(unless noninteractive (message "concat sig1: %s %s" mstr (match-string 1 mstr)))
6229 )
6230 ((string-match "\\([^[({).]+\\)\\s-*\\(\\[[^]]+\\]\\)\\s-*" mstr)
6231 (setq sig (verilog-string-remove-spaces (match-string 1 mstr))
6232 vec (match-string 2 mstr))
6233 ;;(unless noninteractive (message "concat sig2: '%s' '%s' '%s'" mstr (match-string 1 mstr) (match-string 2 mstr)))
6234 )
6235 (t
6236 (setq sig nil)))
6237 ;; Process signals
6238 (verilog-read-sub-decls-sig submodi comment port sig vec multidim))))
6239 (t
6240 (setq sig nil)))
6241 ;; Process signals
6242 (verilog-read-sub-decls-sig submodi comment port sig vec multidim))
6243 ;;
6244 (forward-line 1)))))
6245
6246 (defun verilog-read-sub-decls ()
6247 "Internally parse signals going to modules under this module.
6248 Return a array of [ outputs inouts inputs ] signals for modules that are
6249 instantiated in this module. For example if declare A A (.B(SIG)) and SIG
6250 is a output, then SIG will be included in the list.
6251
6252 This only works on instantiations created with /*AUTOINST*/ converted by
6253 \\[verilog-auto-inst]. Otherwise, it would have to read in the whole
6254 component library to determine connectivity of the design.
6255
6256 One work around for this problem is to manually create // Inputs and //
6257 Outputs comments above subcell signals, for example:
6258
6259 module1 instance1x (
6260 // Outputs
6261 .out (out),
6262 // Inputs
6263 .in (in));"
6264 (save-excursion
6265 (let ((end-mod-point (verilog-get-end-of-defun t))
6266 st-point end-inst-point
6267 ;; below 3 modified by verilog-read-sub-decls-line
6268 sigs-out sigs-inout sigs-in)
6269 (verilog-beg-of-defun)
6270 (while (re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-mod-point t)
6271 (save-excursion
6272 (goto-char (match-beginning 0))
6273 (unless (verilog-inside-comment-p)
6274 ;; Attempt to snarf a comment
6275 (let* ((submod (verilog-read-inst-module))
6276 (inst (verilog-read-inst-name))
6277 (comment (concat inst " of " submod ".v")) submodi)
6278 (when (setq submodi (verilog-modi-lookup submod t))
6279 ;; This could have used a list created by verilog-auto-inst
6280 ;; However I want it to be runnable even on user's manually added signals
6281 (verilog-backward-open-paren)
6282 (setq end-inst-point (save-excursion (forward-sexp 1) (point))
6283 st-point (point))
6284 (while (re-search-forward "\\s *(?\\s *// Outputs" end-inst-point t)
6285 (verilog-read-sub-decls-line submodi comment)) ;; Modifies sigs-out
6286 (goto-char st-point)
6287 (while (re-search-forward "\\s *// Inouts" end-inst-point t)
6288 (verilog-read-sub-decls-line submodi comment)) ;; Modifies sigs-inout
6289 (goto-char st-point)
6290 (while (re-search-forward "\\s *// Inputs" end-inst-point t)
6291 (verilog-read-sub-decls-line submodi comment)) ;; Modifies sigs-in
6292 )))))
6293 ;; Combine duplicate bits
6294 ;;(setq rr (vector sigs-out sigs-inout sigs-in))
6295 (vector (verilog-signals-combine-bus (nreverse sigs-out))
6296 (verilog-signals-combine-bus (nreverse sigs-inout))
6297 (verilog-signals-combine-bus (nreverse sigs-in))))))
6298
6299 (defun verilog-read-inst-pins ()
6300 "Return an array of [ pins ] for the current instantiation at point.
6301 For example if declare A A (.B(SIG)) then B will be included in the list."
6302 (save-excursion
6303 (let ((end-mod-point (point)) ;; presume at /*AUTOINST*/ point
6304 pins pin)
6305 (verilog-backward-open-paren)
6306 (while (re-search-forward "\\.\\([^(,) \t\n\f]*\\)\\s-*" end-mod-point t)
6307 (setq pin (match-string 1))
6308 (unless (verilog-inside-comment-p)
6309 (setq pins (cons (list pin) pins))
6310 (when (looking-at "(")
6311 (forward-sexp 1))))
6312 (vector pins))))
6313
6314 (defun verilog-read-arg-pins ()
6315 "Return an array of [ pins ] for the current argument declaration at point."
6316 (save-excursion
6317 (let ((end-mod-point (point)) ;; presume at /*AUTOARG*/ point
6318 pins pin)
6319 (verilog-backward-open-paren)
6320 (while (re-search-forward "\\([a-zA-Z0-9$_.%`]+\\)" end-mod-point t)
6321 (setq pin (match-string 1))
6322 (unless (verilog-inside-comment-p)
6323 (setq pins (cons (list pin) pins))))
6324 (vector pins))))
6325
6326 (defun verilog-read-auto-constants (beg end-mod-point)
6327 "Return a list of AUTO_CONSTANTs used in the region from BEG to END-MOD-POINT."
6328 ;; Insert new
6329 (save-excursion
6330 (let (sig-list tpl-end-pt)
6331 (goto-char beg)
6332 (while (re-search-forward "\\<AUTO_CONSTANT" end-mod-point t)
6333 (if (not (looking-at "\\s *("))
6334 (error "%s: Missing () after AUTO_CONSTANT" (verilog-point-text)))
6335 (search-forward "(" end-mod-point)
6336 (setq tpl-end-pt (save-excursion
6337 (backward-char 1)
6338 (forward-sexp 1) ;; Moves to paren that closes argdecl's
6339 (backward-char 1)
6340 (point)))
6341 (while (re-search-forward "\\s-*\\([\"a-zA-Z0-9$_.%`]+\\)\\s-*,*" tpl-end-pt t)
6342 (setq sig-list (cons (list (match-string 1) nil nil) sig-list))))
6343 sig-list)))
6344
6345 (defun verilog-read-auto-lisp (start end)
6346 "Look for and evaluate a AUTO_LISP between START and END."
6347 (save-excursion
6348 (goto-char start)
6349 (while (re-search-forward "\\<AUTO_LISP(" end t)
6350 (backward-char)
6351 (let* ((beg-pt (prog1 (point)
6352 (forward-sexp 1))) ;; Closing paren
6353 (end-pt (point)))
6354 (eval-region beg-pt end-pt nil)))))
6355
6356 (eval-when-compile
6357 ;; Prevent compile warnings; these are let's, not globals
6358 ;; Do not remove the eval-when-compile
6359 ;; - we want a error when we are debugging this code if they are refed.
6360 (defvar sigs-in)
6361 (defvar sigs-out)
6362 (defvar got-sig)
6363 (defvar got-rvalue)
6364 (defvar uses-delayed)
6365 (defvar vector-skip-list))
6366
6367 (defun verilog-read-always-signals-recurse
6368 (exit-keywd rvalue ignore-next)
6369 "Recursive routine for parentheses/bracket matching.
6370 EXIT-KEYWD is expression to stop at, nil if top level.
6371 RVALUE is true if at right hand side of equal.
6372 IGNORE-NEXT is true to ignore next token, fake from inside case statement."
6373 (let* ((semi-rvalue (equal "endcase" exit-keywd)) ;; true if after a ; we are looking for rvalue
6374 keywd last-keywd sig-tolk sig-last-tolk gotend got-sig got-rvalue end-else-check)
6375 ;;(if dbg (setq dbg (concat dbg (format "Recursion %S %S %S\n" exit-keywd rvalue ignore-next))))
6376 (while (not (or (eobp) gotend))
6377 (cond
6378 ((looking-at "//")
6379 (search-forward "\n"))
6380 ((looking-at "/\\*")
6381 (or (search-forward "*/")
6382 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
6383 ((looking-at "(\\*")
6384 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
6385 (search-forward "*)")
6386 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
6387 (t (setq keywd (buffer-substring-no-properties
6388 (point)
6389 (save-excursion (when (eq 0 (skip-chars-forward "a-zA-Z0-9$_.%`"))
6390 (forward-char 1))
6391 (point)))
6392 sig-last-tolk sig-tolk
6393 sig-tolk nil)
6394 ;;(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))))
6395 (cond
6396 ((equal keywd "\"")
6397 (or (re-search-forward "[^\\]\"" nil t)
6398 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
6399 ;; else at top level loop, keep parsing
6400 ((and end-else-check (equal keywd "else"))
6401 ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else %s\n" keywd))))
6402 ;; no forward movement, want to see else in lower loop
6403 (setq end-else-check nil))
6404 ;; End at top level loop
6405 ((and end-else-check (looking-at "[^ \t\n\f]"))
6406 ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else-other %s\n" keywd))))
6407 (setq gotend t))
6408 ;; Final statement?
6409 ((and exit-keywd (equal keywd exit-keywd))
6410 (setq gotend t)
6411 (forward-char (length keywd)))
6412 ;; Standard tokens...
6413 ((equal keywd ";")
6414 (setq ignore-next nil rvalue semi-rvalue)
6415 ;; Final statement at top level loop?
6416 (when (not exit-keywd)
6417 ;;(if dbg (setq dbg (concat dbg (format "\ttop-end-check %s\n" keywd))))
6418 (setq end-else-check t))
6419 (forward-char 1))
6420 ((equal keywd "'")
6421 (if (looking-at "'s?[hdxbo][0-9a-fA-F_xz? \t]*")
6422 (goto-char (match-end 0))
6423 (forward-char 1)))
6424 ((equal keywd ":") ;; Case statement, begin/end label, x?y:z
6425 (cond ((equal "endcase" exit-keywd) ;; case x: y=z; statement next
6426 (setq ignore-next nil rvalue nil))
6427 ((equal "?" exit-keywd) ;; x?y:z rvalue
6428 ) ;; NOP
6429 (got-sig ;; label: statement
6430 (setq ignore-next nil rvalue semi-rvalue got-sig nil))
6431 ((not rvalue) ;; begin label
6432 (setq ignore-next t rvalue nil)))
6433 (forward-char 1))
6434 ((equal keywd "=")
6435 (if (eq (char-before) ?< )
6436 (setq uses-delayed 1))
6437 (setq ignore-next nil rvalue t)
6438 (forward-char 1))
6439 ((equal keywd "?")
6440 (forward-char 1)
6441 (verilog-read-always-signals-recurse ":" rvalue nil))
6442 ((equal keywd "[")
6443 (forward-char 1)
6444 (verilog-read-always-signals-recurse "]" t nil))
6445 ((equal keywd "(")
6446 (forward-char 1)
6447 (cond (sig-last-tolk ;; Function call; zap last signal
6448 (setq got-sig nil)))
6449 (cond ((equal last-keywd "for")
6450 (verilog-read-always-signals-recurse ";" nil nil)
6451 (verilog-read-always-signals-recurse ";" t nil)
6452 (verilog-read-always-signals-recurse ")" nil nil))
6453 (t (verilog-read-always-signals-recurse ")" t nil))))
6454 ((equal keywd "begin")
6455 (skip-syntax-forward "w_")
6456 (verilog-read-always-signals-recurse "end" nil nil)
6457 ;;(if dbg (setq dbg (concat dbg (format "\tgot-end %s\n" exit-keywd))))
6458 (setq ignore-next nil rvalue semi-rvalue)
6459 (if (not exit-keywd) (setq end-else-check t)))
6460 ((or (equal keywd "case")
6461 (equal keywd "casex")
6462 (equal keywd "casez"))
6463 (skip-syntax-forward "w_")
6464 (verilog-read-always-signals-recurse "endcase" t nil)
6465 (setq ignore-next nil rvalue semi-rvalue)
6466 (if (not exit-keywd) (setq gotend t))) ;; top level begin/end
6467 ((string-match "^[$`a-zA-Z_]" keywd) ;; not exactly word constituent
6468 (cond ((or (equal keywd "`ifdef")
6469 (equal keywd "`ifndef"))
6470 (setq ignore-next t))
6471 ((or ignore-next
6472 (member keywd verilog-keywords)
6473 (string-match "^\\$" keywd)) ;; PLI task
6474 (setq ignore-next nil))
6475 (t
6476 (setq keywd (verilog-symbol-detick-denumber keywd))
6477 (when got-sig
6478 (if got-rvalue (setq sigs-in (cons got-sig sigs-in))
6479 (setq sigs-out (cons got-sig sigs-out)))
6480 ;;(if dbg (setq dbg (concat dbg (format "\t\tgot-sig=%S rv=%S\n" got-sig got-rvalue))))
6481 )
6482 (setq got-rvalue rvalue
6483 got-sig (if (or (not keywd)
6484 (assoc keywd (if got-rvalue sigs-in sigs-out)))
6485 nil (list keywd nil nil))
6486 sig-tolk t)))
6487 (skip-chars-forward "a-zA-Z0-9$_.%`"))
6488 (t
6489 (forward-char 1)))
6490 ;; End of non-comment token
6491 (setq last-keywd keywd)))
6492 (skip-syntax-forward " "))
6493 ;; Append the final pending signal
6494 (when got-sig
6495 (if got-rvalue (setq sigs-in (cons got-sig sigs-in))
6496 (setq sigs-out (cons got-sig sigs-out)))
6497 ;;(if dbg (setq dbg (concat dbg (format "\t\tgot-sig=%S rv=%S\n" got-sig got-rvalue))))
6498 (setq got-sig nil))
6499 ;;(if dbg (setq dbg (concat dbg (format "ENDRecursion %s\n" exit-keywd))))
6500 ))
6501
6502 (defun verilog-read-always-signals ()
6503 "Parse always block at point and return list of (outputs inout inputs)."
6504 ;; Insert new
6505 (save-excursion
6506 (let* (;;(dbg "")
6507 sigs-in sigs-out
6508 uses-delayed) ;; Found signal/rvalue; push if not function
6509 (search-forward ")")
6510 (verilog-read-always-signals-recurse nil nil nil)
6511 ;;(if dbg (save-excursion (set-buffer (get-buffer-create "*vl-dbg*")) (delete-region (point-min) (point-max)) (insert dbg) (setq dbg "")))
6512 ;; Return what was found
6513 (list sigs-out nil sigs-in uses-delayed))))
6514
6515 (defun verilog-read-instants ()
6516 "Parse module at point and return list of ( ( file instance ) ... )."
6517 (verilog-beg-of-defun)
6518 (let* ((end-mod-point (verilog-get-end-of-defun t))
6519 (state nil)
6520 (instants-list nil))
6521 (save-excursion
6522 (while (< (point) end-mod-point)
6523 ;; Stay at level 0, no comments
6524 (while (progn
6525 (setq state (parse-partial-sexp (point) end-mod-point 0 t nil))
6526 (or (> (car state) 0) ; in parens
6527 (nth 5 state) ; comment
6528 ))
6529 (forward-line 1))
6530 (beginning-of-line)
6531 (if (looking-at "^\\s-*\\([a-zA-Z0-9`_$]+\\)\\s-+\\([a-zA-Z0-9`_$]+\\)\\s-*(")
6532 ;;(if (looking-at "^\\(.+\\)$")
6533 (let ((module (match-string 1))
6534 (instant (match-string 2)))
6535 (if (not (member module verilog-keywords))
6536 (setq instants-list (cons (list module instant) instants-list)))))
6537 (forward-line 1)))
6538 instants-list))
6539
6540
6541 (defun verilog-read-auto-template (module)
6542 "Look for a auto_template for the instantiation of the given MODULE.
6543 If found returns the signal name connections. Return REGEXP and
6544 list of ( (signal_name connection_name)... )."
6545 (save-excursion
6546 ;; Find beginning
6547 (let ((tpl-regexp "\\([0-9]+\\)")
6548 (lineno 0)
6549 (templateno 0)
6550 tpl-sig-list tpl-wild-list tpl-end-pt rep)
6551 (cond ((or
6552 (re-search-backward (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)
6553 (progn
6554 (goto-char (point-min))
6555 (re-search-forward (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)))
6556 (goto-char (match-end 0))
6557 ;; Parse "REGEXP"
6558 ;; We reserve @"..." for future lisp expressions that evaluate once-per-AUTOINST
6559 (when (looking-at "\\s-*\"\\([^\"]*)\\)\"")
6560 (setq tpl-regexp (match-string 1))
6561 (goto-char (match-end 0)))
6562 (search-forward "(")
6563 ;; Parse lines in the template
6564 (when verilog-auto-inst-template-numbers
6565 (save-excursion
6566 (goto-char (point-min))
6567 (while (search-forward "AUTO_TEMPLATE" nil t)
6568 (setq templateno (1+ templateno)))))
6569 (setq tpl-end-pt (save-excursion
6570 (backward-char 1)
6571 (forward-sexp 1) ;; Moves to paren that closes argdecl's
6572 (backward-char 1)
6573 (point)))
6574 ;;
6575 (while (< (point) tpl-end-pt)
6576 (cond ((looking-at "\\s-*\\.\\([a-zA-Z0-9`_$]+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
6577 (setq tpl-sig-list (cons (list
6578 (match-string-no-properties 1)
6579 (match-string-no-properties 2)
6580 templateno lineno)
6581 tpl-sig-list))
6582 (goto-char (match-end 0)))
6583 ;; Regexp form??
6584 ((looking-at
6585 ;; Regexp bug in xemacs disallows ][ inside [], and wants + last
6586 "\\s-*\\.\\(\\([a-zA-Z0-9`_$+@^.*?|---]+\\|[][]\\|\\\\[()|]\\)+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
6587 (setq rep (match-string-no-properties 3))
6588 (goto-char (match-end 0))
6589 (setq tpl-wild-list
6590 (cons (list
6591 (concat "^"
6592 (verilog-string-replace-matches "@" "\\\\([0-9]+\\\\)" nil nil
6593 (match-string 1))
6594 "$")
6595 rep
6596 templateno lineno)
6597 tpl-wild-list)))
6598 ((looking-at "[ \t\f]+")
6599 (goto-char (match-end 0)))
6600 ((looking-at "\n")
6601 (setq lineno (1+ lineno))
6602 (goto-char (match-end 0)))
6603 ((looking-at "//")
6604 (search-forward "\n"))
6605 ((looking-at "/\\*")
6606 (forward-char 2)
6607 (or (search-forward "*/")
6608 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
6609 (t
6610 (error "%s: AUTO_TEMPLATE parsing error: %s"
6611 (verilog-point-text)
6612 (progn (looking-at ".*$") (match-string 0))))))
6613 ;; Return
6614 (vector tpl-regexp
6615 (list tpl-sig-list tpl-wild-list)))
6616 ;; If no template found
6617 (t (vector tpl-regexp nil))))))
6618 ;;(progn (find-file "auto-template.v") (verilog-read-auto-template "ptl_entry"))
6619
6620 (defun verilog-set-define (defname defvalue &optional buffer enumname)
6621 "Set the definition DEFNAME to the DEFVALUE in the given BUFFER.
6622 Optionally associate it with the specified enumeration ENUMNAME."
6623 (save-excursion
6624 (set-buffer (or buffer (current-buffer)))
6625 (let ((mac (intern (concat "vh-" defname))))
6626 ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
6627 ;; Need to define to a constant if no value given
6628 (set (make-variable-buffer-local mac)
6629 (if (equal defvalue "") "1" defvalue)))
6630 (if enumname
6631 (let ((enumvar (intern (concat "venum-" enumname))))
6632 ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
6633 (make-variable-buffer-local enumvar)
6634 (add-to-list enumvar defname)))))
6635
6636 (defun verilog-read-defines (&optional filename recurse subcall)
6637 "Read `defines and parameters for the current file, or optional FILENAME.
6638 If the filename is provided, `verilog-library-flags' will be used to
6639 resolve it. If optional RECURSE is non-nil, recurse through `includes.
6640
6641 Parameters must be simple assignments to constants, or have their own
6642 \"parameter\" label rather than a list of parameters. Thus:
6643
6644 parameter X = 5, Y = 10; // Ok
6645 parameter X = {1'b1, 2'h2}; // Ok
6646 parameter X = {1'b1, 2'h2}, Y = 10; // Bad, make into 2 parameter lines
6647
6648 Defines must be simple text substitutions, one on a line, starting
6649 at the beginning of the line. Any ifdefs or multiline comments around the
6650 define are ignored.
6651
6652 Defines are stored inside Emacs variables using the name vh-{definename}.
6653
6654 This function is useful for setting vh-* variables. The file variables
6655 feature can be used to set defines that `verilog-mode' can see; put at the
6656 *END* of your file something like:
6657
6658 // Local Variables:
6659 // vh-macro:\"macro_definition\"
6660 // End:
6661
6662 If macros are defined earlier in the same file and you want their values,
6663 you can read them automatically (provided `enable-local-eval' is on):
6664
6665 // Local Variables:
6666 // eval:(verilog-read-defines)
6667 // eval:(verilog-read-defines \"group_standard_includes.v\")
6668 // End:
6669
6670 Note these are only read when the file is first visited, you must use
6671 \\[find-alternate-file] RET to have these take effect after editing them!
6672
6673 If you want to disable the \"Process `eval' or hook local variables\"
6674 warning message, you need to add to your .emacs file:
6675
6676 (setq enable-local-eval t)"
6677 (let ((origbuf (current-buffer)))
6678 (save-excursion
6679 (unless subcall (verilog-getopt-flags))
6680 (when filename
6681 (let ((fns (verilog-library-filenames filename (buffer-file-name))))
6682 (if fns
6683 (set-buffer (find-file-noselect (car fns)))
6684 (error (concat (verilog-point-text)
6685 ": Can't find verilog-read-defines file: " filename)))))
6686 (when recurse
6687 (goto-char (point-min))
6688 (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
6689 (let ((inc (verilog-string-replace-matches "\"" "" nil nil (match-string-no-properties 1))))
6690 (unless (verilog-inside-comment-p)
6691 (verilog-read-defines inc recurse t)))))
6692 ;; Read `defines
6693 ;; note we don't use verilog-re... it's faster this way, and that
6694 ;; function has problems when comments are at the end of the define
6695 (goto-char (point-min))
6696 (while (re-search-forward "^\\s-*`define\\s-+\\([a-zA-Z0-9_$]+\\)\\s-+\\(.*\\)$" nil t)
6697 (let ((defname (match-string-no-properties 1))
6698 (defvalue (match-string-no-properties 2)))
6699 (setq defvalue (verilog-string-replace-matches "\\s-*/[/*].*$" "" nil nil defvalue))
6700 (verilog-set-define defname defvalue origbuf)))
6701 ;; Hack: Read parameters
6702 (goto-char (point-min))
6703 (while (re-search-forward
6704 "^\\s-*\\(parameter\\|localparam\\)\\(\\(\\s-*\\[[^]]*\\]\\|\\)\\s-+\\([a-zA-Z0-9_$]+\\)\\s-*=\\s-*\\([^;,]*\\),?\\|\\)\\s-*" nil t)
6705 (let ((var (match-string-no-properties 4))
6706 (val (match-string-no-properties 5))
6707 enumname)
6708 ;; The primary way of getting defines is verilog-read-decls
6709 ;; However, that isn't called yet for included files, so we'll add another scheme
6710 (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
6711 (setq enumname (match-string-no-properties 1)))
6712 (if var
6713 (verilog-set-define var val origbuf enumname))
6714 (forward-comment 999)
6715 (while (looking-at "\\s-*,?\\s-*\\([a-zA-Z0-9_$]+\\)\\s-*=\\s-*\\([^;,]*\\),?\\s-*")
6716 (verilog-set-define (match-string-no-properties 1) (match-string-no-properties 2) origbuf enumname)
6717 (goto-char (match-end 0))
6718 (forward-comment 999)))))))
6719
6720 (defun verilog-read-includes ()
6721 "Read `includes for the current file.
6722 This will find all of the `includes which are at the beginning of lines,
6723 ignoring any ifdefs or multiline comments around them.
6724 `verilog-read-defines' is then performed on the current and each included
6725 file.
6726
6727 It is often useful put at the *END* of your file something like:
6728
6729 // Local Variables:
6730 // eval:(verilog-read-defines)
6731 // eval:(verilog-read-includes)
6732 // End:
6733
6734 Note includes are only read when the file is first visited, you must use
6735 \\[find-alternate-file] RET to have these take effect after editing them!
6736
6737 It is good to get in the habit of including all needed files in each .v
6738 file that needs it, rather than waiting for compile time. This will aid
6739 this process, Verilint, and readability. To prevent defining the same
6740 variable over and over when many modules are compiled together, put a test
6741 around the inside each include file:
6742
6743 foo.v (a include):
6744 `ifdef _FOO_V // include if not already included
6745 `else
6746 `define _FOO_V
6747 ... contents of file
6748 `endif // _FOO_V"
6749 ;;slow: (verilog-read-defines nil t))
6750 (save-excursion
6751 (verilog-getopt-flags)
6752 (goto-char (point-min))
6753 (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
6754 (let ((inc (verilog-string-replace-matches "\"" "" nil nil (match-string 1))))
6755 (verilog-read-defines inc nil t)))))
6756
6757 (defun verilog-read-signals (&optional start end)
6758 "Return a simple list of all possible signals in the file.
6759 Bounded by optional region from START to END. Overly aggressive but fast.
6760 Some macros and such are also found and included. For dinotrace.el."
6761 (let (sigs-all keywd)
6762 (progn;save-excursion
6763 (goto-char (or start (point-min)))
6764 (setq end (or end (point-max)))
6765 (while (re-search-forward "[\"/a-zA-Z_.%`]" end t)
6766 (forward-char -1)
6767 (cond
6768 ((looking-at "//")
6769 (search-forward "\n"))
6770 ((looking-at "/\\*")
6771 (search-forward "*/"))
6772 ((looking-at "(\\*")
6773 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
6774 (search-forward "*)")))
6775 ((eq ?\" (following-char))
6776 (re-search-forward "[^\\]\"")) ;; don't forward-char first, since we look for a non backslash first
6777 ((looking-at "\\s-*\\([a-zA-Z0-9$_.%`]+\\)")
6778 (goto-char (match-end 0))
6779 (setq keywd (match-string-no-properties 1))
6780 (or (member keywd verilog-keywords)
6781 (member keywd sigs-all)
6782 (setq sigs-all (cons keywd sigs-all))))
6783 (t (forward-char 1))))
6784 ;; Return list
6785 sigs-all)))
6786
6787 ;;
6788 ;; Argument file parsing
6789 ;;
6790
6791 (defun verilog-getopt (arglist)
6792 "Parse -f, -v etc arguments in ARGLIST list or string."
6793 (unless (listp arglist) (setq arglist (list arglist)))
6794 (let ((space-args '())
6795 arg next-param)
6796 ;; Split on spaces, so users can pass whole command lines
6797 (while arglist
6798 (setq arg (car arglist)
6799 arglist (cdr arglist))
6800 (while (string-match "^\\([^ \t\n\f]+\\)[ \t\n\f]*\\(.*$\\)" arg)
6801 (setq space-args (append space-args
6802 (list (match-string-no-properties 1 arg))))
6803 (setq arg (match-string 2 arg))))
6804 ;; Parse arguments
6805 (while space-args
6806 (setq arg (car space-args)
6807 space-args (cdr space-args))
6808 (cond
6809 ;; Need another arg
6810 ((equal arg "-f")
6811 (setq next-param arg))
6812 ((equal arg "-v")
6813 (setq next-param arg))
6814 ((equal arg "-y")
6815 (setq next-param arg))
6816 ;; +libext+(ext1)+(ext2)...
6817 ((string-match "^\\+libext\\+\\(.*\\)" arg)
6818 (setq arg (match-string 1 arg))
6819 (while (string-match "\\([^+]+\\)\\+?\\(.*\\)" arg)
6820 (verilog-add-list-unique `verilog-library-extensions
6821 (match-string 1 arg))
6822 (setq arg (match-string 2 arg))))
6823 ;;
6824 ((or (string-match "^-D\\([^+=]*\\)[+=]\\(.*\\)" arg) ;; -Ddefine=val
6825 (string-match "^-D\\([^+=]*\\)\\(\\)" arg) ;; -Ddefine
6826 (string-match "^\\+define\\([^+=]*\\)[+=]\\(.*\\)" arg) ;; +define+val
6827 (string-match "^\\+define\\([^+=]*\\)\\(\\)" arg)) ;; +define+define
6828 (verilog-set-define (match-string 1 arg) (match-string 2 arg)))
6829 ;;
6830 ((or (string-match "^\\+incdir\\+\\(.*\\)" arg) ;; +incdir+dir
6831 (string-match "^-I\\(.*\\)" arg)) ;; -Idir
6832 (verilog-add-list-unique `verilog-library-directories
6833 (match-string 1 arg)))
6834 ;; Ignore
6835 ((equal "+librescan" arg))
6836 ((string-match "^-U\\(.*\\)" arg)) ;; -Udefine
6837 ;; Second parameters
6838 ((equal next-param "-f")
6839 (setq next-param nil)
6840 (verilog-getopt-file arg))
6841 ((equal next-param "-v")
6842 (setq next-param nil)
6843 (verilog-add-list-unique `verilog-library-files arg))
6844 ((equal next-param "-y")
6845 (setq next-param nil)
6846 (verilog-add-list-unique `verilog-library-directories arg))
6847 ;; Filename
6848 ((string-match "^[^-+]" arg)
6849 (verilog-add-list-unique `verilog-library-files arg))
6850 ;; Default - ignore; no warning
6851 ))))
6852 ;;(verilog-getopt (list "+libext+.a+.b" "+incdir+foodir" "+define+a+aval" "-f" "otherf" "-v" "library" "-y" "dir"))
6853
6854 (defun verilog-getopt-file (filename)
6855 "Read Verilog options from the specified FILENAME."
6856 (save-excursion
6857 (let ((fns (verilog-library-filenames filename (buffer-file-name)))
6858 (orig-buffer (current-buffer))
6859 line)
6860 (if fns
6861 (set-buffer (find-file-noselect (car fns)))
6862 (error (concat (verilog-point-text)
6863 "Can't find verilog-getopt-file -f file: " filename)))
6864 (goto-char (point-min))
6865 (while (not (eobp))
6866 (setq line (buffer-substring (point)
6867 (save-excursion (end-of-line) (point))))
6868 (forward-line 1)
6869 (when (string-match "//" line)
6870 (setq line (substring line 0 (match-beginning 0))))
6871 (save-excursion
6872 (set-buffer orig-buffer) ; Variables are buffer-local, so need right context.
6873 (verilog-getopt line))))))
6874
6875 (defun verilog-getopt-flags ()
6876 "Convert `verilog-library-flags' into standard library variables."
6877 ;; If the flags are local, then all the outputs should be local also
6878 (when (local-variable-p `verilog-library-flags (current-buffer))
6879 (mapc 'make-local-variable '(verilog-library-extensions
6880 verilog-library-directories
6881 verilog-library-files
6882 verilog-library-flags)))
6883 ;; Allow user to customize
6884 (run-hooks 'verilog-before-getopt-flags-hook)
6885 ;; Process arguments
6886 (verilog-getopt verilog-library-flags)
6887 ;; Allow user to customize
6888 (run-hooks 'verilog-getopt-flags-hook))
6889
6890 (defun verilog-add-list-unique (varref object)
6891 "Append to VARREF list the given OBJECT,
6892 unless it is already a member of the variable's list."
6893 (unless (member object (symbol-value varref))
6894 (set varref (append (symbol-value varref) (list object))))
6895 varref)
6896 ;;(progn (setq l '()) (verilog-add-list-unique `l "a") (verilog-add-list-unique `l "a") l)
6897
6898 \f
6899 ;;
6900 ;; Module name lookup
6901 ;;
6902
6903 (defun verilog-module-inside-filename-p (module filename)
6904 "Return point if MODULE is specified inside FILENAME, else nil.
6905 Allows version control to check out the file if need be."
6906 (and (or (file-exists-p filename)
6907 (and (fboundp 'vc-backend)
6908 (vc-backend filename)))
6909 (let (pt)
6910 (save-excursion
6911 (set-buffer (find-file-noselect filename))
6912 (goto-char (point-min))
6913 (while (and
6914 ;; It may be tempting to look for verilog-defun-re, don't, it slows things down a lot!
6915 (verilog-re-search-forward-quick "\\<module\\>" nil t)
6916 (verilog-re-search-forward-quick "[(;]" nil t))
6917 (if (equal module (verilog-read-module-name))
6918 (setq pt (point))))
6919 pt))))
6920
6921 (defun verilog-is-number (symbol)
6922 "Return true if SYMBOL is number-like."
6923 (or (string-match "^[0-9 \t:]+$" symbol)
6924 (string-match "^[---]*[0-9]+$" symbol)
6925 (string-match "^[0-9 \t]+'s?[hdxbo][0-9a-fA-F_xz? \t]*$" symbol)))
6926
6927 (defun verilog-symbol-detick (symbol wing-it)
6928 "Return an expanded SYMBOL name without any defines.
6929 If the variable vh-{symbol} is defined, return that value.
6930 If undefined, and WING-IT, return just SYMBOL without the tick, else nil."
6931 (while (and symbol (string-match "^`" symbol))
6932 (setq symbol (substring symbol 1))
6933 (setq symbol
6934 (if (boundp (intern (concat "vh-" symbol)))
6935 ;; Emacs has a bug where boundp on a buffer-local
6936 ;; variable in only one buffer returns t in another.
6937 ;; This can confuse, so check for nil.
6938 (let ((val (eval (intern (concat "vh-" symbol)))))
6939 (if (eq val nil)
6940 (if wing-it symbol nil)
6941 val))
6942 (if wing-it symbol nil))))
6943 symbol)
6944 ;;(verilog-symbol-detick "`mod" nil)
6945
6946 (defun verilog-symbol-detick-denumber (symbol)
6947 "Return SYMBOL with defines converted and any numbers dropped to nil."
6948 (when (string-match "^`" symbol)
6949 ;; This only will work if the define is a simple signal, not
6950 ;; something like a[b]. Sorry, it should be substituted into the parser
6951 (setq symbol
6952 (verilog-string-replace-matches
6953 "\[[^0-9: \t]+\]" "" nil nil
6954 (or (verilog-symbol-detick symbol nil)
6955 (if verilog-auto-sense-defines-constant
6956 "0"
6957 symbol)))))
6958 (if (verilog-is-number symbol)
6959 nil
6960 symbol))
6961
6962 (defun verilog-symbol-detick-text (text)
6963 "Return TEXT without any known defines.
6964 If the variable vh-{symbol} is defined, substitute that value."
6965 (let ((ok t) symbol val)
6966 (while (and ok (string-match "`\\([a-zA-Z0-9_]+\\)" text))
6967 (setq symbol (match-string 1 text))
6968 (message symbol)
6969 (cond ((and
6970 (boundp (intern (concat "vh-" symbol)))
6971 ;; Emacs has a bug where boundp on a buffer-local
6972 ;; variable in only one buffer returns t in another.
6973 ;; This can confuse, so check for nil.
6974 (setq val (eval (intern (concat "vh-" symbol)))))
6975 (setq text (replace-match val nil nil text)))
6976 (t (setq ok nil)))))
6977 text)
6978 ;;(progn (setq vh-mod "`foo" vh-foo "bar") (verilog-symbol-detick-text "bar `mod `undefed"))
6979
6980 (defun verilog-expand-dirnames (&optional dirnames)
6981 "Return a list of existing directories given a list of wildcarded DIRNAMES.
6982 Or, just the existing dirnames themselves if there are no wildcards."
6983 (interactive)
6984 (unless dirnames (error "`verilog-library-directories' should include at least '.'"))
6985 (setq dirnames (reverse dirnames)) ; not nreverse
6986 (let ((dirlist nil)
6987 pattern dirfile dirfiles dirname root filename rest)
6988 (while dirnames
6989 (setq dirname (substitute-in-file-name (car dirnames))
6990 dirnames (cdr dirnames))
6991 (cond ((string-match (concat "^\\(\\|[/\\]*[^*?]*[/\\]\\)" ;; root
6992 "\\([^/\\]*[*?][^/\\]*\\)" ;; filename with *?
6993 "\\(.*\\)") ;; rest
6994 dirname)
6995 (setq root (match-string 1 dirname)
6996 filename (match-string 2 dirname)
6997 rest (match-string 3 dirname)
6998 pattern filename)
6999 ;; now replace those * and ? with .+ and .
7000 ;; use ^ and /> to get only whole file names
7001 ;;verilog-string-replace-matches
7002 (setq pattern (verilog-string-replace-matches "[*]" ".+" nil nil pattern)
7003 pattern (verilog-string-replace-matches "[?]" "." nil nil pattern)
7004
7005 ;; Unfortunately allows abc/*/rtl to match abc/rtl
7006 ;; because abc/.. shows up in dirfiles. Solutions welcome.
7007 dirfiles (if (file-directory-p root) ; Ignore version control external
7008 (directory-files root t pattern nil)))
7009 (while dirfiles
7010 (setq dirfile (expand-file-name (concat (car dirfiles) rest))
7011 dirfiles (cdr dirfiles))
7012 (if (file-directory-p dirfile)
7013 (setq dirlist (cons dirfile dirlist)))))
7014 ;; Defaults
7015 (t
7016 (if (file-directory-p dirname)
7017 (setq dirlist (cons dirname dirlist))))))
7018 dirlist))
7019 ;;(verilog-expand-dirnames (list "." ".." "nonexist" "../*" "/home/wsnyder/*/v"))
7020
7021 (defun verilog-library-filenames (filename current &optional check-ext)
7022 "Return a search path to find the given FILENAME name.
7023 Uses the CURRENT filename, `verilog-library-directories' and
7024 `verilog-library-extensions' variables to build the path.
7025 With optional CHECK-EXT also check `verilog-library-extensions'."
7026 (let ((ckdir (verilog-expand-dirnames verilog-library-directories))
7027 fn outlist)
7028 (while ckdir
7029 (let ((ckext (if check-ext verilog-library-extensions `(""))))
7030 (while ckext
7031 (setq fn (expand-file-name
7032 (concat filename (car ckext))
7033 (expand-file-name (car ckdir) (file-name-directory current))))
7034 (if (file-exists-p fn)
7035 (setq outlist (cons fn outlist)))
7036 (setq ckext (cdr ckext))))
7037 (setq ckdir (cdr ckdir)))
7038 (nreverse outlist)))
7039
7040 (defun verilog-module-filenames (module current)
7041 "Return a search path to find the given MODULE name.
7042 Uses the CURRENT filename, `verilog-library-extensions',
7043 `verilog-library-directories' and `verilog-library-files'
7044 variables to build the path."
7045 ;; Return search locations for it
7046 (append (list current) ; first, current buffer
7047 (verilog-library-filenames module current t)
7048 verilog-library-files)) ; finally, any libraries
7049
7050 ;;
7051 ;; Module Information
7052 ;;
7053 ;; Many of these functions work on "modi" a module information structure
7054 ;; A modi is: [module-name-string file-name begin-point]
7055
7056 (defvar verilog-cache-enabled t
7057 "If true, enable caching of signals, etc. Set to nil for debugging to make things SLOW!")
7058
7059 (defvar verilog-modi-cache-list nil
7060 "Cache of ((Module Function) Buf-Tick Buf-Modtime Func-Returns)...
7061 For speeding up verilog-modi-get-* commands.
7062 Buffer-local.")
7063
7064 (make-variable-buffer-local 'verilog-modi-cache-list)
7065
7066 (defvar verilog-modi-cache-preserve-tick nil
7067 "Modification tick after which the cache is still considered valid.
7068 Use `verilog-preserve-cache' to set it.")
7069 (defvar verilog-modi-cache-preserve-buffer nil
7070 "Modification tick after which the cache is still considered valid.
7071 Use `verilog-preserve-cache' to set it.")
7072
7073 (defun verilog-modi-current ()
7074 "Return the modi structure for the module currently at point."
7075 (let* (name pt)
7076 ;; read current module's name
7077 (save-excursion
7078 (verilog-re-search-backward-quick verilog-defun-re nil nil)
7079 (verilog-re-search-forward-quick "(" nil nil)
7080 (setq name (verilog-read-module-name))
7081 (setq pt (point)))
7082 ;; return
7083 (vector name (or (buffer-file-name) (current-buffer)) pt)))
7084
7085 (defvar verilog-modi-lookup-last-mod nil "Cache of last module looked up.")
7086 (defvar verilog-modi-lookup-last-modi nil "Cache of last modi returned.")
7087 (defvar verilog-modi-lookup-last-current nil "Cache of last `current-buffer' looked up.")
7088 (defvar verilog-modi-lookup-last-tick nil "Cache of last `buffer-modified-tick' looked up.")
7089
7090 (defun verilog-modi-lookup (module allow-cache &optional ignore-error)
7091 "Find the file and point at which MODULE is defined.
7092 If ALLOW-CACHE is set, check and remember cache of previous lookups.
7093 Return modi if successful, else print message unless IGNORE-ERROR is true."
7094 (let* ((current (or (buffer-file-name) (current-buffer))))
7095 (cond ((and verilog-modi-lookup-last-modi
7096 verilog-cache-enabled
7097 allow-cache
7098 (equal verilog-modi-lookup-last-mod module)
7099 (equal verilog-modi-lookup-last-current current)
7100 (equal verilog-modi-lookup-last-tick (buffer-modified-tick)))
7101 ;; ok as is
7102 )
7103 (t (let* ((realmod (verilog-symbol-detick module t))
7104 (orig-filenames (verilog-module-filenames realmod current))
7105 (filenames orig-filenames)
7106 pt)
7107 (while (and filenames (not pt))
7108 (if (not (setq pt (verilog-module-inside-filename-p realmod (car filenames))))
7109 (setq filenames (cdr filenames))))
7110 (cond (pt (setq verilog-modi-lookup-last-modi
7111 (vector realmod (car filenames) pt)))
7112 (t (setq verilog-modi-lookup-last-modi nil)
7113 (or ignore-error
7114 (error (concat (verilog-point-text)
7115 ": Can't locate " module " module definition"
7116 (if (not (equal module realmod))
7117 (concat " (Expanded macro to " realmod ")")
7118 "")
7119 "\n Check the verilog-library-directories variable."
7120 "\n I looked in (if not listed, doesn't exist):\n\t"
7121 (mapconcat 'concat orig-filenames "\n\t"))))))
7122 (setq verilog-modi-lookup-last-mod module
7123 verilog-modi-lookup-last-current current
7124 verilog-modi-lookup-last-tick (buffer-modified-tick)))))
7125 verilog-modi-lookup-last-modi))
7126
7127 (defsubst verilog-modi-name (modi)
7128 (aref modi 0))
7129 (defsubst verilog-modi-file-or-buffer (modi)
7130 (aref modi 1))
7131 (defsubst verilog-modi-point (modi)
7132 (aref modi 2))
7133
7134 (defun verilog-modi-filename (modi)
7135 "Filename of MODI, or name of buffer if it's never been saved."
7136 (if (bufferp (verilog-modi-file-or-buffer modi))
7137 (or (buffer-file-name (verilog-modi-file-or-buffer modi))
7138 (buffer-name (verilog-modi-file-or-buffer modi)))
7139 (verilog-modi-file-or-buffer modi)))
7140
7141 (defun verilog-modi-goto (modi)
7142 "Move point/buffer to specified MODI."
7143 (or modi (error "Passed unfound modi to goto, check earlier"))
7144 (set-buffer (if (bufferp (verilog-modi-file-or-buffer modi))
7145 (verilog-modi-file-or-buffer modi)
7146 (find-file-noselect (verilog-modi-file-or-buffer modi))))
7147 (or (equal major-mode `verilog-mode) ;; Put into Verilog mode to get syntax
7148 (verilog-mode))
7149 (goto-char (verilog-modi-point modi)))
7150
7151 (defun verilog-goto-defun-file (module)
7152 "Move point to the file at which a given MODULE is defined."
7153 (interactive "sGoto File for Module: ")
7154 (let* ((modi (verilog-modi-lookup module nil)))
7155 (when modi
7156 (verilog-modi-goto modi)
7157 (switch-to-buffer (current-buffer)))))
7158
7159 (defun verilog-modi-cache-results (modi function)
7160 "Run on MODI the given FUNCTION. Locate the module in a file.
7161 Cache the output of function so next call may have faster access."
7162 (let (func-returns fass)
7163 (save-excursion
7164 (verilog-modi-goto modi)
7165 (if (and (setq fass (assoc (list (verilog-modi-name modi) function)
7166 verilog-modi-cache-list))
7167 ;; Destroy caching when incorrect; Modified or file changed
7168 (not (and verilog-cache-enabled
7169 (or (equal (buffer-modified-tick) (nth 1 fass))
7170 (and verilog-modi-cache-preserve-tick
7171 (<= verilog-modi-cache-preserve-tick (nth 1 fass))
7172 (equal verilog-modi-cache-preserve-buffer (current-buffer))))
7173 (equal (visited-file-modtime) (nth 2 fass)))))
7174 (setq verilog-modi-cache-list nil
7175 fass nil))
7176 (cond (fass
7177 ;; Found
7178 (setq func-returns (nth 3 fass)))
7179 (t
7180 ;; Read from file
7181 ;; Clear then restore any hilighting to make emacs19 happy
7182 (let ((fontlocked (when (and (boundp 'font-lock-mode)
7183 font-lock-mode)
7184 (font-lock-mode nil)
7185 t)))
7186 (setq func-returns (funcall function))
7187 (when fontlocked (font-lock-mode t)))
7188 ;; Cache for next time
7189 (setq verilog-modi-cache-list
7190 (cons (list (list (verilog-modi-name modi) function)
7191 (buffer-modified-tick)
7192 (visited-file-modtime)
7193 func-returns)
7194 verilog-modi-cache-list)))))
7195 ;;
7196 func-returns))
7197
7198 (defun verilog-modi-cache-add (modi function element sig-list)
7199 "Add function return results to the module cache.
7200 Update MODI's cache for given FUNCTION so that the return ELEMENT of that
7201 function now contains the additional SIG-LIST parameters."
7202 (let (fass)
7203 (save-excursion
7204 (verilog-modi-goto modi)
7205 (if (setq fass (assoc (list (verilog-modi-name modi) function)
7206 verilog-modi-cache-list))
7207 (let ((func-returns (nth 3 fass)))
7208 (aset func-returns element
7209 (append sig-list (aref func-returns element))))))))
7210
7211 (defmacro verilog-preserve-cache (&rest body)
7212 "Execute the BODY forms, allowing cache preservation within BODY.
7213 This means that changes to the buffer will not result in the cache being
7214 flushed. If the changes affect the modsig state, they must call the
7215 modsig-cache-add-* function, else the results of later calls may be
7216 incorrect. Without this, changes are assumed to be adding/removing signals
7217 and invalidating the cache."
7218 `(let ((verilog-modi-cache-preserve-tick (buffer-modified-tick))
7219 (verilog-modi-cache-preserve-buffer (current-buffer)))
7220 (progn ,@body)))
7221
7222
7223 (defun verilog-signals-matching-enum (in-list enum)
7224 "Return all signals in IN-LIST matching the given ENUM."
7225 (let (out-list)
7226 (while in-list
7227 (if (equal (verilog-sig-enum (car in-list)) enum)
7228 (setq out-list (cons (car in-list) out-list)))
7229 (setq in-list (cdr in-list)))
7230 ;; New scheme
7231 (let* ((enumvar (intern (concat "venum-" enum)))
7232 (enumlist (and (boundp enumvar) (eval enumvar))))
7233 (while enumlist
7234 (add-to-list 'out-list (list (car enumlist)))
7235 (setq enumlist (cdr enumlist))))
7236 (nreverse out-list)))
7237
7238 (defun verilog-signals-not-matching-regexp (in-list regexp)
7239 "Return all signals in IN-LIST not matching the given REGEXP, if non-nil."
7240 (if (not regexp)
7241 in-list
7242 (let (out-list)
7243 (while in-list
7244 (if (not (string-match regexp (verilog-sig-name (car in-list))))
7245 (setq out-list (cons (car in-list) out-list)))
7246 (setq in-list (cdr in-list)))
7247 (nreverse out-list))))
7248
7249 ;; Combined
7250 (defun verilog-modi-get-signals (modi)
7251 (append
7252 (verilog-modi-get-outputs modi)
7253 (verilog-modi-get-inouts modi)
7254 (verilog-modi-get-inputs modi)
7255 (verilog-modi-get-wires modi)
7256 (verilog-modi-get-regs modi)
7257 (verilog-modi-get-assigns modi)
7258 (verilog-modi-get-consts modi)
7259 (verilog-modi-get-gparams modi)))
7260
7261 (defun verilog-modi-get-ports (modi)
7262 (append
7263 (verilog-modi-get-outputs modi)
7264 (verilog-modi-get-inouts modi)
7265 (verilog-modi-get-inputs modi)))
7266
7267 (defsubst verilog-modi-cache-add-outputs (modi sig-list)
7268 (verilog-modi-cache-add modi 'verilog-read-decls 0 sig-list))
7269 (defsubst verilog-modi-cache-add-inouts (modi sig-list)
7270 (verilog-modi-cache-add modi 'verilog-read-decls 1 sig-list))
7271 (defsubst verilog-modi-cache-add-inputs (modi sig-list)
7272 (verilog-modi-cache-add modi 'verilog-read-decls 2 sig-list))
7273 (defsubst verilog-modi-cache-add-wires (modi sig-list)
7274 (verilog-modi-cache-add modi 'verilog-read-decls 3 sig-list))
7275 (defsubst verilog-modi-cache-add-regs (modi sig-list)
7276 (verilog-modi-cache-add modi 'verilog-read-decls 4 sig-list))
7277
7278 (defun verilog-signals-from-signame (signame-list)
7279 "Return signals in standard form from SIGNAME-LIST, a simple list of signal names."
7280 (mapcar (function (lambda (name) (list name nil nil)))
7281 signame-list))
7282 \f
7283 ;;
7284 ;; Auto creation utilities
7285 ;;
7286
7287 (defun verilog-auto-search-do (search-for func)
7288 "Search for the given auto text SEARCH-FOR, and perform FUNC where it occurs."
7289 (goto-char (point-min))
7290 (while (search-forward search-for nil t)
7291 (if (not (save-excursion
7292 (goto-char (match-beginning 0))
7293 (verilog-inside-comment-p)))
7294 (funcall func))))
7295
7296 (defun verilog-auto-re-search-do (search-for func)
7297 "Search for the given auto text SEARCH-FOR, and perform FUNC where it occurs."
7298 (goto-char (point-min))
7299 (while (re-search-forward search-for nil t)
7300 (if (not (save-excursion
7301 (goto-char (match-beginning 0))
7302 (verilog-inside-comment-p)))
7303 (funcall func))))
7304
7305 (defun verilog-insert-one-definition (sig type indent-pt)
7306 "Print out a definition for SIG of the given TYPE,
7307 with appropriate INDENT-PT indentation."
7308 (indent-to indent-pt)
7309 (insert type)
7310 (when (verilog-sig-signed sig)
7311 (insert " " (verilog-sig-signed sig)))
7312 (when (verilog-sig-multidim sig)
7313 (insert " " (verilog-sig-multidim-string sig)))
7314 (when (verilog-sig-bits sig)
7315 (insert " " (verilog-sig-bits sig)))
7316 (indent-to (max 24 (+ indent-pt 16)))
7317 (unless (= (char-syntax (preceding-char)) ?\ )
7318 (insert " ")) ; Need space between "]name" if indent-to did nothing
7319 (insert (verilog-sig-name sig)))
7320
7321 (defun verilog-insert-definition (sigs direction indent-pt v2k &optional dont-sort)
7322 "Print out a definition for a list of SIGS of the given DIRECTION,
7323 with appropriate INDENT-PT indentation. If V2K, use Verilog 2001 I/O
7324 format. Sort unless DONT-SORT. DIRECTION is normally wire/reg/output."
7325 (or dont-sort
7326 (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
7327 (while sigs
7328 (let ((sig (car sigs)))
7329 (verilog-insert-one-definition
7330 sig
7331 ;; Want "type x" or "output type x", not "wire type x"
7332 (cond ((verilog-sig-type sig)
7333 (concat
7334 (if (not (equal direction "wire"))
7335 (concat direction " "))
7336 (verilog-sig-type sig)))
7337 (t direction))
7338 indent-pt)
7339 (insert (if v2k "," ";"))
7340 (if (or (not (verilog-sig-comment sig))
7341 (equal "" (verilog-sig-comment sig)))
7342 (insert "\n")
7343 (indent-to (max 48 (+ indent-pt 40)))
7344 (insert (concat "// " (verilog-sig-comment sig) "\n")))
7345 (setq sigs (cdr sigs)))))
7346
7347 (eval-when-compile
7348 (if (not (boundp 'indent-pt))
7349 (defvar indent-pt nil "Local used by insert-indent")))
7350
7351 (defun verilog-insert-indent (&rest stuff)
7352 "Indent to position stored in local `indent-pt' variable, then insert STUFF.
7353 Presumes that any newlines end a list element."
7354 (let ((need-indent t))
7355 (while stuff
7356 (if need-indent (indent-to indent-pt))
7357 (setq need-indent nil)
7358 (insert (car stuff))
7359 (setq need-indent (string-match "\n$" (car stuff))
7360 stuff (cdr stuff)))))
7361 ;;(let ((indent-pt 10)) (verilog-insert-indent "hello\n" "addon" "there\n"))
7362
7363 (defun verilog-repair-open-comma ()
7364 "If backwards-from-point is other than a open parenthesis insert comma."
7365 (save-excursion
7366 (verilog-backward-syntactic-ws)
7367 (when (save-excursion
7368 (backward-char 1)
7369 (and (not (looking-at "[(,]"))
7370 (progn
7371 (verilog-re-search-backward "[(`]" nil t)
7372 (looking-at "("))))
7373 (insert ","))))
7374
7375 (defun verilog-repair-close-comma ()
7376 "If point is at a comma followed by a close parenthesis, fix it.
7377 This repairs those mis-inserted by a AUTOARG."
7378 ;; It would be much nicer if Verilog allowed extra commas like Perl does!
7379 (save-excursion
7380 (verilog-forward-close-paren)
7381 (backward-char 1)
7382 (verilog-backward-syntactic-ws)
7383 (backward-char 1)
7384 (when (looking-at ",")
7385 (delete-char 1))))
7386
7387 (defun verilog-get-list (start end)
7388 "Return the elements of a comma separated list between START and END."
7389 (interactive)
7390 (let ((my-list (list))
7391 my-string)
7392 (save-excursion
7393 (while (< (point) end)
7394 (when (re-search-forward "\\([^,{]+\\)" end t)
7395 (setq my-string (verilog-string-remove-spaces (match-string 1)))
7396 (setq my-list (nconc my-list (list my-string) ))
7397 (goto-char (match-end 0))))
7398 my-list)))
7399
7400 (defun verilog-make-width-expression (range-exp)
7401 "Return an expression calculating the length of a range [x:y] in RANGE-EXP."
7402 ;; strip off the []
7403 (cond ((not range-exp)
7404 "1")
7405 (t
7406 (if (string-match "^\\[\\(.*\\)\\]$" range-exp)
7407 (setq range-exp (match-string 1 range-exp)))
7408 (cond ((not range-exp)
7409 "1")
7410 ((string-match "^\\s *\\([0-9]+\\)\\s *:\\s *\\([0-9]+\\)\\s *$"
7411 range-exp)
7412 (int-to-string
7413 (1+ (abs (- (string-to-number (match-string 1 range-exp))
7414 (string-to-number (match-string 2 range-exp)))))))
7415 ((string-match "^\\(.*\\)\\s *:\\s *\\(.*\\)\\s *$" range-exp)
7416 (concat "(1+(" (match-string 1 range-exp) ")"
7417 (if (equal "0" (match-string 2 range-exp))
7418 "" ;; Don't bother with -(0)
7419 (concat "-(" (match-string 2 range-exp) ")"))
7420 ")"))
7421 (t nil)))))
7422 ;;(verilog-make-width-expression "`A:`B")
7423
7424 (defun verilog-typedef-name-p (variable-name)
7425 "Return true if the VARIABLE-NAME is a type definition."
7426 (when verilog-typedef-regexp
7427 (string-match verilog-typedef-regexp variable-name)))
7428 \f
7429 ;;
7430 ;; Auto deletion
7431 ;;
7432
7433 (defun verilog-delete-autos-lined ()
7434 "Delete autos that occupy multiple lines, between begin and end comments."
7435 (let ((pt (point)))
7436 (forward-line 1)
7437 (when (and
7438 (looking-at "\\s-*// Beginning")
7439 (search-forward "// End of automatic" nil t))
7440 ;; End exists
7441 (end-of-line)
7442 (delete-region pt (point))
7443 (forward-line 1))))
7444
7445 (defun verilog-forward-close-paren ()
7446 "Find the close parenthesis that match the current point.
7447 Ignore other close parenthesis with matching open parens."
7448 (let ((parens 1))
7449 (while (> parens 0)
7450 (unless (verilog-re-search-forward-quick "[()]" nil t)
7451 (error "%s: Mismatching ()" (verilog-point-text)))
7452 (cond ((= (preceding-char) ?\( )
7453 (setq parens (1+ parens)))
7454 ((= (preceding-char) ?\) )
7455 (setq parens (1- parens)))))))
7456
7457 (defun verilog-backward-open-paren ()
7458 "Find the open parenthesis that match the current point.
7459 Ignore other open parenthesis with matching close parens."
7460 (let ((parens 1))
7461 (while (> parens 0)
7462 (unless (verilog-re-search-backward-quick "[()]" nil t)
7463 (error "%s: Mismatching ()" (verilog-point-text)))
7464 (cond ((= (following-char) ?\) )
7465 (setq parens (1+ parens)))
7466 ((= (following-char) ?\( )
7467 (setq parens (1- parens)))))))
7468
7469 (defun verilog-backward-open-bracket ()
7470 "Find the open bracket that match the current point.
7471 Ignore other open bracket with matching close bracket."
7472 (let ((parens 1))
7473 (while (> parens 0)
7474 (unless (verilog-re-search-backward-quick "[][]" nil t)
7475 (error "%s: Mismatching []" (verilog-point-text)))
7476 (cond ((= (following-char) ?\] )
7477 (setq parens (1+ parens)))
7478 ((= (following-char) ?\[ )
7479 (setq parens (1- parens)))))))
7480
7481 (defun verilog-delete-to-paren ()
7482 "Delete the automatic inst/sense/arg created by autos.
7483 Deletion stops at the matching end parenthesis."
7484 (delete-region (point)
7485 (save-excursion
7486 (verilog-backward-open-paren)
7487 (forward-sexp 1) ;; Moves to paren that closes argdecl's
7488 (backward-char 1)
7489 (point))))
7490
7491 (defun verilog-auto-star-safe ()
7492 "Return if a .* AUTOINST is safe to delete or expand.
7493 It was created by the AUTOS themselves, or by the user."
7494 (and verilog-auto-star-expand
7495 (looking-at "[ \t\n\f,]*\\([)]\\|// \\(Outputs\\|Inouts\\|Inputs\\)\\)")))
7496
7497 (defun verilog-delete-auto-star-all ()
7498 "Delete a .* AUTOINST, if it is safe."
7499 (when (verilog-auto-star-safe)
7500 (verilog-delete-to-paren)))
7501
7502 (defun verilog-delete-auto-star-implicit ()
7503 "Delete all .* implicit connections created by `verilog-auto-star'.
7504 This function will be called automatically at save unless
7505 `verilog-auto-star-save' is set, any non-templated expanded pins will be
7506 removed."
7507 (interactive)
7508 (let (paren-pt indent have-close-paren)
7509 (save-excursion
7510 (goto-char (point-min))
7511 ;; We need to match these even outside of comments.
7512 ;; For reasonable performance, we don't check if inside comments, sorry.
7513 (while (re-search-forward "// Implicit \\.\\*" nil t)
7514 (setq paren-pt (point))
7515 (beginning-of-line)
7516 (setq have-close-paren
7517 (save-excursion
7518 (when (search-forward ");" paren-pt t)
7519 (setq indent (current-indentation))
7520 t)))
7521 (delete-region (point) (+ 1 paren-pt)) ; Nuke line incl CR
7522 (when have-close-paren
7523 ;; Delete extra commentary
7524 (save-excursion
7525 (while (progn
7526 (forward-line -1)
7527 (looking-at "\\s *//\\s *\\(Outputs\\|Inouts\\|Inputs\\)\n"))
7528 (delete-region (match-beginning 0) (match-end 0))))
7529 ;; If it is simple, we can put the ); on the same line as the last text
7530 (let ((rtn-pt (point)))
7531 (save-excursion
7532 (while (progn (backward-char 1)
7533 (looking-at "[ \t\n\f]")))
7534 (when (looking-at ",")
7535 (delete-region (+ 1 (point)) rtn-pt))))
7536 (when (bolp)
7537 (indent-to indent))
7538 (insert ");\n")
7539 ;; Still need to kill final comma - always is one as we put one after the .*
7540 (re-search-backward ",")
7541 (delete-char 1))))))
7542
7543 (defun verilog-delete-auto ()
7544 "Delete the automatic outputs, regs, and wires created by \\[verilog-auto].
7545 Use \\[verilog-auto] to re-insert the updated AUTOs.
7546
7547 The hooks `verilog-before-delete-auto-hook' and `verilog-delete-auto-hook' are
7548 called before and after this function, respectively."
7549 (interactive)
7550 (save-excursion
7551 (if (buffer-file-name)
7552 (find-file-noselect (buffer-file-name))) ;; To check we have latest version
7553 ;; Allow user to customize
7554 (run-hooks 'verilog-before-delete-auto-hook)
7555
7556 ;; Remove those that have multi-line insertions
7557 (verilog-auto-re-search-do "/\\*AUTO\\(OUTPUTEVERY\\|CONCATCOMMENT\\|WIRE\\|REG\\|DEFINEVALUE\\|REGINPUT\\|INPUT\\|OUTPUT\\|INOUT\\|RESET\\|TIEOFF\\|UNUSED\\)\\*/"
7558 'verilog-delete-autos-lined)
7559 ;; Remove those that have multi-line insertions with parameters
7560 (verilog-auto-re-search-do "/\\*AUTO\\(INOUTMODULE\\|ASCIIENUM\\)([^)]*)\\*/"
7561 'verilog-delete-autos-lined)
7562 ;; Remove those that are in parenthesis
7563 (verilog-auto-re-search-do "/\\*\\(AS\\|AUTO\\(ARG\\|CONCATWIDTH\\|INST\\|INSTPARAM\\|SENSE\\)\\)\\*/"
7564 'verilog-delete-to-paren)
7565 ;; Do .* instantiations, but avoid removing any user pins by looking for our magic comments
7566 (verilog-auto-re-search-do "\\.\\*"
7567 'verilog-delete-auto-star-all)
7568 ;; Remove template comments ... anywhere in case was pasted after AUTOINST removed
7569 (goto-char (point-min))
7570 (while (re-search-forward "\\s-*// \\(Templated\\|Implicit \\.\\*\\)[ \tLT0-9]*$" nil t)
7571 (replace-match ""))
7572
7573 ;; Final customize
7574 (run-hooks 'verilog-delete-auto-hook)))
7575 \f
7576 ;;
7577 ;; Auto inject
7578 ;;
7579
7580 (defun verilog-inject-auto ()
7581 "Examine legacy non-AUTO code and insert AUTOs in appropriate places.
7582
7583 Any always @ blocks with sensitivity lists that match computed lists will
7584 be replaced with /*AS*/ comments.
7585
7586 Any cells will get /*AUTOINST*/ added to the end of the pin list.
7587 Pins with have identical names will be deleted.
7588
7589 Argument lists will not be deleted, /*AUTOARG*/ will only be inserted to
7590 support adding new ports. You may wish to delete older ports yourself.
7591
7592 For example:
7593
7594 module ex_inject (i, o);
7595 input i;
7596 input j;
7597 output o;
7598 always @ (i or j)
7599 o = i | j;
7600 cell cell (.foobar(baz),
7601 .j(j));
7602 endmodule
7603
7604 Typing \\[verilog-inject-auto] will make this into:
7605
7606 module ex_inject (i, o/*AUTOARG*/
7607 // Inputs
7608 j);
7609 input i;
7610 output o;
7611 always @ (/*AS*/i or j)
7612 o = i | j;
7613 cell cell (.foobar(baz),
7614 /*AUTOINST*/
7615 // Outputs
7616 .j(j));
7617 endmodule"
7618 (interactive)
7619 (verilog-auto t))
7620
7621 (defun verilog-inject-arg ()
7622 "Inject AUTOARG into new code. See `verilog-inject-auto'."
7623 ;; Presume one module per file.
7624 (save-excursion
7625 (goto-char (point-min))
7626 (while (verilog-re-search-forward-quick "\\<module\\>" nil t)
7627 (let ((endmodp (save-excursion
7628 (verilog-re-search-forward-quick "\\<endmodule\\>" nil t)
7629 (point))))
7630 ;; See if there's already a comment .. inside a comment so not verilog-re-search
7631 (when (not (re-search-forward "/\\*AUTOARG\\*/" endmodp t))
7632 (verilog-re-search-forward-quick ";" nil t)
7633 (backward-char 1)
7634 (verilog-backward-syntactic-ws)
7635 (backward-char 1) ; Moves to paren that closes argdecl's
7636 (when (looking-at ")")
7637 (insert "/*AUTOARG*/")))))))
7638
7639 (defun verilog-inject-sense ()
7640 "Inject AUTOSENSE into new code. See `verilog-inject-auto'."
7641 (save-excursion
7642 (goto-char (point-min))
7643 (while (verilog-re-search-forward-quick "\\<always\\s *@\\s *(" nil t)
7644 (let ((start-pt (point))
7645 (modi (verilog-modi-current))
7646 pre-sigs
7647 got-sigs)
7648 (backward-char 1)
7649 (forward-sexp 1)
7650 (backward-char 1) ;; End )
7651 (when (not (verilog-re-search-backward "/\\*\\(AUTOSENSE\\|AS\\)\\*/" start-pt t))
7652 (setq pre-sigs (verilog-signals-from-signame
7653 (verilog-read-signals start-pt (point)))
7654 got-sigs (verilog-auto-sense-sigs modi nil))
7655 (when (not (or (verilog-signals-not-in pre-sigs got-sigs) ; Both are equal?
7656 (verilog-signals-not-in got-sigs pre-sigs)))
7657 (delete-region start-pt (point))
7658 (insert "/*AS*/")))))))
7659
7660 (defun verilog-inject-inst ()
7661 "Inject AUTOINST into new code. See `verilog-inject-auto'."
7662 (save-excursion
7663 (goto-char (point-min))
7664 ;; It's hard to distinguish modules; we'll instead search for pins.
7665 (while (verilog-re-search-forward-quick "\\.\\s *[a-zA-Z0-9`_\$]+\\s *(\\s *[a-zA-Z0-9`_\$]+\\s *)" nil t)
7666 (verilog-backward-open-paren) ;; Inst start
7667 (cond
7668 ((= (preceding-char) ?\#) ;; #(...) parameter section, not pin. Skip.
7669 (forward-char 1)
7670 (verilog-forward-close-paren)) ;; Parameters done
7671 (t
7672 (forward-char 1)
7673 (let ((indent-pt (+ (current-column)))
7674 (end-pt (save-excursion (verilog-forward-close-paren) (point))))
7675 (cond ((verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-pt t)
7676 (goto-char end-pt)) ;; Already there, continue search with next instance
7677 (t
7678 ;; Delete identical interconnect
7679 (let ((case-fold-search nil)) ;; So we don't convert upper-to-lower, etc
7680 (while (verilog-re-search-forward "\\.\\s *\\([a-zA-Z0-9`_\$]+\\)*\\s *(\\s *\\1\\s *)\\s *" end-pt t)
7681 (delete-region (match-beginning 0) (match-end 0))
7682 (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))) ;; Keep it correct
7683 (while (or (looking-at "[ \t\n\f,]+")
7684 (looking-at "//[^\n]*"))
7685 (delete-region (match-beginning 0) (match-end 0))
7686 (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))))))
7687 (verilog-forward-close-paren)
7688 (backward-char 1)
7689 ;; Not verilog-re-search, as we don't want to strip comments
7690 (while (re-search-backward "[ \t\n\f]+" (- (point) 1) t)
7691 (delete-region (match-beginning 0) (match-end 0)))
7692 (insert "\n")
7693 (indent-to indent-pt)
7694 (insert "/*AUTOINST*/")))))))))
7695 \f
7696 ;;
7697 ;; Auto save
7698 ;;
7699
7700 (defun verilog-auto-save-check ()
7701 "On saving see if we need auto update."
7702 (cond ((not verilog-auto-save-policy)) ; disabled
7703 ((not (save-excursion
7704 (save-match-data
7705 (let ((case-fold-search nil))
7706 (goto-char (point-min))
7707 (re-search-forward "AUTO" nil t))))))
7708 ((eq verilog-auto-save-policy 'force)
7709 (verilog-auto))
7710 ((not (buffer-modified-p)))
7711 ((eq verilog-auto-update-tick (buffer-modified-tick))) ; up-to-date
7712 ((eq verilog-auto-save-policy 'detect)
7713 (verilog-auto))
7714 (t
7715 (when (yes-or-no-p "AUTO statements not recomputed, do it now? ")
7716 (verilog-auto))
7717 ;; Don't ask again if didn't update
7718 (set (make-local-variable 'verilog-auto-update-tick) (buffer-modified-tick))))
7719 (when (not verilog-auto-star-save)
7720 (verilog-delete-auto-star-implicit))
7721 nil) ;; Always return nil -- we don't write the file ourselves
7722
7723 (defun verilog-auto-read-locals ()
7724 "Return file local variable segment at bottom of file."
7725 (save-excursion
7726 (goto-char (point-max))
7727 (if (re-search-backward "Local Variables:" nil t)
7728 (buffer-substring-no-properties (point) (point-max))
7729 "")))
7730
7731 (defun verilog-auto-reeval-locals (&optional force)
7732 "Read file local variable segment at bottom of file if it has changed.
7733 If FORCE, always reread it."
7734 (make-local-variable 'verilog-auto-last-file-locals)
7735 (let ((curlocal (verilog-auto-read-locals)))
7736 (when (or force (not (equal verilog-auto-last-file-locals curlocal)))
7737 (setq verilog-auto-last-file-locals curlocal)
7738 ;; Note this may cause this function to be recursively invoked.
7739 ;; The above when statement will prevent it from recursing forever.
7740 (hack-local-variables)
7741 t)))
7742 \f
7743 ;;
7744 ;; Auto creation
7745 ;;
7746
7747 (defun verilog-auto-arg-ports (sigs message indent-pt)
7748 "Print a list of ports for a AUTOINST.
7749 Takes SIGS list, adds MESSAGE to front and inserts each at INDENT-PT."
7750 (when sigs
7751 (insert "\n")
7752 (indent-to indent-pt)
7753 (insert message)
7754 (insert "\n")
7755 (let ((space ""))
7756 (indent-to indent-pt)
7757 (while sigs
7758 (cond ((> (+ 2 (current-column) (length (verilog-sig-name (car sigs)))) fill-column)
7759 (insert "\n")
7760 (indent-to indent-pt))
7761 (t (insert space)))
7762 (insert (verilog-sig-name (car sigs)) ",")
7763 (setq sigs (cdr sigs)
7764 space " ")))))
7765
7766 (defun verilog-auto-arg ()
7767 "Expand AUTOARG statements.
7768 Replace the argument declarations at the beginning of the
7769 module with ones automatically derived from input and output
7770 statements. This can be dangerous if the module is instantiated
7771 using position-based connections, so use only name-based when
7772 instantiating the resulting module. Long lines are split based
7773 on the `fill-column', see \\[set-fill-column].
7774
7775 Limitations:
7776 Concatenation and outputting partial busses is not supported.
7777
7778 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
7779
7780 For example:
7781
7782 module ex_arg (/*AUTOARG*/);
7783 input i;
7784 output o;
7785 endmodule
7786
7787 Typing \\[verilog-auto] will make this into:
7788
7789 module ex_arg (/*AUTOARG*/
7790 // Outputs
7791 o,
7792 // Inputs
7793 i
7794 );
7795 input i;
7796 output o;
7797 endmodule
7798
7799 Any ports declared between the ( and /*AUTOARG*/ are presumed to be
7800 predeclared and are not redeclared by AUTOARG. AUTOARG will make a
7801 conservative guess on adding a comma for the first signal, if you have
7802 any ifdefs or complicated expressions before the AUTOARG you will need
7803 to choose the comma yourself.
7804
7805 Avoid declaring ports manually, as it makes code harder to maintain."
7806 (save-excursion
7807 (let ((modi (verilog-modi-current))
7808 (skip-pins (aref (verilog-read-arg-pins) 0)))
7809 (verilog-repair-open-comma)
7810 (verilog-auto-arg-ports (verilog-signals-not-in
7811 (verilog-modi-get-outputs modi)
7812 skip-pins)
7813 "// Outputs"
7814 verilog-indent-level-declaration)
7815 (verilog-auto-arg-ports (verilog-signals-not-in
7816 (verilog-modi-get-inouts modi)
7817 skip-pins)
7818 "// Inouts"
7819 verilog-indent-level-declaration)
7820 (verilog-auto-arg-ports (verilog-signals-not-in
7821 (verilog-modi-get-inputs modi)
7822 skip-pins)
7823 "// Inputs"
7824 verilog-indent-level-declaration)
7825 (verilog-repair-close-comma)
7826 (unless (eq (char-before) ?/ )
7827 (insert "\n"))
7828 (indent-to verilog-indent-level-declaration))))
7829
7830 (defun verilog-auto-inst-port-map (port-st)
7831 nil)
7832
7833 (defvar vl-cell-type nil "See `verilog-auto-inst'.") ; Prevent compile warning
7834 (defvar vl-cell-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
7835 (defvar vl-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
7836 (defvar vl-width nil "See `verilog-auto-inst'.") ; Prevent compile warning
7837 (defvar vl-dir nil "See `verilog-auto-inst'.") ; Prevent compile warning
7838
7839 (defun verilog-auto-inst-port (port-st indent-pt tpl-list tpl-num for-star)
7840 "Print out a instantiation connection for this PORT-ST.
7841 Insert to INDENT-PT, use template TPL-LIST.
7842 @ are instantiation numbers, replaced with TPL-NUM.
7843 @\"(expression @)\" are evaluated, with @ as a variable.
7844 If FOR-STAR add comment it is a .* expansion."
7845 (let* ((port (verilog-sig-name port-st))
7846 (tpl-ass (or (assoc port (car tpl-list))
7847 (verilog-auto-inst-port-map port-st)))
7848 ;; vl-* are documented for user use
7849 (vl-name (verilog-sig-name port-st))
7850 (vl-width (verilog-sig-width port-st))
7851 (vl-bits (if (or verilog-auto-inst-vector
7852 (not (assoc port vector-skip-list))
7853 (not (equal (verilog-sig-bits port-st)
7854 (verilog-sig-bits (assoc port vector-skip-list)))))
7855 (or (verilog-sig-bits port-st) "")
7856 ""))
7857 ;; Default if not found
7858 (tpl-net (if (verilog-sig-multidim port-st)
7859 (concat port "/*" (verilog-sig-multidim-string port-st)
7860 vl-bits "*/")
7861 (concat port vl-bits)))
7862 (case-fold-search nil))
7863 ;; Find template
7864 (cond (tpl-ass ; Template of exact port name
7865 (setq tpl-net (nth 1 tpl-ass)))
7866 ((nth 1 tpl-list) ; Wildcards in template, search them
7867 (let ((wildcards (nth 1 tpl-list)))
7868 (while wildcards
7869 (when (string-match (nth 0 (car wildcards)) port)
7870 (setq tpl-ass (car wildcards) ; so allow @ parsing
7871 tpl-net (replace-match (nth 1 (car wildcards))
7872 t nil port)))
7873 (setq wildcards (cdr wildcards))))))
7874 ;; Parse Templated variable
7875 (when tpl-ass
7876 ;; Evaluate @"(lispcode)"
7877 (when (string-match "@\".*[^\\]\"" tpl-net)
7878 (while (string-match "@\"\\(\\([^\\\"]*\\(\\\\.\\)*\\)*\\)\"" tpl-net)
7879 (setq tpl-net
7880 (concat
7881 (substring tpl-net 0 (match-beginning 0))
7882 (save-match-data
7883 (let* ((expr (match-string 1 tpl-net))
7884 (value
7885 (progn
7886 (setq expr (verilog-string-replace-matches "\\\\\"" "\"" nil nil expr))
7887 (setq expr (verilog-string-replace-matches "@" tpl-num nil nil expr))
7888 (prin1 (eval (car (read-from-string expr)))
7889 (lambda (ch) ())))))
7890 (if (numberp value) (setq value (number-to-string value)))
7891 value))
7892 (substring tpl-net (match-end 0))))))
7893 ;; Replace @ and [] magic variables in final output
7894 (setq tpl-net (verilog-string-replace-matches "@" tpl-num nil nil tpl-net))
7895 (setq tpl-net (verilog-string-replace-matches "\\[\\]" vl-bits nil nil tpl-net)))
7896 (indent-to indent-pt)
7897 (insert "." port)
7898 (indent-to verilog-auto-inst-column)
7899 (insert "(" tpl-net "),")
7900 (cond (tpl-ass
7901 (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
7902 verilog-auto-inst-column))
7903 (insert " // Templated")
7904 (when verilog-auto-inst-template-numbers
7905 (insert " T" (int-to-string (nth 2 tpl-ass))
7906 " L" (int-to-string (nth 3 tpl-ass)))))
7907 (for-star
7908 (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
7909 verilog-auto-inst-column))
7910 (insert " // Implicit .\*"))) ;For some reason the . or * must be escaped...
7911 (insert "\n")))
7912 ;;(verilog-auto-inst-port (list "foo" "[5:0]") 10 (list (list "foo" "a@\"(% (+ @ 1) 4)\"a")) "3")
7913 ;;(x "incom[@\"(+ (* 8 @) 7)\":@\"(* 8 @)\"]")
7914 ;;(x ".out (outgo[@\"(concat (+ (* 8 @) 7) \\\":\\\" ( * 8 @))\"]));")
7915
7916 (defun verilog-auto-inst-first ()
7917 "Insert , etc before first ever port in this instant, as part of \\[verilog-auto-inst]."
7918 ;; Do we need a trailing comma?
7919 ;; There maybe a ifdef or something similar before us. What a mess. Thus
7920 ;; to avoid trouble we only insert on preceeding ) or *.
7921 ;; Insert first port on new line
7922 (insert "\n") ;; Must insert before search, so point will move forward if insert comma
7923 (save-excursion
7924 (verilog-re-search-backward "[^ \t\n\f]" nil nil)
7925 (when (looking-at ")\\|\\*") ;; Generally don't insert, unless we are fairly sure
7926 (forward-char 1)
7927 (insert ","))))
7928
7929 (defun verilog-auto-star ()
7930 "Expand SystemVerilog .* pins, as part of \\[verilog-auto].
7931
7932 If `verilog-auto-star-expand' is set, .* pins are treated if they were
7933 AUTOINST statements, otherwise they are ignored. For safety, Verilog mode
7934 will also ignore any .* that are not last in your pin list (this prevents
7935 it from deleting pins following the .* when it expands the AUTOINST.)
7936
7937 On writing your file, unless `verilog-auto-star-save' is set, any
7938 non-templated expanded pins will be removed. You may do this at any time
7939 with \\[verilog-delete-auto-star-implicit].
7940
7941 If you are converting a module to use .* for the first time, you may wish
7942 to use \\[verilog-inject-auto] and then replace the created AUTOINST with .*.
7943
7944 See `verilog-auto-inst' for examples, templates, and more information."
7945 (when (verilog-auto-star-safe)
7946 (verilog-auto-inst)))
7947
7948 (defun verilog-auto-inst ()
7949 "Expand AUTOINST statements, as part of \\[verilog-auto].
7950 Replace the pin connections to an instantiation with ones
7951 automatically derived from the module header of the instantiated netlist.
7952
7953 If `verilog-auto-star-expand' is set, also expand SystemVerilog .* ports,
7954 and delete them before saving unless `verilog-auto-star-save' is set.
7955 See `verilog-auto-star' for more information.
7956
7957 Limitations:
7958 Module names must be resolvable to filenames by adding a
7959 `verilog-library-extensions', and being found in the same directory, or
7960 by changing the variable `verilog-library-flags' or
7961 `verilog-library-directories'. Macros `modname are translated through the
7962 vh-{name} Emacs variable, if that is not found, it just ignores the `.
7963
7964 In templates you must have one signal per line, ending in a ), or ));,
7965 and have proper () nesting, including a final ); to end the template.
7966
7967 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
7968
7969 SystemVerilog multidimensional input/output has only experimental support.
7970
7971 For example, first take the submodule inst.v:
7972
7973 module inst (o,i)
7974 output [31:0] o;
7975 input i;
7976 wire [31:0] o = {32{i}};
7977 endmodule
7978
7979 This is then used in a upper level module:
7980
7981 module ex_inst (o,i)
7982 output o;
7983 input i;
7984 inst inst (/*AUTOINST*/);
7985 endmodule
7986
7987 Typing \\[verilog-auto] will make this into:
7988
7989 module ex_inst (o,i)
7990 output o;
7991 input i;
7992 inst inst (/*AUTOINST*/
7993 // Outputs
7994 .ov (ov[31:0]),
7995 // Inputs
7996 .i (i));
7997 endmodule
7998
7999 Where the list of inputs and outputs came from the inst module.
8000 \f
8001 Exceptions:
8002
8003 Unless you are instantiating a module multiple times, or the module is
8004 something trivial like an adder, DO NOT CHANGE SIGNAL NAMES ACROSS HIERARCHY.
8005 It just makes for unmaintainable code. To sanitize signal names, try
8006 vrename from http://www.veripool.com.
8007
8008 When you need to violate this suggestion there are two ways to list
8009 exceptions, placing them before the AUTOINST, or using templates.
8010
8011 Any ports defined before the /*AUTOINST*/ are not included in the list of
8012 automatics. This is similar to making a template as described below, but
8013 is restricted to simple connections just like you normally make. Also note
8014 that any signals before the AUTOINST will only be picked up by AUTOWIRE if
8015 you have the appropriate // Input or // Output comment, and exactly the
8016 same line formatting as AUTOINST itself uses.
8017
8018 inst inst (// Inputs
8019 .i (my_i_dont_mess_with_it),
8020 /*AUTOINST*/
8021 // Outputs
8022 .ov (ov[31:0]));
8023
8024 \f
8025 Templates:
8026
8027 For multiple instantiations based upon a single template, create a
8028 commented out template:
8029
8030 /* instantiating_module_name AUTO_TEMPLATE (
8031 .sig3 (sigz[]),
8032 );
8033 */
8034
8035 Templates go ABOVE the instantiation(s). When an instantiation is
8036 expanded `verilog-mode' simply searches up for the closest template.
8037 Thus you can have multiple templates for the same module, just alternate
8038 between the template for an instantiation and the instantiation itself.
8039
8040 The module name must be the same as the name of the module in the
8041 instantiation name, and the code \"AUTO_TEMPLATE\" must be in these exact
8042 words and capitalized. Only signals that must be different for each
8043 instantiation need to be listed.
8044
8045 Inside a template, a [] in a connection name (with nothing else inside
8046 the brackets) will be replaced by the same bus subscript as it is being
8047 connected to, or the [] will be removed if it is a single bit signal.
8048 Generally it is a good idea to do this for all connections in a template,
8049 as then they will work for any width signal, and with AUTOWIRE. See
8050 PTL_BUS becoming PTL_BUSNEW below.
8051
8052 If you have a complicated template, set `verilog-auto-inst-template-numbers'
8053 to see which regexps are matching. Don't leave that mode set after
8054 debugging is completed though, it will result in lots of extra differences
8055 and merge conflicts.
8056
8057 For example:
8058
8059 /* psm_mas AUTO_TEMPLATE (
8060 .ptl_bus (ptl_busnew[]),
8061 );
8062 */
8063 psm_mas ms2m (/*AUTOINST*/);
8064
8065 Typing \\[verilog-auto] will make this into:
8066
8067 psm_mas ms2m (/*AUTOINST*/
8068 // Outputs
8069 .NotInTemplate (NotInTemplate),
8070 .ptl_bus (ptl_busnew[3:0]), // Templated
8071 ....
8072 \f
8073 @ Templates:
8074
8075 It is common to instantiate a cell multiple times, so templates make it
8076 trivial to substitute part of the cell name into the connection name.
8077
8078 /* cell_type AUTO_TEMPLATE <optional \"REGEXP\"> (
8079 .sig1 (sigx[@]),
8080 .sig2 (sigy[@\"(% (+ 1 @) 4)\"]),
8081 );
8082 */
8083
8084 If no regular expression is provided immediately after the AUTO_TEMPLATE
8085 keyword, then the @ character in any connection names will be replaced
8086 with the instantiation number; the first digits found in the cell's
8087 instantiation name.
8088
8089 If a regular expression is provided, the @ character will be replaced
8090 with the first \(\) grouping that matches against the cell name. Using a
8091 regexp of \"\\([0-9]+\\)\" provides identical values for @ as when no
8092 regexp is provided. If you use multiple layers of parenthesis,
8093 \"test\\([^0-9]+\\)_\\([0-9]+\\)\" would replace @ with non-number
8094 characters after test and before _, whereas
8095 \"\\(test\\([a-z]+\\)_\\([0-9]+\\)\\)\" would replace @ with the entire
8096 match.
8097
8098 For example:
8099
8100 /* psm_mas AUTO_TEMPLATE (
8101 .ptl_mapvalidx (ptl_mapvalid[@]),
8102 .ptl_mapvalidp1x (ptl_mapvalid[@\"(% (+ 1 @) 4)\"]),
8103 );
8104 */
8105 psm_mas ms2m (/*AUTOINST*/);
8106
8107 Typing \\[verilog-auto] will make this into:
8108
8109 psm_mas ms2m (/*AUTOINST*/
8110 // Outputs
8111 .ptl_mapvalidx (ptl_mapvalid[2]),
8112 .ptl_mapvalidp1x (ptl_mapvalid[3]));
8113
8114 Note the @ character was replaced with the 2 from \"ms2m\".
8115
8116 Alternatively, using a regular expression for @:
8117
8118 /* psm_mas AUTO_TEMPLATE \"_\\([a-z]+\\)\" (
8119 .ptl_mapvalidx (@_ptl_mapvalid),
8120 .ptl_mapvalidp1x (ptl_mapvalid_@),
8121 );
8122 */
8123 psm_mas ms2_FOO (/*AUTOINST*/);
8124 psm_mas ms2_BAR (/*AUTOINST*/);
8125
8126 Typing \\[verilog-auto] will make this into:
8127
8128 psm_mas ms2_FOO (/*AUTOINST*/
8129 // Outputs
8130 .ptl_mapvalidx (FOO_ptl_mapvalid),
8131 .ptl_mapvalidp1x (ptl_mapvalid_FOO));
8132 psm_mas ms2_BAR (/*AUTOINST*/
8133 // Outputs
8134 .ptl_mapvalidx (BAR_ptl_mapvalid),
8135 .ptl_mapvalidp1x (ptl_mapvalid_BAR));
8136
8137 \f
8138 Regexp Templates:
8139
8140 A template entry of the form
8141
8142 .pci_req\\([0-9]+\\)_l (pci_req_jtag_[\\1]),
8143
8144 will apply an Emacs style regular expression search for any port beginning
8145 in pci_req followed by numbers and ending in _l and connecting that to
8146 the pci_req_jtag_[] net, with the bus subscript coming from what matches
8147 inside the first set of \\( \\). Thus pci_req2_l becomes pci_req_jtag_[2].
8148
8149 Since \\([0-9]+\\) is so common and ugly to read, a @ in the port name
8150 does the same thing. (Note a @ in the connection/replacement text is
8151 completely different -- still use \\1 there!) Thus this is the same as
8152 the above template:
8153
8154 .pci_req@_l (pci_req_jtag_[\\1]),
8155
8156 Here's another example to remove the _l, useful when naming conventions
8157 specify _ alone to mean active low. Note the use of [] to keep the bus
8158 subscript:
8159
8160 .\\(.*\\)_l (\\1_[]),
8161 \f
8162 Lisp Templates:
8163
8164 First any regular expression template is expanded.
8165
8166 If the syntax @\"( ... )\" is found in a connection, the expression in
8167 quotes will be evaluated as a Lisp expression, with @ replaced by the
8168 instantiation number. The MAPVALIDP1X example above would put @+1 modulo
8169 4 into the brackets. Quote all double-quotes inside the expression with
8170 a leading backslash (\\\"). There are special variables defined that are
8171 useful in these Lisp functions:
8172
8173 vl-name Name portion of the input/output port.
8174 vl-bits Bus bits portion of the input/output port ('[2:0]').
8175 vl-width Width of the input/output port ('3' for [2:0]).
8176 May be a (...) expression if bits isn't a constant.
8177 vl-dir Direction of the pin input/output/inout.
8178 vl-cell-type Module name/type of the cell ('psm_mas').
8179 vl-cell-name Instance name of the cell ('ms2m').
8180
8181 Normal Lisp variables may be used in expressions. See
8182 `verilog-read-defines' which can set vh-{definename} variables for use
8183 here. Also, any comments of the form:
8184
8185 /*AUTO_LISP(setq foo 1)*/
8186
8187 will evaluate any Lisp expression inside the parenthesis between the
8188 beginning of the buffer and the point of the AUTOINST. This allows
8189 functions to be defined or variables to be changed between instantiations.
8190
8191 Note that when using lisp expressions errors may occur when @ is not a
8192 number; you may need to use the standard Emacs Lisp functions
8193 `number-to-string' and `string-to-number'.
8194
8195 After the evaluation is completed, @ substitution and [] substitution
8196 occur."
8197 (save-excursion
8198 ;; Find beginning
8199 (let* ((pt (point))
8200 (for-star (save-excursion (backward-char 2) (looking-at "\\.\\*")))
8201 (indent-pt (save-excursion (verilog-backward-open-paren)
8202 (1+ (current-column))))
8203 (verilog-auto-inst-column (max verilog-auto-inst-column
8204 (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
8205 (modi (verilog-modi-current))
8206 (vector-skip-list (unless verilog-auto-inst-vector
8207 (verilog-modi-get-signals modi)))
8208 submod submodi inst skip-pins tpl-list tpl-num did-first)
8209 ;; Find module name that is instantiated
8210 (setq submod (verilog-read-inst-module)
8211 inst (verilog-read-inst-name)
8212 vl-cell-type submod
8213 vl-cell-name inst
8214 skip-pins (aref (verilog-read-inst-pins) 0))
8215
8216 ;; Parse any AUTO_LISP() before here
8217 (verilog-read-auto-lisp (point-min) pt)
8218
8219 ;; Lookup position, etc of submodule
8220 ;; Note this may raise an error
8221 (when (setq submodi (verilog-modi-lookup submod t))
8222 ;; If there's a number in the instantiation, it may be a argument to the
8223 ;; automatic variable instantiation program.
8224 (let* ((tpl-info (verilog-read-auto-template submod))
8225 (tpl-regexp (aref tpl-info 0)))
8226 (setq tpl-num (if (string-match tpl-regexp inst)
8227 (match-string 1 inst)
8228 "")
8229 tpl-list (aref tpl-info 1)))
8230 ;; Find submodule's signals and dump
8231 (let ((sig-list (verilog-signals-not-in
8232 (verilog-modi-get-outputs submodi)
8233 skip-pins))
8234 (vl-dir "output"))
8235 (when sig-list
8236 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
8237 (indent-to indent-pt)
8238 ;; Note these are searched for in verilog-read-sub-decls.
8239 (insert "// Outputs\n")
8240 (mapc (lambda (port)
8241 (verilog-auto-inst-port port indent-pt
8242 tpl-list tpl-num for-star))
8243 sig-list)))
8244 (let ((sig-list (verilog-signals-not-in
8245 (verilog-modi-get-inouts submodi)
8246 skip-pins))
8247 (vl-dir "inout"))
8248 (when sig-list
8249 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
8250 (indent-to indent-pt)
8251 (insert "// Inouts\n")
8252 (mapc (lambda (port)
8253 (verilog-auto-inst-port port indent-pt
8254 tpl-list tpl-num for-star))
8255 sig-list)))
8256 (let ((sig-list (verilog-signals-not-in
8257 (verilog-modi-get-inputs submodi)
8258 skip-pins))
8259 (vl-dir "input"))
8260 (when sig-list
8261 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
8262 (indent-to indent-pt)
8263 (insert "// Inputs\n")
8264 (mapc (lambda (port)
8265 (verilog-auto-inst-port port indent-pt
8266 tpl-list tpl-num for-star))
8267 sig-list)))
8268 ;; Kill extra semi
8269 (save-excursion
8270 (cond (did-first
8271 (re-search-backward "," pt t)
8272 (delete-char 1)
8273 (insert ");")
8274 (search-forward "\n") ;; Added by inst-port
8275 (delete-backward-char 1)
8276 (if (search-forward ")" nil t) ;; From user, moved up a line
8277 (delete-backward-char 1))
8278 (if (search-forward ";" nil t) ;; Don't error if user had syntax error and forgot it
8279 (delete-backward-char 1)))))))))
8280
8281 (defun verilog-auto-inst-param ()
8282 "Expand AUTOINSTPARAM statements, as part of \\[verilog-auto].
8283 Replace the parameter connections to an instantiation with ones
8284 automatically derived from the module header of the instantiated netlist.
8285
8286 See \\[verilog-auto-inst] for limitations, and templates to customize the
8287 output.
8288
8289 For example, first take the submodule inst.v:
8290
8291 module inst (o,i)
8292 parameter PAR;
8293 endmodule
8294
8295 This is then used in a upper level module:
8296
8297 module ex_inst (o,i)
8298 parameter PAR;
8299 inst #(/*AUTOINSTPARAM*/)
8300 inst (/*AUTOINST*/);
8301 endmodule
8302
8303 Typing \\[verilog-auto] will make this into:
8304
8305 module ex_inst (o,i)
8306 output o;
8307 input i;
8308 inst (/*AUTOINSTPARAM*/
8309 // Parameters
8310 .PAR (PAR));
8311 inst (/*AUTOINST*/);
8312 endmodule
8313
8314 Where the list of parameter connections come from the inst module.
8315 \f
8316 Templates:
8317
8318 You can customize the parameter connections using AUTO_TEMPLATEs,
8319 just as you would with \\[verilog-auto-inst]."
8320 (save-excursion
8321 ;; Find beginning
8322 (let* ((pt (point))
8323 (indent-pt (save-excursion (verilog-backward-open-paren)
8324 (1+ (current-column))))
8325 (verilog-auto-inst-column (max verilog-auto-inst-column
8326 (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
8327 (modi (verilog-modi-current))
8328 (vector-skip-list (unless verilog-auto-inst-vector
8329 (verilog-modi-get-signals modi)))
8330 submod submodi inst skip-pins tpl-list tpl-num did-first)
8331 ;; Find module name that is instantiated
8332 (setq submod (save-excursion
8333 ;; Get to the point where AUTOINST normally is to read the module
8334 (verilog-re-search-forward-quick "[(;]" nil nil)
8335 (verilog-read-inst-module))
8336 inst (save-excursion
8337 ;; Get to the point where AUTOINST normally is to read the module
8338 (verilog-re-search-forward-quick "[(;]" nil nil)
8339 (verilog-read-inst-name))
8340 vl-cell-type submod
8341 vl-cell-name inst
8342 skip-pins (aref (verilog-read-inst-pins) 0))
8343
8344 ;; Parse any AUTO_LISP() before here
8345 (verilog-read-auto-lisp (point-min) pt)
8346
8347 ;; Lookup position, etc of submodule
8348 ;; Note this may raise an error
8349 (when (setq submodi (verilog-modi-lookup submod t))
8350 ;; If there's a number in the instantiation, it may be a argument to the
8351 ;; automatic variable instantiation program.
8352 (let* ((tpl-info (verilog-read-auto-template submod))
8353 (tpl-regexp (aref tpl-info 0)))
8354 (setq tpl-num (if (string-match tpl-regexp inst)
8355 (match-string 1 inst)
8356 "")
8357 tpl-list (aref tpl-info 1)))
8358 ;; Find submodule's signals and dump
8359 (let ((sig-list (verilog-signals-not-in
8360 (verilog-modi-get-gparams submodi)
8361 skip-pins))
8362 (vl-dir "parameter"))
8363 (when sig-list
8364 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
8365 (indent-to indent-pt)
8366 ;; Note these are searched for in verilog-read-sub-decls.
8367 (insert "// Parameters\n")
8368 (mapc (lambda (port)
8369 (verilog-auto-inst-port port indent-pt
8370 tpl-list tpl-num nil))
8371 sig-list)))
8372 ;; Kill extra semi
8373 (save-excursion
8374 (cond (did-first
8375 (re-search-backward "," pt t)
8376 (delete-char 1)
8377 (insert ")")
8378 (search-forward "\n") ;; Added by inst-port
8379 (delete-backward-char 1)
8380 (if (search-forward ")" nil t) ;; From user, moved up a line
8381 (delete-backward-char 1)))))))))
8382
8383 (defun verilog-auto-reg ()
8384 "Expand AUTOREG statements, as part of \\[verilog-auto].
8385 Make reg statements for any output that isn't already declared,
8386 and isn't a wire output from a block.
8387
8388 Limitations:
8389 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
8390
8391 This does NOT work on memories, declare those yourself.
8392
8393 An example:
8394
8395 module ex_reg (o,i)
8396 output o;
8397 input i;
8398 /*AUTOREG*/
8399 always o = i;
8400 endmodule
8401
8402 Typing \\[verilog-auto] will make this into:
8403
8404 module ex_reg (o,i)
8405 output o;
8406 input i;
8407 /*AUTOREG*/
8408 // Beginning of automatic regs (for this module's undeclared outputs)
8409 reg o;
8410 // End of automatics
8411 always o = i;
8412 endmodule"
8413 (save-excursion
8414 ;; Point must be at insertion point.
8415 (let* ((indent-pt (current-indentation))
8416 (modi (verilog-modi-current))
8417 (sig-list (verilog-signals-not-in
8418 (verilog-modi-get-outputs modi)
8419 (append (verilog-modi-get-wires modi)
8420 (verilog-modi-get-regs modi)
8421 (verilog-modi-get-assigns modi)
8422 (verilog-modi-get-consts modi)
8423 (verilog-modi-get-gparams modi)
8424 (verilog-modi-get-sub-outputs modi)
8425 (verilog-modi-get-sub-inouts modi)))))
8426 (forward-line 1)
8427 (when sig-list
8428 (verilog-insert-indent "// Beginning of automatic regs (for this module's undeclared outputs)\n")
8429 (verilog-insert-definition sig-list "reg" indent-pt nil)
8430 (verilog-modi-cache-add-regs modi sig-list)
8431 (verilog-insert-indent "// End of automatics\n")))))
8432
8433 (defun verilog-auto-reg-input ()
8434 "Expand AUTOREGINPUT statements, as part of \\[verilog-auto].
8435 Make reg statements instantiation inputs that aren't already declared.
8436 This is useful for making a top level shell for testing the module that is
8437 to be instantiated.
8438
8439 Limitations:
8440 This ONLY detects inputs of AUTOINSTants (see `verilog-read-sub-decls').
8441
8442 This does NOT work on memories, declare those yourself.
8443
8444 An example (see `verilog-auto-inst' for what else is going on here):
8445
8446 module ex_reg_input (o,i)
8447 output o;
8448 input i;
8449 /*AUTOREGINPUT*/
8450 inst inst (/*AUTOINST*/);
8451 endmodule
8452
8453 Typing \\[verilog-auto] will make this into:
8454
8455 module ex_reg_input (o,i)
8456 output o;
8457 input i;
8458 /*AUTOREGINPUT*/
8459 // Beginning of automatic reg inputs (for undeclared ...
8460 reg [31:0] iv; // From inst of inst.v
8461 // End of automatics
8462 inst inst (/*AUTOINST*/
8463 // Outputs
8464 .o (o[31:0]),
8465 // Inputs
8466 .iv (iv));
8467 endmodule"
8468 (save-excursion
8469 ;; Point must be at insertion point.
8470 (let* ((indent-pt (current-indentation))
8471 (modi (verilog-modi-current))
8472 (sig-list (verilog-signals-combine-bus
8473 (verilog-signals-not-in
8474 (append (verilog-modi-get-sub-inputs modi)
8475 (verilog-modi-get-sub-inouts modi))
8476 (verilog-modi-get-signals modi)))))
8477 (forward-line 1)
8478 (when sig-list
8479 (verilog-insert-indent "// Beginning of automatic reg inputs (for undeclared instantiated-module inputs)\n")
8480 (verilog-insert-definition sig-list "reg" indent-pt nil)
8481 (verilog-modi-cache-add-regs modi sig-list)
8482 (verilog-insert-indent "// End of automatics\n")))))
8483
8484 (defun verilog-auto-wire ()
8485 "Expand AUTOWIRE statements, as part of \\[verilog-auto].
8486 Make wire statements for instantiations outputs that aren't
8487 already declared.
8488
8489 Limitations:
8490 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls'),
8491 and all busses must have widths, such as those from AUTOINST, or using []
8492 in AUTO_TEMPLATEs.
8493
8494 This does NOT work on memories or SystemVerilog .name connections,
8495 declare those yourself.
8496
8497 Verilog mode will add \"Couldn't Merge\" comments to signals it cannot
8498 determine how to bus together. This occurs when you have ports with
8499 non-numeric or non-sequential bus subscripts. If Verilog mode
8500 mis-guessed, you'll have to declare them yourself.
8501
8502 An example (see `verilog-auto-inst' for what else is going on here):
8503
8504 module ex_wire (o,i)
8505 output o;
8506 input i;
8507 /*AUTOWIRE*/
8508 inst inst (/*AUTOINST*/);
8509 endmodule
8510
8511 Typing \\[verilog-auto] will make this into:
8512
8513 module ex_wire (o,i)
8514 output o;
8515 input i;
8516 /*AUTOWIRE*/
8517 // Beginning of automatic wires
8518 wire [31:0] ov; // From inst of inst.v
8519 // End of automatics
8520 inst inst (/*AUTOINST*/
8521 // Outputs
8522 .ov (ov[31:0]),
8523 // Inputs
8524 .i (i));
8525 wire o = | ov;
8526 endmodule"
8527 (save-excursion
8528 ;; Point must be at insertion point.
8529 (let* ((indent-pt (current-indentation))
8530 (modi (verilog-modi-current))
8531 (sig-list (verilog-signals-combine-bus
8532 (verilog-signals-not-in
8533 (append (verilog-modi-get-sub-outputs modi)
8534 (verilog-modi-get-sub-inouts modi))
8535 (verilog-modi-get-signals modi)))))
8536 (forward-line 1)
8537 (when sig-list
8538 (verilog-insert-indent "// Beginning of automatic wires (for undeclared instantiated-module outputs)\n")
8539 (verilog-insert-definition sig-list "wire" indent-pt nil)
8540 (verilog-modi-cache-add-wires modi sig-list)
8541 (verilog-insert-indent "// End of automatics\n")
8542 (when nil ;; Too slow on huge modules, plus makes everyone's module change
8543 (beginning-of-line)
8544 (setq pnt (point))
8545 (verilog-pretty-declarations quiet)
8546 (goto-char pnt)
8547 (verilog-pretty-expr "//"))))))
8548
8549 (defun verilog-auto-output ()
8550 "Expand AUTOOUTPUT statements, as part of \\[verilog-auto].
8551 Make output statements for any output signal from an /*AUTOINST*/ that
8552 isn't a input to another AUTOINST. This is useful for modules which
8553 only instantiate other modules.
8554
8555 Limitations:
8556 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
8557
8558 If placed inside the parenthesis of a module declaration, it creates
8559 Verilog 2001 style, else uses Verilog 1995 style.
8560
8561 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
8562 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
8563
8564 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
8565
8566 Signals matching `verilog-auto-output-ignore-regexp' are not included.
8567
8568 An example (see `verilog-auto-inst' for what else is going on here):
8569
8570 module ex_output (ov,i)
8571 input i;
8572 /*AUTOOUTPUT*/
8573 inst inst (/*AUTOINST*/);
8574 endmodule
8575
8576 Typing \\[verilog-auto] will make this into:
8577
8578 module ex_output (ov,i)
8579 input i;
8580 /*AUTOOUTPUT*/
8581 // Beginning of automatic outputs (from unused autoinst outputs)
8582 output [31:0] ov; // From inst of inst.v
8583 // End of automatics
8584 inst inst (/*AUTOINST*/
8585 // Outputs
8586 .ov (ov[31:0]),
8587 // Inputs
8588 .i (i));
8589 endmodule"
8590 (save-excursion
8591 ;; Point must be at insertion point.
8592 (let* ((indent-pt (current-indentation))
8593 (v2k (verilog-in-paren))
8594 (modi (verilog-modi-current))
8595 (sig-list (verilog-signals-not-in
8596 (verilog-modi-get-sub-outputs modi)
8597 (append (verilog-modi-get-outputs modi)
8598 (verilog-modi-get-inouts modi)
8599 (verilog-modi-get-sub-inputs modi)
8600 (verilog-modi-get-sub-inouts modi)))))
8601 (setq sig-list (verilog-signals-not-matching-regexp
8602 sig-list verilog-auto-output-ignore-regexp))
8603 (forward-line 1)
8604 (when v2k (verilog-repair-open-comma))
8605 (when sig-list
8606 (verilog-insert-indent "// Beginning of automatic outputs (from unused autoinst outputs)\n")
8607 (verilog-insert-definition sig-list "output" indent-pt v2k)
8608 (verilog-modi-cache-add-outputs modi sig-list)
8609 (verilog-insert-indent "// End of automatics\n"))
8610 (when v2k (verilog-repair-close-comma)))))
8611
8612 (defun verilog-auto-output-every ()
8613 "Expand AUTOOUTPUTEVERY statements, as part of \\[verilog-auto].
8614 Make output statements for any signals that aren't primary inputs or
8615 outputs already. This makes every signal in the design a output. This is
8616 useful to get Synopsys to preserve every signal in the design, since it
8617 won't optimize away the outputs.
8618
8619 An example:
8620
8621 module ex_output_every (o,i,tempa,tempb)
8622 output o;
8623 input i;
8624 /*AUTOOUTPUTEVERY*/
8625 wire tempa = i;
8626 wire tempb = tempa;
8627 wire o = tempb;
8628 endmodule
8629
8630 Typing \\[verilog-auto] will make this into:
8631
8632 module ex_output_every (o,i,tempa,tempb)
8633 output o;
8634 input i;
8635 /*AUTOOUTPUTEVERY*/
8636 // Beginning of automatic outputs (every signal)
8637 output tempb;
8638 output tempa;
8639 // End of automatics
8640 wire tempa = i;
8641 wire tempb = tempa;
8642 wire o = tempb;
8643 endmodule"
8644 (save-excursion
8645 ;;Point must be at insertion point
8646 (let* ((indent-pt (current-indentation))
8647 (v2k (verilog-in-paren))
8648 (modi (verilog-modi-current))
8649 (sig-list (verilog-signals-combine-bus
8650 (verilog-signals-not-in
8651 (verilog-modi-get-signals modi)
8652 (verilog-modi-get-ports modi)))))
8653 (forward-line 1)
8654 (when v2k (verilog-repair-open-comma))
8655 (when sig-list
8656 (verilog-insert-indent "// Beginning of automatic outputs (every signal)\n")
8657 (verilog-insert-definition sig-list "output" indent-pt v2k)
8658 (verilog-modi-cache-add-outputs modi sig-list)
8659 (verilog-insert-indent "// End of automatics\n"))
8660 (when v2k (verilog-repair-close-comma)))))
8661
8662 (defun verilog-auto-input ()
8663 "Expand AUTOINPUT statements, as part of \\[verilog-auto].
8664 Make input statements for any input signal into an /*AUTOINST*/ that
8665 isn't declared elsewhere inside the module. This is useful for modules which
8666 only instantiate other modules.
8667
8668 Limitations:
8669 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
8670
8671 If placed inside the parenthesis of a module declaration, it creates
8672 Verilog 2001 style, else uses Verilog 1995 style.
8673
8674 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
8675 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
8676
8677 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
8678
8679 Signals matching `verilog-auto-input-ignore-regexp' are not included.
8680
8681 An example (see `verilog-auto-inst' for what else is going on here):
8682
8683 module ex_input (ov,i)
8684 output [31:0] ov;
8685 /*AUTOINPUT*/
8686 inst inst (/*AUTOINST*/);
8687 endmodule
8688
8689 Typing \\[verilog-auto] will make this into:
8690
8691 module ex_input (ov,i)
8692 output [31:0] ov;
8693 /*AUTOINPUT*/
8694 // Beginning of automatic inputs (from unused autoinst inputs)
8695 input i; // From inst of inst.v
8696 // End of automatics
8697 inst inst (/*AUTOINST*/
8698 // Outputs
8699 .ov (ov[31:0]),
8700 // Inputs
8701 .i (i));
8702 endmodule"
8703 (save-excursion
8704 (let* ((indent-pt (current-indentation))
8705 (v2k (verilog-in-paren))
8706 (modi (verilog-modi-current))
8707 (sig-list (verilog-signals-not-in
8708 (verilog-modi-get-sub-inputs modi)
8709 (append (verilog-modi-get-inputs modi)
8710 (verilog-modi-get-inouts modi)
8711 (verilog-modi-get-wires modi)
8712 (verilog-modi-get-regs modi)
8713 (verilog-modi-get-consts modi)
8714 (verilog-modi-get-gparams modi)
8715 (verilog-modi-get-sub-outputs modi)
8716 (verilog-modi-get-sub-inouts modi)))))
8717 (setq sig-list (verilog-signals-not-matching-regexp
8718 sig-list verilog-auto-input-ignore-regexp))
8719 (forward-line 1)
8720 (when v2k (verilog-repair-open-comma))
8721 (when sig-list
8722 (verilog-insert-indent "// Beginning of automatic inputs (from unused autoinst inputs)\n")
8723 (verilog-insert-definition sig-list "input" indent-pt v2k)
8724 (verilog-modi-cache-add-inputs modi sig-list)
8725 (verilog-insert-indent "// End of automatics\n"))
8726 (when v2k (verilog-repair-close-comma)))))
8727
8728 (defun verilog-auto-inout ()
8729 "Expand AUTOINOUT statements, as part of \\[verilog-auto].
8730 Make inout statements for any inout signal in an /*AUTOINST*/ that
8731 isn't declared elsewhere inside the module.
8732
8733 Limitations:
8734 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
8735
8736 If placed inside the parenthesis of a module declaration, it creates
8737 Verilog 2001 style, else uses Verilog 1995 style.
8738
8739 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
8740 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
8741
8742 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
8743
8744 Signals matching `verilog-auto-inout-ignore-regexp' are not included.
8745
8746 An example (see `verilog-auto-inst' for what else is going on here):
8747
8748 module ex_inout (ov,i)
8749 input i;
8750 /*AUTOINOUT*/
8751 inst inst (/*AUTOINST*/);
8752 endmodule
8753
8754 Typing \\[verilog-auto] will make this into:
8755
8756 module ex_inout (ov,i)
8757 input i;
8758 /*AUTOINOUT*/
8759 // Beginning of automatic inouts (from unused autoinst inouts)
8760 inout [31:0] ov; // From inst of inst.v
8761 // End of automatics
8762 inst inst (/*AUTOINST*/
8763 // Inouts
8764 .ov (ov[31:0]),
8765 // Inputs
8766 .i (i));
8767 endmodule"
8768 (save-excursion
8769 ;; Point must be at insertion point.
8770 (let* ((indent-pt (current-indentation))
8771 (v2k (verilog-in-paren))
8772 (modi (verilog-modi-current))
8773 (sig-list (verilog-signals-not-in
8774 (verilog-modi-get-sub-inouts modi)
8775 (append (verilog-modi-get-outputs modi)
8776 (verilog-modi-get-inouts modi)
8777 (verilog-modi-get-inputs modi)
8778 (verilog-modi-get-sub-inputs modi)
8779 (verilog-modi-get-sub-outputs modi)))))
8780 (setq sig-list (verilog-signals-not-matching-regexp
8781 sig-list verilog-auto-inout-ignore-regexp))
8782 (forward-line 1)
8783 (when v2k (verilog-repair-open-comma))
8784 (when sig-list
8785 (verilog-insert-indent "// Beginning of automatic inouts (from unused autoinst inouts)\n")
8786 (verilog-insert-definition sig-list "inout" indent-pt v2k)
8787 (verilog-modi-cache-add-inouts modi sig-list)
8788 (verilog-insert-indent "// End of automatics\n"))
8789 (when v2k (verilog-repair-close-comma)))))
8790
8791 (defun verilog-auto-inout-module ()
8792 "Expand AUTOINOUTMODULE statements, as part of \\[verilog-auto].
8793 Take input/output/inout statements from the specified module and insert
8794 into the current module. This is useful for making null templates and
8795 shell modules which need to have identical I/O with another module.
8796 Any I/O which are already defined in this module will not be redefined.
8797
8798 Limitations:
8799 If placed inside the parenthesis of a module declaration, it creates
8800 Verilog 2001 style, else uses Verilog 1995 style.
8801
8802 Concatenation and outputting partial busses is not supported.
8803
8804 Module names must be resolvable to filenames. See `verilog-auto-inst'.
8805
8806 Signals are not inserted in the same order as in the original module,
8807 though they will appear to be in the same order to a AUTOINST
8808 instantiating either module.
8809
8810 An example:
8811
8812 module ex_shell (/*AUTOARG*/)
8813 /*AUTOINOUTMODULE(\"ex_main\")*/
8814 endmodule
8815
8816 module ex_main (i,o,io)
8817 input i;
8818 output o;
8819 inout io;
8820 endmodule
8821
8822 Typing \\[verilog-auto] will make this into:
8823
8824 module ex_shell (/*AUTOARG*/i,o,io)
8825 /*AUTOINOUTMODULE(\"ex_main\")*/
8826 // Beginning of automatic in/out/inouts (from specific module)
8827 input i;
8828 output o;
8829 inout io;
8830 // End of automatics
8831 endmodule"
8832 (save-excursion
8833 (let* ((submod (car (verilog-read-auto-params 1))) submodi)
8834 ;; Lookup position, etc of co-module
8835 ;; Note this may raise an error
8836 (when (setq submodi (verilog-modi-lookup submod t))
8837 (let* ((indent-pt (current-indentation))
8838 (v2k (verilog-in-paren))
8839 (modi (verilog-modi-current))
8840 (sig-list-i (verilog-signals-not-in
8841 (verilog-modi-get-inputs submodi)
8842 (append (verilog-modi-get-inputs modi))))
8843 (sig-list-o (verilog-signals-not-in
8844 (verilog-modi-get-outputs submodi)
8845 (append (verilog-modi-get-outputs modi))))
8846 (sig-list-io (verilog-signals-not-in
8847 (verilog-modi-get-inouts submodi)
8848 (append (verilog-modi-get-inouts modi)))))
8849 (forward-line 1)
8850 (when v2k (verilog-repair-open-comma))
8851 (when (or sig-list-i sig-list-o sig-list-io)
8852 (verilog-insert-indent "// Beginning of automatic in/out/inouts (from specific module)\n")
8853 ;; Don't sort them so a upper AUTOINST will match the main module
8854 (verilog-insert-definition sig-list-o "output" indent-pt v2k t)
8855 (verilog-insert-definition sig-list-io "inout" indent-pt v2k t)
8856 (verilog-insert-definition sig-list-i "input" indent-pt v2k t)
8857 (verilog-modi-cache-add-inputs modi sig-list-i)
8858 (verilog-modi-cache-add-outputs modi sig-list-o)
8859 (verilog-modi-cache-add-inouts modi sig-list-io)
8860 (verilog-insert-indent "// End of automatics\n"))
8861 (when v2k (verilog-repair-close-comma)))))))
8862
8863 (defun verilog-auto-sense-sigs (modi presense-sigs)
8864 "Return list of signals for current AUTOSENSE block."
8865 (let* ((sigss (verilog-read-always-signals))
8866 (sig-list (verilog-signals-not-params
8867 (verilog-signals-not-in (verilog-alw-get-inputs sigss)
8868 (append (and (not verilog-auto-sense-include-inputs)
8869 (verilog-alw-get-outputs sigss))
8870 (verilog-modi-get-consts modi)
8871 (verilog-modi-get-gparams modi)
8872 presense-sigs)))))
8873 sig-list))
8874
8875 (defun verilog-auto-sense ()
8876 "Expand AUTOSENSE statements, as part of \\[verilog-auto].
8877 Replace the always (/*AUTOSENSE*/) sensitivity list (/*AS*/ for short)
8878 with one automatically derived from all inputs declared in the always
8879 statement. Signals that are generated within the same always block are NOT
8880 placed into the sensitivity list (see `verilog-auto-sense-include-inputs').
8881 Long lines are split based on the `fill-column', see \\[set-fill-column].
8882
8883 Limitations:
8884 Verilog does not allow memories (multidimensional arrays) in sensitivity
8885 lists. AUTOSENSE will thus exclude them, and add a /*memory or*/ comment.
8886
8887 Constant signals:
8888 AUTOSENSE cannot always determine if a `define is a constant or a signal
8889 (it could be in a include file for example). If a `define or other signal
8890 is put into the AUTOSENSE list and is not desired, use the AUTO_CONSTANT
8891 declaration anywhere in the module (parenthesis are required):
8892
8893 /* AUTO_CONSTANT ( `this_is_really_constant_dont_autosense_it ) */
8894
8895 Better yet, use a parameter, which will be understood to be constant
8896 automatically.
8897
8898 OOps!
8899 If AUTOSENSE makes a mistake, please report it. (First try putting
8900 a begin/end after your always!) As a workaround, if a signal that
8901 shouldn't be in the sensitivity list was, use the AUTO_CONSTANT above.
8902 If a signal should be in the sensitivity list wasn't, placing it before
8903 the /*AUTOSENSE*/ comment will prevent it from being deleted when the
8904 autos are updated (or added if it occurs there already).
8905
8906 An example:
8907
8908 always @ (/*AUTOSENSE*/) begin
8909 /* AUTO_CONSTANT (`constant) */
8910 outin = ina | inb | `constant;
8911 out = outin;
8912 end
8913
8914 Typing \\[verilog-auto] will make this into:
8915
8916 always @ (/*AUTOSENSE*/ina or inb) begin
8917 /* AUTO_CONSTANT (`constant) */
8918 outin = ina | inb | `constant;
8919 out = outin;
8920 end"
8921 (save-excursion
8922 ;; Find beginning
8923 (let* ((start-pt (save-excursion
8924 (verilog-re-search-backward "(" nil t)
8925 (point)))
8926 (indent-pt (save-excursion
8927 (or (and (goto-char start-pt) (1+ (current-column)))
8928 (current-indentation))))
8929 (modi (verilog-modi-current))
8930 (sig-memories (verilog-signals-memory
8931 (append
8932 (verilog-modi-get-regs modi)
8933 (verilog-modi-get-wires modi))))
8934 sig-list not-first presense-sigs)
8935 ;; Read signals in always, eliminate outputs from sense list
8936 (setq presense-sigs (verilog-signals-from-signame
8937 (save-excursion
8938 (verilog-read-signals start-pt (point)))))
8939 (setq sig-list (verilog-auto-sense-sigs modi presense-sigs))
8940 (when sig-memories
8941 (let ((tlen (length sig-list)))
8942 (setq sig-list (verilog-signals-not-in sig-list sig-memories))
8943 (if (not (eq tlen (length sig-list))) (insert " /*memory or*/ "))))
8944 (if (and presense-sigs ;; Add a "or" if not "(.... or /*AUTOSENSE*/"
8945 (save-excursion (goto-char (point))
8946 (verilog-re-search-backward "[a-zA-Z0-9$_.%`]+" start-pt t)
8947 (verilog-re-search-backward "\\s-" start-pt t)
8948 (while (looking-at "\\s-`endif")
8949 (verilog-re-search-backward "[a-zA-Z0-9$_.%`]+" start-pt t)
8950 (verilog-re-search-backward "\\s-" start-pt t))
8951 (not (looking-at "\\s-or\\b"))))
8952 (setq not-first t))
8953 (setq sig-list (sort sig-list `verilog-signals-sort-compare))
8954 (while sig-list
8955 (cond ((> (+ 4 (current-column) (length (verilog-sig-name (car sig-list)))) fill-column) ;+4 for width of or
8956 (insert "\n")
8957 (indent-to indent-pt)
8958 (if not-first (insert "or ")))
8959 (not-first (insert " or ")))
8960 (insert (verilog-sig-name (car sig-list)))
8961 (setq sig-list (cdr sig-list)
8962 not-first t)))))
8963
8964 (defun verilog-auto-reset ()
8965 "Expand AUTORESET statements, as part of \\[verilog-auto].
8966 Replace the /*AUTORESET*/ comment with code to initialize all
8967 registers set elsewhere in the always block.
8968
8969 Limitations:
8970 AUTORESET will not clear memories.
8971
8972 AUTORESET uses <= if there are any <= in the block, else it uses =.
8973
8974 /*AUTORESET*/ presumes that any signals mentioned between the previous
8975 begin/case/if statement and the AUTORESET comment are being reset manually
8976 and should not be automatically reset. This includes omitting any signals
8977 used on the right hand side of assignments.
8978
8979 By default, AUTORESET will include the width of the signal in the autos,
8980 this is a recent change. To control this behavior, see
8981 `verilog-auto-reset-widths'.
8982
8983 AUTORESET ties signals to deasserted, which is presumed to be zero.
8984 Signals that match `verilog-active-low-regexp' will be deasserted by tieing
8985 them to a one.
8986
8987 An example:
8988
8989 always @(posedge clk or negedge reset_l) begin
8990 if (!reset_l) begin
8991 c <= 1;
8992 /*AUTORESET*/
8993 end
8994 else begin
8995 a <= in_a;
8996 b <= in_b;
8997 c <= in_c;
8998 end
8999 end
9000
9001 Typing \\[verilog-auto] will make this into:
9002
9003 always @(posedge core_clk or negedge reset_l) begin
9004 if (!reset_l) begin
9005 c <= 1;
9006 /*AUTORESET*/
9007 // Beginning of autoreset for uninitialized flops
9008 a <= 0;
9009 b <= 0;
9010 // End of automatics
9011 end
9012 else begin
9013 a <= in_a;
9014 b <= in_b;
9015 c <= in_c;
9016 end
9017 end"
9018
9019 (interactive)
9020 (save-excursion
9021 ;; Find beginning
9022 (let* ((indent-pt (current-indentation))
9023 (modi (verilog-modi-current))
9024 (all-list (verilog-modi-get-signals modi))
9025 sigss sig-list prereset-sigs assignment-str)
9026 ;; Read signals in always, eliminate outputs from reset list
9027 (setq prereset-sigs (verilog-signals-from-signame
9028 (save-excursion
9029 (verilog-read-signals
9030 (save-excursion
9031 (verilog-re-search-backward "\\(@\\|\\<begin\\>\\|\\<if\\>\\|\\<case\\>\\)" nil t)
9032 (point))
9033 (point)))))
9034 (save-excursion
9035 (verilog-re-search-backward "@" nil t)
9036 (setq sigss (verilog-read-always-signals)))
9037 (setq assignment-str (if (verilog-alw-get-uses-delayed sigss)
9038 (concat " <= " verilog-assignment-delay)
9039 " = "))
9040 (setq sig-list (verilog-signals-not-in (verilog-alw-get-outputs sigss)
9041 prereset-sigs))
9042 (setq sig-list (sort sig-list `verilog-signals-sort-compare))
9043 (when sig-list
9044 (insert "\n");
9045 (indent-to indent-pt)
9046 (insert "// Beginning of autoreset for uninitialized flops\n");
9047 (indent-to indent-pt)
9048 (while sig-list
9049 (let ((sig (or (assoc (verilog-sig-name (car sig-list)) all-list) ;; As sig-list has no widths
9050 (car sig-list))))
9051 (insert (verilog-sig-name sig)
9052 assignment-str
9053 (verilog-sig-tieoff sig (not verilog-auto-reset-widths))
9054 ";\n")
9055 (indent-to indent-pt)
9056 (setq sig-list (cdr sig-list))))
9057 (insert "// End of automatics")))))
9058
9059 (defun verilog-auto-tieoff ()
9060 "Expand AUTOTIEOFF statements, as part of \\[verilog-auto].
9061 Replace the /*AUTOTIEOFF*/ comment with code to wire-tie all unused output
9062 signals to deasserted.
9063
9064 /*AUTOTIEOFF*/ is used to make stub modules; modules that have the same
9065 input/output list as another module, but no internals. Specifically, it
9066 finds all outputs in the module, and if that input is not otherwise declared
9067 as a register or wire, creates a tieoff.
9068
9069 AUTORESET ties signals to deasserted, which is presumed to be zero.
9070 Signals that match `verilog-active-low-regexp' will be deasserted by tieing
9071 them to a one.
9072
9073 An example of making a stub for another module:
9074
9075 module FooStub (/*AUTOINST*/);
9076 /*AUTOINOUTMODULE(\"Foo\")*/
9077 /*AUTOTIEOFF*/
9078 // verilator lint_off UNUSED
9079 wire _unused_ok = &{1'b0,
9080 /*AUTOUNUSED*/
9081 1'b0};
9082 // verilator lint_on UNUSED
9083 endmodule
9084
9085 Typing \\[verilog-auto] will make this into:
9086
9087 module FooStub (/*AUTOINST*/...);
9088 /*AUTOINOUTMODULE(\"Foo\")*/
9089 // Beginning of autotieoff
9090 output [2:0] foo;
9091 // End of automatics
9092
9093 /*AUTOTIEOFF*/
9094 // Beginning of autotieoff
9095 wire [2:0] foo = 3'b0;
9096 // End of automatics
9097 ...
9098 endmodule"
9099 (interactive)
9100 (save-excursion
9101 ;; Find beginning
9102 (let* ((indent-pt (current-indentation))
9103 (modi (verilog-modi-current))
9104 (sig-list (verilog-signals-not-in
9105 (verilog-modi-get-outputs modi)
9106 (append (verilog-modi-get-wires modi)
9107 (verilog-modi-get-regs modi)
9108 (verilog-modi-get-assigns modi)
9109 (verilog-modi-get-consts modi)
9110 (verilog-modi-get-gparams modi)
9111 (verilog-modi-get-sub-outputs modi)
9112 (verilog-modi-get-sub-inouts modi)))))
9113 (when sig-list
9114 (forward-line 1)
9115 (verilog-insert-indent "// Beginning of automatic tieoffs (for this module's unterminated outputs)\n")
9116 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
9117 (verilog-modi-cache-add-wires modi sig-list) ; Before we trash list
9118 (while sig-list
9119 (let ((sig (car sig-list)))
9120 (verilog-insert-one-definition sig "wire" indent-pt)
9121 (indent-to (max 48 (+ indent-pt 40)))
9122 (insert "= " (verilog-sig-tieoff sig)
9123 ";\n")
9124 (setq sig-list (cdr sig-list))))
9125 (verilog-insert-indent "// End of automatics\n")))))
9126
9127 (defun verilog-auto-unused ()
9128 "Expand AUTOUNUSED statements, as part of \\[verilog-auto].
9129 Replace the /*AUTOUNUSED*/ comment with a comma separated list of all unused
9130 input and inout signals.
9131
9132 /*AUTOUNUSED*/ is used to make stub modules; modules that have the same
9133 input/output list as another module, but no internals. Specifically, it
9134 finds all inputs and inouts in the module, and if that input is not otherwise
9135 used, adds it to a comma separated list.
9136
9137 The comma separated list is intended to be used to create a _unused_ok
9138 signal. Using the exact name \"_unused_ok\" for name of the temporary
9139 signal is recommended as it will insure maximum forward compatibility, it
9140 also makes lint warnings easy to understand; ignore any unused warnings
9141 with \"unused\" in the signal name.
9142
9143 To reduce simulation time, the _unused_ok signal should be forced to a
9144 constant to prevent wiggling. The easiest thing to do is use a
9145 reduction-and with 1'b0 as shown.
9146
9147 This way all unused signals are in one place, making it convenient to add
9148 your tool's specific pragmas around the assignment to disable any unused
9149 warnings.
9150
9151 You can add signals you do not want included in AUTOUNUSED with
9152 `verilog-auto-unused-ignore-regexp'.
9153
9154 An example of making a stub for another module:
9155
9156 module FooStub (/*AUTOINST*/);
9157 /*AUTOINOUTMODULE(\"Foo\")*/
9158 /*AUTOTIEOFF*/
9159 // verilator lint_off UNUSED
9160 wire _unused_ok = &{1'b0,
9161 /*AUTOUNUSED*/
9162 1'b0};
9163 // verilator lint_on UNUSED
9164 endmodule
9165
9166 Typing \\[verilog-auto] will make this into:
9167
9168 ...
9169 // verilator lint_off UNUSED
9170 wire _unused_ok = &{1'b0,
9171 /*AUTOUNUSED*/
9172 // Beginning of automatics
9173 unused_input_a,
9174 unused_input_b,
9175 unused_input_c,
9176 // End of automatics
9177 1'b0};
9178 // verilator lint_on UNUSED
9179 endmodule"
9180 (interactive)
9181 (save-excursion
9182 ;; Find beginning
9183 (let* ((indent-pt (progn (search-backward "/*") (current-column)))
9184 (modi (verilog-modi-current))
9185 (sig-list (verilog-signals-not-in
9186 (append (verilog-modi-get-inputs modi)
9187 (verilog-modi-get-inouts modi))
9188 (append (verilog-modi-get-sub-inputs modi)
9189 (verilog-modi-get-sub-inouts modi)))))
9190 (setq sig-list (verilog-signals-not-matching-regexp
9191 sig-list verilog-auto-unused-ignore-regexp))
9192 (when sig-list
9193 (forward-line 1)
9194 (verilog-insert-indent "// Beginning of automatic unused inputs\n")
9195 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
9196 (while sig-list
9197 (let ((sig (car sig-list)))
9198 (indent-to indent-pt)
9199 (insert (verilog-sig-name sig) ",\n")
9200 (setq sig-list (cdr sig-list))))
9201 (verilog-insert-indent "// End of automatics\n")))))
9202
9203 (defun verilog-enum-ascii (signm elim-regexp)
9204 "Convert an enum name SIGNM to an ascii string for insertion.
9205 Remove user provided prefix ELIM-REGEXP."
9206 (or elim-regexp (setq elim-regexp "_ DONT MATCH IT_"))
9207 (let ((case-fold-search t))
9208 ;; All upper becomes all lower for readability
9209 (downcase (verilog-string-replace-matches elim-regexp "" nil nil signm))))
9210
9211 (defun verilog-auto-ascii-enum ()
9212 "Expand AUTOASCIIENUM statements, as part of \\[verilog-auto].
9213 Create a register to contain the ASCII decode of a enumerated signal type.
9214 This will allow trace viewers to show the ASCII name of states.
9215
9216 First, parameters are built into a enumeration using the synopsys enum
9217 comment. The comment must be between the keyword and the symbol.
9218 \(Annoying, but that's what Synopsys's dc_shell FSM reader requires.)
9219
9220 Next, registers which that enum applies to are also tagged with the same
9221 enum. Synopsys also suggests labeling state vectors, but `verilog-mode'
9222 doesn't care.
9223
9224 Finally, a AUTOASCIIENUM command is used.
9225
9226 The first parameter is the name of the signal to be decoded.
9227
9228 The second parameter is the name to store the ASCII code into. For the
9229 signal foo, I suggest the name _foo__ascii, where the leading _ indicates
9230 a signal that is just for simulation, and the magic characters _ascii
9231 tell viewers like Dinotrace to display in ASCII format.
9232
9233 The final optional parameter is a string which will be removed from the
9234 state names.
9235
9236 An example:
9237
9238 //== State enumeration
9239 parameter [2:0] // synopsys enum state_info
9240 SM_IDLE = 3'b000,
9241 SM_SEND = 3'b001,
9242 SM_WAIT1 = 3'b010;
9243 //== State variables
9244 reg [2:0] /* synopsys enum state_info */
9245 state_r; /* synopsys state_vector state_r */
9246 reg [2:0] /* synopsys enum state_info */
9247 state_e1;
9248
9249 //== ASCII state decoding
9250
9251 /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
9252
9253 Typing \\[verilog-auto] will make this into:
9254
9255 ... same front matter ...
9256
9257 /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
9258 // Beginning of automatic ASCII enum decoding
9259 reg [39:0] state_ascii_r; // Decode of state_r
9260 always @(state_r) begin
9261 case ({state_r})
9262 SM_IDLE: state_ascii_r = \"idle \";
9263 SM_SEND: state_ascii_r = \"send \";
9264 SM_WAIT1: state_ascii_r = \"wait1\";
9265 default: state_ascii_r = \"%Erro\";
9266 endcase
9267 end
9268 // End of automatics"
9269 (save-excursion
9270 (let* ((params (verilog-read-auto-params 2 3))
9271 (undecode-name (nth 0 params))
9272 (ascii-name (nth 1 params))
9273 (elim-regexp (nth 2 params))
9274 ;;
9275 (indent-pt (current-indentation))
9276 (modi (verilog-modi-current))
9277 ;;
9278 (sig-list-consts (append (verilog-modi-get-consts modi)
9279 (verilog-modi-get-gparams modi)))
9280 (sig-list-all (append (verilog-modi-get-regs modi)
9281 (verilog-modi-get-outputs modi)
9282 (verilog-modi-get-inouts modi)
9283 (verilog-modi-get-inputs modi)
9284 (verilog-modi-get-wires modi)))
9285 ;;
9286 (undecode-sig (or (assoc undecode-name sig-list-all)
9287 (error "%s: Signal %s not found in design" (verilog-point-text) undecode-name)))
9288 (undecode-enum (or (verilog-sig-enum undecode-sig)
9289 (error "%s: Signal %s does not have a enum tag" (verilog-point-text) undecode-name)))
9290 ;;
9291 (enum-sigs (or (verilog-signals-matching-enum sig-list-consts undecode-enum)
9292 (error "%s: No state definitions for %s" (verilog-point-text) undecode-enum)))
9293 ;;
9294 (enum-chars 0)
9295 (ascii-chars 0))
9296 ;;
9297 ;; Find number of ascii chars needed
9298 (let ((tmp-sigs enum-sigs))
9299 (while tmp-sigs
9300 (setq enum-chars (max enum-chars (length (verilog-sig-name (car tmp-sigs))))
9301 ascii-chars (max ascii-chars (length (verilog-enum-ascii
9302 (verilog-sig-name (car tmp-sigs))
9303 elim-regexp)))
9304 tmp-sigs (cdr tmp-sigs))))
9305 ;;
9306 (forward-line 1)
9307 (verilog-insert-indent "// Beginning of automatic ASCII enum decoding\n")
9308 (let ((decode-sig-list (list (list ascii-name (format "[%d:0]" (- (* ascii-chars 8) 1))
9309 (concat "Decode of " undecode-name) nil nil))))
9310 (verilog-insert-definition decode-sig-list "reg" indent-pt nil)
9311 (verilog-modi-cache-add-regs modi decode-sig-list))
9312 ;;
9313 (verilog-insert-indent "always @(" undecode-name ") begin\n")
9314 (setq indent-pt (+ indent-pt verilog-indent-level))
9315 (indent-to indent-pt)
9316 (insert "case ({" undecode-name "})\n")
9317 (setq indent-pt (+ indent-pt verilog-case-indent))
9318 ;;
9319 (let ((tmp-sigs enum-sigs)
9320 (chrfmt (format "%%-%ds %s = \"%%-%ds\";\n" (1+ (max 8 enum-chars))
9321 ascii-name ascii-chars))
9322 (errname (substring "%Error" 0 (min 6 ascii-chars))))
9323 (while tmp-sigs
9324 (verilog-insert-indent
9325 (format chrfmt (concat (verilog-sig-name (car tmp-sigs)) ":")
9326 (verilog-enum-ascii (verilog-sig-name (car tmp-sigs))
9327 elim-regexp)))
9328 (setq tmp-sigs (cdr tmp-sigs)))
9329 (verilog-insert-indent (format chrfmt "default:" errname)))
9330 ;;
9331 (setq indent-pt (- indent-pt verilog-case-indent))
9332 (verilog-insert-indent "endcase\n")
9333 (setq indent-pt (- indent-pt verilog-indent-level))
9334 (verilog-insert-indent "end\n"
9335 "// End of automatics\n"))))
9336
9337 (defun verilog-auto-templated-rel ()
9338 "Replace Templated relative line numbers with absolute line numbers.
9339 Internal use only. This hacks around the line numbers in AUTOINST Templates
9340 being different from the final output's line numbering."
9341 (let ((templateno 0) (template-line (list 0)))
9342 ;; Find line number each template is on
9343 (goto-char (point-min))
9344 (while (search-forward "AUTO_TEMPLATE" nil t)
9345 (setq templateno (1+ templateno))
9346 (setq template-line
9347 (cons (count-lines (point-min) (point)) template-line)))
9348 (setq template-line (nreverse template-line))
9349 ;; Replace T# L# with absolute line number
9350 (goto-char (point-min))
9351 (while (re-search-forward " Templated T\\([0-9]+\\) L\\([0-9]+\\)" nil t)
9352 (replace-match
9353 (concat " Templated "
9354 (int-to-string (+ (nth (string-to-number (match-string 1))
9355 template-line)
9356 (string-to-number (match-string 2)))))
9357 t t))))
9358
9359 \f
9360 ;;
9361 ;; Auto top level
9362 ;;
9363
9364 (defun verilog-auto (&optional inject) ; Use verilog-inject-auto instead of passing a arg
9365 "Expand AUTO statements.
9366 Look for any /*AUTO...*/ commands in the code, as used in
9367 instantiations or argument headers. Update the list of signals
9368 following the /*AUTO...*/ command.
9369
9370 Use \\[verilog-delete-auto] to remove the AUTOs.
9371
9372 Use \\[verilog-inject-auto] to insert AUTOs for the first time.
9373
9374 Use \\[verilog-faq] for a pointer to frequently asked questions.
9375
9376 The hooks `verilog-before-auto-hook' and `verilog-auto-hook' are
9377 called before and after this function, respectively.
9378
9379 For example:
9380 module (/*AUTOARG*/)
9381 /*AUTOINPUT*/
9382 /*AUTOOUTPUT*/
9383 /*AUTOWIRE*/
9384 /*AUTOREG*/
9385 somesub sub #(/*AUTOINSTPARAM*/) (/*AUTOINST*/);
9386
9387 You can also update the AUTOs from the shell using:
9388 emacs --batch <filenames.v> -f verilog-batch-auto
9389 Or fix indentation with:
9390 emacs --batch <filenames.v> -f verilog-batch-indent
9391 Likewise, you can delete or inject AUTOs with:
9392 emacs --batch <filenames.v> -f verilog-batch-delete-auto
9393 emacs --batch <filenames.v> -f verilog-batch-inject-auto
9394
9395 Using \\[describe-function], see also:
9396 `verilog-auto-arg' for AUTOARG module instantiations
9397 `verilog-auto-ascii-enum' for AUTOASCIIENUM enumeration decoding
9398 `verilog-auto-inout-module' for AUTOINOUTMODULE copying i/o from elsewhere
9399 `verilog-auto-inout' for AUTOINOUT making hierarchy inouts
9400 `verilog-auto-input' for AUTOINPUT making hierarchy inputs
9401 `verilog-auto-inst' for AUTOINST instantiation pins
9402 `verilog-auto-star' for AUTOINST .* SystemVerilog pins
9403 `verilog-auto-inst-param' for AUTOINSTPARAM instantiation params
9404 `verilog-auto-output' for AUTOOUTPUT making hierarchy outputs
9405 `verilog-auto-output-every' for AUTOOUTPUTEVERY making all outputs
9406 `verilog-auto-reg' for AUTOREG registers
9407 `verilog-auto-reg-input' for AUTOREGINPUT instantiation registers
9408 `verilog-auto-reset' for AUTORESET flop resets
9409 `verilog-auto-sense' for AUTOSENSE always sensitivity lists
9410 `verilog-auto-tieoff' for AUTOTIEOFF output tieoffs
9411 `verilog-auto-unused' for AUTOUNUSED unused inputs/inouts
9412 `verilog-auto-wire' for AUTOWIRE instantiation wires
9413
9414 `verilog-read-defines' for reading `define values
9415 `verilog-read-includes' for reading `includes
9416
9417 If you have bugs with these autos, try contacting the AUTOAUTHOR
9418 Wilson Snyder (wsnyder@wsnyder.org), and/or see http://www.veripool.com."
9419 (interactive)
9420 (unless noninteractive (message "Updating AUTOs..."))
9421 (if (fboundp 'dinotrace-unannotate-all)
9422 (dinotrace-unannotate-all))
9423 (let ((oldbuf (if (not (buffer-modified-p))
9424 (buffer-string)))
9425 ;; Before version 20, match-string with font-lock returns a
9426 ;; vector that is not equal to the string. IE if on "input"
9427 ;; nil==(equal "input" (progn (looking-at "input") (match-string 0)))
9428 (fontlocked (when (and (boundp 'font-lock-mode)
9429 font-lock-mode)
9430 (font-lock-mode nil)
9431 t)))
9432 (unwind-protect
9433 (save-excursion
9434 ;; If we're not in verilog-mode, change syntax table so parsing works right
9435 (unless (eq major-mode `verilog-mode) (verilog-mode))
9436 ;; Allow user to customize
9437 (run-hooks 'verilog-before-auto-hook)
9438 ;; Try to save the user from needing to revert-file to reread file local-variables
9439 (verilog-auto-reeval-locals)
9440 (verilog-read-auto-lisp (point-min) (point-max))
9441 (verilog-getopt-flags)
9442 ;; These two may seem obvious to do always, but on large includes it can be way too slow
9443 (when verilog-auto-read-includes
9444 (verilog-read-includes)
9445 (verilog-read-defines nil nil t))
9446 ;; This particular ordering is important
9447 ;; INST: Lower modules correct, no internal dependencies, FIRST
9448 (verilog-preserve-cache
9449 ;; Clear existing autos else we'll be screwed by existing ones
9450 (verilog-delete-auto)
9451 ;; Injection if appropriate
9452 (when inject
9453 (verilog-inject-inst)
9454 (verilog-inject-sense)
9455 (verilog-inject-arg))
9456 ;;
9457 (verilog-auto-search-do "/*AUTOINSTPARAM*/" 'verilog-auto-inst-param)
9458 (verilog-auto-search-do "/*AUTOINST*/" 'verilog-auto-inst)
9459 (verilog-auto-search-do ".*" 'verilog-auto-star)
9460 ;; Doesn't matter when done, but combine it with a common changer
9461 (verilog-auto-re-search-do "/\\*\\(AUTOSENSE\\|AS\\)\\*/" 'verilog-auto-sense)
9462 (verilog-auto-re-search-do "/\\*AUTORESET\\*/" 'verilog-auto-reset)
9463 ;; Must be done before autoin/out as creates a reg
9464 (verilog-auto-re-search-do "/\\*AUTOASCIIENUM([^)]*)\\*/" 'verilog-auto-ascii-enum)
9465 ;;
9466 ;; first in/outs from other files
9467 (verilog-auto-re-search-do "/\\*AUTOINOUTMODULE([^)]*)\\*/" 'verilog-auto-inout-module)
9468 ;; next in/outs which need previous sucked inputs first
9469 (verilog-auto-search-do "/*AUTOOUTPUT*/" 'verilog-auto-output)
9470 (verilog-auto-search-do "/*AUTOINPUT*/" 'verilog-auto-input)
9471 (verilog-auto-search-do "/*AUTOINOUT*/" 'verilog-auto-inout)
9472 ;; Then tie off those in/outs
9473 (verilog-auto-search-do "/*AUTOTIEOFF*/" 'verilog-auto-tieoff)
9474 ;; Wires/regs must be after inputs/outputs
9475 (verilog-auto-search-do "/*AUTOWIRE*/" 'verilog-auto-wire)
9476 (verilog-auto-search-do "/*AUTOREG*/" 'verilog-auto-reg)
9477 (verilog-auto-search-do "/*AUTOREGINPUT*/" 'verilog-auto-reg-input)
9478 ;; outputevery needs AUTOOUTPUTs done first
9479 (verilog-auto-search-do "/*AUTOOUTPUTEVERY*/" 'verilog-auto-output-every)
9480 ;; After we've created all new variables
9481 (verilog-auto-search-do "/*AUTOUNUSED*/" 'verilog-auto-unused)
9482 ;; Must be after all inputs outputs are generated
9483 (verilog-auto-search-do "/*AUTOARG*/" 'verilog-auto-arg)
9484 ;; Fix line numbers (comments only)
9485 (verilog-auto-templated-rel))
9486 ;;
9487 (run-hooks 'verilog-auto-hook)
9488 ;;
9489 (set (make-local-variable 'verilog-auto-update-tick) (buffer-modified-tick))
9490 ;;
9491 ;; If end result is same as when started, clear modified flag
9492 (cond ((and oldbuf (equal oldbuf (buffer-string)))
9493 (set-buffer-modified-p nil)
9494 (unless noninteractive (message "Updating AUTOs...done (no changes)")))
9495 (t (unless noninteractive (message "Updating AUTOs...done")))))
9496 ;; Unwind forms
9497 (progn
9498 ;; Restore font-lock
9499 (when fontlocked (font-lock-mode t))))))
9500 \f
9501
9502 ;;
9503 ;; Skeleton based code insertion
9504 ;;
9505 (defvar verilog-template-map
9506 (let ((map (make-sparse-keymap)))
9507 (define-key map "a" 'verilog-sk-always)
9508 (define-key map "b" 'verilog-sk-begin)
9509 (define-key map "c" 'verilog-sk-case)
9510 (define-key map "f" 'verilog-sk-for)
9511 (define-key map "g" 'verilog-sk-generate)
9512 (define-key map "h" 'verilog-sk-header)
9513 (define-key map "i" 'verilog-sk-initial)
9514 (define-key map "j" 'verilog-sk-fork)
9515 (define-key map "m" 'verilog-sk-module)
9516 (define-key map "p" 'verilog-sk-primitive)
9517 (define-key map "r" 'verilog-sk-repeat)
9518 (define-key map "s" 'verilog-sk-specify)
9519 (define-key map "t" 'verilog-sk-task)
9520 (define-key map "w" 'verilog-sk-while)
9521 (define-key map "x" 'verilog-sk-casex)
9522 (define-key map "z" 'verilog-sk-casez)
9523 (define-key map "?" 'verilog-sk-if)
9524 (define-key map ":" 'verilog-sk-else-if)
9525 (define-key map "/" 'verilog-sk-comment)
9526 (define-key map "A" 'verilog-sk-assign)
9527 (define-key map "F" 'verilog-sk-function)
9528 (define-key map "I" 'verilog-sk-input)
9529 (define-key map "O" 'verilog-sk-output)
9530 (define-key map "S" 'verilog-sk-state-machine)
9531 (define-key map "=" 'verilog-sk-inout)
9532 (define-key map "W" 'verilog-sk-wire)
9533 (define-key map "R" 'verilog-sk-reg)
9534 (define-key map "D" 'verilog-sk-define-signal)
9535 map)
9536 "Keymap used in Verilog mode for smart template operations.")
9537
9538
9539 ;;
9540 ;; Place the templates into Verilog Mode. They may be inserted under any key.
9541 ;; C-c C-t will be the default. If you use templates a lot, you
9542 ;; may want to consider moving the binding to another key in your .emacs
9543 ;; file.
9544 ;;
9545 ;(define-key verilog-mode-map "\C-ct" verilog-template-map)
9546 (define-key verilog-mode-map "\C-c\C-t" verilog-template-map)
9547
9548 ;;; ---- statement skeletons ------------------------------------------
9549
9550 (define-skeleton verilog-sk-prompt-condition
9551 "Prompt for the loop condition."
9552 "[condition]: " str )
9553
9554 (define-skeleton verilog-sk-prompt-init
9555 "Prompt for the loop init statement."
9556 "[initial statement]: " str )
9557
9558 (define-skeleton verilog-sk-prompt-inc
9559 "Prompt for the loop increment statement."
9560 "[increment statement]: " str )
9561
9562 (define-skeleton verilog-sk-prompt-name
9563 "Prompt for the name of something."
9564 "[name]: " str)
9565
9566 (define-skeleton verilog-sk-prompt-clock
9567 "Prompt for the name of something."
9568 "name and edge of clock(s): " str)
9569
9570 (defvar verilog-sk-reset nil)
9571 (defun verilog-sk-prompt-reset ()
9572 "Prompt for the name of a state machine reset."
9573 (setq verilog-sk-reset (read-string "name of reset: " "rst")))
9574
9575
9576 (define-skeleton verilog-sk-prompt-state-selector
9577 "Prompt for the name of a state machine selector."
9578 "name of selector (eg {a,b,c,d}): " str )
9579
9580 (define-skeleton verilog-sk-prompt-output
9581 "Prompt for the name of something."
9582 "output: " str)
9583
9584 (define-skeleton verilog-sk-prompt-msb
9585 "Prompt for least significant bit specification."
9586 "msb:" str & ?: & '(verilog-sk-prompt-lsb) | -1 )
9587
9588 (define-skeleton verilog-sk-prompt-lsb
9589 "Prompt for least significant bit specification."
9590 "lsb:" str )
9591
9592 (defvar verilog-sk-p nil)
9593 (define-skeleton verilog-sk-prompt-width
9594 "Prompt for a width specification."
9595 ()
9596 (progn
9597 (setq verilog-sk-p (point))
9598 (verilog-sk-prompt-msb)
9599 (if (> (point) verilog-sk-p) "] " " ")))
9600
9601 (defun verilog-sk-header ()
9602 "Insert a descriptive header at the top of the file."
9603 (interactive "*")
9604 (save-excursion
9605 (goto-char (point-min))
9606 (verilog-sk-header-tmpl)))
9607
9608 (define-skeleton verilog-sk-header-tmpl
9609 "Insert a comment block containing the module title, author, etc."
9610 "[Description]: "
9611 "// -*- Mode: Verilog -*-"
9612 "\n// Filename : " (buffer-name)
9613 "\n// Description : " str
9614 "\n// Author : " (user-full-name)
9615 "\n// Created On : " (current-time-string)
9616 "\n// Last Modified By: ."
9617 "\n// Last Modified On: ."
9618 "\n// Update Count : 0"
9619 "\n// Status : Unknown, Use with caution!"
9620 "\n")
9621
9622 (define-skeleton verilog-sk-module
9623 "Insert a module definition."
9624 ()
9625 > "module " '(verilog-sk-prompt-name) " (/*AUTOARG*/ ) ;" \n
9626 > _ \n
9627 > (- verilog-indent-level-behavioral) "endmodule" (progn (electric-verilog-terminate-line) nil))
9628
9629 (define-skeleton verilog-sk-primitive
9630 "Insert a task definition."
9631 ()
9632 > "primitive " '(verilog-sk-prompt-name) " ( " '(verilog-sk-prompt-output) ("input:" ", " str ) " );"\n
9633 > _ \n
9634 > (- verilog-indent-level-behavioral) "endprimitive" (progn (electric-verilog-terminate-line) nil))
9635
9636 (define-skeleton verilog-sk-task
9637 "Insert a task definition."
9638 ()
9639 > "task " '(verilog-sk-prompt-name) & ?; \n
9640 > _ \n
9641 > "begin" \n
9642 > \n
9643 > (- verilog-indent-level-behavioral) "end" \n
9644 > (- verilog-indent-level-behavioral) "endtask" (progn (electric-verilog-terminate-line) nil))
9645
9646 (define-skeleton verilog-sk-function
9647 "Insert a function definition."
9648 ()
9649 > "function [" '(verilog-sk-prompt-width) | -1 '(verilog-sk-prompt-name) ?; \n
9650 > _ \n
9651 > "begin" \n
9652 > \n
9653 > (- verilog-indent-level-behavioral) "end" \n
9654 > (- verilog-indent-level-behavioral) "endfunction" (progn (electric-verilog-terminate-line) nil))
9655
9656 (define-skeleton verilog-sk-always
9657 "Insert always block. Uses the minibuffer to prompt
9658 for sensitivity list."
9659 ()
9660 > "always @ ( /*AUTOSENSE*/ ) begin\n"
9661 > _ \n
9662 > (- verilog-indent-level-behavioral) "end" \n >
9663 )
9664
9665 (define-skeleton verilog-sk-initial
9666 "Insert an initial block."
9667 ()
9668 > "initial begin\n"
9669 > _ \n
9670 > (- verilog-indent-level-behavioral) "end" \n > )
9671
9672 (define-skeleton verilog-sk-specify
9673 "Insert specify block. "
9674 ()
9675 > "specify\n"
9676 > _ \n
9677 > (- verilog-indent-level-behavioral) "endspecify" \n > )
9678
9679 (define-skeleton verilog-sk-generate
9680 "Insert generate block. "
9681 ()
9682 > "generate\n"
9683 > _ \n
9684 > (- verilog-indent-level-behavioral) "endgenerate" \n > )
9685
9686 (define-skeleton verilog-sk-begin
9687 "Insert begin end block. Uses the minibuffer to prompt for name."
9688 ()
9689 > "begin" '(verilog-sk-prompt-name) \n
9690 > _ \n
9691 > (- verilog-indent-level-behavioral) "end"
9692 )
9693
9694 (define-skeleton verilog-sk-fork
9695 "Insert a fork join block."
9696 ()
9697 > "fork\n"
9698 > "begin" \n
9699 > _ \n
9700 > (- verilog-indent-level-behavioral) "end" \n
9701 > "begin" \n
9702 > \n
9703 > (- verilog-indent-level-behavioral) "end" \n
9704 > (- verilog-indent-level-behavioral) "join" \n
9705 > )
9706
9707
9708 (define-skeleton verilog-sk-case
9709 "Build skeleton case statement, prompting for the selector expression,
9710 and the case items."
9711 "[selector expression]: "
9712 > "case (" str ") " \n
9713 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n )
9714 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
9715
9716 (define-skeleton verilog-sk-casex
9717 "Build skeleton casex statement, prompting for the selector expression,
9718 and the case items."
9719 "[selector expression]: "
9720 > "casex (" str ") " \n
9721 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n )
9722 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
9723
9724 (define-skeleton verilog-sk-casez
9725 "Build skeleton casez statement, prompting for the selector expression,
9726 and the case items."
9727 "[selector expression]: "
9728 > "casez (" str ") " \n
9729 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n )
9730 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
9731
9732 (define-skeleton verilog-sk-if
9733 "Insert a skeleton if statement."
9734 > "if (" '(verilog-sk-prompt-condition) & ")" " begin" \n
9735 > _ \n
9736 > (- verilog-indent-level-behavioral) "end " \n )
9737
9738 (define-skeleton verilog-sk-else-if
9739 "Insert a skeleton else if statement."
9740 > (verilog-indent-line) "else if ("
9741 (progn (setq verilog-sk-p (point)) nil) '(verilog-sk-prompt-condition) (if (> (point) verilog-sk-p) ") " -1 ) & " begin" \n
9742 > _ \n
9743 > "end" (progn (electric-verilog-terminate-line) nil))
9744
9745 (define-skeleton verilog-sk-datadef
9746 "Common routine to get data definition."
9747 ()
9748 '(verilog-sk-prompt-width) | -1 ("name (RET to end):" str ", ") -2 ";" \n)
9749
9750 (define-skeleton verilog-sk-input
9751 "Insert an input definition."
9752 ()
9753 > "input [" '(verilog-sk-datadef))
9754
9755 (define-skeleton verilog-sk-output
9756 "Insert an output definition."
9757 ()
9758 > "output [" '(verilog-sk-datadef))
9759
9760 (define-skeleton verilog-sk-inout
9761 "Insert an inout definition."
9762 ()
9763 > "inout [" '(verilog-sk-datadef))
9764
9765 (defvar verilog-sk-signal nil)
9766 (define-skeleton verilog-sk-def-reg
9767 "Insert a reg definition."
9768 ()
9769 > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-signal ";" \n (verilog-pretty-declarations) )
9770
9771 (defun verilog-sk-define-signal ()
9772 "Insert a definition of signal under point at top of module."
9773 (interactive "*")
9774 (let* ((sig-re "[a-zA-Z0-9_]*")
9775 (v1 (buffer-substring
9776 (save-excursion
9777 (skip-chars-backward sig-re)
9778 (point))
9779 (save-excursion
9780 (skip-chars-forward sig-re)
9781 (point)))))
9782 (if (not (member v1 verilog-keywords))
9783 (save-excursion
9784 (setq verilog-sk-signal v1)
9785 (verilog-beg-of-defun)
9786 (verilog-end-of-statement)
9787 (verilog-forward-syntactic-ws)
9788 (verilog-sk-def-reg)
9789 (message "signal at point is %s" v1))
9790 (message "object at point (%s) is a keyword" v1))))
9791
9792 (define-skeleton verilog-sk-wire
9793 "Insert a wire definition."
9794 ()
9795 > "wire [" '(verilog-sk-datadef))
9796
9797 (define-skeleton verilog-sk-reg
9798 "Insert a reg definition."
9799 ()
9800 > "reg [" '(verilog-sk-datadef))
9801
9802 (define-skeleton verilog-sk-assign
9803 "Insert a skeleton assign statement."
9804 ()
9805 > "assign " '(verilog-sk-prompt-name) " = " _ ";" \n)
9806
9807 (define-skeleton verilog-sk-while
9808 "Insert a skeleton while loop statement."
9809 ()
9810 > "while (" '(verilog-sk-prompt-condition) ") begin" \n
9811 > _ \n
9812 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
9813
9814 (define-skeleton verilog-sk-repeat
9815 "Insert a skeleton repeat loop statement."
9816 ()
9817 > "repeat (" '(verilog-sk-prompt-condition) ") begin" \n
9818 > _ \n
9819 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
9820
9821 (define-skeleton verilog-sk-for
9822 "Insert a skeleton while loop statement."
9823 ()
9824 > "for ("
9825 '(verilog-sk-prompt-init) "; "
9826 '(verilog-sk-prompt-condition) "; "
9827 '(verilog-sk-prompt-inc)
9828 ") begin" \n
9829 > _ \n
9830 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
9831
9832 (define-skeleton verilog-sk-comment
9833 "Inserts three comment lines, making a display comment."
9834 ()
9835 > "/*\n"
9836 > "* " _ \n
9837 > "*/")
9838
9839 (define-skeleton verilog-sk-state-machine
9840 "Insert a state machine definition."
9841 "Name of state variable: "
9842 '(setq input "state")
9843 > "// State registers for " str | -23 \n
9844 '(setq verilog-sk-state str)
9845 > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-state ", next_" verilog-sk-state ?; \n
9846 '(setq input nil)
9847 > \n
9848 > "// State FF for " verilog-sk-state \n
9849 > "always @ ( " (read-string "clock:" "posedge clk") " or " (verilog-sk-prompt-reset) " ) begin" \n
9850 > "if ( " verilog-sk-reset " ) " verilog-sk-state " = 0; else" \n
9851 > verilog-sk-state " = next_" verilog-sk-state ?; \n
9852 > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil)
9853 > \n
9854 > "// Next State Logic for " verilog-sk-state \n
9855 > "always @ ( /*AUTOSENSE*/ ) begin\n"
9856 > "case (" '(verilog-sk-prompt-state-selector) ") " \n
9857 > ("case selector: " str ": begin" \n > "next_" verilog-sk-state " = " _ ";" \n > (- verilog-indent-level-behavioral) "end" \n )
9858 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil)
9859 > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil))
9860 \f
9861
9862 ;;
9863 ;; Include file loading with mouse/return event
9864 ;;
9865 ;; idea & first impl.: M. Rouat (eldo-mode.el)
9866 ;; second (emacs/xemacs) impl.: G. Van der Plas (spice-mode.el)
9867
9868 (if (featurep 'xemacs)
9869 (require 'overlay)
9870 (require 'lucid)) ;; what else can we do ??
9871
9872 (defconst verilog-include-file-regexp
9873 "^`include\\s-+\"\\([^\n\"]*\\)\""
9874 "Regexp that matches the include file.")
9875
9876 (defvar verilog-mode-mouse-map
9877 (let ((map (make-sparse-keymap))) ; as described in info pages, make a map
9878 (set-keymap-parent map verilog-mode-map)
9879 ;; mouse button bindings
9880 (define-key map "\r" 'verilog-load-file-at-point)
9881 (if (featurep 'xemacs)
9882 (define-key map 'button2 'verilog-load-file-at-mouse);ffap-at-mouse ?
9883 (define-key map [mouse-2] 'verilog-load-file-at-mouse))
9884 (if (featurep 'xemacs)
9885 (define-key map 'Sh-button2 'mouse-yank) ; you wanna paste don't you ?
9886 (define-key map [S-mouse-2] 'mouse-yank-at-click))
9887 map)
9888 "Map containing mouse bindings for `verilog-mode'.")
9889
9890
9891 (defun verilog-colorize-include-files (beg end old-len)
9892 "This function colorizes included files when the mouse passes over them.
9893 Clicking on the middle-mouse button loads them in a buffer (as in dired)."
9894 (save-excursion
9895 (save-match-data
9896 (let (end-point)
9897 (goto-char end)
9898 (setq end-point (verilog-get-end-of-line))
9899 (goto-char beg)
9900 (beginning-of-line) ; scan entire line !
9901 ;; delete overlays existing on this line
9902 (let ((overlays (overlays-in (point) end-point)))
9903 (while overlays
9904 (if (and
9905 (overlay-get (car overlays) 'detachable)
9906 (overlay-get (car overlays) 'verilog-include-file))
9907 (delete-overlay (car overlays)))
9908 (setq overlays (cdr overlays)))) ; let
9909 ;; make new ones, could reuse deleted one ?
9910 (while (search-forward-regexp verilog-include-file-regexp end-point t)
9911 (let (ov)
9912 (goto-char (match-beginning 1))
9913 (setq ov (make-overlay (match-beginning 1) (match-end 1)))
9914 (overlay-put ov 'start-closed 't)
9915 (overlay-put ov 'end-closed 't)
9916 (overlay-put ov 'evaporate 't)
9917 (overlay-put ov 'verilog-include-file 't)
9918 (overlay-put ov 'mouse-face 'highlight)
9919 (overlay-put ov 'local-map verilog-mode-mouse-map)))))))
9920
9921
9922 (defun verilog-colorize-include-files-buffer ()
9923 "Colorize an include file."
9924 (interactive)
9925 ;; delete overlays
9926 (let ((overlays (overlays-in (point-min) (point-max))))
9927 (while overlays
9928 (if (and
9929 (overlay-get (car overlays) 'detachable)
9930 (overlay-get (car overlays) 'verilog-include-file))
9931 (delete-overlay (car overlays)))
9932 (setq overlays (cdr overlays)))) ; let
9933 ;; remake overlays
9934 (verilog-colorize-include-files (point-min) (point-max) nil))
9935
9936 ;; ffap-at-mouse isn't useful for Verilog mode. It uses library paths.
9937 ;; so define this function to do more or less the same as ffap-at-mouse
9938 ;; but first resolve filename...
9939 (defun verilog-load-file-at-mouse (event)
9940 "Load file under button 2 click's EVENT.
9941 Files are checked based on `verilog-library-directories'."
9942 (interactive "@e")
9943 (save-excursion ;; implement a Verilog specific ffap-at-mouse
9944 (mouse-set-point event)
9945 (beginning-of-line)
9946 (if (looking-at verilog-include-file-regexp)
9947 (if (and (car (verilog-library-filenames
9948 (match-string 1) (buffer-file-name)))
9949 (file-readable-p (car (verilog-library-filenames
9950 (match-string 1) (buffer-file-name)))))
9951 (find-file (car (verilog-library-filenames
9952 (match-string 1) (buffer-file-name))))
9953 (progn
9954 (message
9955 "File '%s' isn't readable, use shift-mouse2 to paste in this field"
9956 (match-string 1)))))))
9957
9958 ;; ffap isn't useable for Verilog mode. It uses library paths.
9959 ;; so define this function to do more or less the same as ffap
9960 ;; but first resolve filename...
9961 (defun verilog-load-file-at-point ()
9962 "Load file under point.
9963 Files are checked based on `verilog-library-directories'."
9964 (interactive)
9965 (save-excursion ;; implement a Verilog specific ffap
9966 (beginning-of-line)
9967 (if (looking-at verilog-include-file-regexp)
9968 (if (and
9969 (car (verilog-library-filenames
9970 (match-string 1) (buffer-file-name)))
9971 (file-readable-p (car (verilog-library-filenames
9972 (match-string 1) (buffer-file-name)))))
9973 (find-file (car (verilog-library-filenames
9974 (match-string 1) (buffer-file-name))))))))
9975
9976
9977 ;;
9978 ;; Bug reporting
9979 ;;
9980
9981 (defun verilog-faq ()
9982 "Tell the user their current version, and where to get the FAQ etc."
9983 (interactive)
9984 (with-output-to-temp-buffer "*verilog-mode help*"
9985 (princ (format "You are using verilog-mode %s\n" verilog-mode-version))
9986 (princ "\n")
9987 (princ "For new releases, see http://www.verilog.com\n")
9988 (princ "\n")
9989 (princ "For frequently asked questions, see http://www.veripool.com/verilog-mode-faq.html\n")
9990 (princ "\n")
9991 (princ "To submit a bug, use M-x verilog-submit-bug-report\n")
9992 (princ "\n")))
9993
9994 (autoload 'reporter-submit-bug-report "reporter")
9995 (defvar reporter-prompt-for-summary-p)
9996
9997 (defun verilog-submit-bug-report ()
9998 "Submit via mail a bug report on verilog-mode.el."
9999 (interactive)
10000 (let ((reporter-prompt-for-summary-p t))
10001 (reporter-submit-bug-report
10002 "mac@verilog.com"
10003 (concat "verilog-mode v" verilog-mode-version)
10004 '(
10005 verilog-align-ifelse
10006 verilog-auto-endcomments
10007 verilog-auto-hook
10008 verilog-auto-indent-on-newline
10009 verilog-auto-inst-vector
10010 verilog-auto-inst-template-numbers
10011 verilog-auto-lineup
10012 verilog-auto-newline
10013 verilog-auto-save-policy
10014 verilog-auto-sense-defines-constant
10015 verilog-auto-sense-include-inputs
10016 verilog-before-auto-hook
10017 verilog-case-indent
10018 verilog-cexp-indent
10019 verilog-compiler
10020 verilog-coverage
10021 verilog-highlight-translate-off
10022 verilog-indent-begin-after-if
10023 verilog-indent-declaration-macros
10024 verilog-indent-level
10025 verilog-indent-level-behavioral
10026 verilog-indent-level-declaration
10027 verilog-indent-level-directive
10028 verilog-indent-level-module
10029 verilog-indent-lists
10030 verilog-library-flags
10031 verilog-library-directories
10032 verilog-library-extensions
10033 verilog-library-files
10034 verilog-linter
10035 verilog-minimum-comment-distance
10036 verilog-mode-hook
10037 verilog-simulator
10038 verilog-tab-always-indent
10039 verilog-tab-to-comment
10040 )
10041 nil nil
10042 (concat "Hi Mac,
10043
10044 I want to report a bug. I've read the `Bugs' section of `Info' on
10045 Emacs, so I know how to make a clear and unambiguous report. To get
10046 to that Info section, I typed
10047
10048 M-x info RET m " invocation-name " RET m bugs RET
10049
10050 Before I go further, I want to say that Verilog mode has changed my life.
10051 I save so much time, my files are colored nicely, my co workers respect
10052 my coding ability... until now. I'd really appreciate anything you
10053 could do to help me out with this minor deficiency in the product.
10054
10055 If you have bugs with the AUTO functions, please CC the AUTOAUTHOR Wilson
10056 Snyder (wsnyder@wsnyder.org) and/or see http://www.veripool.com.
10057 You may also want to look at the Verilog-Mode FAQ, see
10058 http://www.veripool.com/verilog-mode-faq.html.
10059
10060 To reproduce the bug, start a fresh Emacs via " invocation-name "
10061 -no-init-file -no-site-file'. In a new buffer, in Verilog mode, type
10062 the code included below.
10063
10064 Given those lines, I expected [[Fill in here]] to happen;
10065 but instead, [[Fill in here]] happens!.
10066
10067 == The code: =="))))
10068
10069 (provide 'verilog-mode)
10070
10071 ;; Local Variables:
10072 ;; checkdoc-permit-comma-termination-flag:t
10073 ;; checkdoc-force-docstrings-flag:nil
10074 ;; End:
10075
10076 ;; arch-tag: 87923725-57b3-41b5-9494-be21118c6a6f
10077 ;;; verilog-mode.el ends here