From cdd033ffb0b88eb6f00e61280de949d476e9d28e Mon Sep 17 00:00:00 2001 From: satyr Date: Mon, 4 Oct 2010 21:50:50 +0900 Subject: [PATCH] disabled interpolations in normal regexes --- lib/cake.js | 4 +- lib/command.js | 8 +- lib/grammar.js | 4 +- lib/lexer.js | 116 +++++++--------- lib/nodes.js | 186 +++++++++++++------------- lib/optparse.js | 4 +- lib/scope.js | 2 +- src/lexer.coffee | 83 +++++------- test/test_regexp_interpolation.coffee | 20 --- test/test_regexps.coffee | 10 +- 10 files changed, 194 insertions(+), 243 deletions(-) delete mode 100644 test/test_regexp_interpolation.coffee diff --git a/lib/cake.js b/lib/cake.js index e8ad2b9b..5b851875 100755 --- a/lib/cake.js +++ b/lib/cake.js @@ -63,12 +63,12 @@ spaces = 20 - name.length; spaces = spaces > 0 ? Array(spaces + 1).join(' ') : ''; desc = task.description ? ("# " + (task.description)) : ''; - puts("cake " + (name) + (spaces) + " " + (desc)); + puts("cake " + name + spaces + " " + desc); } return switches.length ? puts(oparse.help()) : undefined; }; missingTask = function(task) { - puts("No such task: \"" + (task) + "\""); + puts("No such task: \"" + task + "\""); return process.exit(1); }; }).call(this); diff --git a/lib/command.js b/lib/command.js index fcc90317..761df2bf 100644 --- a/lib/command.js +++ b/lib/command.js @@ -60,7 +60,7 @@ compile = function(source, topLevel) { return path.exists(source, function(exists) { if (!(exists)) { - throw new Error("File not found: " + (source)); + throw new Error("File not found: " + source); } return fs.stat(source, function(err, stats) { if (stats.isDirectory()) { @@ -168,11 +168,11 @@ js = ' '; } return fs.writeFile(jsPath, js, function(err) { - return opts.compile && opts.watch ? puts("Compiled " + (source)) : undefined; + return opts.compile && opts.watch ? puts("Compiled " + source) : undefined; }); }; return path.exists(dir, function(exists) { - return exists ? compile() : exec("mkdir -p " + (dir), compile); + return exists ? compile() : exec("mkdir -p " + dir, compile); }); }; lint = function(js) { @@ -195,7 +195,7 @@ token = tokens[_i]; _result.push((function() { _ref2 = [token[0], token[1].toString().replace(/\n/, '\\n')], tag = _ref2[0], value = _ref2[1]; - return "[" + (tag) + " " + (value) + "]"; + return "[" + tag + " " + value + "]"; })()); } return _result; diff --git a/lib/grammar.js b/lib/grammar.js index 059a04af..3520e3b4 100644 --- a/lib/grammar.js +++ b/lib/grammar.js @@ -8,9 +8,9 @@ if (!(action)) { return [patternString, '$$ = $1;', options]; } - action = (match = (action + '').match(unwrap)) ? match[1] : ("(" + (action) + "())"); + action = (match = (action + '').match(unwrap)) ? match[1] : ("(" + action + "())"); action = action.replace(/\b(?:[A-Z][a-z]+Node|Expressions)\b/g, 'yy.$&'); - return [patternString, ("$$ = " + (action) + ";"), options]; + return [patternString, ("$$ = " + action + ";"), options]; }; grammar = { Root: [ diff --git a/lib/lexer.js b/lib/lexer.js index 16d14fb6..f1caca4d 100644 --- a/lib/lexer.js +++ b/lib/lexer.js @@ -1,5 +1,5 @@ (function() { - var ASSIGNED, CALLABLE, CODE, COFFEE_ALIASES, COFFEE_KEYWORDS, COMMENT, COMPARE, COMPOUND_ASSIGN, CONVERSIONS, HEREDOC, HEREDOC_INDENT, HEREGEX, HEREGEX_OMIT, IDENTIFIER, JSTOKEN, JS_FORBIDDEN, JS_KEYWORDS, LEADING_SPACES, LINE_BREAK, LOGIC, Lexer, MATH, MULTILINER, MULTI_DENT, NEXT_CHARACTER, NOT_REGEX, NO_NEWLINE, NUMBER, OPERATOR, REGEX_END, REGEX_ESCAPE, REGEX_START, RESERVED, Rewriter, SHIFT, SIMPLESTR, TRAILING_SPACES, UNARY, WHITESPACE, _ref, compact, count, include, last, starts; + var ASSIGNED, CALLABLE, CODE, COFFEE_ALIASES, COFFEE_KEYWORDS, COMMENT, COMPARE, COMPOUND_ASSIGN, CONVERSIONS, HEREDOC, HEREDOC_INDENT, HEREGEX, HEREGEX_OMIT, IDENTIFIER, JSTOKEN, JS_FORBIDDEN, JS_KEYWORDS, LEADING_SPACES, LINE_BREAK, LOGIC, Lexer, MATH, MULTILINER, MULTI_DENT, NEXT_CHARACTER, NOT_REGEX, NO_NEWLINE, NUMBER, OPERATOR, REGEX, RESERVED, Rewriter, SHIFT, SIMPLESTR, TRAILING_SPACES, UNARY, WHITESPACE, _ref, compact, count, include, last, starts; Rewriter = require('./rewriter').Rewriter; _ref = require('./helpers'), include = _ref.include, count = _ref.count, starts = _ref.starts, compact = _ref.compact, last = _ref.last; exports.Lexer = (function() { @@ -49,7 +49,7 @@ if (include(JS_FORBIDDEN, id)) { if (forcedIdentifier) { tag = 'STRING'; - id = ("\"" + (id) + "\""); + id = ("\"" + id + "\""); if (forcedIdentifier === 'accessor') { closeIndex = true; if (this.tag() !== '@') { @@ -165,60 +165,55 @@ return true; }; Lexer.prototype.regexToken = function() { - var _ref2, end, first, flags, match, regex, str; + var match; if (this.chunk.charAt(0) !== '/') { return false; } if (match = HEREGEX.exec(this.chunk)) { return this.heregexToken(match); } - if (!(first = REGEX_START.exec(this.chunk))) { - return false; - } - if (first[1] === ' ' && !('CALL_START' === (_ref2 = this.tag()) || '=' === _ref2)) { - return false; - } if (include(NOT_REGEX, this.tag())) { return false; } - if (!(regex = this.balancedString(this.chunk, [['/', '/']]))) { + if (!(match = REGEX.exec(this.chunk))) { return false; } - if (!(end = this.chunk.slice(regex.length).match(REGEX_END))) { - return false; - } - flags = end[0]; - if (~regex.indexOf('#{')) { - str = regex.slice(1, -1); - this.tokens.push(['IDENTIFIER', 'RegExp'], ['CALL_START', '(']); - this.interpolateString("\"" + (str) + "\"", { - regex: true - }); - if (flags) { - this.tokens.push([',', ','], ['STRING', ("\"" + (flags) + "\"")]); - } - this.tokens.push(['CALL_END', ')']); - } else { - this.token('REGEX', regex + flags); - } - this.i += regex.length + flags.length; + this.token('REGEX', match[0]); + this.i += match[0].length; return true; }; Lexer.prototype.heregexToken = function(match) { - var _ref2, body, flags, heregex, re; + var _i, _len, _ref2, _ref3, _this, body, flags, heregex, re, tag, tokens, value; _ref2 = match, heregex = _ref2[0], body = _ref2[1], flags = _ref2[2]; this.i += heregex.length; if (!(~body.indexOf('#{'))) { re = body.replace(HEREGEX_OMIT, '').replace(/\//g, '\\/'); - this.token('REGEX', "/" + (re || '(?:)') + "/" + (flags)); + this.token('REGEX', "/" + (re || '(?:)') + "/" + flags); return true; } this.token('IDENTIFIER', 'RegExp'); this.tokens.push(['CALL_START', '(']); - this.interpolateString("\"" + (body) + "\"", { - regex: true, - heregex: true + tokens = []; + _ref2 = this.interpolateString('"' + body + '"', { + regex: true }); + for (_i = 0, _len = _ref2.length; _i < _len; _i++) { + _ref3 = _ref2[_i], tag = _ref3[0], value = _ref3[1]; + if (tag === 'TOKENS') { + tokens.push.apply(tokens, value); + } else { + if (!(value = value.slice(1, -1).replace(HEREGEX_OMIT, ''))) { + continue; + } + tokens.push(['STRING', '"' + value.replace(/[\\\"]/g, '\\$&') + '"']); + } + tokens.push(['+', '+']); + } + tokens.pop(); + if ((((_ref2 = tokens[0]) != null) ? _ref2[0] !== 'STRING' : undefined)) { + this.tokens.push(['STRING', '""'], ['+', '+']); + } + (_this = this.tokens).push.apply(_this, tokens); if (flags) { this.tokens.push([',', ','], ['STRING', '"' + flags + '"']); } @@ -404,7 +399,7 @@ } } if (indent) { - doc = doc.replace(RegExp("\\n" + (indent), "g"), '\n'); + doc = doc.replace(RegExp("\\n" + indent, "g"), '\n'); } if (herecomment) { return doc; @@ -414,7 +409,7 @@ doc = doc.replace(/\\([\s\S])/g, function(m, c) { return ('\n' === c || quote === c) ? c : m; }); - doc = doc.replace(RegExp("" + (quote), "g"), '\\$&'); + doc = doc.replace(RegExp("" + quote, "g"), '\\$&'); if (quote === "'") { doc = this.escapeLines(doc, true); } @@ -448,15 +443,14 @@ return this.outdentToken(this.indent); }; Lexer.prototype.identifierError = function(word) { - throw new Error("SyntaxError: Reserved word \"" + (word) + "\" on line " + (this.line + 1)); + throw new Error("SyntaxError: Reserved word \"" + word + "\" on line " + (this.line + 1)); }; Lexer.prototype.assignmentError = function() { throw new Error("SyntaxError: Reserved word \"" + (this.value()) + "\" on line " + (this.line + 1) + " can't be assigned"); }; Lexer.prototype.balancedString = function(str, delimited, options) { - var _i, _len, _ref2, close, i, levels, open, pair, slash, slen; + var _i, _len, _ref2, close, i, levels, open, pair, slen; options || (options = {}); - slash = delimited[0][0] === '/'; levels = []; i = 0; slen = str.length; @@ -482,21 +476,18 @@ } } } - if (!levels.length || slash && str.charAt(i) === '\n') { + if (!levels.length) { break; } i += 1; } if (levels.length) { - if (slash) { - return false; - } throw new Error("SyntaxError: Unterminated " + (levels.pop()[0]) + " starting on line " + (this.line + 1)); } return !i ? false : str.slice(0, i); }; Lexer.prototype.interpolateString = function(str, options) { - var _i, _len, _ref2, char, expr, heredoc, i, inner, interpolated, lexer, nested, pi, push, regex, s, tag, tok, tokens, value; + var _i, _len, _ref2, _this, char, expr, heredoc, i, inner, interpolated, lexer, nested, pi, regex, tag, tok, tokens, value; if (str.length < 5) { return this.token('STRING', this.escapeLines(str, heredoc)); } @@ -514,14 +505,14 @@ continue; } if (pi < i) { - tokens.push(['STRING', '"' + this.escapeLines(str.slice(pi, i), heredoc) + '"']); + tokens.push(['STRING', '"' + str.slice(pi, i) + '"']); } inner = expr.slice(1, -1).replace(LEADING_SPACES, '').replace(TRAILING_SPACES, ''); if (inner.length) { if (heredoc) { inner = inner.replace(/\\\"/g, '"'); } - nested = lexer.tokenize("(" + (inner) + ")", { + nested = lexer.tokenize("(" + inner + "\n)", { line: this.line }); for (_i = 0, _len = nested.length; _i < _len; _i++) { @@ -531,43 +522,38 @@ } } nested.pop(); + if (nested.length < 5) { + nested.pop(); + nested.shift(); + } tokens.push(['TOKENS', nested]); - } else { - tokens.push(['STRING', '""']); } i += expr.length; pi = i + 1; } if ((i > pi) && (pi < str.length - 1)) { - s = this.escapeLines(str.slice(pi, -1), heredoc); - tokens.push(['STRING', '"' + s + '"']); + tokens.push(['STRING', '"' + str.slice(pi)]); } - if (tokens[0][0] !== 'STRING') { + if (regex) { + return tokens; + } + interpolated = tokens.length > 1; + if ((((_ref2 = tokens[0]) != null) ? _ref2[0] !== 'STRING' : undefined)) { tokens.unshift(['STRING', '""']); } - interpolated = !regex && tokens.length > 1; if (interpolated) { this.token('(', '('); } - push = tokens.push; for (i = 0, _len = tokens.length; i < _len; i++) { _ref2 = tokens[i], tag = _ref2[0], value = _ref2[1]; if (i) { this.token('+', '+'); } if (tag === 'TOKENS') { - push.apply(this.tokens, value); - continue; + (_this = this.tokens).push.apply(_this, value); + } else { + this.token(tag, this.escapeLines(value, heredoc)); } - if (regex) { - value = value.slice(1, -1); - value = value.replace(/[\\\"]/g, '\\$&'); - if (options.heregex) { - value = value.replace(HEREGEX_OMIT, ''); - } - value = '"' + value + '"'; - } - this.token(tag, value); } if (interpolated) { this.token(')', ')'); @@ -615,9 +601,7 @@ MULTI_DENT = /^(?:\n[ \t]*)+/; SIMPLESTR = /^'[^\\']*(?:\\.[^\\']*)*'/; JSTOKEN = /^`[^\\`]*(?:\\.[^\\`]*)*`/; - REGEX_START = /^\/([^\/])/; - REGEX_END = /^[imgy]{0,4}(?![a-zA-Z])/; - REGEX_ESCAPE = /\\[^#]/g; + REGEX = /^\/(?!\s)(?:[^[\/\n\\]+|\\.|\[([^\\\]]+|\\.)*])+\/[imgy]{0,4}(?![A-Za-z])/; HEREGEX = /^\/{3}([\s\S]+?)\/{3}([imgy]{0,4})(?![A-Za-z])/; HEREGEX_OMIT = /\s+(?:#.*)?/g; MULTILINER = /\n/g; diff --git a/lib/nodes.js b/lib/nodes.js index 795db29b..9edeecd4 100644 --- a/lib/nodes.js +++ b/lib/nodes.js @@ -214,16 +214,16 @@ o.scope = new Scope(null, this, null); code = this.compileWithDeclarations(o); code = code.replace(TRAILING_WHITESPACE, ''); - return o.noWrap ? code : ("(function() {\n" + (code) + "\n}).call(this);\n"); + return o.noWrap ? code : ("(function() {\n" + code + "\n}).call(this);\n"); }; Expressions.prototype.compileWithDeclarations = function(o) { var code; code = this.compileNode(o); if (o.scope.hasAssignments(this)) { - code = ("" + (this.tab) + "var " + (o.scope.compiledAssignments()) + ";\n" + (code)); + code = ("" + this.tab + "var " + (o.scope.compiledAssignments()) + ";\n" + code); } if (!o.globals && o.scope.hasDeclarations(this)) { - code = ("" + (this.tab) + "var " + (o.scope.compiledDeclarations()) + ";\n" + (code)); + code = ("" + this.tab + "var " + (o.scope.compiledDeclarations()) + ";\n" + code); } return code; }; @@ -233,7 +233,7 @@ compiledNode = node.compile(merge(o, { top: true })); - return node.isStatement(o) ? compiledNode : ("" + (this.idt()) + (compiledNode) + ";"); + return node.isStatement(o) ? compiledNode : ("" + (this.idt()) + compiledNode + ";"); }; return Expressions; })(); @@ -295,7 +295,7 @@ if (this.expression.isStatement(o)) { o.asStatement = true; } - return "" + (this.tab) + "return " + (this.expression.compile(o)) + ";"; + return "" + this.tab + "return " + (this.expression.compile(o)) + ";"; }; return ReturnNode; })(); @@ -376,7 +376,7 @@ } code = this.base.compile(o); if (props[0] instanceof AccessorNode && this.isNumber() || o.top && this.base instanceof ObjectNode) { - code = ("(" + (code) + ")"); + code = ("(" + code + ")"); } for (_i = 0, _len = props.length; _i < _len; _i++) { prop = props[_i]; @@ -477,7 +477,7 @@ if (!(name)) { throw Error("cannot call super on an anonymous function."); } - return method.klass ? ("" + (method.klass) + ".__super__." + (name)) : ("" + (name) + ".__super__.constructor"); + return method.klass ? ("" + (method.klass) + ".__super__." + name) : ("" + name + ".__super__.constructor"); }; CallNode.prototype.unfoldSoak = function(o) { var _i, _len, _ref2, call, list, node; @@ -530,7 +530,7 @@ } left = ("typeof " + (left.compile(o)) + " !== \"function\""); rite = rite.compile(o); - return ("(" + (left) + " ? undefined : " + (rite) + ")"); + return ("(" + left + " ? undefined : " + rite + ")"); } _ref2 = this.args; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { @@ -547,16 +547,16 @@ } return _result; }).call(this).join(', '); - return this.isSuper ? this.compileSuper(args, o) : ("" + (this.prefix()) + (this.variable.compile(o)) + "(" + (args) + ")"); + return this.isSuper ? this.compileSuper(args, o) : ("" + (this.prefix()) + (this.variable.compile(o)) + "(" + args + ")"); }; CallNode.prototype.compileSuper = function(args, o) { - return "" + (this.superReference(o)) + ".call(this" + (args.length ? ', ' : '') + (args) + ")"; + return "" + (this.superReference(o)) + ".call(this" + (args.length ? ', ' : '') + args + ")"; }; CallNode.prototype.compileSplat = function(o) { var _i, _len, _ref2, a, arg, argvar, b, base, c, call, fun, idt, name, ref, splatargs; splatargs = this.compileSplatArguments(o); if (this.isSuper) { - return ("" + (this.superReference(o)) + ".apply(this, " + (splatargs) + ")"); + return ("" + (this.superReference(o)) + ".apply(this, " + splatargs + ")"); } if (!(this.isNew)) { if (!((base = this.variable) instanceof ValueNode)) { @@ -564,14 +564,14 @@ } if ((name = base.properties.pop()) && base.isComplex()) { ref = o.scope.freeVariable('this'); - fun = ("(" + (ref) + " = " + (base.compile(o)) + ")" + (name.compile(o))); + fun = ("(" + ref + " = " + (base.compile(o)) + ")" + (name.compile(o))); } else { fun = (ref = base.compile(o)); if (name) { fun += name.compile(o); } } - return ("" + (fun) + ".apply(" + (ref) + ", " + (splatargs) + ")"); + return ("" + fun + ".apply(" + ref + ", " + splatargs + ")"); } call = 'call(this)'; argvar = function(n) { @@ -588,7 +588,7 @@ a = o.scope.freeVariable('ctor'); b = o.scope.freeVariable('ref'); c = o.scope.freeVariable('result'); - return "(function() {\n" + (idt = this.idt(1)) + "var ctor = function() {};\n" + (idt) + (utility('extends')) + "(ctor, " + (a) + " = " + (this.variable.compile(o)) + ");\n" + (idt) + "return typeof (" + (c) + " = " + (a) + ".apply(" + (b) + " = new ctor, " + (splatargs) + ")) === \"object\" ? " + (c) + " : " + (b) + ";\n" + (this.tab) + "})." + (call); + return "(function() {\n" + (idt = this.idt(1)) + "var ctor = function() {};\n" + idt + (utility('extends')) + "(ctor, " + a + " = " + (this.variable.compile(o)) + ");\n" + idt + "return typeof (" + c + " = " + a + ".apply(" + b + " = new ctor, " + splatargs + ")) === \"object\" ? " + c + " : " + b + ";\n" + this.tab + "})." + call; }; return CallNode; })(); @@ -623,7 +623,7 @@ AccessorNode.prototype.compileNode = function(o) { var name, namePart; name = this.name.compile(o); - namePart = name.match(IS_STRING) ? ("[" + (name) + "]") : ("." + (name)); + namePart = name.match(IS_STRING) ? ("[" + name + "]") : ("." + name); return this.prototype + namePart; }; AccessorNode.prototype.isComplex = NO; @@ -642,7 +642,7 @@ var idx, prefix; idx = this.index.compile(o); prefix = this.proto ? '.prototype' : ''; - return "" + (prefix) + "[" + (idx) + "]"; + return "" + prefix + "[" + idx + "]"; }; IndexNode.prototype.isComplex = function() { return this.index.isComplex(); @@ -692,20 +692,20 @@ } idx = del(o, 'index'); step = del(o, 'step'); - vars = ("" + (idx) + " = " + (this.fromVar)); - intro = ("(" + (this.fromVar) + " <= " + (this.toVar) + " ? " + (idx)); - compare = ("" + (intro) + " <" + (this.equals) + " " + (this.toVar) + " : " + (idx) + " >" + (this.equals) + " " + (this.toVar) + ")"); + vars = ("" + idx + " = " + this.fromVar); + intro = ("(" + this.fromVar + " <= " + this.toVar + " ? " + idx); + compare = ("" + intro + " <" + this.equals + " " + this.toVar + " : " + idx + " >" + this.equals + " " + this.toVar + ")"); stepPart = step ? step.compile(o) : '1'; - incr = step ? ("" + (idx) + " += " + (stepPart)) : ("" + (intro) + " += " + (stepPart) + " : " + (idx) + " -= " + (stepPart) + ")"); - return "" + (vars) + "; " + (compare) + "; " + (incr); + incr = step ? ("" + idx + " += " + stepPart) : ("" + intro + " += " + stepPart + " : " + idx + " -= " + stepPart + ")"); + return "" + vars + "; " + compare + "; " + incr; }; RangeNode.prototype.compileSimple = function(o) { var _ref2, from, idx, step, to; _ref2 = [+this.fromNum, +this.toNum], from = _ref2[0], to = _ref2[1]; idx = del(o, 'index'); step = del(o, 'step'); - step && (step = ("" + (idx) + " += " + (step.compile(o)))); - return from <= to ? ("" + (idx) + " = " + (from) + "; " + (idx) + " <" + (this.equals) + " " + (to) + "; " + (step || ("" + (idx) + "++"))) : ("" + (idx) + " = " + (from) + "; " + (idx) + " >" + (this.equals) + " " + (to) + "; " + (step || ("" + (idx) + "--"))); + step && (step = ("" + idx + " += " + (step.compile(o)))); + return from <= to ? ("" + idx + " = " + from + "; " + idx + " <" + this.equals + " " + to + "; " + (step || ("" + idx + "++"))) : ("" + idx + " = " + from + "; " + idx + " >" + this.equals + " " + to + "; " + (step || ("" + idx + "--"))); }; RangeNode.prototype.compileArray = function(o) { var _i, _ref2, _ref3, _result, body, clause, i, idt, post, pre, range, result, vars; @@ -726,16 +726,16 @@ } i = o.scope.freeVariable('i'); result = o.scope.freeVariable('result'); - pre = ("\n" + (idt) + (result) + " = []; " + (vars)); + pre = ("\n" + idt + result + " = []; " + vars); if (this.fromNum && this.toNum) { o.index = i; body = this.compileSimple(o); } else { - clause = ("" + (this.fromVar) + " <= " + (this.toVar) + " ?"); - body = ("var " + (i) + " = " + (this.fromVar) + "; " + (clause) + " " + (i) + " <" + (this.equals) + " " + (this.toVar) + " : " + (i) + " >" + (this.equals) + " " + (this.toVar) + "; " + (clause) + " " + (i) + " += 1 : " + (i) + " -= 1"); + clause = ("" + this.fromVar + " <= " + this.toVar + " ?"); + body = ("var " + i + " = " + this.fromVar + "; " + clause + " " + i + " <" + this.equals + " " + this.toVar + " : " + i + " >" + this.equals + " " + this.toVar + "; " + clause + " " + i + " += 1 : " + i + " -= 1"); } - post = ("{ " + (result) + ".push(" + (i) + "); }\n" + (idt) + "return " + (result) + ";\n" + (o.indent)); - return "(function() {" + (pre) + "\n" + (idt) + "for (" + (body) + ")" + (post) + "}).call(this)"; + post = ("{ " + result + ".push(" + i + "); }\n" + idt + "return " + result + ";\n" + (o.indent)); + return "(function() {" + pre + "\n" + idt + "for (" + body + ")" + post + "}).call(this)"; }; return RangeNode; })(); @@ -756,7 +756,7 @@ if (to) { to = ', ' + to; } - return ".slice(" + (from) + (to) + ")"; + return ".slice(" + from + to + ")"; }; return SliceNode; })(); @@ -808,7 +808,7 @@ }).call(this); props = props.join(''); obj = '{' + (props ? '\n' + props + '\n' + this.idt() : '') + '}'; - return top ? ("(" + (obj) + ")") : obj; + return top ? ("(" + obj + ")") : obj; }; return ObjectNode; })(); @@ -836,15 +836,15 @@ if (obj instanceof SplatNode) { return this.compileSplatLiteral(o); } else if (obj instanceof CommentNode) { - objects.push("\n" + (code) + "\n" + (o.indent)); + objects.push("\n" + code + "\n" + (o.indent)); } else if (i === this.objects.length - 1) { objects.push(code); } else { - objects.push("" + (code) + ", "); + objects.push("" + code + ", "); } } objects = objects.join(''); - return indexOf(objects, '\n') >= 0 ? ("[\n" + (this.idt(1)) + (objects) + "\n" + (this.tab) + "]") : ("[" + (objects) + "]"); + return indexOf(objects, '\n') >= 0 ? ("[\n" + (this.idt(1)) + objects + "\n" + this.tab + "]") : ("[" + objects + "]"); }; return ArrayNode; })(); @@ -909,7 +909,7 @@ if (constructor.body.empty()) { constructor.body.push(new ReturnNode(literal('this'))); } - constructor.body.unshift(literal("this." + (pname) + " = function(){ return " + (className) + ".prototype." + (pname) + ".apply(" + (me) + ", arguments); }")); + constructor.body.unshift(literal("this." + pname + " = function(){ return " + className + ".prototype." + pname + ".apply(" + me + ", arguments); }")); } } if (pvar) { @@ -920,7 +920,7 @@ props.push(prop); } if (me) { - constructor.body.unshift(literal("" + (me) + " = this")); + constructor.body.unshift(literal("" + me + " = this")); } construct = this.idt() + (new AssignNode(this.variable, constructor)).compile(merge(o, { sharedScope: constScope @@ -970,16 +970,16 @@ } val = this.value.compile(o); if (this.context === 'object') { - return ("" + (name) + ": " + (val)); + return ("" + name + ": " + val); } if (!(isValue && (this.variable.hasProperties() || this.variable.namespaced))) { o.scope.find(name); } - val = ("" + (name) + " = " + (val)); + val = ("" + name + " = " + val); if (stmt) { - return ("" + (this.tab) + (val) + ";"); + return ("" + this.tab + val + ";"); } - return top || this.parenthetical ? val : ("(" + (val) + ")"); + return top || this.parenthetical ? val : ("(" + val + ")"); }; AssignNode.prototype.compilePatternMatch = function(o) { var _len, _ref2, accessClass, assigns, code, i, idx, isObject, obj, objects, olength, otop, splat, top, val, valVar, value; @@ -1009,7 +1009,7 @@ top: true }); valVar = o.scope.freeVariable('ref'); - assigns = [("" + (valVar) + " = " + (value.compile(o)))]; + assigns = [("" + valVar + " = " + (value.compile(o)))]; splat = false; for (i = 0, _len = objects.length; i < _len; i++) { obj = objects[i]; @@ -1030,7 +1030,7 @@ splat = true; } else { if (typeof idx !== 'object') { - idx = literal(splat ? ("" + (valVar) + ".length - " + (olength - idx)) : idx); + idx = literal(splat ? ("" + valVar + ".length - " + (olength - idx)) : idx); } val = new ValueNode(literal(valVar), [new accessClass(idx)]); } @@ -1040,7 +1040,7 @@ assigns.push(valVar); } code = assigns.join(', '); - return top || this.parenthetical ? code : ("(" + (code) + ")"); + return top || this.parenthetical ? code : ("(" + code + ")"); }; AssignNode.prototype.compileSplice = function(o) { var from, name, plus, range, ref, to, val; @@ -1048,10 +1048,10 @@ name = this.variable.compile(o); plus = range.exclusive ? '' : ' + 1'; from = range.from ? range.from.compile(o) : '0'; - to = range.to ? range.to.compile(o) + ' - ' + from + plus : ("" + (name) + ".length"); + to = range.to ? range.to.compile(o) + ' - ' + from + plus : ("" + name + ".length"); ref = o.scope.freeVariable('ref'); val = this.value.compile(o); - return "([].splice.apply(" + (name) + ", [" + (from) + ", " + (to) + "].concat(" + (ref) + " = " + (val) + ")), " + (ref) + ")"; + return "([].splice.apply(" + name + ", [" + from + ", " + to + "].concat(" + ref + " = " + val + ")), " + ref + ")"; }; return AssignNode; })(); @@ -1125,11 +1125,11 @@ (o.scope.parameter(param)); } code = this.body.expressions.length ? ("\n" + (this.body.compileWithDeclarations(o)) + "\n") : ''; - func = ("function(" + (params.join(', ')) + ") {" + (code) + (code && this.tab) + "}"); + func = ("function(" + (params.join(', ')) + ") {" + code + (code && this.tab) + "}"); if (this.bound) { - return ("(" + (utility('bind')) + "(" + (func) + ", " + (this.context) + "))"); + return ("(" + (utility('bind')) + "(" + func + ", " + this.context + "))"); } - return top ? ("(" + (func) + ")") : func; + return top ? ("(" + func + ")") : func; }; CodeNode.prototype.topSensitive = YES; CodeNode.prototype.traverseChildren = function(crossScope, func) { @@ -1190,7 +1190,7 @@ o.scope.assign(len, "arguments.length"); variadic = o.scope.freeVariable('result'); o.scope.assign(variadic, len + ' >= ' + this.arglength); - end = this.trailings.length ? (", " + (len) + " - " + (this.trailings.length)) : undefined; + end = this.trailings.length ? (", " + len + " - " + (this.trailings.length)) : undefined; _ref2 = this.trailings; for (idx = 0, _len = _ref2.length; idx < _len; idx++) { trailing = _ref2[idx]; @@ -1200,15 +1200,15 @@ assign.value = trailing; } pos = this.trailings.length - idx; - o.scope.assign(trailing.compile(o), "arguments[" + (variadic) + " ? " + (len) + " - " + (pos) + " : " + (this.index + idx) + "]"); + o.scope.assign(trailing.compile(o), "arguments[" + variadic + " ? " + len + " - " + pos + " : " + (this.index + idx) + "]"); } } - return "" + (name) + " = " + (utility('slice')) + ".call(arguments, " + (this.index) + (end) + ")"; + return "" + name + " = " + (utility('slice')) + ".call(arguments, " + this.index + end + ")"; }; SplatNode.prototype.compileValue = function(o, name, index, trailings) { var trail; - trail = trailings ? (", " + (name) + ".length - " + (trailings)) : ''; - return "" + (utility('slice')) + ".call(" + (name) + ", " + (index) + (trail) + ")"; + trail = trailings ? (", " + name + ".length - " + trailings) : ''; + return "" + (utility('slice')) + ".call(" + name + ", " + index + trail + ")"; }; SplatNode.compileSplattedArray = function(list, o) { var _len, arg, args, code, end, i, prev; @@ -1220,16 +1220,16 @@ prev = args[end]; if (!(arg instanceof SplatNode)) { if (prev && starts(prev, '[') && ends(prev, ']')) { - args[end] = ("" + (prev.slice(0, -1)) + ", " + (code) + "]"); + args[end] = ("" + (prev.slice(0, -1)) + ", " + code + "]"); continue; } if (prev && starts(prev, '.concat([') && ends(prev, '])')) { - args[end] = ("" + (prev.slice(0, -2)) + ", " + (code) + "])"); + args[end] = ("" + (prev.slice(0, -2)) + ", " + code + "])"); continue; } - code = ("[" + (code) + "]"); + code = ("[" + code + "]"); } - args[++end] = i === 0 ? code : (".concat(" + (code) + ")"); + args[++end] = i === 0 ? code : (".concat(" + code + ")"); } return args.join(''); }; @@ -1271,12 +1271,12 @@ set = ''; if (!(top)) { rvar = o.scope.freeVariable('result'); - set = ("" + (this.tab) + (rvar) + " = [];\n"); + set = ("" + this.tab + rvar + " = [];\n"); if (this.body) { this.body = PushNode.wrap(rvar, this.body); } } - pre = ("" + (set) + (this.tab) + "while (" + (cond) + ")"); + pre = ("" + set + this.tab + "while (" + cond + ")"); if (this.guard) { this.body = Expressions.wrap([new IfNode(this.guard, this.body)]); } @@ -1287,7 +1287,7 @@ } else { post = ''; } - return "" + (pre) + " {\n" + (this.body.compile(o)) + "\n" + (this.tab) + "}" + (post); + return "" + pre + " {\n" + (this.body.compile(o)) + "\n" + this.tab + "}" + post; }; return WhileNode; })(); @@ -1377,7 +1377,7 @@ shared = this.first.unwrap().second; _ref2 = shared.compileReference(o), this.first.second = _ref2[0], shared = _ref2[1]; _ref2 = [this.first.compile(o), this.second.compile(o), shared.compile(o)], first = _ref2[0], second = _ref2[1], shared = _ref2[2]; - return "(" + (first) + ") && (" + (shared) + " " + (this.operator) + " " + (second) + ")"; + return "(" + first + ") && (" + shared + " " + this.operator + " " + second + ")"; }; OpNode.prototype.compileAssignment = function(o) { var _ref2, left, rite; @@ -1394,7 +1394,7 @@ fst = this.first; ref = fst.compile(o); } - return new ExistenceNode(fst).compile(o) + (" ? " + (ref) + " : " + (this.second.compile(o))); + return new ExistenceNode(fst).compile(o) + (" ? " + ref + " : " + (this.second.compile(o))); }; OpNode.prototype.compileUnary = function(o) { var parts, space; @@ -1446,7 +1446,7 @@ }), this.arr1 = _ref2[0], this.arr2 = _ref2[1]; _ref2 = [o.scope.freeVariable('i'), o.scope.freeVariable('len')], i = _ref2[0], l = _ref2[1]; prefix = this.obj1 !== this.obj2 ? this.obj1 + '; ' : ''; - return "(function(){ " + (prefix) + "for (var " + (i) + "=0, " + (l) + "=" + (this.arr1) + ".length; " + (i) + "<" + (l) + "; " + (i) + "++) { if (" + (this.arr2) + "[" + (i) + "] === " + (this.obj2) + ") return true; } return false; }).call(this)"; + return "(function(){ " + prefix + "for (var " + i + "=0, " + l + "=" + this.arr1 + ".length; " + i + "<" + l + "; " + i + "++) { if (" + this.arr2 + "[" + i + "] === " + this.obj2 + ") return true; } return false; }).call(this)"; }; return InNode; })(); @@ -1478,9 +1478,9 @@ o.top = true; attemptPart = this.attempt.compile(o); errorPart = this.error ? (" (" + (this.error.compile(o)) + ") ") : ' '; - catchPart = this.recovery ? (" catch" + (errorPart) + "{\n" + (this.recovery.compile(o)) + "\n" + (this.tab) + "}") : ''; - finallyPart = (this.ensure || '') && ' finally {\n' + this.ensure.compile(merge(o)) + ("\n" + (this.tab) + "}"); - return "" + (this.tab) + "try {\n" + (attemptPart) + "\n" + (this.tab) + "}" + (catchPart) + (finallyPart); + catchPart = this.recovery ? (" catch" + errorPart + "{\n" + (this.recovery.compile(o)) + "\n" + this.tab + "}") : ''; + finallyPart = (this.ensure || '') && ' finally {\n' + this.ensure.compile(merge(o)) + ("\n" + this.tab + "}"); + return "" + this.tab + "try {\n" + attemptPart + "\n" + this.tab + "}" + catchPart + finallyPart; }; return TryNode; })(); @@ -1496,7 +1496,7 @@ ThrowNode.prototype.isStatement = YES; ThrowNode.prototype.makeReturn = THIS; ThrowNode.prototype.compileNode = function(o) { - return "" + (this.tab) + "throw " + (this.expression.compile(o)) + ";"; + return "" + this.tab + "throw " + (this.expression.compile(o)) + ";"; }; return ThrowNode; })(); @@ -1512,8 +1512,8 @@ ExistenceNode.prototype.compileNode = function(o) { var code; code = this.expression.compile(o); - code = IDENTIFIER.test(code) && !o.scope.check(code) ? ("typeof " + (code) + " !== \"undefined\" && " + (code) + " !== null") : ("" + (code) + " != null"); - return this.parenthetical ? code : ("(" + (code) + ")"); + code = IDENTIFIER.test(code) && !o.scope.check(code) ? ("typeof " + code + " !== \"undefined\" && " + code + " !== null") : ("" + code + " != null"); + return this.parenthetical ? code : ("(" + code + ")"); }; return ExistenceNode; })(); @@ -1547,7 +1547,7 @@ if (this.parenthetical || this.isStatement(o)) { return top ? this.tab + code + ';' : code; } - return "(" + (code) + ")"; + return "(" + code + ")"; }; return ParentheticalNode; })(); @@ -1638,20 +1638,20 @@ sourcePart = ''; } else { ref = scope.freeVariable('ref'); - sourcePart = ("" + (ref) + " = " + (svar) + ";"); + sourcePart = ("" + ref + " = " + svar + ";"); svar = ref; } - namePart = this.pattern ? new AssignNode(this.name, literal("" + (svar) + "[" + (ivar) + "]")).compile(merge(o, { + namePart = this.pattern ? new AssignNode(this.name, literal("" + svar + "[" + ivar + "]")).compile(merge(o, { top: true - })) : (name ? ("" + (name) + " = " + (svar) + "[" + (ivar) + "]") : undefined); + })) : (name ? ("" + name + " = " + svar + "[" + ivar + "]") : undefined); if (!(this.object)) { lvar = scope.freeVariable('len'); - stepPart = this.step ? ("" + (ivar) + " += " + (this.step.compile(o))) : ("" + (ivar) + "++"); - forPart = ("" + (ivar) + " = 0, " + (lvar) + " = " + (svar) + ".length; " + (ivar) + " < " + (lvar) + "; " + (stepPart)); + stepPart = this.step ? ("" + ivar + " += " + (this.step.compile(o))) : ("" + ivar + "++"); + forPart = ("" + ivar + " = 0, " + lvar + " = " + svar + ".length; " + ivar + " < " + lvar + "; " + stepPart); } } - sourcePart = (rvar ? ("" + (rvar) + " = []; ") : '') + sourcePart; - sourcePart = sourcePart ? ("" + (this.tab) + (sourcePart) + "\n" + (this.tab)) : this.tab; + sourcePart = (rvar ? ("" + rvar + " = []; ") : '') + sourcePart; + sourcePart = sourcePart ? ("" + this.tab + sourcePart + "\n" + this.tab) : this.tab; returnResult = this.compileReturnValue(rvar, o); if (!(topLevel)) { body = PushNode.wrap(rvar, body); @@ -1661,32 +1661,32 @@ } if (codeInBody) { if (range) { - body.unshift(literal("var " + (name) + " = " + (ivar))); + body.unshift(literal("var " + name + " = " + ivar)); } if (namePart) { - body.unshift(literal("var " + (namePart))); + body.unshift(literal("var " + namePart)); } if (index) { - body.unshift(literal("var " + (index) + " = " + (ivar))); + body.unshift(literal("var " + index + " = " + ivar)); } body = ClosureNode.wrap(body, true); } else { if (namePart) { - varPart = ("" + (idt1) + (namePart) + ";\n"); + varPart = ("" + idt1 + namePart + ";\n"); } } if (this.object) { - forPart = ("" + (ivar) + " in " + (svar)); + forPart = ("" + ivar + " in " + svar); if (!(this.raw)) { - guardPart = ("\n" + (idt1) + "if (!" + (utility('hasProp')) + ".call(" + (svar) + ", " + (ivar) + ")) continue;"); + guardPart = ("\n" + idt1 + "if (!" + (utility('hasProp')) + ".call(" + svar + ", " + ivar + ")) continue;"); } } body = body.compile(merge(o, { indent: idt1, top: true })); - vars = range ? name : ("" + (name) + ", " + (ivar)); - return "" + (sourcePart) + "for (" + (forPart) + ") {" + (guardPart) + "\n" + (varPart) + (body) + "\n" + (this.tab) + "}" + (returnResult); + vars = range ? name : ("" + name + ", " + ivar); + return "" + sourcePart + "for (" + forPart + ") {" + guardPart + "\n" + varPart + body + "\n" + this.tab + "}" + returnResult; }; return ForNode; })(); @@ -1720,7 +1720,7 @@ var _i, _j, _len, _len2, _ref2, _ref3, block, code, condition, conditions, exprs, idt, pair; idt = (o.indent = this.idt(2)); o.top = true; - code = ("" + (this.tab) + "switch (" + (this.subject.compile(o)) + ") {"); + code = ("" + this.tab + "switch (" + (this.subject.compile(o)) + ") {"); _ref2 = this.cases; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { pair = _ref2[_i]; @@ -1736,13 +1736,13 @@ } code += ("\n" + (block.compile(o))); if (!(last(exprs) instanceof ReturnNode)) { - code += ("\n" + (idt) + "break;"); + code += ("\n" + idt + "break;"); } } if (this.otherwise) { code += ("\n" + (this.idt(1)) + "default:\n" + (this.otherwise.compile(o))); } - code += ("\n" + (this.tab) + "}"); + code += ("\n" + this.tab + "}"); return code; }; return SwitchNode; @@ -1828,15 +1828,15 @@ ifDent = child || (top && !this.isStatement(o)) ? '' : this.idt(); comDent = child ? this.idt() : ''; body = this.body.compile(o); - ifPart = ("" + (ifDent) + "if (" + (this.compileCondition(condO)) + ") {\n" + (body) + "\n" + (this.tab) + "}"); + ifPart = ("" + ifDent + "if (" + (this.compileCondition(condO)) + ") {\n" + body + "\n" + this.tab + "}"); if (!(this.elseBody)) { return ifPart; } elsePart = this.isChain ? ' else ' + this.elseBodyNode().compile(merge(o, { indent: this.idt(), chainChild: true - })) : (" else {\n" + (this.elseBody.compile(o)) + "\n" + (this.tab) + "}"); - return "" + (ifPart) + (elsePart); + })) : (" else {\n" + (this.elseBody.compile(o)) + "\n" + this.tab + "}"); + return "" + ifPart + elsePart; }; IfNode.prototype.compileTernary = function(o) { var code, elsePart, ifPart; @@ -1846,8 +1846,8 @@ } ifPart = this.condition.compile(o) + ' ? ' + this.bodyNode().compile(o); elsePart = this.elseBody ? this.elseBodyNode().compile(o) : 'undefined'; - code = ("" + (ifPart) + " : " + (elsePart)); - return this.tags.operation ? ("(" + (code) + ")") : code; + code = ("" + ifPart + " : " + elsePart); + return this.tags.operation ? ("(" + code + ")") : code; }; return IfNode; })(); @@ -1904,7 +1904,7 @@ }; utility = function(name) { var ref; - ref = ("__" + (name)); + ref = ("__" + name); Scope.root.assign(ref, UTILITIES[name]); return ref; }; diff --git a/lib/optparse.js b/lib/optparse.js index 2839c242..3188b2cc 100755 --- a/lib/optparse.js +++ b/lib/optparse.js @@ -27,7 +27,7 @@ } } if (isOption && !matchedRule) { - throw new Error("unrecognized option: " + (arg)); + throw new Error("unrecognized option: " + arg); } if (!isOption) { options.arguments = args.slice(i, args.length); @@ -40,7 +40,7 @@ var _i, _len, _ref, letPart, lines, rule, spaces; lines = ['Available options:']; if (this.banner) { - lines.unshift("" + (this.banner) + "\n"); + lines.unshift("" + this.banner + "\n"); } _ref = this.rules; for (_i = 0, _len = _ref.length; _i < _len; _i++) { diff --git a/lib/scope.js b/lib/scope.js index 82b1eb1c..3d23e407 100644 --- a/lib/scope.js +++ b/lib/scope.js @@ -116,7 +116,7 @@ if (!__hasProp.call(_ref2, key)) continue; val = _ref2[key]; if (val.assigned) { - _result.push("" + (key) + " = " + (val.value)); + _result.push("" + key + " = " + (val.value)); } } return _result; diff --git a/src/lexer.coffee b/src/lexer.coffee index d03b6287..cbefc874 100644 --- a/src/lexer.coffee +++ b/src/lexer.coffee @@ -171,26 +171,14 @@ exports.Lexer = class Lexer # Matches regular expression literals. Lexing regular expressions is difficult # to distinguish from division, so we borrow some basic heuristics from - # JavaScript and Ruby, borrow slash balancing from `@balancedString`, and - # borrow interpolation from `@interpolateString`. + # JavaScript and Ruby. regexToken: -> return false if @chunk.charAt(0) isnt '/' return @heregexToken match if match = HEREGEX.exec @chunk - return false unless first = REGEX_START.exec @chunk - return false if first[1] is ' ' and @tag() not in ['CALL_START', '='] return false if include NOT_REGEX, @tag() - return false unless regex = @balancedString @chunk, [['/', '/']] - return false unless end = @chunk[regex.length..].match REGEX_END - flags = end[0] - if ~regex.indexOf '#{' - str = regex.slice 1, -1 - @tokens.push ['IDENTIFIER', 'RegExp'], ['CALL_START', '('] - @interpolateString "\"#{str}\"", regex: yes - @tokens.push [',', ','], ['STRING', "\"#{flags}\""] if flags - @tokens.push ['CALL_END', ')'] - else - @token 'REGEX', regex + flags - @i += regex.length + flags.length + return false unless match = REGEX.exec @chunk + @token 'REGEX', match[0] + @i += match[0].length true # Matches experimental, multiline and extended regular expression literals. @@ -199,11 +187,21 @@ exports.Lexer = class Lexer @i += heregex.length unless ~body.indexOf '#{' re = body.replace(HEREGEX_OMIT, '').replace(/\//g, '\\/') - @token 'REGEX', "/#{ re or '(?:)' }/#{flags}" + @token 'REGEX', "/#{ re or '(?:)' }/#{flags}" return true @token 'IDENTIFIER', 'RegExp' @tokens.push ['CALL_START', '('] - @interpolateString "\"#{body}\"", regex: yes, heregex: yes + tokens = [] + for [tag, value] in @interpolateString('"' + body + '"', regex: yes) + if tag is 'TOKENS' + tokens.push value... + else + continue unless value = value.slice(1, -1).replace HEREGEX_OMIT, '' + tokens.push ['STRING', '"' + value.replace(/[\\\"]/g, '\\$&') + '"'] + tokens.push ['+', '+'] + tokens.pop() + @tokens.push ['STRING', '""'], ['+', '+'] unless tokens[0]?[0] is 'STRING' + @tokens.push tokens... @tokens.push [',', ','], ['STRING', '"' + flags + '"'] if flags @tokens.push ['CALL_END', ')'] true @@ -355,12 +353,12 @@ exports.Lexer = class Lexer while (match = HEREDOC_INDENT.exec doc) attempt = match[1] indent = attempt if indent is null or 0 < attempt.length < indent.length - doc = doc.replace /\n#{ indent }/g, '\n' if indent + doc = doc.replace /// \n #{indent} ///g, '\n' if indent return doc if herecomment {quote} = options doc = doc.replace /^\n/, '' doc = doc.replace /\\([\s\S])/g, (m, c) -> if c in ['\n', quote] then c else m - doc = doc.replace /#{quote}/g, '\\$&' + doc = doc.replace /// #{quote} ///g, '\\$&' doc = @escapeLines doc, yes if quote is "'" doc @@ -398,7 +396,6 @@ exports.Lexer = class Lexer # interpolations within strings, ad infinitum. balancedString: (str, delimited, options) -> options or= {} - slash = delimited[0][0] is '/' levels = [] i = 0 slen = str.length @@ -417,10 +414,9 @@ exports.Lexer = class Lexer levels.push(pair) i += open.length - 1 break - break if not levels.length or slash and str.charAt(i) is '\n' + break if not levels.length i += 1 if levels.length - return false if slash throw new Error "SyntaxError: Unterminated #{levels.pop()[0]} starting on line #{@line + 1}" if not i then false else str[0...i] @@ -446,37 +442,28 @@ exports.Lexer = class Lexer unless char is '#' and str.charAt(i+1) is '{' and (expr = @balancedString str[i+1..], [['{', '}']]) continue - if pi < i - tokens.push ['STRING', '"' + @escapeLines(str[pi...i], heredoc) + '"'] + tokens.push ['STRING', '"' + str[pi...i] + '"'] if pi < i inner = expr.slice(1, -1).replace(LEADING_SPACES, '').replace(TRAILING_SPACES, '') if inner.length inner = inner.replace /\\\"/g, '"' if heredoc - nested = lexer.tokenize "(#{inner})", line: @line + nested = lexer.tokenize "(#{inner}\n)", line: @line (tok[0] = ')') for tok in nested when tok[0] is 'CALL_END' nested.pop() + if nested.length < 5 then nested.pop(); nested.shift() tokens.push ['TOKENS', nested] - else - tokens.push ['STRING', '""'] i += expr.length pi = i + 1 - if i > pi < str.length - 1 - s = @escapeLines str.slice(pi, -1), heredoc - tokens.push ['STRING', '"' + s + '"'] - tokens.unshift ['STRING', '""'] unless tokens[0][0] is 'STRING' - interpolated = not regex and tokens.length > 1 + tokens.push ['STRING', '"' + str.slice pi] if i > pi < str.length - 1 + return tokens if regex + interpolated = tokens.length > 1 + tokens.unshift ['STRING', '""'] unless tokens[0]?[0] is 'STRING' @token '(', '(' if interpolated - {push} = tokens for [tag, value], i in tokens @token '+', '+' if i if tag is 'TOKENS' - push.apply @tokens, value - continue - if regex - value = value.slice 1, -1 - value = value.replace /[\\\"]/g, '\\$&' - value = value.replace HEREGEX_OMIT, '' if options.heregex - value = '"' + value + '"' - @token tag, value + @tokens.push value... + else + @token tag, @escapeLines value, heredoc @token ')', ')' if interpolated tokens @@ -558,10 +545,14 @@ SIMPLESTR = /^'[^\\']*(?:\\.[^\\']*)*'/ JSTOKEN = /^`[^\\`]*(?:\\.[^\\`]*)*`/ # Regex-matching-regexes. -REGEX_START = /^\/([^\/])/ -REGEX_END = /^[imgy]{0,4}(?![a-zA-Z])/ -REGEX_ESCAPE = /\\[^#]/g - +REGEX = /// ^ + / (?!\s) # disallow leading whitespace + (?: [^ [ / \n \\ ]+ # every other things + | \\. # anything escaped + | \[ ( [^\\\]]+ | \\. )* ] # character class + )+ + / [imgy]{0,4} (?![A-Za-z]) +/// HEREGEX = /^\/{3}([\s\S]+?)\/{3}([imgy]{0,4})(?![A-Za-z])/ HEREGEX_OMIT = /\s+(?:#.*)?/g diff --git a/test/test_regexp_interpolation.coffee b/test/test_regexp_interpolation.coffee deleted file mode 100644 index 95b921cb..00000000 --- a/test/test_regexp_interpolation.coffee +++ /dev/null @@ -1,20 +0,0 @@ -# Interpolate regular expressions. -name = 'Moe' - -ok not not '"Moe"'.match(/^"#{name}"$/i) -ok '"Moe!"'.match(/^"#{name}"$/i) is null - -ok not not 'Moe'.match(/^#{name}$/) -ok 'Moe!'.match(/^#{name}/) - -ok 'Moe!'.match(/#{"#{"#{"#{name}"}"}"}/imgy) - -ok '$a$b$c'.match(/\$A\$B\$C/i) - -a = 1 -b = 2 -c = 3 -ok '123'.match(/#{a}#{b}#{c}/i) - -[a, b, c] = [1, 2, /\d+/] -ok (/#{a}#{b}#{c}$/i).toString() is '/12/\\d+/$/i' diff --git a/test/test_regexps.coffee b/test/test_regexps.coffee index ff7c3ff3..759f75e7 100644 --- a/test/test_regexps.coffee +++ b/test/test_regexps.coffee @@ -12,7 +12,7 @@ g = 1 ok y / x/g is 2 -ok 'http://google.com'.match(/:\/\/goog/) +ok /:\/[/]goog/.test 'http://google.com' obj = { width: -> 10 @@ -20,11 +20,6 @@ obj = { } id = 2 -ok ' '.match(/ /)[0] is ' ' - -regexp = / / -ok ' '.match regexp - ok (obj.width()/id - obj.height()/id) is -5 eq /^I'm\s+Heregex?\/\/\//gim + '', /// @@ -32,8 +27,9 @@ eq /^I'm\s+Heregex?\/\/\//gim + '', /// ///gim + '' eq '\\\\#{}', /// #{ - "#{ '\\' }" + "#{ '\\' }" # normal comment } + # regex comment \#{} ///.source eq /// /// + '', '/(?:)/'