erlang.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. /*jshint unused:true, eqnull:true, curly:true, bitwise:true */
  4. /*jshint undef:true, latedef:true, trailing:true */
  5. /*global CodeMirror:true */
  6. // erlang mode.
  7. // tokenizer -> token types -> CodeMirror styles
  8. // tokenizer maintains a parse stack
  9. // indenter uses the parse stack
  10. // TODO indenter:
  11. // bit syntax
  12. // old guard/bif/conversion clashes (e.g. "float/1")
  13. // type/spec/opaque
  14. (function(mod) {
  15. if (typeof exports == "object" && typeof module == "object") // CommonJS
  16. mod(require("../../lib/codemirror"));
  17. else if (typeof define == "function" && define.amd) // AMD
  18. define(["../../lib/codemirror"], mod);
  19. else // Plain browser env
  20. mod(CodeMirror);
  21. })(function(CodeMirror) {
  22. "use strict";
  23. CodeMirror.defineMIME("text/x-erlang", "erlang");
  24. CodeMirror.defineMode("erlang", function(cmCfg) {
  25. "use strict";
  26. /////////////////////////////////////////////////////////////////////////////
  27. // constants
  28. var typeWords = [
  29. "-type", "-spec", "-export_type", "-opaque"];
  30. var keywordWords = [
  31. "after","begin","catch","case","cond","end","fun","if",
  32. "let","of","query","receive","try","when"];
  33. var separatorRE = /[\->,;]/;
  34. var separatorWords = [
  35. "->",";",","];
  36. var operatorAtomWords = [
  37. "and","andalso","band","bnot","bor","bsl","bsr","bxor",
  38. "div","not","or","orelse","rem","xor"];
  39. var operatorSymbolRE = /[\+\-\*\/<>=\|:!]/;
  40. var operatorSymbolWords = [
  41. "=","+","-","*","/",">",">=","<","=<","=:=","==","=/=","/=","||","<-","!"];
  42. var openParenRE = /[<\(\[\{]/;
  43. var openParenWords = [
  44. "<<","(","[","{"];
  45. var closeParenRE = /[>\)\]\}]/;
  46. var closeParenWords = [
  47. "}","]",")",">>"];
  48. var guardWords = [
  49. "is_atom","is_binary","is_bitstring","is_boolean","is_float",
  50. "is_function","is_integer","is_list","is_number","is_pid",
  51. "is_port","is_record","is_reference","is_tuple",
  52. "atom","binary","bitstring","boolean","function","integer","list",
  53. "number","pid","port","record","reference","tuple"];
  54. var bifWords = [
  55. "abs","adler32","adler32_combine","alive","apply","atom_to_binary",
  56. "atom_to_list","binary_to_atom","binary_to_existing_atom",
  57. "binary_to_list","binary_to_term","bit_size","bitstring_to_list",
  58. "byte_size","check_process_code","contact_binary","crc32",
  59. "crc32_combine","date","decode_packet","delete_module",
  60. "disconnect_node","element","erase","exit","float","float_to_list",
  61. "garbage_collect","get","get_keys","group_leader","halt","hd",
  62. "integer_to_list","internal_bif","iolist_size","iolist_to_binary",
  63. "is_alive","is_atom","is_binary","is_bitstring","is_boolean",
  64. "is_float","is_function","is_integer","is_list","is_number","is_pid",
  65. "is_port","is_process_alive","is_record","is_reference","is_tuple",
  66. "length","link","list_to_atom","list_to_binary","list_to_bitstring",
  67. "list_to_existing_atom","list_to_float","list_to_integer",
  68. "list_to_pid","list_to_tuple","load_module","make_ref","module_loaded",
  69. "monitor_node","node","node_link","node_unlink","nodes","notalive",
  70. "now","open_port","pid_to_list","port_close","port_command",
  71. "port_connect","port_control","pre_loaded","process_flag",
  72. "process_info","processes","purge_module","put","register",
  73. "registered","round","self","setelement","size","spawn","spawn_link",
  74. "spawn_monitor","spawn_opt","split_binary","statistics",
  75. "term_to_binary","time","throw","tl","trunc","tuple_size",
  76. "tuple_to_list","unlink","unregister","whereis"];
  77. // upper case: [A-Z] [Ø-Þ] [À-Ö]
  78. // lower case: [a-z] [ß-ö] [ø-ÿ]
  79. var anumRE = /[\w@Ø-ÞÀ-Öß-öø-ÿ]/;
  80. var escapesRE =
  81. /[0-7]{1,3}|[bdefnrstv\\"']|\^[a-zA-Z]|x[0-9a-zA-Z]{2}|x{[0-9a-zA-Z]+}/;
  82. /////////////////////////////////////////////////////////////////////////////
  83. // tokenizer
  84. function tokenizer(stream,state) {
  85. // in multi-line string
  86. if (state.in_string) {
  87. state.in_string = (!doubleQuote(stream));
  88. return rval(state,stream,"string");
  89. }
  90. // in multi-line atom
  91. if (state.in_atom) {
  92. state.in_atom = (!singleQuote(stream));
  93. return rval(state,stream,"atom");
  94. }
  95. // whitespace
  96. if (stream.eatSpace()) {
  97. return rval(state,stream,"whitespace");
  98. }
  99. // attributes and type specs
  100. if (!peekToken(state) &&
  101. stream.match(/-\s*[a-zß-öø-ÿ][\wØ-ÞÀ-Öß-öø-ÿ]*/)) {
  102. if (is_member(stream.current(),typeWords)) {
  103. return rval(state,stream,"type");
  104. }else{
  105. return rval(state,stream,"attribute");
  106. }
  107. }
  108. var ch = stream.next();
  109. // comment
  110. if (ch == '%') {
  111. stream.skipToEnd();
  112. return rval(state,stream,"comment");
  113. }
  114. // colon
  115. if (ch == ":") {
  116. return rval(state,stream,"colon");
  117. }
  118. // macro
  119. if (ch == '?') {
  120. stream.eatSpace();
  121. stream.eatWhile(anumRE);
  122. return rval(state,stream,"macro");
  123. }
  124. // record
  125. if (ch == "#") {
  126. stream.eatSpace();
  127. stream.eatWhile(anumRE);
  128. return rval(state,stream,"record");
  129. }
  130. // dollar escape
  131. if (ch == "$") {
  132. if (stream.next() == "\\" && !stream.match(escapesRE)) {
  133. return rval(state,stream,"error");
  134. }
  135. return rval(state,stream,"number");
  136. }
  137. // dot
  138. if (ch == ".") {
  139. return rval(state,stream,"dot");
  140. }
  141. // quoted atom
  142. if (ch == '\'') {
  143. if (!(state.in_atom = (!singleQuote(stream)))) {
  144. if (stream.match(/\s*\/\s*[0-9]/,false)) {
  145. stream.match(/\s*\/\s*[0-9]/,true);
  146. return rval(state,stream,"fun"); // 'f'/0 style fun
  147. }
  148. if (stream.match(/\s*\(/,false) || stream.match(/\s*:/,false)) {
  149. return rval(state,stream,"function");
  150. }
  151. }
  152. return rval(state,stream,"atom");
  153. }
  154. // string
  155. if (ch == '"') {
  156. state.in_string = (!doubleQuote(stream));
  157. return rval(state,stream,"string");
  158. }
  159. // variable
  160. if (/[A-Z_Ø-ÞÀ-Ö]/.test(ch)) {
  161. stream.eatWhile(anumRE);
  162. return rval(state,stream,"variable");
  163. }
  164. // atom/keyword/BIF/function
  165. if (/[a-z_ß-öø-ÿ]/.test(ch)) {
  166. stream.eatWhile(anumRE);
  167. if (stream.match(/\s*\/\s*[0-9]/,false)) {
  168. stream.match(/\s*\/\s*[0-9]/,true);
  169. return rval(state,stream,"fun"); // f/0 style fun
  170. }
  171. var w = stream.current();
  172. if (is_member(w,keywordWords)) {
  173. return rval(state,stream,"keyword");
  174. }else if (is_member(w,operatorAtomWords)) {
  175. return rval(state,stream,"operator");
  176. }else if (stream.match(/\s*\(/,false)) {
  177. // 'put' and 'erlang:put' are bifs, 'foo:put' is not
  178. if (is_member(w,bifWords) &&
  179. ((peekToken(state).token != ":") ||
  180. (peekToken(state,2).token == "erlang"))) {
  181. return rval(state,stream,"builtin");
  182. }else if (is_member(w,guardWords)) {
  183. return rval(state,stream,"guard");
  184. }else{
  185. return rval(state,stream,"function");
  186. }
  187. }else if (lookahead(stream) == ":") {
  188. if (w == "erlang") {
  189. return rval(state,stream,"builtin");
  190. } else {
  191. return rval(state,stream,"function");
  192. }
  193. }else if (is_member(w,["true","false"])) {
  194. return rval(state,stream,"boolean");
  195. }else{
  196. return rval(state,stream,"atom");
  197. }
  198. }
  199. // number
  200. var digitRE = /[0-9]/;
  201. var radixRE = /[0-9a-zA-Z]/; // 36#zZ style int
  202. if (digitRE.test(ch)) {
  203. stream.eatWhile(digitRE);
  204. if (stream.eat('#')) { // 36#aZ style integer
  205. if (!stream.eatWhile(radixRE)) {
  206. stream.backUp(1); //"36#" - syntax error
  207. }
  208. } else if (stream.eat('.')) { // float
  209. if (!stream.eatWhile(digitRE)) {
  210. stream.backUp(1); // "3." - probably end of function
  211. } else {
  212. if (stream.eat(/[eE]/)) { // float with exponent
  213. if (stream.eat(/[-+]/)) {
  214. if (!stream.eatWhile(digitRE)) {
  215. stream.backUp(2); // "2e-" - syntax error
  216. }
  217. } else {
  218. if (!stream.eatWhile(digitRE)) {
  219. stream.backUp(1); // "2e" - syntax error
  220. }
  221. }
  222. }
  223. }
  224. }
  225. return rval(state,stream,"number"); // normal integer
  226. }
  227. // open parens
  228. if (nongreedy(stream,openParenRE,openParenWords)) {
  229. return rval(state,stream,"open_paren");
  230. }
  231. // close parens
  232. if (nongreedy(stream,closeParenRE,closeParenWords)) {
  233. return rval(state,stream,"close_paren");
  234. }
  235. // separators
  236. if (greedy(stream,separatorRE,separatorWords)) {
  237. return rval(state,stream,"separator");
  238. }
  239. // operators
  240. if (greedy(stream,operatorSymbolRE,operatorSymbolWords)) {
  241. return rval(state,stream,"operator");
  242. }
  243. return rval(state,stream,null);
  244. }
  245. /////////////////////////////////////////////////////////////////////////////
  246. // utilities
  247. function nongreedy(stream,re,words) {
  248. if (stream.current().length == 1 && re.test(stream.current())) {
  249. stream.backUp(1);
  250. while (re.test(stream.peek())) {
  251. stream.next();
  252. if (is_member(stream.current(),words)) {
  253. return true;
  254. }
  255. }
  256. stream.backUp(stream.current().length-1);
  257. }
  258. return false;
  259. }
  260. function greedy(stream,re,words) {
  261. if (stream.current().length == 1 && re.test(stream.current())) {
  262. while (re.test(stream.peek())) {
  263. stream.next();
  264. }
  265. while (0 < stream.current().length) {
  266. if (is_member(stream.current(),words)) {
  267. return true;
  268. }else{
  269. stream.backUp(1);
  270. }
  271. }
  272. stream.next();
  273. }
  274. return false;
  275. }
  276. function doubleQuote(stream) {
  277. return quote(stream, '"', '\\');
  278. }
  279. function singleQuote(stream) {
  280. return quote(stream,'\'','\\');
  281. }
  282. function quote(stream,quoteChar,escapeChar) {
  283. while (!stream.eol()) {
  284. var ch = stream.next();
  285. if (ch == quoteChar) {
  286. return true;
  287. }else if (ch == escapeChar) {
  288. stream.next();
  289. }
  290. }
  291. return false;
  292. }
  293. function lookahead(stream) {
  294. var m = stream.match(/([\n\s]+|%[^\n]*\n)*(.)/,false);
  295. return m ? m.pop() : "";
  296. }
  297. function is_member(element,list) {
  298. return (-1 < list.indexOf(element));
  299. }
  300. function rval(state,stream,type) {
  301. // parse stack
  302. pushToken(state,realToken(type,stream));
  303. // map erlang token type to CodeMirror style class
  304. // erlang -> CodeMirror tag
  305. switch (type) {
  306. case "atom": return "atom";
  307. case "attribute": return "attribute";
  308. case "boolean": return "atom";
  309. case "builtin": return "builtin";
  310. case "close_paren": return null;
  311. case "colon": return null;
  312. case "comment": return "comment";
  313. case "dot": return null;
  314. case "error": return "error";
  315. case "fun": return "meta";
  316. case "function": return "tag";
  317. case "guard": return "property";
  318. case "keyword": return "keyword";
  319. case "macro": return "variable-2";
  320. case "number": return "number";
  321. case "open_paren": return null;
  322. case "operator": return "operator";
  323. case "record": return "bracket";
  324. case "separator": return null;
  325. case "string": return "string";
  326. case "type": return "def";
  327. case "variable": return "variable";
  328. default: return null;
  329. }
  330. }
  331. function aToken(tok,col,ind,typ) {
  332. return {token: tok,
  333. column: col,
  334. indent: ind,
  335. type: typ};
  336. }
  337. function realToken(type,stream) {
  338. return aToken(stream.current(),
  339. stream.column(),
  340. stream.indentation(),
  341. type);
  342. }
  343. function fakeToken(type) {
  344. return aToken(type,0,0,type);
  345. }
  346. function peekToken(state,depth) {
  347. var len = state.tokenStack.length;
  348. var dep = (depth ? depth : 1);
  349. if (len < dep) {
  350. return false;
  351. }else{
  352. return state.tokenStack[len-dep];
  353. }
  354. }
  355. function pushToken(state,token) {
  356. if (!(token.type == "comment" || token.type == "whitespace")) {
  357. state.tokenStack = maybe_drop_pre(state.tokenStack,token);
  358. state.tokenStack = maybe_drop_post(state.tokenStack);
  359. }
  360. }
  361. function maybe_drop_pre(s,token) {
  362. var last = s.length-1;
  363. if (0 < last && s[last].type === "record" && token.type === "dot") {
  364. s.pop();
  365. }else if (0 < last && s[last].type === "group") {
  366. s.pop();
  367. s.push(token);
  368. }else{
  369. s.push(token);
  370. }
  371. return s;
  372. }
  373. function maybe_drop_post(s) {
  374. var last = s.length-1;
  375. if (s[last].type === "dot") {
  376. return [];
  377. }
  378. if (s[last].type === "fun" && s[last-1].token === "fun") {
  379. return s.slice(0,last-1);
  380. }
  381. switch (s[s.length-1].token) {
  382. case "}": return d(s,{g:["{"]});
  383. case "]": return d(s,{i:["["]});
  384. case ")": return d(s,{i:["("]});
  385. case ">>": return d(s,{i:["<<"]});
  386. case "end": return d(s,{i:["begin","case","fun","if","receive","try"]});
  387. case ",": return d(s,{e:["begin","try","when","->",
  388. ",","(","[","{","<<"]});
  389. case "->": return d(s,{r:["when"],
  390. m:["try","if","case","receive"]});
  391. case ";": return d(s,{E:["case","fun","if","receive","try","when"]});
  392. case "catch":return d(s,{e:["try"]});
  393. case "of": return d(s,{e:["case"]});
  394. case "after":return d(s,{e:["receive","try"]});
  395. default: return s;
  396. }
  397. }
  398. function d(stack,tt) {
  399. // stack is a stack of Token objects.
  400. // tt is an object; {type:tokens}
  401. // type is a char, tokens is a list of token strings.
  402. // The function returns (possibly truncated) stack.
  403. // It will descend the stack, looking for a Token such that Token.token
  404. // is a member of tokens. If it does not find that, it will normally (but
  405. // see "E" below) return stack. If it does find a match, it will remove
  406. // all the Tokens between the top and the matched Token.
  407. // If type is "m", that is all it does.
  408. // If type is "i", it will also remove the matched Token and the top Token.
  409. // If type is "g", like "i", but add a fake "group" token at the top.
  410. // If type is "r", it will remove the matched Token, but not the top Token.
  411. // If type is "e", it will keep the matched Token but not the top Token.
  412. // If type is "E", it behaves as for type "e", except if there is no match,
  413. // in which case it will return an empty stack.
  414. for (var type in tt) {
  415. var len = stack.length-1;
  416. var tokens = tt[type];
  417. for (var i = len-1; -1 < i ; i--) {
  418. if (is_member(stack[i].token,tokens)) {
  419. var ss = stack.slice(0,i);
  420. switch (type) {
  421. case "m": return ss.concat(stack[i]).concat(stack[len]);
  422. case "r": return ss.concat(stack[len]);
  423. case "i": return ss;
  424. case "g": return ss.concat(fakeToken("group"));
  425. case "E": return ss.concat(stack[i]);
  426. case "e": return ss.concat(stack[i]);
  427. }
  428. }
  429. }
  430. }
  431. return (type == "E" ? [] : stack);
  432. }
  433. /////////////////////////////////////////////////////////////////////////////
  434. // indenter
  435. function indenter(state,textAfter) {
  436. var t;
  437. var unit = cmCfg.indentUnit;
  438. var wordAfter = wordafter(textAfter);
  439. var currT = peekToken(state,1);
  440. var prevT = peekToken(state,2);
  441. if (state.in_string || state.in_atom) {
  442. return CodeMirror.Pass;
  443. }else if (!prevT) {
  444. return 0;
  445. }else if (currT.token == "when") {
  446. return currT.column+unit;
  447. }else if (wordAfter === "when" && prevT.type === "function") {
  448. return prevT.indent+unit;
  449. }else if (wordAfter === "(" && currT.token === "fun") {
  450. return currT.column+3;
  451. }else if (wordAfter === "catch" && (t = getToken(state,["try"]))) {
  452. return t.column;
  453. }else if (is_member(wordAfter,["end","after","of"])) {
  454. t = getToken(state,["begin","case","fun","if","receive","try"]);
  455. return t ? t.column : CodeMirror.Pass;
  456. }else if (is_member(wordAfter,closeParenWords)) {
  457. t = getToken(state,openParenWords);
  458. return t ? t.column : CodeMirror.Pass;
  459. }else if (is_member(currT.token,[",","|","||"]) ||
  460. is_member(wordAfter,[",","|","||"])) {
  461. t = postcommaToken(state);
  462. return t ? t.column+t.token.length : unit;
  463. }else if (currT.token == "->") {
  464. if (is_member(prevT.token, ["receive","case","if","try"])) {
  465. return prevT.column+unit+unit;
  466. }else{
  467. return prevT.column+unit;
  468. }
  469. }else if (is_member(currT.token,openParenWords)) {
  470. return currT.column+currT.token.length;
  471. }else{
  472. t = defaultToken(state);
  473. return truthy(t) ? t.column+unit : 0;
  474. }
  475. }
  476. function wordafter(str) {
  477. var m = str.match(/,|[a-z]+|\}|\]|\)|>>|\|+|\(/);
  478. return truthy(m) && (m.index === 0) ? m[0] : "";
  479. }
  480. function postcommaToken(state) {
  481. var objs = state.tokenStack.slice(0,-1);
  482. var i = getTokenIndex(objs,"type",["open_paren"]);
  483. return truthy(objs[i]) ? objs[i] : false;
  484. }
  485. function defaultToken(state) {
  486. var objs = state.tokenStack;
  487. var stop = getTokenIndex(objs,"type",["open_paren","separator","keyword"]);
  488. var oper = getTokenIndex(objs,"type",["operator"]);
  489. if (truthy(stop) && truthy(oper) && stop < oper) {
  490. return objs[stop+1];
  491. } else if (truthy(stop)) {
  492. return objs[stop];
  493. } else {
  494. return false;
  495. }
  496. }
  497. function getToken(state,tokens) {
  498. var objs = state.tokenStack;
  499. var i = getTokenIndex(objs,"token",tokens);
  500. return truthy(objs[i]) ? objs[i] : false;
  501. }
  502. function getTokenIndex(objs,propname,propvals) {
  503. for (var i = objs.length-1; -1 < i ; i--) {
  504. if (is_member(objs[i][propname],propvals)) {
  505. return i;
  506. }
  507. }
  508. return false;
  509. }
  510. function truthy(x) {
  511. return (x !== false) && (x != null);
  512. }
  513. /////////////////////////////////////////////////////////////////////////////
  514. // this object defines the mode
  515. return {
  516. startState:
  517. function() {
  518. return {tokenStack: [],
  519. in_string: false,
  520. in_atom: false};
  521. },
  522. token:
  523. function(stream, state) {
  524. return tokenizer(stream, state);
  525. },
  526. indent:
  527. function(state, textAfter) {
  528. return indenter(state,textAfter);
  529. },
  530. lineComment: "%"
  531. };
  532. });
  533. });