javascript.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. // TODO actually recognize syntax of TypeScript constructs
  2. CodeMirror.defineMode("javascript", function(config, parserConfig) {
  3. var indentUnit = config.indentUnit;
  4. var statementIndent = parserConfig.statementIndent;
  5. var jsonMode = parserConfig.json;
  6. var isTS = parserConfig.typescript;
  7. // Tokenizer
  8. var keywords = function(){
  9. function kw(type) {return {type: type, style: "keyword"};}
  10. var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
  11. var operator = kw("operator"), atom = {type: "atom", style: "atom"};
  12. var jsKeywords = {
  13. "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
  14. "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C,
  15. "var": kw("var"), "const": kw("var"), "let": kw("var"),
  16. "function": kw("function"), "catch": kw("catch"),
  17. "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
  18. "in": operator, "typeof": operator, "instanceof": operator,
  19. "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
  20. "this": kw("this")
  21. };
  22. // Extend the 'normal' keywords with the TypeScript language extensions
  23. if (isTS) {
  24. var type = {type: "variable", style: "variable-3"};
  25. var tsKeywords = {
  26. // object-like things
  27. "interface": kw("interface"),
  28. "class": kw("class"),
  29. "extends": kw("extends"),
  30. "constructor": kw("constructor"),
  31. // scope modifiers
  32. "public": kw("public"),
  33. "private": kw("private"),
  34. "protected": kw("protected"),
  35. "static": kw("static"),
  36. "super": kw("super"),
  37. // types
  38. "string": type, "number": type, "bool": type, "any": type
  39. };
  40. for (var attr in tsKeywords) {
  41. jsKeywords[attr] = tsKeywords[attr];
  42. }
  43. }
  44. return jsKeywords;
  45. }();
  46. var isOperatorChar = /[+\-*&%=<>!?|~^]/;
  47. function chain(stream, state, f) {
  48. state.tokenize = f;
  49. return f(stream, state);
  50. }
  51. function nextUntilUnescaped(stream, end) {
  52. var escaped = false, next;
  53. while ((next = stream.next()) != null) {
  54. if (next == end && !escaped)
  55. return false;
  56. escaped = !escaped && next == "\\";
  57. }
  58. return escaped;
  59. }
  60. // Used as scratch variables to communicate multiple values without
  61. // consing up tons of objects.
  62. var type, content;
  63. function ret(tp, style, cont) {
  64. type = tp; content = cont;
  65. return style;
  66. }
  67. function jsTokenBase(stream, state) {
  68. var ch = stream.next();
  69. if (ch == '"' || ch == "'")
  70. return chain(stream, state, jsTokenString(ch));
  71. else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/))
  72. return ret("number", "number");
  73. else if (/[\[\]{}\(\),;\:\.]/.test(ch))
  74. return ret(ch);
  75. else if (ch == "0" && stream.eat(/x/i)) {
  76. stream.eatWhile(/[\da-f]/i);
  77. return ret("number", "number");
  78. }
  79. else if (/\d/.test(ch)) {
  80. stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
  81. return ret("number", "number");
  82. }
  83. else if (ch == "/") {
  84. if (stream.eat("*")) {
  85. return chain(stream, state, jsTokenComment);
  86. }
  87. else if (stream.eat("/")) {
  88. stream.skipToEnd();
  89. return ret("comment", "comment");
  90. }
  91. else if (state.lastType == "operator" || state.lastType == "keyword c" ||
  92. /^[\[{}\(,;:]$/.test(state.lastType)) {
  93. nextUntilUnescaped(stream, "/");
  94. stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla
  95. return ret("regexp", "string-2");
  96. }
  97. else {
  98. stream.eatWhile(isOperatorChar);
  99. return ret("operator", null, stream.current());
  100. }
  101. }
  102. else if (ch == "#") {
  103. stream.skipToEnd();
  104. return ret("error", "error");
  105. }
  106. else if (isOperatorChar.test(ch)) {
  107. stream.eatWhile(isOperatorChar);
  108. return ret("operator", null, stream.current());
  109. }
  110. else {
  111. stream.eatWhile(/[\w\$_]/);
  112. var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
  113. return (known && state.lastType != ".") ? ret(known.type, known.style, word) :
  114. ret("variable", "variable", word);
  115. }
  116. }
  117. function jsTokenString(quote) {
  118. return function(stream, state) {
  119. if (!nextUntilUnescaped(stream, quote))
  120. state.tokenize = jsTokenBase;
  121. return ret("string", "string");
  122. };
  123. }
  124. function jsTokenComment(stream, state) {
  125. var maybeEnd = false, ch;
  126. while (ch = stream.next()) {
  127. if (ch == "/" && maybeEnd) {
  128. state.tokenize = jsTokenBase;
  129. break;
  130. }
  131. maybeEnd = (ch == "*");
  132. }
  133. return ret("comment", "comment");
  134. }
  135. // Parser
  136. var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true};
  137. function JSLexical(indented, column, type, align, prev, info) {
  138. this.indented = indented;
  139. this.column = column;
  140. this.type = type;
  141. this.prev = prev;
  142. this.info = info;
  143. if (align != null) this.align = align;
  144. }
  145. function inScope(state, varname) {
  146. for (var v = state.localVars; v; v = v.next)
  147. if (v.name == varname) return true;
  148. }
  149. function parseJS(state, style, type, content, stream) {
  150. var cc = state.cc;
  151. // Communicate our context to the combinators.
  152. // (Less wasteful than consing up a hundred closures on every call.)
  153. cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc;
  154. if (!state.lexical.hasOwnProperty("align"))
  155. state.lexical.align = true;
  156. while(true) {
  157. var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
  158. if (combinator(type, content)) {
  159. while(cc.length && cc[cc.length - 1].lex)
  160. cc.pop()();
  161. if (cx.marked) return cx.marked;
  162. if (type == "variable" && inScope(state, content)) return "variable-2";
  163. return style;
  164. }
  165. }
  166. }
  167. // Combinator utils
  168. var cx = {state: null, column: null, marked: null, cc: null};
  169. function pass() {
  170. for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
  171. }
  172. function cont() {
  173. pass.apply(null, arguments);
  174. return true;
  175. }
  176. function register(varname) {
  177. function inList(list) {
  178. for (var v = list; v; v = v.next)
  179. if (v.name == varname) return true;
  180. return false;
  181. }
  182. var state = cx.state;
  183. if (state.context) {
  184. cx.marked = "def";
  185. if (inList(state.localVars)) return;
  186. state.localVars = {name: varname, next: state.localVars};
  187. } else {
  188. if (inList(state.globalVars)) return;
  189. state.globalVars = {name: varname, next: state.globalVars};
  190. }
  191. }
  192. // Combinators
  193. var defaultVars = {name: "this", next: {name: "arguments"}};
  194. function pushcontext() {
  195. cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
  196. cx.state.localVars = defaultVars;
  197. }
  198. function popcontext() {
  199. cx.state.localVars = cx.state.context.vars;
  200. cx.state.context = cx.state.context.prev;
  201. }
  202. function pushlex(type, info) {
  203. var result = function() {
  204. var state = cx.state, indent = state.indented;
  205. if (state.lexical.type == "stat") indent = state.lexical.indented;
  206. state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
  207. };
  208. result.lex = true;
  209. return result;
  210. }
  211. function poplex() {
  212. var state = cx.state;
  213. if (state.lexical.prev) {
  214. if (state.lexical.type == ")")
  215. state.indented = state.lexical.indented;
  216. state.lexical = state.lexical.prev;
  217. }
  218. }
  219. poplex.lex = true;
  220. function expect(wanted) {
  221. return function(type) {
  222. if (type == wanted) return cont();
  223. else if (wanted == ";") return pass();
  224. else return cont(arguments.callee);
  225. };
  226. }
  227. function statement(type) {
  228. if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex);
  229. if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
  230. if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
  231. if (type == "{") return cont(pushlex("}"), block, poplex);
  232. if (type == ";") return cont();
  233. if (type == "if") return cont(pushlex("form"), expression, statement, poplex, maybeelse);
  234. if (type == "function") return cont(functiondef);
  235. if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"),
  236. poplex, statement, poplex);
  237. if (type == "variable") return cont(pushlex("stat"), maybelabel);
  238. if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
  239. block, poplex, poplex);
  240. if (type == "case") return cont(expression, expect(":"));
  241. if (type == "default") return cont(expect(":"));
  242. if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
  243. statement, poplex, popcontext);
  244. return pass(pushlex("stat"), expression, expect(";"), poplex);
  245. }
  246. function expression(type) {
  247. return expressionInner(type, false);
  248. }
  249. function expressionNoComma(type) {
  250. return expressionInner(type, true);
  251. }
  252. function expressionInner(type, noComma) {
  253. var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
  254. if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
  255. if (type == "function") return cont(functiondef);
  256. if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression);
  257. if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop);
  258. if (type == "operator") return cont(noComma ? expressionNoComma : expression);
  259. if (type == "[") return cont(pushlex("]"), commasep(expressionNoComma, "]"), poplex, maybeop);
  260. if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeop);
  261. return cont();
  262. }
  263. function maybeexpression(type) {
  264. if (type.match(/[;\}\)\],]/)) return pass();
  265. return pass(expression);
  266. }
  267. function maybeexpressionNoComma(type) {
  268. if (type.match(/[;\}\)\],]/)) return pass();
  269. return pass(expressionNoComma);
  270. }
  271. function maybeoperatorComma(type, value) {
  272. if (type == ",") return cont(expression);
  273. return maybeoperatorNoComma(type, value, false);
  274. }
  275. function maybeoperatorNoComma(type, value, noComma) {
  276. var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
  277. var expr = noComma == false ? expression : expressionNoComma;
  278. if (type == "operator") {
  279. if (/\+\+|--/.test(value)) return cont(me);
  280. if (value == "?") return cont(expression, expect(":"), expr);
  281. return cont(expr);
  282. }
  283. if (type == ";") return;
  284. if (type == "(") return cont(pushlex(")", "call"), commasep(expressionNoComma, ")"), poplex, me);
  285. if (type == ".") return cont(property, me);
  286. if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
  287. }
  288. function maybelabel(type) {
  289. if (type == ":") return cont(poplex, statement);
  290. return pass(maybeoperatorComma, expect(";"), poplex);
  291. }
  292. function property(type) {
  293. if (type == "variable") {cx.marked = "property"; return cont();}
  294. }
  295. function objprop(type, value) {
  296. if (type == "variable") {
  297. cx.marked = "property";
  298. if (value == "get" || value == "set") return cont(getterSetter);
  299. } else if (type == "number" || type == "string") {
  300. cx.marked = type + " property";
  301. }
  302. if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expressionNoComma);
  303. }
  304. function getterSetter(type) {
  305. if (type == ":") return cont(expression);
  306. if (type != "variable") return cont(expect(":"), expression);
  307. cx.marked = "property";
  308. return cont(functiondef);
  309. }
  310. function commasep(what, end) {
  311. function proceed(type) {
  312. if (type == ",") {
  313. var lex = cx.state.lexical;
  314. if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
  315. return cont(what, proceed);
  316. }
  317. if (type == end) return cont();
  318. return cont(expect(end));
  319. }
  320. return function(type) {
  321. if (type == end) return cont();
  322. else return pass(what, proceed);
  323. };
  324. }
  325. function block(type) {
  326. if (type == "}") return cont();
  327. return pass(statement, block);
  328. }
  329. function maybetype(type) {
  330. if (type == ":") return cont(typedef);
  331. return pass();
  332. }
  333. function typedef(type) {
  334. if (type == "variable"){cx.marked = "variable-3"; return cont();}
  335. return pass();
  336. }
  337. function vardef1(type, value) {
  338. if (type == "variable") {
  339. register(value);
  340. return isTS ? cont(maybetype, vardef2) : cont(vardef2);
  341. }
  342. return pass();
  343. }
  344. function vardef2(type, value) {
  345. if (value == "=") return cont(expressionNoComma, vardef2);
  346. if (type == ",") return cont(vardef1);
  347. }
  348. function maybeelse(type, value) {
  349. if (type == "keyword b" && value == "else") return cont(pushlex("form"), statement, poplex);
  350. }
  351. function forspec1(type) {
  352. if (type == "var") return cont(vardef1, expect(";"), forspec2);
  353. if (type == ";") return cont(forspec2);
  354. if (type == "variable") return cont(formaybein);
  355. return pass(expression, expect(";"), forspec2);
  356. }
  357. function formaybein(_type, value) {
  358. if (value == "in") return cont(expression);
  359. return cont(maybeoperatorComma, forspec2);
  360. }
  361. function forspec2(type, value) {
  362. if (type == ";") return cont(forspec3);
  363. if (value == "in") return cont(expression);
  364. return pass(expression, expect(";"), forspec3);
  365. }
  366. function forspec3(type) {
  367. if (type != ")") cont(expression);
  368. }
  369. function functiondef(type, value) {
  370. if (type == "variable") {register(value); return cont(functiondef);}
  371. if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, statement, popcontext);
  372. }
  373. function funarg(type, value) {
  374. if (type == "variable") {register(value); return isTS ? cont(maybetype) : cont();}
  375. }
  376. // Interface
  377. return {
  378. startState: function(basecolumn) {
  379. return {
  380. tokenize: jsTokenBase,
  381. lastType: null,
  382. cc: [],
  383. lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
  384. localVars: parserConfig.localVars,
  385. globalVars: parserConfig.globalVars,
  386. context: parserConfig.localVars && {vars: parserConfig.localVars},
  387. indented: 0
  388. };
  389. },
  390. token: function(stream, state) {
  391. if (stream.sol()) {
  392. if (!state.lexical.hasOwnProperty("align"))
  393. state.lexical.align = false;
  394. state.indented = stream.indentation();
  395. }
  396. if (state.tokenize != jsTokenComment && stream.eatSpace()) return null;
  397. var style = state.tokenize(stream, state);
  398. if (type == "comment") return style;
  399. state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
  400. return parseJS(state, style, type, content, stream);
  401. },
  402. indent: function(state, textAfter) {
  403. if (state.tokenize == jsTokenComment) return CodeMirror.Pass;
  404. if (state.tokenize != jsTokenBase) return 0;
  405. var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
  406. // Kludge to prevent 'maybelse' from blocking lexical scope pops
  407. for (var i = state.cc.length - 1; i >= 0; --i) {
  408. var c = state.cc[i];
  409. if (c == poplex) lexical = lexical.prev;
  410. else if (c != maybeelse || /^else\b/.test(textAfter)) break;
  411. }
  412. if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev;
  413. if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
  414. lexical = lexical.prev;
  415. var type = lexical.type, closing = firstChar == type;
  416. if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? 4 : 0);
  417. else if (type == "form" && firstChar == "{") return lexical.indented;
  418. else if (type == "form") return lexical.indented + indentUnit;
  419. else if (type == "stat")
  420. return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? statementIndent || indentUnit : 0);
  421. else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
  422. return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
  423. else if (lexical.align) return lexical.column + (closing ? 0 : 1);
  424. else return lexical.indented + (closing ? 0 : indentUnit);
  425. },
  426. electricChars: ":{}",
  427. blockCommentStart: jsonMode ? null : "/*",
  428. blockCommentEnd: jsonMode ? null : "*/",
  429. lineComment: jsonMode ? null : "//",
  430. fold: "brace",
  431. helperType: jsonMode ? "json" : "javascript",
  432. jsonMode: jsonMode
  433. };
  434. });
  435. CodeMirror.defineMIME("text/javascript", "javascript");
  436. CodeMirror.defineMIME("text/ecmascript", "javascript");
  437. CodeMirror.defineMIME("application/javascript", "javascript");
  438. CodeMirror.defineMIME("application/ecmascript", "javascript");
  439. CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
  440. CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
  441. CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
  442. CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });