選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

verilog.js 29KB

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