Debian Codegraph @

codemirror-legacy-modes/mode/verilog.js

raw
1 function mkVerilog(parserConfig) {
2
3 var statementIndentUnit = parserConfig.statementIndentUnit,
4 dontAlignCalls = parserConfig.dontAlignCalls,
5 noIndentKeywords = parserConfig.noIndentKeywords || [],
6 multiLineStrings = parserConfig.multiLineStrings,
7 hooks = parserConfig.hooks || {};
8
9 function words(str) {
10 var obj = {}, words = str.split(" ");
11 for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
12 return obj;
13 }
14
15 /**
16 * Keywords from IEEE 1800-2012
17 */
18 var keywords = words(
19 "accept_on alias always always_comb always_ff always_latch and assert assign assume automatic before begin bind " +
20 "bins binsof bit break buf bufif0 bufif1 byte case casex casez cell chandle checker class clocking cmos config " +
21 "const constraint context continue cover covergroup coverpoint cross deassign default defparam design disable " +
22 "dist do edge else end endcase endchecker endclass endclocking endconfig endfunction endgenerate endgroup " +
23 "endinterface endmodule endpackage endprimitive endprogram endproperty endspecify endsequence endtable endtask " +
24 "enum event eventually expect export extends extern final first_match for force foreach forever fork forkjoin " +
25 "function generate genvar global highz0 highz1 if iff ifnone ignore_bins illegal_bins implements implies import " +
26 "incdir include initial inout input inside instance int integer interconnect interface intersect join join_any " +
27 "join_none large let liblist library local localparam logic longint macromodule matches medium modport module " +
28 "nand negedge nettype new nexttime nmos nor noshowcancelled not notif0 notif1 null or output package packed " +
29 "parameter pmos posedge primitive priority program property protected pull0 pull1 pulldown pullup " +
30 "pulsestyle_ondetect pulsestyle_onevent pure rand randc randcase randsequence rcmos real realtime ref reg " +
31 "reject_on release repeat restrict return rnmos rpmos rtran rtranif0 rtranif1 s_always s_eventually s_nexttime " +
32 "s_until s_until_with scalared sequence shortint shortreal showcancelled signed small soft solve specify " +
33 "specparam static string strong strong0 strong1 struct super supply0 supply1 sync_accept_on sync_reject_on " +
34 "table tagged task this throughout time timeprecision timeunit tran tranif0 tranif1 tri tri0 tri1 triand trior " +
35 "trireg type typedef union unique unique0 unsigned until until_with untyped use uwire var vectored virtual void " +
36 "wait wait_order wand weak weak0 weak1 while wildcard wire with within wor xnor xor");
37
38 /** Operators from IEEE 1800-2012
39 unary_operator ::=
40 + | - | ! | ~ | & | ~& | | | ~| | ^ | ~^ | ^~
41 binary_operator ::=
42 + | - | * | / | % | == | != | === | !== | ==? | !=? | && | || | **
43 | < | <= | > | >= | & | | | ^ | ^~ | ~^ | >> | << | >>> | <<<
44 | -> | <->
45 inc_or_dec_operator ::= ++ | --
46 unary_module_path_operator ::=
47 ! | ~ | & | ~& | | | ~| | ^ | ~^ | ^~
48 binary_module_path_operator ::=
49 == | != | && | || | & | | | ^ | ^~ | ~^
50 */
51 var isOperatorChar = /[\+\-\*\/!~&|^%=?:]/;
52 var isBracketChar = /[\[\]{}()]/;
53
54 var unsignedNumber = /\d[0-9_]*/;
55 var decimalLiteral = /\d*\s*'s?d\s*\d[0-9_]*/i;
56 var binaryLiteral = /\d*\s*'s?b\s*[xz01][xz01_]*/i;
57 var octLiteral = /\d*\s*'s?o\s*[xz0-7][xz0-7_]*/i;
58 var hexLiteral = /\d*\s*'s?h\s*[0-9a-fxz?][0-9a-fxz?_]*/i;
59 var realLiteral = /(\d[\d_]*(\.\d[\d_]*)?E-?[\d_]+)|(\d[\d_]*\.\d[\d_]*)/i;
60
61 var closingBracketOrWord = /^((\w+)|[)}\]])/;
62 var closingBracket = /[)}\]]/;
63
64 var curPunc;
65 var curKeyword;
66
67 // Block openings which are closed by a matching keyword in the form of ("end" + keyword)
68 // E.g. "task" => "endtask"
69 var blockKeywords = words(
70 "case checker class clocking config function generate interface module package " +
71 "primitive program property specify sequence table task"
72 );
73
74 // Opening/closing pairs
75 var openClose = {};
76 for (var keyword in blockKeywords) {
77 openClose[keyword] = "end" + keyword;
78 }
79 openClose["begin"] = "end";
80 openClose["casex"] = "endcase";
81 openClose["casez"] = "endcase";
82 openClose["do" ] = "while";
83 openClose["fork" ] = "join;join_any;join_none";
84 openClose["covergroup"] = "endgroup";
85
86 for (var i in noIndentKeywords) {
87 var keyword = noIndentKeywords[i];
88 if (openClose[keyword]) {
89 openClose[keyword] = undefined;
90 }
91 }
92
93 // Keywords which open statements that are ended with a semi-colon
94 var statementKeywords = words("always always_comb always_ff always_latch assert assign assume else export for foreach forever if import initial repeat while");
95
96 function tokenBase(stream, state) {
97 var ch = stream.peek(), style;
98 if (hooks[ch] && (style = hooks[ch](stream, state)) != false) return style;
99 if (hooks.tokenBase && (style = hooks.tokenBase(stream, state)) != false)
100 return style;
101
102 if (/[,;:\.]/.test(ch)) {
103 curPunc = stream.next();
104 return null;
105 }
106 if (isBracketChar.test(ch)) {
107 curPunc = stream.next();
108 return "bracket";
109 }
110 // Macros (tick-defines)
111 if (ch == '`') {
112 stream.next();
113 if (stream.eatWhile(/[\w\$_]/)) {
114 return "def";
115 } else {
116 return null;
117 }
118 }
119 // System calls
120 if (ch == '$') {
121 stream.next();
122 if (stream.eatWhile(/[\w\$_]/)) {
123 return "meta";
124 } else {
125 return null;
126 }
127 }
128 // Time literals
129 if (ch == '#') {
130 stream.next();
131 stream.eatWhile(/[\d_.]/);
132 return "def";
133 }
134 // Strings
135 if (ch == '"') {
136 stream.next();
137 state.tokenize = tokenString(ch);
138 return state.tokenize(stream, state);
139 }
140 // Comments
141 if (ch == "/") {
142 stream.next();
143 if (stream.eat("*")) {
144 state.tokenize = tokenComment;
145 return tokenComment(stream, state);
146 }
147 if (stream.eat("/")) {
148 stream.skipToEnd();
149 return "comment";
150 }
151 stream.backUp(1);
152 }
153
154 // Numeric literals
155 if (stream.match(realLiteral) ||
156 stream.match(decimalLiteral) ||
157 stream.match(binaryLiteral) ||
158 stream.match(octLiteral) ||
159 stream.match(hexLiteral) ||
160 stream.match(unsignedNumber) ||
161 stream.match(realLiteral)) {
162 return "number";
163 }
164
165 // Operators
166 if (stream.eatWhile(isOperatorChar)) {
167 return "meta";
168 }
169
170 // Keywords / plain variables
171 if (stream.eatWhile(/[\w\$_]/)) {
172 var cur = stream.current();
173 if (keywords[cur]) {
174 if (openClose[cur]) {
175 curPunc = "newblock";
176 }
177 if (statementKeywords[cur]) {
178 curPunc = "newstatement";
179 }
180 curKeyword = cur;
181 return "keyword";
182 }
183 return "variable";
184 }
185
186 stream.next();
187 return null;
188 }
189
190 function tokenString(quote) {
191 return function(stream, state) {
192 var escaped = false, next, end = false;
193 while ((next = stream.next()) != null) {
194 if (next == quote && !escaped) {end = true; break;}
195 escaped = !escaped && next == "\\";
196 }
197 if (end || !(escaped || multiLineStrings))
198 state.tokenize = tokenBase;
199 return "string";
200 };
201 }
202
203 function tokenComment(stream, state) {
204 var maybeEnd = false, ch;
205 while (ch = stream.next()) {
206 if (ch == "/" && maybeEnd) {
207 state.tokenize = tokenBase;
208 break;
209 }
210 maybeEnd = (ch == "*");
211 }
212 return "comment";
213 }
214
215 function Context(indented, column, type, align, prev) {
216 this.indented = indented;
217 this.column = column;
218 this.type = type;
219 this.align = align;
220 this.prev = prev;
221 }
222 function pushContext(state, col, type) {
223 var indent = state.indented;
224 var c = new Context(indent, col, type, null, state.context);
225 return state.context = c;
226 }
227 function popContext(state) {
228 var t = state.context.type;
229 if (t == ")" || t == "]" || t == "}") {
230 state.indented = state.context.indented;
231 }
232 return state.context = state.context.prev;
233 }
234
235 function isClosing(text, contextClosing) {
236 if (text == contextClosing) {
237 return true;
238 } else {
239 // contextClosing may be multiple keywords separated by ;
240 var closingKeywords = contextClosing.split(";");
241 for (var i in closingKeywords) {
242 if (text == closingKeywords[i]) {
243 return true;
244 }
245 }
246 return false;
247 }
248 }
249
250 function buildElectricInputRegEx() {
251 // Reindentation should occur on any bracket char: {}()[]
252 // or on a match of any of the block closing keywords, at
253 // the end of a line
254 var allClosings = [];
255 for (var i in openClose) {
256 if (openClose[i]) {
257 var closings = openClose[i].split(";");
258 for (var j in closings) {
259 allClosings.push(closings[j]);
260 }
261 }
262 }
263 var re = new RegExp("[{}()\\[\\]]|(" + allClosings.join("|") + ")$");
264 return re;
265 }
266
267 // Interface
268 return {
269 name: "verilog",
270
271 startState: function(indentUnit) {
272 var state = {
273 tokenize: null,
274 context: new Context(-indentUnit, 0, "top", false),
275 indented: 0,
276 startOfLine: true
277 };
278 if (hooks.startState) hooks.startState(state);
279 return state;
280 },
281
282 token: function(stream, state) {
283 var ctx = state.context;
284 if (stream.sol()) {
285 if (ctx.align == null) ctx.align = false;
286 state.indented = stream.indentation();
287 state.startOfLine = true;
288 }
289 if (hooks.token) {
290 // Call hook, with an optional return value of a style to override verilog styling.
291 var style = hooks.token(stream, state);
292 if (style !== undefined) {
293 return style;
294 }
295 }
296 if (stream.eatSpace()) return null;
297 curPunc = null;
298 curKeyword = null;
299 var style = (state.tokenize || tokenBase)(stream, state);
300 if (style == "comment" || style == "meta" || style == "variable") return style;
301 if (ctx.align == null) ctx.align = true;
302
303 if (curPunc == ctx.type) {
304 popContext(state);
305 } else if ((curPunc == ";" && ctx.type == "statement") ||
306 (ctx.type && isClosing(curKeyword, ctx.type))) {
307 ctx = popContext(state);
308 while (ctx && ctx.type == "statement") ctx = popContext(state);
309 } else if (curPunc == "{") {
310 pushContext(state, stream.column(), "}");
311 } else if (curPunc == "[") {
312 pushContext(state, stream.column(), "]");
313 } else if (curPunc == "(") {
314 pushContext(state, stream.column(), ")");
315 } else if (ctx && ctx.type == "endcase" && curPunc == ":") {
316 pushContext(state, stream.column(), "statement");
317 } else if (curPunc == "newstatement") {
318 pushContext(state, stream.column(), "statement");
319 } else if (curPunc == "newblock") {
320 if (curKeyword == "function" && ctx && (ctx.type == "statement" || ctx.type == "endgroup")) {
321 // The 'function' keyword can appear in some other contexts where it actually does not
322 // indicate a function (import/export DPI and covergroup definitions).
323 // Do nothing in this case
324 } else if (curKeyword == "task" && ctx && ctx.type == "statement") {
325 // Same thing for task
326 } else {
327 var close = openClose[curKeyword];
328 pushContext(state, stream.column(), close);
329 }
330 }
331
332 state.startOfLine = false;
333 return style;
334 },
335
336 indent: function(state, textAfter, cx) {
337 if (state.tokenize != tokenBase && state.tokenize != null) return null;
338 if (hooks.indent) {
339 var fromHook = hooks.indent(state);
340 if (fromHook >= 0) return fromHook;
341 }
342 var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
343 if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
344 var closing = false;
345 var possibleClosing = textAfter.match(closingBracketOrWord);
346 if (possibleClosing)
347 closing = isClosing(possibleClosing[0], ctx.type);
348 if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit || cx.unit);
349 else if (closingBracket.test(ctx.type) && ctx.align && !dontAlignCalls) return ctx.column + (closing ? 0 : 1);
350 else if (ctx.type == ")" && !closing) return ctx.indented + (statementIndentUnit || cx.unit);
351 else return ctx.indented + (closing ? 0 : cx.unit);
352 },
353
354 languageData: {
355 indentOnInput: buildElectricInputRegEx(),
356 commentTokens: {line: "//", block: {open: "/*", close: "*/"}}
357 }
358 };
359 };
360
361 export const verilog = mkVerilog({})
362
363 // TL-Verilog mode.
364 // See tl-x.org for language spec.
365 // See the mode in action at makerchip.com.
366 // Contact: [email protected]
367
368 // TLV Identifier prefixes.
369 // Note that sign is not treated separately, so "+/-" versions of numeric identifiers
370 // are included.
371 var tlvIdentifierStyle = {
372 "|": "link",
373 ">": "property", // Should condition this off for > TLV 1c.
374 "$": "variable",
375 "$$": "variable",
376 "?$": "qualifier",
377 "?*": "qualifier",
378 "-": "contentSeparator",
379 "/": "property",
380 "/-": "property",
381 "@": "variableName.special",
382 "@-": "variableName.special",
383 "@++": "variableName.special",
384 "@+=": "variableName.special",
385 "@+=-": "variableName.special",
386 "@--": "variableName.special",
387 "@-=": "variableName.special",
388 "%+": "tag",
389 "%-": "tag",
390 "%": "tag",
391 ">>": "tag",
392 "<<": "tag",
393 "<>": "tag",
394 "#": "tag", // Need to choose a style for this.
395 "^": "attribute",
396 "^^": "attribute",
397 "^!": "attribute",
398 "*": "variable",
399 "**": "variable",
400 "\\": "keyword",
401 "\"": "comment"
402 };
403
404 // Lines starting with these characters define scope (result in indentation).
405 var tlvScopePrefixChars = {
406 "/": "beh-hier",
407 ">": "beh-hier",
408 "-": "phys-hier",
409 "|": "pipe",
410 "?": "when",
411 "@": "stage",
412 "\\": "keyword"
413 };
414 var tlvIndentUnit = 3;
415 var tlvTrackStatements = false;
416 var tlvIdentMatch = /^([~!@#\$%\^&\*-\+=\?\/\\\|'"<>]+)([\d\w_]*)/; // Matches an identifier.
417 // Note that ':' is excluded, because of it's use in [:].
418 var tlvLineIndentationMatch = /^[! ] */;
419 var tlvCommentMatch = /^\/[\/\*]/;
420
421 export const tlv = mkVerilog({
422 hooks: {
423 electricInput: false,
424
425 // Return undefined for verilog tokenizing, or style for TLV token (null not used).
426 // Standard CM styles are used for most formatting, but some TL-Verilog-specific highlighting
427 // can be enabled with the definition of cm-tlv-* styles, including highlighting for:
428 // - M4 tokens
429 // - TLV scope indentation
430 // - Statement delimitation (enabled by tlvTrackStatements)
431 token: function(stream, state) {
432 var style = undefined;
433 var match; // Return value of pattern matches.
434
435 // Set highlighting mode based on code region (TLV or SV).
436 if (stream.sol() && ! state.tlvInBlockComment) {
437 // Process region.
438 if (stream.peek() == '\\') {
439 style = "def";
440 stream.skipToEnd();
441 if (stream.string.match(/\\SV/)) {
442 state.tlvCodeActive = false;
443 } else if (stream.string.match(/\\TLV/)){
444 state.tlvCodeActive = true;
445 }
446 }
447 // Correct indentation in the face of a line prefix char.
448 if (state.tlvCodeActive && stream.pos == 0 &&
449 (state.indented == 0) && (match = stream.match(tlvLineIndentationMatch, false))) {
450 state.indented = match[0].length;
451 }
452
453 // Compute indentation state:
454 // o Auto indentation on next line
455 // o Indentation scope styles
456 var indented = state.indented;
457 var depth = indented / tlvIndentUnit;
458 if (depth <= state.tlvIndentationStyle.length) {
459 // not deeper than current scope
460
461 var blankline = stream.string.length == indented;
462 var chPos = depth * tlvIndentUnit;
463 if (chPos < stream.string.length) {
464 var bodyString = stream.string.slice(chPos);
465 var ch = bodyString[0];
466 if (tlvScopePrefixChars[ch] && ((match = bodyString.match(tlvIdentMatch)) &&
467 tlvIdentifierStyle[match[1]])) {
468 // This line begins scope.
469 // Next line gets indented one level.
470 indented += tlvIndentUnit;
471 // Style the next level of indentation (except non-region keyword identifiers,
472 // which are statements themselves)
473 if (!(ch == "\\" && chPos > 0)) {
474 state.tlvIndentationStyle[depth] = tlvScopePrefixChars[ch];
475 if (tlvTrackStatements) {state.statementComment = false;}
476 depth++;
477 }
478 }
479 }
480 // Clear out deeper indentation levels unless line is blank.
481 if (!blankline) {
482 while (state.tlvIndentationStyle.length > depth) {
483 state.tlvIndentationStyle.pop();
484 }
485 }
486 }
487 // Set next level of indentation.
488 state.tlvNextIndent = indented;
489 }
490
491 if (state.tlvCodeActive) {
492 // Highlight as TLV.
493
494 var beginStatement = false;
495 if (tlvTrackStatements) {
496 // This starts a statement if the position is at the scope level
497 // and we're not within a statement leading comment.
498 beginStatement =
499 (stream.peek() != " ") && // not a space
500 (style === undefined) && // not a region identifier
501 !state.tlvInBlockComment && // not in block comment
502 //!stream.match(tlvCommentMatch, false) && // not comment start
503 (stream.column() == state.tlvIndentationStyle.length * tlvIndentUnit); // at scope level
504 if (beginStatement) {
505 if (state.statementComment) {
506 // statement already started by comment
507 beginStatement = false;
508 }
509 state.statementComment =
510 stream.match(tlvCommentMatch, false); // comment start
511 }
512 }
513
514 var match;
515 if (style !== undefined) {
516 } else if (state.tlvInBlockComment) {
517 // In a block comment.
518 if (stream.match(/^.*?\*\//)) {
519 // Exit block comment.
520 state.tlvInBlockComment = false;
521 if (tlvTrackStatements && !stream.eol()) {
522 // Anything after comment is assumed to be real statement content.
523 state.statementComment = false;
524 }
525 } else {
526 stream.skipToEnd();
527 }
528 style = "comment";
529 } else if ((match = stream.match(tlvCommentMatch)) && !state.tlvInBlockComment) {
530 // Start comment.
531 if (match[0] == "//") {
532 // Line comment.
533 stream.skipToEnd();
534 } else {
535 // Block comment.
536 state.tlvInBlockComment = true;
537 }
538 style = "comment";
539 } else if (match = stream.match(tlvIdentMatch)) {
540 // looks like an identifier (or identifier prefix)
541 var prefix = match[1];
542 var mnemonic = match[2];
543 if (// is identifier prefix
544 tlvIdentifierStyle.hasOwnProperty(prefix) &&
545 // has mnemonic or we're at the end of the line (maybe it hasn't been typed yet)
546 (mnemonic.length > 0 || stream.eol())) {
547 style = tlvIdentifierStyle[prefix];
548 } else {
549 // Just swallow one character and try again.
550 // This enables subsequent identifier match with preceding symbol character, which
551 // is legal within a statement. (Eg, !$reset). It also enables detection of
552 // comment start with preceding symbols.
553 stream.backUp(stream.current().length - 1);
554 }
555 } else if (stream.match(/^\t+/)) {
556 // Highlight tabs, which are illegal.
557 style = "invalid";
558 } else if (stream.match(/^[\[\]{}\(\);\:]+/)) {
559 // [:], (), {}, ;.
560 style = "meta";
561 } else if (match = stream.match(/^[mM]4([\+_])?[\w\d_]*/)) {
562 // m4 pre proc
563 style = (match[1] == "+") ? "keyword.special" : "keyword";
564 } else if (stream.match(/^ +/)){
565 // Skip over spaces.
566 if (stream.eol()) {
567 // Trailing spaces.
568 style = "error";
569 }
570 } else if (stream.match(/^[\w\d_]+/)) {
571 // alpha-numeric token.
572 style = "number";
573 } else {
574 // Eat the next char w/ no formatting.
575 stream.next();
576 }
577 } else {
578 if (stream.match(/^[mM]4([\w\d_]*)/)) {
579 // m4 pre proc
580 style = "keyword";
581 }
582 }
583 return style;
584 },
585
586 indent: function(state) {
587 return (state.tlvCodeActive == true) ? state.tlvNextIndent : -1;
588 },
589
590 startState: function(state) {
591 state.tlvIndentationStyle = []; // Styles to use for each level of indentation.
592 state.tlvCodeActive = true; // True when we're in a TLV region (and at beginning of file).
593 state.tlvNextIndent = -1; // The number of spaces to autoindent the next line if tlvCodeActive.
594 state.tlvInBlockComment = false; // True inside /**/ comment.
595 if (tlvTrackStatements) {
596 state.statementComment = false; // True inside a statement's header comment.
597 }
598 }
599
600 }
601 });