rewriter.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. /**
  2. * Copyright (c) 2009-2013 Jeremy Ashkenas
  3. *
  4. * Permission is hereby granted, free of charge, to any person
  5. * obtaining a copy of this software and associated documentation
  6. * files (the "Software"), to deal in the Software without
  7. * restriction, including without limitation the rights to use,
  8. * copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. * copies of the Software, and to permit persons to whom the
  10. * Software is furnished to do so, subject to the following
  11. * conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be
  14. * included in all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  18. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  20. * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  21. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  22. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  23. * OTHER DEALINGS IN THE SOFTWARE.
  24. *
  25. */
  26. define(function(require, exports, module) {
  27. // Generated by CoffeeScript 1.6.3
  28. var BALANCED_PAIRS, EXPRESSION_CLOSE, EXPRESSION_END, EXPRESSION_START, IMPLICIT_CALL, IMPLICIT_END, IMPLICIT_FUNC, IMPLICIT_UNSPACED_CALL, INVERSES, LINEBREAKS, SINGLE_CLOSERS, SINGLE_LINERS, generate, left, rite, _i, _len, _ref,
  29. __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
  30. __slice = [].slice;
  31. generate = function(tag, value) {
  32. var tok;
  33. tok = [tag, value];
  34. tok.generated = true;
  35. return tok;
  36. };
  37. exports.Rewriter = (function() {
  38. function Rewriter() {}
  39. Rewriter.prototype.rewrite = function(tokens) {
  40. this.tokens = tokens;
  41. this.removeLeadingNewlines();
  42. this.removeMidExpressionNewlines();
  43. this.closeOpenCalls();
  44. this.closeOpenIndexes();
  45. this.addImplicitIndentation();
  46. this.tagPostfixConditionals();
  47. this.addImplicitBracesAndParens();
  48. this.addLocationDataToGeneratedTokens();
  49. return this.tokens;
  50. };
  51. Rewriter.prototype.scanTokens = function(block) {
  52. var i, token, tokens;
  53. tokens = this.tokens;
  54. i = 0;
  55. while (token = tokens[i]) {
  56. i += block.call(this, token, i, tokens);
  57. }
  58. return true;
  59. };
  60. Rewriter.prototype.detectEnd = function(i, condition, action) {
  61. var levels, token, tokens, _ref, _ref1;
  62. tokens = this.tokens;
  63. levels = 0;
  64. while (token = tokens[i]) {
  65. if (levels === 0 && condition.call(this, token, i)) {
  66. return action.call(this, token, i);
  67. }
  68. if (!token || levels < 0) {
  69. return action.call(this, token, i - 1);
  70. }
  71. if (_ref = token[0], __indexOf.call(EXPRESSION_START, _ref) >= 0) {
  72. levels += 1;
  73. } else if (_ref1 = token[0], __indexOf.call(EXPRESSION_END, _ref1) >= 0) {
  74. levels -= 1;
  75. }
  76. i += 1;
  77. }
  78. return i - 1;
  79. };
  80. Rewriter.prototype.removeLeadingNewlines = function() {
  81. var i, tag, _i, _len, _ref;
  82. _ref = this.tokens;
  83. for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
  84. tag = _ref[i][0];
  85. if (tag !== 'TERMINATOR') {
  86. break;
  87. }
  88. }
  89. if (i) {
  90. return this.tokens.splice(0, i);
  91. }
  92. };
  93. Rewriter.prototype.removeMidExpressionNewlines = function() {
  94. return this.scanTokens(function(token, i, tokens) {
  95. var _ref;
  96. if (!(token[0] === 'TERMINATOR' && (_ref = this.tag(i + 1), __indexOf.call(EXPRESSION_CLOSE, _ref) >= 0))) {
  97. return 1;
  98. }
  99. tokens.splice(i, 1);
  100. return 0;
  101. });
  102. };
  103. Rewriter.prototype.closeOpenCalls = function() {
  104. var action, condition;
  105. condition = function(token, i) {
  106. var _ref;
  107. return ((_ref = token[0]) === ')' || _ref === 'CALL_END') || token[0] === 'OUTDENT' && this.tag(i - 1) === ')';
  108. };
  109. action = function(token, i) {
  110. return this.tokens[token[0] === 'OUTDENT' ? i - 1 : i][0] = 'CALL_END';
  111. };
  112. return this.scanTokens(function(token, i) {
  113. if (token[0] === 'CALL_START') {
  114. this.detectEnd(i + 1, condition, action);
  115. }
  116. return 1;
  117. });
  118. };
  119. Rewriter.prototype.closeOpenIndexes = function() {
  120. var action, condition;
  121. condition = function(token, i) {
  122. var _ref;
  123. return (_ref = token[0]) === ']' || _ref === 'INDEX_END';
  124. };
  125. action = function(token, i) {
  126. return token[0] = 'INDEX_END';
  127. };
  128. return this.scanTokens(function(token, i) {
  129. if (token[0] === 'INDEX_START') {
  130. this.detectEnd(i + 1, condition, action);
  131. }
  132. return 1;
  133. });
  134. };
  135. Rewriter.prototype.matchTags = function() {
  136. var fuzz, i, j, pattern, _i, _ref, _ref1;
  137. i = arguments[0], pattern = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
  138. fuzz = 0;
  139. for (j = _i = 0, _ref = pattern.length; 0 <= _ref ? _i < _ref : _i > _ref; j = 0 <= _ref ? ++_i : --_i) {
  140. while (this.tag(i + j + fuzz) === 'HERECOMMENT') {
  141. fuzz += 2;
  142. }
  143. if (pattern[j] == null) {
  144. continue;
  145. }
  146. if (typeof pattern[j] === 'string') {
  147. pattern[j] = [pattern[j]];
  148. }
  149. if (_ref1 = this.tag(i + j + fuzz), __indexOf.call(pattern[j], _ref1) < 0) {
  150. return false;
  151. }
  152. }
  153. return true;
  154. };
  155. Rewriter.prototype.looksObjectish = function(j) {
  156. return this.matchTags(j, '@', null, ':') || this.matchTags(j, null, ':');
  157. };
  158. Rewriter.prototype.findTagsBackwards = function(i, tags) {
  159. var backStack, _ref, _ref1, _ref2, _ref3, _ref4, _ref5;
  160. backStack = [];
  161. while (i >= 0 && (backStack.length || (_ref2 = this.tag(i), __indexOf.call(tags, _ref2) < 0) && ((_ref3 = this.tag(i), __indexOf.call(EXPRESSION_START, _ref3) < 0) || this.tokens[i].generated) && (_ref4 = this.tag(i), __indexOf.call(LINEBREAKS, _ref4) < 0))) {
  162. if (_ref = this.tag(i), __indexOf.call(EXPRESSION_END, _ref) >= 0) {
  163. backStack.push(this.tag(i));
  164. }
  165. if ((_ref1 = this.tag(i), __indexOf.call(EXPRESSION_START, _ref1) >= 0) && backStack.length) {
  166. backStack.pop();
  167. }
  168. i -= 1;
  169. }
  170. return _ref5 = this.tag(i), __indexOf.call(tags, _ref5) >= 0;
  171. };
  172. Rewriter.prototype.addImplicitBracesAndParens = function() {
  173. var stack;
  174. stack = [];
  175. return this.scanTokens(function(token, i, tokens) {
  176. var endImplicitCall, endImplicitObject, forward, inImplicit, inImplicitCall, inImplicitControl, inImplicitObject, nextTag, offset, prevTag, s, sameLine, stackIdx, stackTag, stackTop, startIdx, startImplicitCall, startImplicitObject, startsLine, tag, _ref, _ref1, _ref2, _ref3, _ref4, _ref5;
  177. tag = token[0];
  178. prevTag = (i > 0 ? tokens[i - 1] : [])[0];
  179. nextTag = (i < tokens.length - 1 ? tokens[i + 1] : [])[0];
  180. stackTop = function() {
  181. return stack[stack.length - 1];
  182. };
  183. startIdx = i;
  184. forward = function(n) {
  185. return i - startIdx + n;
  186. };
  187. inImplicit = function() {
  188. var _ref, _ref1;
  189. return (_ref = stackTop()) != null ? (_ref1 = _ref[2]) != null ? _ref1.ours : void 0 : void 0;
  190. };
  191. inImplicitCall = function() {
  192. var _ref;
  193. return inImplicit() && ((_ref = stackTop()) != null ? _ref[0] : void 0) === '(';
  194. };
  195. inImplicitObject = function() {
  196. var _ref;
  197. return inImplicit() && ((_ref = stackTop()) != null ? _ref[0] : void 0) === '{';
  198. };
  199. inImplicitControl = function() {
  200. var _ref;
  201. return inImplicit && ((_ref = stackTop()) != null ? _ref[0] : void 0) === 'CONTROL';
  202. };
  203. startImplicitCall = function(j) {
  204. var idx;
  205. idx = j != null ? j : i;
  206. stack.push([
  207. '(', idx, {
  208. ours: true
  209. }
  210. ]);
  211. tokens.splice(idx, 0, generate('CALL_START', '('));
  212. if (j == null) {
  213. return i += 1;
  214. }
  215. };
  216. endImplicitCall = function() {
  217. stack.pop();
  218. tokens.splice(i, 0, generate('CALL_END', ')'));
  219. return i += 1;
  220. };
  221. startImplicitObject = function(j, startsLine) {
  222. var idx;
  223. if (startsLine == null) {
  224. startsLine = true;
  225. }
  226. idx = j != null ? j : i;
  227. stack.push([
  228. '{', idx, {
  229. sameLine: true,
  230. startsLine: startsLine,
  231. ours: true
  232. }
  233. ]);
  234. tokens.splice(idx, 0, generate('{', generate(new String('{'))));
  235. if (j == null) {
  236. return i += 1;
  237. }
  238. };
  239. endImplicitObject = function(j) {
  240. j = j != null ? j : i;
  241. stack.pop();
  242. tokens.splice(j, 0, generate('}', '}'));
  243. return i += 1;
  244. };
  245. if (inImplicitCall() && (tag === 'IF' || tag === 'TRY' || tag === 'FINALLY' || tag === 'CATCH' || tag === 'CLASS' || tag === 'SWITCH')) {
  246. stack.push([
  247. 'CONTROL', i, {
  248. ours: true
  249. }
  250. ]);
  251. return forward(1);
  252. }
  253. if (tag === 'INDENT' && inImplicit()) {
  254. if (prevTag !== '=>' && prevTag !== '->' && prevTag !== '[' && prevTag !== '(' && prevTag !== ',' && prevTag !== '{' && prevTag !== 'TRY' && prevTag !== 'ELSE' && prevTag !== '=') {
  255. while (inImplicitCall()) {
  256. endImplicitCall();
  257. }
  258. }
  259. if (inImplicitControl()) {
  260. stack.pop();
  261. }
  262. stack.push([tag, i]);
  263. return forward(1);
  264. }
  265. if (__indexOf.call(EXPRESSION_START, tag) >= 0) {
  266. stack.push([tag, i]);
  267. return forward(1);
  268. }
  269. if (__indexOf.call(EXPRESSION_END, tag) >= 0) {
  270. while (inImplicit()) {
  271. if (inImplicitCall()) {
  272. endImplicitCall();
  273. } else if (inImplicitObject()) {
  274. endImplicitObject();
  275. } else {
  276. stack.pop();
  277. }
  278. }
  279. stack.pop();
  280. }
  281. if ((__indexOf.call(IMPLICIT_FUNC, tag) >= 0 && token.spaced && !token.stringEnd || tag === '?' && i > 0 && !tokens[i - 1].spaced) && (__indexOf.call(IMPLICIT_CALL, nextTag) >= 0 || __indexOf.call(IMPLICIT_UNSPACED_CALL, nextTag) >= 0 && !((_ref = tokens[i + 1]) != null ? _ref.spaced : void 0) && !((_ref1 = tokens[i + 1]) != null ? _ref1.newLine : void 0))) {
  282. if (tag === '?') {
  283. tag = token[0] = 'FUNC_EXIST';
  284. }
  285. startImplicitCall(i + 1);
  286. return forward(2);
  287. }
  288. if (__indexOf.call(IMPLICIT_FUNC, tag) >= 0 && this.matchTags(i + 1, 'INDENT', null, ':') && !this.findTagsBackwards(i, ['CLASS', 'EXTENDS', 'IF', 'CATCH', 'SWITCH', 'LEADING_WHEN', 'FOR', 'WHILE', 'UNTIL'])) {
  289. startImplicitCall(i + 1);
  290. stack.push(['INDENT', i + 2]);
  291. return forward(3);
  292. }
  293. if (tag === ':') {
  294. if (this.tag(i - 2) === '@') {
  295. s = i - 2;
  296. } else {
  297. s = i - 1;
  298. }
  299. while (this.tag(s - 2) === 'HERECOMMENT') {
  300. s -= 2;
  301. }
  302. startsLine = s === 0 || (_ref2 = this.tag(s - 1), __indexOf.call(LINEBREAKS, _ref2) >= 0) || tokens[s - 1].newLine;
  303. if (stackTop()) {
  304. _ref3 = stackTop(), stackTag = _ref3[0], stackIdx = _ref3[1];
  305. if ((stackTag === '{' || stackTag === 'INDENT' && this.tag(stackIdx - 1) === '{') && (startsLine || this.tag(s - 1) === ',' || this.tag(s - 1) === '{')) {
  306. return forward(1);
  307. }
  308. }
  309. startImplicitObject(s, !!startsLine);
  310. return forward(2);
  311. }
  312. if (prevTag === 'OUTDENT' && inImplicitCall() && (tag === '.' || tag === '?.' || tag === '::' || tag === '?::')) {
  313. endImplicitCall();
  314. return forward(1);
  315. }
  316. if (inImplicitObject() && __indexOf.call(LINEBREAKS, tag) >= 0) {
  317. stackTop()[2].sameLine = false;
  318. }
  319. if (__indexOf.call(IMPLICIT_END, tag) >= 0) {
  320. while (inImplicit()) {
  321. _ref4 = stackTop(), stackTag = _ref4[0], stackIdx = _ref4[1], (_ref5 = _ref4[2], sameLine = _ref5.sameLine, startsLine = _ref5.startsLine);
  322. if (inImplicitCall() && prevTag !== ',') {
  323. endImplicitCall();
  324. } else if (inImplicitObject() && sameLine && !startsLine) {
  325. endImplicitObject();
  326. } else if (inImplicitObject() && tag === 'TERMINATOR' && prevTag !== ',' && !(startsLine && this.looksObjectish(i + 1))) {
  327. endImplicitObject();
  328. } else {
  329. break;
  330. }
  331. }
  332. }
  333. if (tag === ',' && !this.looksObjectish(i + 1) && inImplicitObject() && (nextTag !== 'TERMINATOR' || !this.looksObjectish(i + 2))) {
  334. offset = nextTag === 'OUTDENT' ? 1 : 0;
  335. while (inImplicitObject()) {
  336. endImplicitObject(i + offset);
  337. }
  338. }
  339. return forward(1);
  340. });
  341. };
  342. Rewriter.prototype.addLocationDataToGeneratedTokens = function() {
  343. return this.scanTokens(function(token, i, tokens) {
  344. var column, line, nextLocation, prevLocation, _ref, _ref1;
  345. if (token[2]) {
  346. return 1;
  347. }
  348. if (!(token.generated || token.explicit)) {
  349. return 1;
  350. }
  351. if (token[0] === '{' && (nextLocation = (_ref = tokens[i + 1]) != null ? _ref[2] : void 0)) {
  352. line = nextLocation.first_line, column = nextLocation.first_column;
  353. } else if (prevLocation = (_ref1 = tokens[i - 1]) != null ? _ref1[2] : void 0) {
  354. line = prevLocation.last_line, column = prevLocation.last_column;
  355. } else {
  356. line = column = 0;
  357. }
  358. token[2] = {
  359. first_line: line,
  360. first_column: column,
  361. last_line: line,
  362. last_column: column
  363. };
  364. return 1;
  365. });
  366. };
  367. Rewriter.prototype.addImplicitIndentation = function() {
  368. var action, condition, indent, outdent, starter;
  369. starter = indent = outdent = null;
  370. condition = function(token, i) {
  371. var _ref, _ref1;
  372. return token[1] !== ';' && (_ref = token[0], __indexOf.call(SINGLE_CLOSERS, _ref) >= 0) && !(token[0] === 'ELSE' && starter !== 'THEN') && !(((_ref1 = token[0]) === 'CATCH' || _ref1 === 'FINALLY') && (starter === '->' || starter === '=>'));
  373. };
  374. action = function(token, i) {
  375. return this.tokens.splice((this.tag(i - 1) === ',' ? i - 1 : i), 0, outdent);
  376. };
  377. return this.scanTokens(function(token, i, tokens) {
  378. var j, tag, _i, _ref, _ref1;
  379. tag = token[0];
  380. if (tag === 'TERMINATOR' && this.tag(i + 1) === 'THEN') {
  381. tokens.splice(i, 1);
  382. return 0;
  383. }
  384. if (tag === 'ELSE' && this.tag(i - 1) !== 'OUTDENT') {
  385. tokens.splice.apply(tokens, [i, 0].concat(__slice.call(this.indentation())));
  386. return 2;
  387. }
  388. if (tag === 'CATCH') {
  389. for (j = _i = 1; _i <= 2; j = ++_i) {
  390. if (!((_ref = this.tag(i + j)) === 'OUTDENT' || _ref === 'TERMINATOR' || _ref === 'FINALLY')) {
  391. continue;
  392. }
  393. tokens.splice.apply(tokens, [i + j, 0].concat(__slice.call(this.indentation())));
  394. return 2 + j;
  395. }
  396. }
  397. if (__indexOf.call(SINGLE_LINERS, tag) >= 0 && this.tag(i + 1) !== 'INDENT' && !(tag === 'ELSE' && this.tag(i + 1) === 'IF')) {
  398. starter = tag;
  399. _ref1 = this.indentation(true), indent = _ref1[0], outdent = _ref1[1];
  400. if (starter === 'THEN') {
  401. indent.fromThen = true;
  402. }
  403. tokens.splice(i + 1, 0, indent);
  404. this.detectEnd(i + 2, condition, action);
  405. if (tag === 'THEN') {
  406. tokens.splice(i, 1);
  407. }
  408. return 1;
  409. }
  410. return 1;
  411. });
  412. };
  413. Rewriter.prototype.tagPostfixConditionals = function() {
  414. var action, condition, original;
  415. original = null;
  416. condition = function(token, i) {
  417. var prevTag, tag;
  418. tag = token[0];
  419. prevTag = this.tokens[i - 1][0];
  420. return tag === 'TERMINATOR' || (tag === 'INDENT' && __indexOf.call(SINGLE_LINERS, prevTag) < 0);
  421. };
  422. action = function(token, i) {
  423. if (token[0] !== 'INDENT' || (token.generated && !token.fromThen)) {
  424. return original[0] = 'POST_' + original[0];
  425. }
  426. };
  427. return this.scanTokens(function(token, i) {
  428. if (token[0] !== 'IF') {
  429. return 1;
  430. }
  431. original = token;
  432. this.detectEnd(i + 1, condition, action);
  433. return 1;
  434. });
  435. };
  436. Rewriter.prototype.indentation = function(implicit) {
  437. var indent, outdent;
  438. if (implicit == null) {
  439. implicit = false;
  440. }
  441. indent = ['INDENT', 2];
  442. outdent = ['OUTDENT', 2];
  443. if (implicit) {
  444. indent.generated = outdent.generated = true;
  445. }
  446. if (!implicit) {
  447. indent.explicit = outdent.explicit = true;
  448. }
  449. return [indent, outdent];
  450. };
  451. Rewriter.prototype.generate = generate;
  452. Rewriter.prototype.tag = function(i) {
  453. var _ref;
  454. return (_ref = this.tokens[i]) != null ? _ref[0] : void 0;
  455. };
  456. return Rewriter;
  457. })();
  458. BALANCED_PAIRS = [['(', ')'], ['[', ']'], ['{', '}'], ['INDENT', 'OUTDENT'], ['CALL_START', 'CALL_END'], ['PARAM_START', 'PARAM_END'], ['INDEX_START', 'INDEX_END']];
  459. exports.INVERSES = INVERSES = {};
  460. EXPRESSION_START = [];
  461. EXPRESSION_END = [];
  462. for (_i = 0, _len = BALANCED_PAIRS.length; _i < _len; _i++) {
  463. _ref = BALANCED_PAIRS[_i], left = _ref[0], rite = _ref[1];
  464. EXPRESSION_START.push(INVERSES[rite] = left);
  465. EXPRESSION_END.push(INVERSES[left] = rite);
  466. }
  467. EXPRESSION_CLOSE = ['CATCH', 'WHEN', 'ELSE', 'FINALLY'].concat(EXPRESSION_END);
  468. IMPLICIT_FUNC = ['IDENTIFIER', 'SUPER', ')', 'CALL_END', ']', 'INDEX_END', '@', 'THIS'];
  469. IMPLICIT_CALL = ['IDENTIFIER', 'NUMBER', 'STRING', 'JS', 'REGEX', 'NEW', 'PARAM_START', 'CLASS', 'IF', 'TRY', 'SWITCH', 'THIS', 'BOOL', 'NULL', 'UNDEFINED', 'UNARY', 'SUPER', 'THROW', '@', '->', '=>', '[', '(', '{', '--', '++'];
  470. IMPLICIT_UNSPACED_CALL = ['+', '-'];
  471. IMPLICIT_END = ['POST_IF', 'FOR', 'WHILE', 'UNTIL', 'WHEN', 'BY', 'LOOP', 'TERMINATOR'];
  472. SINGLE_LINERS = ['ELSE', '->', '=>', 'TRY', 'FINALLY', 'THEN'];
  473. SINGLE_CLOSERS = ['TERMINATOR', 'CATCH', 'FINALLY', 'ELSE', 'OUTDENT', 'LEADING_WHEN'];
  474. LINEBREAKS = ['TERMINATOR', 'INDENT', 'OUTDENT'];
  475. });