verilog.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://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. noIndentKeywords = parserConfig.noIndentKeywords || [],
  17. multiLineStrings = parserConfig.multiLineStrings;
  18. function words(str) {
  19. var obj = {}, words = str.split(" ");
  20. for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
  21. return obj;
  22. }
  23. /**
  24. * Keywords from IEEE 1800-2012
  25. */
  26. var keywords = words(
  27. "accept_on alias always always_comb always_ff always_latch and assert assign assume automatic before begin bind " +
  28. "bins binsof bit break buf bufif0 bufif1 byte case casex casez cell chandle checker class clocking cmos config " +
  29. "const constraint context continue cover covergroup coverpoint cross deassign default defparam design disable " +
  30. "dist do edge else end endcase endchecker endclass endclocking endconfig endfunction endgenerate endgroup " +
  31. "endinterface endmodule endpackage endprimitive endprogram endproperty endspecify endsequence endtable endtask " +
  32. "enum event eventually expect export extends extern final first_match for force foreach forever fork forkjoin " +
  33. "function generate genvar global highz0 highz1 if iff ifnone ignore_bins illegal_bins implements implies import " +
  34. "incdir include initial inout input inside instance int integer interconnect interface intersect join join_any " +
  35. "join_none large let liblist library local localparam logic longint macromodule matches medium modport module " +
  36. "nand negedge nettype new nexttime nmos nor noshowcancelled not notif0 notif1 null or output package packed " +
  37. "parameter pmos posedge primitive priority program property protected pull0 pull1 pulldown pullup " +
  38. "pulsestyle_ondetect pulsestyle_onevent pure rand randc randcase randsequence rcmos real realtime ref reg " +
  39. "reject_on release repeat restrict return rnmos rpmos rtran rtranif0 rtranif1 s_always s_eventually s_nexttime " +
  40. "s_until s_until_with scalared sequence shortint shortreal showcancelled signed small soft solve specify " +
  41. "specparam static string strong strong0 strong1 struct super supply0 supply1 sync_accept_on sync_reject_on " +
  42. "table tagged task this throughout time timeprecision timeunit tran tranif0 tranif1 tri tri0 tri1 triand trior " +
  43. "trireg type typedef union unique unique0 unsigned until until_with untyped use uwire var vectored virtual void " +
  44. "wait wait_order wand weak weak0 weak1 while wildcard wire with within wor xnor xor");
  45. /** Operators from IEEE 1800-2012
  46. unary_operator ::=
  47. + | - | ! | ~ | & | ~& | | | ~| | ^ | ~^ | ^~
  48. binary_operator ::=
  49. + | - | * | / | % | == | != | === | !== | ==? | !=? | && | || | **
  50. | < | <= | > | >= | & | | | ^ | ^~ | ~^ | >> | << | >>> | <<<
  51. | -> | <->
  52. inc_or_dec_operator ::= ++ | --
  53. unary_module_path_operator ::=
  54. ! | ~ | & | ~& | | | ~| | ^ | ~^ | ^~
  55. binary_module_path_operator ::=
  56. == | != | && | || | & | | | ^ | ^~ | ~^
  57. */
  58. var isOperatorChar = /[\+\-\*\/!~&|^%=?:]/;
  59. var isBracketChar = /[\[\]{}()]/;
  60. var unsignedNumber = /\d[0-9_]*/;
  61. var decimalLiteral = /\d*\s*'s?d\s*\d[0-9_]*/i;
  62. var binaryLiteral = /\d*\s*'s?b\s*[xz01][xz01_]*/i;
  63. var octLiteral = /\d*\s*'s?o\s*[xz0-7][xz0-7_]*/i;
  64. var hexLiteral = /\d*\s*'s?h\s*[0-9a-fxz?][0-9a-fxz?_]*/i;
  65. var realLiteral = /(\d[\d_]*(\.\d[\d_]*)?E-?[\d_]+)|(\d[\d_]*\.\d[\d_]*)/i;
  66. var closingBracketOrWord = /^((\w+)|[)}\]])/;
  67. var closingBracket = /[)}\]]/;
  68. var curPunc;
  69. var curKeyword;
  70. // Block openings which are closed by a matching keyword in the form of ("end" + keyword)
  71. // E.g. "task" => "endtask"
  72. var blockKeywords = words(
  73. "case checker class clocking config function generate group interface module package" +
  74. "primitive program property specify sequence table task"
  75. );
  76. // Opening/closing pairs
  77. var openClose = {};
  78. for (var keyword in blockKeywords) {
  79. openClose[keyword] = "end" + keyword;
  80. }
  81. openClose["begin"] = "end";
  82. openClose["casex"] = "endcase";
  83. openClose["casez"] = "endcase";
  84. openClose["do" ] = "while";
  85. openClose["fork" ] = "join;join_any;join_none";
  86. // This is a bit of a hack but will work to not indent after import/epxort statements
  87. // as long as the function/task name is on the same line
  88. openClose["import"] = "function;task";
  89. openClose["export"] = "function;task";
  90. for (var i in noIndentKeywords) {
  91. var keyword = noIndentKeywords[i];
  92. if (openClose[keyword]) {
  93. openClose[keyword] = undefined;
  94. }
  95. }
  96. var statementKeywords = words("always always_comb always_ff always_latch assert assign assume else for foreach forever if initial repeat while");
  97. function tokenBase(stream, state) {
  98. var ch = stream.peek();
  99. if (/[,;:\.]/.test(ch)) {
  100. curPunc = stream.next();
  101. return null;
  102. }
  103. if (isBracketChar.test(ch)) {
  104. curPunc = stream.next();
  105. return "bracket";
  106. }
  107. // Macros (tick-defines)
  108. if (ch == '`') {
  109. stream.next();
  110. if (stream.eatWhile(/[\w\$_]/)) {
  111. return "def";
  112. } else {
  113. return null;
  114. }
  115. }
  116. // System calls
  117. if (ch == '$') {
  118. stream.next();
  119. if (stream.eatWhile(/[\w\$_]/)) {
  120. return "meta";
  121. } else {
  122. return null;
  123. }
  124. }
  125. // Time literals
  126. if (ch == '#') {
  127. stream.next();
  128. stream.eatWhile(/[\d_.]/);
  129. return "def";
  130. }
  131. // Strings
  132. if (ch == '"') {
  133. stream.next();
  134. state.tokenize = tokenString(ch);
  135. return state.tokenize(stream, state);
  136. }
  137. // Comments
  138. if (ch == "/") {
  139. stream.next();
  140. if (stream.eat("*")) {
  141. state.tokenize = tokenComment;
  142. return tokenComment(stream, state);
  143. }
  144. if (stream.eat("/")) {
  145. stream.skipToEnd();
  146. return "comment";
  147. }
  148. stream.backUp(1);
  149. }
  150. // Numeric literals
  151. if (stream.match(realLiteral) ||
  152. stream.match(decimalLiteral) ||
  153. stream.match(binaryLiteral) ||
  154. stream.match(octLiteral) ||
  155. stream.match(hexLiteral) ||
  156. stream.match(unsignedNumber) ||
  157. stream.match(realLiteral)) {
  158. return "number";
  159. }
  160. // Operators
  161. if (stream.eatWhile(isOperatorChar)) {
  162. return "meta";
  163. }
  164. // Keywords / plain variables
  165. if (stream.eatWhile(/[\w\$_]/)) {
  166. var cur = stream.current();
  167. if (keywords[cur]) {
  168. if (openClose[cur]) {
  169. curPunc = "newblock";
  170. }
  171. if (statementKeywords[cur]) {
  172. curPunc = "newstatement";
  173. }
  174. curKeyword = cur;
  175. return "keyword";
  176. }
  177. return "variable";
  178. }
  179. stream.next();
  180. return null;
  181. }
  182. function tokenString(quote) {
  183. return function(stream, state) {
  184. var escaped = false, next, end = false;
  185. while ((next = stream.next()) != null) {
  186. if (next == quote && !escaped) {end = true; break;}
  187. escaped = !escaped && next == "\\";
  188. }
  189. if (end || !(escaped || multiLineStrings))
  190. state.tokenize = tokenBase;
  191. return "string";
  192. };
  193. }
  194. function tokenComment(stream, state) {
  195. var maybeEnd = false, ch;
  196. while (ch = stream.next()) {
  197. if (ch == "/" && maybeEnd) {
  198. state.tokenize = tokenBase;
  199. break;
  200. }
  201. maybeEnd = (ch == "*");
  202. }
  203. return "comment";
  204. }
  205. function Context(indented, column, type, align, prev) {
  206. this.indented = indented;
  207. this.column = column;
  208. this.type = type;
  209. this.align = align;
  210. this.prev = prev;
  211. }
  212. function pushContext(state, col, type) {
  213. var indent = state.indented;
  214. var c = new Context(indent, col, type, null, state.context);
  215. return state.context = c;
  216. }
  217. function popContext(state) {
  218. var t = state.context.type;
  219. if (t == ")" || t == "]" || t == "}") {
  220. state.indented = state.context.indented;
  221. }
  222. return state.context = state.context.prev;
  223. }
  224. function isClosing(text, contextClosing) {
  225. if (text == contextClosing) {
  226. return true;
  227. } else {
  228. // contextClosing may be mulitple keywords separated by ;
  229. var closingKeywords = contextClosing.split(";");
  230. for (var i in closingKeywords) {
  231. if (text == closingKeywords[i]) {
  232. return true;
  233. }
  234. }
  235. return false;
  236. }
  237. }
  238. function buildElectricInputRegEx() {
  239. // Reindentation should occur on any bracket char: {}()[]
  240. // or on a match of any of the block closing keywords, at
  241. // the end of a line
  242. var allClosings = [];
  243. for (var i in openClose) {
  244. if (openClose[i]) {
  245. var closings = openClose[i].split(";");
  246. for (var j in closings) {
  247. allClosings.push(closings[j]);
  248. }
  249. }
  250. }
  251. var re = new RegExp("[{}()\\[\\]]|(" + allClosings.join("|") + ")$");
  252. return re;
  253. }
  254. // Interface
  255. return {
  256. // Regex to force current line to reindent
  257. electricInput: buildElectricInputRegEx(),
  258. startState: function(basecolumn) {
  259. return {
  260. tokenize: null,
  261. context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
  262. indented: 0,
  263. startOfLine: true
  264. };
  265. },
  266. token: function(stream, state) {
  267. var ctx = state.context;
  268. if (stream.sol()) {
  269. if (ctx.align == null) ctx.align = false;
  270. state.indented = stream.indentation();
  271. state.startOfLine = true;
  272. }
  273. if (stream.eatSpace()) return null;
  274. curPunc = null;
  275. curKeyword = null;
  276. var style = (state.tokenize || tokenBase)(stream, state);
  277. if (style == "comment" || style == "meta" || style == "variable") return style;
  278. if (ctx.align == null) ctx.align = true;
  279. if (curPunc == ctx.type) {
  280. popContext(state);
  281. }
  282. else if ((curPunc == ";" && ctx.type == "statement") ||
  283. (ctx.type && isClosing(curKeyword, ctx.type))) {
  284. ctx = popContext(state);
  285. while (ctx && ctx.type == "statement") ctx = popContext(state);
  286. }
  287. else if (curPunc == "{") { pushContext(state, stream.column(), "}"); }
  288. else if (curPunc == "[") { pushContext(state, stream.column(), "]"); }
  289. else if (curPunc == "(") { pushContext(state, stream.column(), ")"); }
  290. else if (ctx && ctx.type == "endcase" && curPunc == ":") { pushContext(state, stream.column(), "statement"); }
  291. else if (curPunc == "newstatement") {
  292. pushContext(state, stream.column(), "statement");
  293. } else if (curPunc == "newblock") {
  294. var close = openClose[curKeyword];
  295. pushContext(state, stream.column(), close);
  296. }
  297. state.startOfLine = false;
  298. return style;
  299. },
  300. indent: function(state, textAfter) {
  301. if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
  302. var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
  303. if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
  304. var closing = false;
  305. var possibleClosing = textAfter.match(closingBracketOrWord);
  306. if (possibleClosing) {
  307. closing = isClosing(possibleClosing[0], ctx.type);
  308. }
  309. if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
  310. else if (closingBracket.test(ctx.type) && ctx.align && !dontAlignCalls) return ctx.column + (closing ? 0 : 1);
  311. else if (ctx.type == ")" && !closing) return ctx.indented + statementIndentUnit;
  312. else return ctx.indented + (closing ? 0 : indentUnit);
  313. },
  314. blockCommentStart: "/*",
  315. blockCommentEnd: "*/",
  316. lineComment: "//"
  317. };
  318. });
  319. CodeMirror.defineMIME("text/x-verilog", {
  320. name: "verilog"
  321. });
  322. CodeMirror.defineMIME("text/x-systemverilog", {
  323. name: "systemverilog"
  324. });
  325. });