From 7be996c01064443297a844ef55097fcfc7183b2d Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Sun, 28 Apr 2013 00:56:44 +0200 Subject: [PATCH] code cleanup --- lib/coffee-script/coffee-script.js | 4 +- lib/coffee-script/command.js | 4 +- lib/coffee-script/lexer.js | 14 +++---- lib/coffee-script/nodes.js | 12 +++--- lib/coffee-script/optparse.js | 6 ++- src/browser.coffee | 2 +- src/coffee-script.coffee | 12 +++--- src/command.coffee | 16 +++---- src/grammar.coffee | 12 +++--- src/lexer.coffee | 30 ++++++------- src/nodes.coffee | 67 +++++++++++++++--------------- src/optparse.coffee | 4 +- src/repl.coffee | 6 +-- src/rewriter.coffee | 18 ++++---- 14 files changed, 106 insertions(+), 101 deletions(-) diff --git a/lib/coffee-script/coffee-script.js b/lib/coffee-script/coffee-script.js index 5a84b742..637755b6 100644 --- a/lib/coffee-script/coffee-script.js +++ b/lib/coffee-script/coffee-script.js @@ -28,11 +28,11 @@ if (options == null) { options = {}; } - merge = exports.helpers.merge; + merge = helpers.merge; if (options.sourceMap) { map = new SourceMap; } - fragments = (parser.parse(lexer.tokenize(code, options))).compileToFragments(options); + fragments = parser.parse(lexer.tokenize(code, options)).compileToFragments(options); currentLine = 0; if (options.header) { currentLine += 1; diff --git a/lib/coffee-script/command.js b/lib/coffee-script/command.js index 6be86d15..70c8ca11 100644 --- a/lib/coffee-script/command.js +++ b/lib/coffee-script/command.js @@ -439,7 +439,7 @@ }; timeLog = function(message) { - return console.log("" + ((new Date).toLocaleTimeString()) + " - " + message); + return console.log("" + (new Date().toLocaleTimeString()) + " - " + message); }; printTokens = function(tokens) { @@ -516,7 +516,7 @@ }; usage = function() { - return printLine((new optparse.OptionParser(SWITCHES, BANNER)).help()); + return printLine(new optparse.OptionParser(SWITCHES, BANNER).help()); }; version = function() { diff --git a/lib/coffee-script/lexer.js b/lib/coffee-script/lexer.js index 4d78ec2a..26428ede 100644 --- a/lib/coffee-script/lexer.js +++ b/lib/coffee-script/lexer.js @@ -1,11 +1,11 @@ // Generated by CoffeeScript 1.6.2 (function() { - var BOM, BOOL, CALLABLE, CODE, COFFEE_ALIASES, COFFEE_ALIAS_MAP, COFFEE_KEYWORDS, COMMENT, COMPARE, COMPOUND_ASSIGN, HEREDOC, HEREDOC_ILLEGAL, HEREDOC_INDENT, HEREGEX, HEREGEX_OMIT, IDENTIFIER, INDEXABLE, INVERSES, JSTOKEN, JS_FORBIDDEN, JS_KEYWORDS, LINE_BREAK, LINE_CONTINUER, LOGIC, Lexer, MATH, MULTILINER, MULTI_DENT, NOT_REGEX, NOT_SPACED_REGEX, NUMBER, OPERATOR, REGEX, RELATION, RESERVED, Rewriter, SHIFT, SIMPLESTR, STRICT_PROSCRIBED, TRAILING_SPACES, UNARY, WHITESPACE, compact, count, invertLiterate, key, last, locationDataToString, starts, throwSyntaxError, _ref, _ref1, + var BOM, BOOL, CALLABLE, CODE, COFFEE_ALIASES, COFFEE_ALIAS_MAP, COFFEE_KEYWORDS, COMMENT, COMPARE, COMPOUND_ASSIGN, HEREDOC, HEREDOC_ILLEGAL, HEREDOC_INDENT, HEREGEX, HEREGEX_OMIT, IDENTIFIER, INDEXABLE, INVERSES, JSTOKEN, JS_FORBIDDEN, JS_KEYWORDS, LINE_BREAK, LINE_CONTINUER, LOGIC, Lexer, MATH, MULTILINER, MULTI_DENT, NOT_REGEX, NOT_SPACED_REGEX, NUMBER, OPERATOR, REGEX, RELATION, RESERVED, Rewriter, SHIFT, SIMPLESTR, STRICT_PROSCRIBED, TRAILING_SPACES, UNARY, WHITESPACE, compact, count, invertLiterate, key, last, locationDataToString, repeat, starts, throwSyntaxError, _ref, _ref1, __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; }; _ref = require('./rewriter'), Rewriter = _ref.Rewriter, INVERSES = _ref.INVERSES; - _ref1 = require('./helpers'), count = _ref1.count, starts = _ref1.starts, compact = _ref1.compact, last = _ref1.last, invertLiterate = _ref1.invertLiterate, locationDataToString = _ref1.locationDataToString, throwSyntaxError = _ref1.throwSyntaxError; + _ref1 = require('./helpers'), count = _ref1.count, starts = _ref1.starts, compact = _ref1.compact, last = _ref1.last, repeat = _ref1.repeat, invertLiterate = _ref1.invertLiterate, locationDataToString = _ref1.locationDataToString, throwSyntaxError = _ref1.throwSyntaxError; exports.Lexer = Lexer = (function() { function Lexer() {} @@ -38,7 +38,7 @@ if (opts.rewrite === false) { return this.tokens; } - return (new Rewriter).rewrite(this.tokens); + return new Rewriter().rewrite(this.tokens); }; Lexer.prototype.clean = function(code) { @@ -155,10 +155,10 @@ } lexedLength = number.length; if (octalLiteral = /^0o([0-7]+)/.exec(number)) { - number = '0x' + (parseInt(octalLiteral[1], 8)).toString(16); + number = '0x' + parseInt(octalLiteral[1], 8).toString(16); } if (binaryLiteral = /^0b([01]+)/.exec(number)) { - number = '0x' + (parseInt(binaryLiteral[1], 2)).toString(16); + number = '0x' + parseInt(binaryLiteral[1], 2).toString(16); } this.token('NUMBER', number, 0, lexedLength); return lexedLength; @@ -228,7 +228,7 @@ if (here) { this.token('HERECOMMENT', this.sanitizeHeredoc(here, { herecomment: true, - indent: Array(this.indent + 1).join(' ') + indent: repeat(' ', this.indent) }), 0, comment.length); } return comment.length; @@ -710,7 +710,7 @@ column = this.chunkColumn; if (lineCount > 0) { lines = string.split('\n'); - column = (last(lines)).length; + column = last(lines).length; } else { column += string.length; } diff --git a/lib/coffee-script/nodes.js b/lib/coffee-script/nodes.js index 0d78ce88..6bd6e127 100644 --- a/lib/coffee-script/nodes.js +++ b/lib/coffee-script/nodes.js @@ -44,7 +44,7 @@ } CodeFragment.prototype.toString = function() { - return "" + this.code + [this.locationData ? ": " + locationDataToString(this.locationData) : void 0]; + return "" + this.code + (this.locationData ? ": " + locationDataToString(this.locationData) : ''); }; return CodeFragment; @@ -866,7 +866,7 @@ accesses.push(new Access(new Literal('constructor'))); } accesses.push(new Access(new Literal(method.name))); - return (new Value(new Literal(method.klass), accesses)).compile(o); + return new Value(new Literal(method.klass), accesses).compile(o); } else if (method != null ? method.ctor : void 0) { return "" + method.name + ".__super__.constructor"; } else { @@ -1310,7 +1310,7 @@ } answer.push.apply(answer, fragments); } - if ((fragmentsToText(answer)).indexOf('\n') >= 0) { + if (fragmentsToText(answer).indexOf('\n') >= 0) { answer.unshift(this.makeCode("[\n" + o.indent)); answer.push(this.makeCode("\n" + this.tab + "]")); } else { @@ -1382,7 +1382,7 @@ _ref4 = this.boundFuncs; for (_i = 0, _len = _ref4.length; _i < _len; _i++) { bvar = _ref4[_i]; - lhs = (new Value(new Literal("this"), [new Access(bvar)])).compile(o); + lhs = new Value(new Literal("this"), [new Access(bvar)]).compile(o); this.ctor.body.unshift(new Literal("" + lhs + " = " + (utility('bind')) + "(" + lhs + ", this)")); } }; @@ -2412,7 +2412,7 @@ var fragments, ref, sub, _ref4; _ref4 = this.object.cache(o, LEVEL_LIST), sub = _ref4[0], ref = _ref4[1]; fragments = [].concat(this.makeCode(utility('indexOf') + ".call("), this.array.compileToFragments(o, LEVEL_LIST), this.makeCode(", "), ref, this.makeCode(") " + (this.negated ? '< 0' : '>= 0'))); - if ((fragmentsToText(sub)) === (fragmentsToText(ref))) { + if (fragmentsToText(sub) === fragmentsToText(ref)) { return fragments; } fragments = sub.concat(this.makeCode(', '), fragments); @@ -2673,7 +2673,7 @@ } if (this.guard) { if (body.expressions.length > 1) { - body.expressions.unshift(new If((new Parens(this.guard)).invert(), new Literal("continue"))); + body.expressions.unshift(new If(new Parens(this.guard).invert(), new Literal("continue"))); } else { if (this.guard) { body = Block.wrap([new If(this.guard, body)]); diff --git a/lib/coffee-script/optparse.js b/lib/coffee-script/optparse.js index 09a77934..4c5c7f0c 100644 --- a/lib/coffee-script/optparse.js +++ b/lib/coffee-script/optparse.js @@ -1,6 +1,8 @@ // Generated by CoffeeScript 1.6.2 (function() { - var LONG_FLAG, MULTI_FLAG, OPTIONAL, OptionParser, SHORT_FLAG, buildRule, buildRules, normalizeArguments; + var LONG_FLAG, MULTI_FLAG, OPTIONAL, OptionParser, SHORT_FLAG, buildRule, buildRules, normalizeArguments, repeat; + + repeat = require('./helpers').repeat; exports.OptionParser = OptionParser = (function() { function OptionParser(rules, banner) { @@ -66,7 +68,7 @@ for (_i = 0, _len = _ref.length; _i < _len; _i++) { rule = _ref[_i]; spaces = 15 - rule.longFlag.length; - spaces = spaces > 0 ? Array(spaces + 1).join(' ') : ''; + spaces = spaces > 0 ? repeat(' ', spaces) : ''; letPart = rule.shortFlag ? rule.shortFlag + ', ' : ' '; lines.push(' ' + letPart + rule.longFlag + spaces + rule.description); } diff --git a/src/browser.coffee b/src/browser.coffee index 2b3d8877..e89749e5 100644 --- a/src/browser.coffee +++ b/src/browser.coffee @@ -35,7 +35,7 @@ if btoa? and JSON? and unescape? and encodeURIComponent? CoffeeScript.load = (url, callback, options = {}) -> options.sourceFiles = [url] xhr = if window.ActiveXObject - new window.ActiveXObject('Microsoft.XMLHTTP') + new window.ActiveXObject 'Microsoft.XMLHTTP' else new window.XMLHttpRequest() xhr.open 'GET', url, true diff --git a/src/coffee-script.coffee b/src/coffee-script.coffee index fa29fd47..172fba80 100644 --- a/src/coffee-script.coffee +++ b/src/coffee-script.coffee @@ -28,12 +28,12 @@ exports.helpers = helpers # object, where sourceMap is a sourcemap.coffee#SourceMap object, handy for doing programatic # lookups. exports.compile = compile = (code, options = {}) -> - {merge} = exports.helpers + {merge} = helpers if options.sourceMap map = new SourceMap - fragments = (parser.parse lexer.tokenize(code, options)).compileToFragments options + fragments = parser.parse(lexer.tokenize code, options).compileToFragments options currentLine = 0 currentLine += 1 if options.header @@ -45,9 +45,9 @@ exports.compile = compile = (code, options = {}) -> if options.sourceMap if fragment.locationData map.add( - [fragment.locationData.first_line, fragment.locationData.first_column], - [currentLine, currentColumn], - {noReplace: true}) + [fragment.locationData.first_line, fragment.locationData.first_column] + [currentLine, currentColumn] + noReplace: true) newLines = helpers.count fragment.code, "\n" currentLine += newLines currentColumn = fragment.code.length - (if newLines then fragment.code.lastIndexOf "\n" else 0) @@ -87,7 +87,7 @@ exports.run = (code, options = {}) -> options.sourceMap ?= true # Set the filename. mainModule.filename = process.argv[1] = - if options.filename then fs.realpathSync(options.filename) else '.' + if options.filename then fs.realpathSync(options.filename) else '.' # Clear the module cache. mainModule.moduleCache and= {} diff --git a/src/command.coffee b/src/command.coffee index 37d54238..2aece925 100644 --- a/src/command.coffee +++ b/src/command.coffee @@ -68,7 +68,7 @@ exports.run = -> return usage() if opts.help return version() if opts.version return require('./repl').start() if opts.interactive - if opts.watch and !fs.watch + if opts.watch and not fs.watch return printWarn "The --watch feature depends on Node v0.6.0+. You are running #{process.version}." return compileStdio() if opts.stdio return compileScript null, sources[0] if opts.eval @@ -104,7 +104,7 @@ compilePath = (source, topLevel, base) -> fs.readFile source, (err, code) -> throw err if err and err.code isnt 'ENOENT' return if err?.code is 'ENOENT' - compileScript(source, code.toString(), base) + compileScript source, code.toString(), base else notSources[source] = yes removeSource source, base @@ -124,7 +124,7 @@ compileScript = (file, input, base=null) -> else if o.run then CoffeeScript.run t.input, t.options else if o.join and t.file isnt o.join t.input = helpers.invertLiterate t.input if helpers.isLiterate file - sourceCode[sources.indexOf(t.file)] = t.input + sourceCode[sources.indexOf t.file] = t.input compileJoin() else compiled = CoffeeScript.compile t.input, t.options @@ -136,7 +136,7 @@ compileScript = (file, input, base=null) -> CoffeeScript.emit 'success', task if o.print printLine t.output.trim() - else if o.compile || o.map + else if o.compile or o.map writeJs base, t.file, t.output, options.jsPath, t.sourceMap catch err CoffeeScript.emit 'failure', err, task @@ -198,7 +198,7 @@ watch = (source, base) -> prevStats = stats fs.readFile source, (err, code) -> return watchErr err if err - compileScript(source, code.toString(), base) + compileScript source, code.toString(), base rewatch() try @@ -291,7 +291,7 @@ wait = (milliseconds, func) -> setTimeout func, milliseconds # When watching scripts, it's useful to log changes with the timestamp. timeLog = (message) -> - console.log "#{(new Date).toLocaleTimeString()} - #{message}" + console.log "#{new Date().toLocaleTimeString()} - #{message}" # Pretty-print a stream of tokens, sans location data. printTokens = (tokens) -> @@ -299,7 +299,7 @@ printTokens = (tokens) -> tag = token[0] value = token[1].toString().replace(/\n/, '\\n') "[#{tag} #{value}]" - printLine strings.join(' ') + printLine strings.join ' ' # Use the [OptionParser module](optparse.html) to extract all options from # `process.argv` that are specified in `SWITCHES`. @@ -354,7 +354,7 @@ forkNode = -> # Print the `--help` usage message and exit. Deprecated switches are not # shown. usage = -> - printLine (new optparse.OptionParser SWITCHES, BANNER).help() + printLine new optparse.OptionParser(SWITCHES, BANNER).help() # Print the `--version` message and exit. version = -> diff --git a/src/grammar.coffee b/src/grammar.coffee index a6af1e34..d9a2a93e 100644 --- a/src/grammar.coffee +++ b/src/grammar.coffee @@ -49,8 +49,8 @@ o = (patternString, action, options) -> else "yy.addLocationDataFn(@#{first}, @#{last})" - action = action.replace /LOC\(([0-9]*)\)/g, addLocationDataFn('$1') - action = action.replace /LOC\(([0-9]*),\s*([0-9]*)\)/g, addLocationDataFn('$1', '$2') + action = action.replace /LOC\(([0-9]*)\)/g, addLocationDataFn '$1' + action = action.replace /LOC\(([0-9]*),\s*([0-9]*)\)/g, addLocationDataFn '$1', '$2' [patternString, "$$ = #{addLocationDataFn(1, patternCount)}(#{action});", options] @@ -159,9 +159,9 @@ grammar = # the ordinary **Assign** is that these allow numbers and strings as keys. AssignObj: [ o 'ObjAssignable', -> new Value $1 - o 'ObjAssignable : Expression', -> new Assign LOC(1)(new Value($1)), $3, 'object' + o 'ObjAssignable : Expression', -> new Assign LOC(1)(new Value $1), $3, 'object' o 'ObjAssignable : - INDENT Expression OUTDENT', -> new Assign LOC(1)(new Value($1)), $4, 'object' + INDENT Expression OUTDENT', -> new Assign LOC(1)(new Value $1), $4, 'object' o 'Comment' ] @@ -336,7 +336,7 @@ grammar = # A reference to a property on *this*. ThisProperty: [ - o '@ Identifier', -> new Value LOC(1)(new Literal('this')), [LOC(2)(new Access($2))], 'this' + o '@ Identifier', -> new Value LOC(1)(new Literal 'this'), [LOC(2)(new Access $2)], 'this' ] # The array literal. @@ -400,7 +400,7 @@ grammar = # A catch clause names its error and runs a block of code. Catch: [ o 'CATCH Identifier Block', -> [$2, $3] - o 'CATCH Object Block', -> [LOC(2)(new Value($2)), $3] + o 'CATCH Object Block', -> [LOC(2)(new Value $2), $3] o 'CATCH Block', -> [null, $2] ] diff --git a/src/lexer.coffee b/src/lexer.coffee index 79b4d23e..08fdd868 100644 --- a/src/lexer.coffee +++ b/src/lexer.coffee @@ -12,8 +12,8 @@ {Rewriter, INVERSES} = require './rewriter' # Import the helpers we need. -{count, starts, compact, last, invertLiterate, locationDataToString, -throwSyntaxError} = require './helpers' +{count, starts, compact, last, repeat, invertLiterate, +locationDataToString, throwSyntaxError} = require './helpers' # The Lexer Class # --------------- @@ -74,13 +74,13 @@ exports.Lexer = class Lexer @closeIndentation() @error "missing #{tag}" if tag = @ends.pop() return @tokens if opts.rewrite is off - (new Rewriter).rewrite @tokens + new Rewriter().rewrite @tokens # Preprocess the code to remove leading and trailing whitespace, carriage # returns, etc. If we're lexing literate CoffeeScript, strip external Markdown # by removing all lines that aren't indented by at least four spaces or a tab. clean: (code) -> - code = code.slice(1) if code.charCodeAt(0) is BOM + code = code.slice 1 if code.charCodeAt(0) is BOM code = code.replace(/\r/g, '').replace TRAILING_SPACES, '' if WHITESPACE.test code code = "\n#{code}" @@ -176,9 +176,9 @@ exports.Lexer = class Lexer @error "octal literal '#{number}' must be prefixed with '0o'" lexedLength = number.length if octalLiteral = /^0o([0-7]+)/.exec number - number = '0x' + (parseInt octalLiteral[1], 8).toString 16 + number = '0x' + parseInt(octalLiteral[1], 8).toString 16 if binaryLiteral = /^0b([01]+)/.exec number - number = '0x' + (parseInt binaryLiteral[1], 2).toString 16 + number = '0x' + parseInt(binaryLiteral[1], 2).toString 16 @token 'NUMBER', number, 0, lexedLength lexedLength @@ -221,8 +221,8 @@ exports.Lexer = class Lexer [comment, here] = match if here @token 'HERECOMMENT', - (@sanitizeHeredoc here, - herecomment: true, indent: Array(@indent + 1).join(' ')), + @sanitizeHeredoc(here, + herecomment: true, indent: repeat ' ', @indent), 0, comment.length comment.length @@ -254,7 +254,7 @@ exports.Lexer = class Lexer heregexToken: (match) -> [heregex, body, flags] = match if 0 > body.indexOf '#{' - re = body.replace(HEREGEX_OMIT, '').replace(/\//g, '\\/') + re = body.replace(HEREGEX_OMIT, '').replace /\//g, '\\/' if re.match /^\*/ then @error 'regular expressions cannot begin with `*`' @token 'REGEX', "/#{ re or '(?:)' }/#{flags}", 0, heregex.length return heregex.length @@ -270,7 +270,7 @@ exports.Lexer = class Lexer # Convert NEOSTRING into STRING value = value.replace /\\/g, '\\\\' token[0] = 'STRING' - token[1] = @makeString(value, '"', yes) + token[1] = @makeString value, '"', yes tokens.push token else @error "Unexpected #{tag}" @@ -542,7 +542,7 @@ exports.Lexer = class Lexer tokens.push @makeToken('NEOSTRING', str[pi...i], strOffset + pi) if pi < i inner = expr[1...-1] if inner.length - [line, column] = @getLineAndColumnFromChunk(strOffset + i + 1) + [line, column] = @getLineAndColumnFromChunk strOffset + i + 1 nested = new Lexer().tokenize inner, line: line, column: column, rewrite: off popped = nested.pop() popped = nested.shift() if nested[0]?[0] is 'TERMINATOR' @@ -630,7 +630,7 @@ exports.Lexer = class Lexer column = @chunkColumn if lineCount > 0 lines = string.split '\n' - column = (last lines).length + column = last(lines).length else column += string.length @@ -647,7 +647,7 @@ exports.Lexer = class Lexer # so if last_column == first_column, then we're looking at a character of length 1. lastCharacter = Math.max 0, length - 1 [locationData.last_line, locationData.last_column] = - @getLineAndColumnFromChunk offsetInChunk + (lastCharacter) + @getLineAndColumnFromChunk offsetInChunk + lastCharacter token = [tag, value, locationData] @@ -739,9 +739,9 @@ STRICT_PROSCRIBED = ['arguments', 'eval'] # The superset of both JavaScript keywords and reserved words, none of which may # be used as identifiers or properties. -JS_FORBIDDEN = JS_KEYWORDS.concat(RESERVED).concat(STRICT_PROSCRIBED) +JS_FORBIDDEN = JS_KEYWORDS.concat(RESERVED).concat STRICT_PROSCRIBED -exports.RESERVED = RESERVED.concat(JS_KEYWORDS).concat(COFFEE_KEYWORDS).concat(STRICT_PROSCRIBED) +exports.RESERVED = RESERVED.concat(JS_KEYWORDS).concat(COFFEE_KEYWORDS).concat STRICT_PROSCRIBED exports.STRICT_PROSCRIBED = STRICT_PROSCRIBED # The character code of the nasty Microsoft madness otherwise known as the BOM. diff --git a/src/nodes.coffee b/src/nodes.coffee index f6e2919d..562ed4f1 100644 --- a/src/nodes.coffee +++ b/src/nodes.coffee @@ -34,12 +34,12 @@ exports.CodeFragment = class CodeFragment @locationData = parent?.locationData @type = parent?.constructor?.name or 'unknown' - toString: () -> - "#{@code}#{[if @locationData then ": " + locationDataToString(@locationData)]}" + toString: -> + "#{@code}#{if @locationData then ": " + locationDataToString @locationData else ''}" # Convert an array of CodeFragments into a string. fragmentsToText = (fragments) -> - (fragment.code for fragment in fragments).join('') + (fragment.code for fragment in fragments).join '' #### Base @@ -147,7 +147,7 @@ exports.Base = class Base traverseChildren: (crossScope, func) -> @eachChild (child) -> recur = func(child) - child.traverseChildren(crossScope, func) unless recur is no + child.traverseChildren crossScope, func unless recur is no invert: -> new Op '!', this @@ -288,11 +288,11 @@ exports.Block = class Block extends Base compiledNodes.push node.compileToFragments o, LEVEL_LIST if top if @spaced - return [].concat @joinFragmentArrays(compiledNodes, '\n\n'), @makeCode("\n") + return [].concat @joinFragmentArrays(compiledNodes, '\n\n'), @makeCode "\n" else - return @joinFragmentArrays(compiledNodes, '\n') + return @joinFragmentArrays compiledNodes, '\n' if compiledNodes.length - answer = @joinFragmentArrays(compiledNodes, ', ') + answer = @joinFragmentArrays compiledNodes, ', ' else answer = [@makeCode "void 0"] if compiledNodes.length > 1 and o.level >= LEVEL_LIST then @wrapInBraces answer else answer @@ -336,7 +336,7 @@ exports.Block = class Block extends Base if i rest = @expressions.splice i, 9e9 [spaced, @spaced] = [@spaced, no] - [fragments, @spaced] = [(@compileNode o), spaced] + [fragments, @spaced] = [@compileNode(o), spaced] @expressions = rest post = @compileNode o {scope} = o @@ -350,7 +350,7 @@ exports.Block = class Block extends Base fragments.push @makeCode(scope.declaredVariables().join ', ') if assigns fragments.push @makeCode ",\n#{@tab + TAB}" if declars - fragments.push @makeCode (scope.assignedVariables().join ",\n#{@tab + TAB}") + fragments.push @makeCode scope.assignedVariables().join ",\n#{@tab + TAB}" fragments.push @makeCode ";\n#{if @spaced then '\n' else ''}" else if fragments.length and post.length fragments.push @makeCode "\n" @@ -439,9 +439,9 @@ exports.Return = class Return extends Base compileNode: (o) -> answer = [] # TODO: If we call expression.compile() here twice, we'll sometimes get back different results! - answer.push @makeCode(@tab + "return#{[" " if @expression]}") + answer.push @makeCode @tab + "return#{[" " if @expression]}" if @expression - answer = answer.concat @expression.compileToFragments(o, LEVEL_PAREN) + answer = answer.concat @expression.compileToFragments o, LEVEL_PAREN answer.push @makeCode ";" return answer @@ -585,10 +585,10 @@ exports.Call = class Call extends Base superReference: (o) -> method = o.scope.namedMethod() if method?.klass - accesses = [new Access(new Literal '__super__')] + accesses = [new Access new Literal '__super__'] accesses.push new Access new Literal 'constructor' if method.static accesses.push new Access new Literal method.name - (new Value (new Literal method.klass), accesses).compile o + new Value(new Literal(method.klass), accesses).compile o else if method?.ctor "#{method.name}.__super__.constructor" else @@ -649,7 +649,7 @@ exports.Call = class Call extends Base fragments.push @makeCode preface else if @isNew then fragments.push @makeCode 'new ' - fragments.push (@variable.compileToFragments(o, LEVEL_ACCESS))... + fragments.push (@variable.compileToFragments o, LEVEL_ACCESS)... fragments.push @makeCode "(" fragments.push compiledArgs... fragments.push @makeCode ")" @@ -741,7 +741,7 @@ exports.Index = class Index extends Base children: ['index'] compileToFragments: (o) -> - [].concat @makeCode("["), (@index.compileToFragments o, LEVEL_PAREN), @makeCode("]") + [].concat @makeCode("["), @index.compileToFragments(o, LEVEL_PAREN), @makeCode("]") isComplex: -> @index.isComplex() @@ -883,7 +883,7 @@ exports.Obj = class Obj extends Base compileNode: (o) -> props = @properties - return [@makeCode(if @front then '({})' else '{}')] unless props.length + return [@makeCode if @front then '({})' else '{}'] unless props.length if @generated for node in props when node instanceof Value node.error 'cannot have an implicit value in an implicit object' @@ -907,7 +907,7 @@ exports.Obj = class Obj extends Base prop = new Assign prop, prop, 'object' (prop.variable.base or prop.variable).asKey = yes if indent then answer.push @makeCode indent - answer.push prop.compileToFragments(o, LEVEL_TOP)... + answer.push (prop.compileToFragments o, LEVEL_TOP)... if join then answer.push @makeCode join answer.unshift @makeCode "{#{ props.length and '\n' }" answer.push @makeCode "#{ props.length and '\n' + @tab }}" @@ -938,7 +938,7 @@ exports.Arr = class Arr extends Base if index answer.push @makeCode ", " answer.push fragments... - if (fragmentsToText answer).indexOf('\n') >= 0 + if fragmentsToText(answer).indexOf('\n') >= 0 answer.unshift @makeCode "[\n#{o.indent}" answer.push @makeCode "\n#{@tab}]" else @@ -988,7 +988,7 @@ exports.Class = class Class extends Base # constructor. addBoundFunctions: (o) -> for bvar in @boundFuncs - lhs = (new Value (new Literal "this"), [new Access bvar]).compile o + lhs = new Value(new Literal("this"), [new Access bvar]).compile o @ctor.body.unshift new Literal "#{lhs} = #{utility 'bind'}(#{lhs}, this)" return @@ -1017,7 +1017,7 @@ exports.Class = class Class extends Base if func.bound func.context = name else - assign.variable = new Value(new Literal(name), [(new Access new Literal 'prototype'), new Access base ]) + assign.variable = new Value(new Literal(name), [new Access(new Literal 'prototype'), new Access base]) if func instanceof Code and func.bound @boundFuncs.push base func.bound = no @@ -1239,7 +1239,7 @@ exports.Assign = class Assign extends Base left.base.value != "this" and not o.scope.check left.base.value @variable.error "the variable \"#{left.base.value}\" can't be assigned with #{@context} because it has not been declared before" if "?" in @context then o.isExistentialEquals = true - new Op(@context[...-1], left, new Assign(right, @value, '=') ).compileToFragments o + new Op(@context[...-1], left, new Assign right, @value, '=').compileToFragments o # Compile the assignment from an array splice literal, using JavaScript's # `Array#splice` method. @@ -1560,7 +1560,7 @@ exports.Op = class Op extends Base not @second isComplex: -> - not (@isUnary() and (@operator in ['+', '-'])) or @first.isComplex() + not (@isUnary() and @operator in ['+', '-']) or @first.isComplex() # Am I capable of # [Python-style comparison chaining](http://docs.python.org/reference/expressions.html#notin)? @@ -1662,9 +1662,9 @@ exports.Op = class Op extends Base if o.level >= LEVEL_ACCESS return (new Parens this).compileToFragments o plusMinus = op in ['+', '-'] - parts.push [@makeCode(' ')] if op in ['new', 'typeof', 'delete'] or + parts.push [@makeCode ' '] if op in ['new', 'typeof', 'delete'] or plusMinus and @first instanceof Op and @first.operator is op - if (plusMinus && @first instanceof Op) or (op is 'new' and @first.isStatement o) + if (plusMinus and @first instanceof Op) or (op is 'new' and @first.isStatement o) @first = new Parens @first parts.push @first.compileToFragments o, LEVEL_OP parts.reverse() if @flip @@ -1704,7 +1704,7 @@ exports.In = class In extends Base [sub, ref] = @object.cache o, LEVEL_LIST fragments = [].concat @makeCode(utility('indexOf') + ".call("), @array.compileToFragments(o, LEVEL_LIST), @makeCode(", "), ref, @makeCode(") " + if @negated then '< 0' else '>= 0') - return fragments if (fragmentsToText sub) is (fragmentsToText ref) + return fragments if fragmentsToText(sub) is fragmentsToText(ref) fragments = sub.concat @makeCode(', '), fragments if o.level < LEVEL_LIST then fragments else @wrapInBraces fragments @@ -1744,7 +1744,8 @@ exports.Try = class Try extends Base else [] - ensurePart = if @ensure then ([].concat @makeCode(" finally {\n"), (@ensure.compileToFragments o, LEVEL_TOP), @makeCode("\n#{@tab}}")) else [] + ensurePart = if @ensure then ([].concat @makeCode(" finally {\n"), @ensure.compileToFragments(o, LEVEL_TOP), + @makeCode("\n#{@tab}}")) else [] [].concat @makeCode("#{@tab}try {\n"), tryPart, @@ -1765,7 +1766,7 @@ exports.Throw = class Throw extends Base makeReturn: THIS compileNode: (o) -> - [].concat @makeCode(@tab + "throw "), (@expression.compileToFragments o), @makeCode(";") + [].concat @makeCode(@tab + "throw "), @expression.compileToFragments(o), @makeCode(";") #### Existence @@ -1867,7 +1868,7 @@ exports.For = class For extends While defPart = '' idt1 = @tab + TAB if @range - forPartFragments = source.compileToFragments merge(o, {index: ivar, name, @step}) + forPartFragments = source.compileToFragments merge o, {index: ivar, name, @step} else svar = @source.compile o, LEVEL_LIST if (name or @own) and not IDENTIFIER.test svar @@ -1900,12 +1901,12 @@ exports.For = class For extends While body.makeReturn rvar if @guard if body.expressions.length > 1 - body.expressions.unshift new If (new Parens @guard).invert(), new Literal "continue" + body.expressions.unshift new If new Parens(@guard).invert(), new Literal "continue" else body = Block.wrap [new If @guard, body] if @guard if @pattern body.expressions.unshift new Assign @name, new Literal "#{svar}[#{kvar}]" - defPartFragments = [].concat @makeCode(defPart), @pluckDirectCall(o, body) + defPartFragments = [].concat @makeCode(defPart), @pluckDirectCall o, body varPart = "\n#{idt1}#{namePart};" if namePart if @object forPartFragments = [@makeCode("#{kvar} in #{svar}")] @@ -1934,7 +1935,7 @@ exports.For = class For extends While if val.base [val.base, base] = [base, val] body.expressions[idx] = new Call base, expr.args - defs = defs.concat @makeCode(@tab), (new Assign(ref, fn).compileToFragments(o, LEVEL_TOP)), @makeCode(';\n') + defs = defs.concat @makeCode(@tab), new Assign(ref, fn).compileToFragments(o, LEVEL_TOP), @makeCode(';\n') defs #### Switch @@ -1962,13 +1963,13 @@ exports.Switch = class Switch extends Base idt1 = o.indent + TAB idt2 = o.indent = idt1 + TAB fragments = [].concat @makeCode(@tab + "switch ("), - (if @subject then @subject.compileToFragments(o, LEVEL_PAREN) else @makeCode("false")), + (if @subject then @subject.compileToFragments o, LEVEL_PAREN else @makeCode "false"), @makeCode(") {\n") for [conditions, block], i in @cases for cond in flatten [conditions] cond = cond.invert() unless @subject fragments = fragments.concat @makeCode(idt1 + "case "), cond.compileToFragments(o, LEVEL_PAREN), @makeCode(":\n") - fragments = fragments.concat body, @makeCode('\n') if (body = block.compileToFragments o, LEVEL_TOP).length > 0 + fragments = fragments.concat body, @makeCode '\n' if (body = block.compileToFragments o, LEVEL_TOP).length > 0 break if i is @cases.length - 1 and not @otherwise expr = @lastNonComment block.expressions continue if expr instanceof Return or (expr instanceof Literal and expr.jumps() and expr.value isnt 'debugger') diff --git a/src/optparse.coffee b/src/optparse.coffee index 3bed118c..b89d20e0 100644 --- a/src/optparse.coffee +++ b/src/optparse.coffee @@ -1,3 +1,5 @@ +{repeat} = require './helpers' + # A simple **OptionParser** class to parse option flags from the command-line. # Use it like so: # @@ -62,7 +64,7 @@ exports.OptionParser = class OptionParser lines.unshift "#{@banner}\n" if @banner for rule in @rules spaces = 15 - rule.longFlag.length - spaces = if spaces > 0 then Array(spaces + 1).join(' ') else '' + spaces = if spaces > 0 then repeat ' ', spaces else '' letPart = if rule.shortFlag then rule.shortFlag + ', ' else ' ' lines.push ' ' + letPart + rule.longFlag + spaces + rule.description "\n#{ lines.join('\n') }\n" diff --git a/src/repl.coffee b/src/repl.coffee index ab9c2de7..941b7b6e 100644 --- a/src/repl.coffee +++ b/src/repl.coffee @@ -36,8 +36,8 @@ addMultilineHandler = (repl) -> multiline = enabled: off - initialPrompt: repl.prompt.replace(/^[^> ]*/, (x) -> x.replace /./g, '-') - prompt: repl.prompt.replace(/^[^> ]*>?/, (x) -> x.replace /./g, '.') + initialPrompt: repl.prompt.replace /^[^> ]*/, (x) -> x.replace /./g, '-' + prompt: repl.prompt.replace /^[^> ]*>?/, (x) -> x.replace /./g, '.' buffer: '' # Proxy node's line listener @@ -89,7 +89,7 @@ addHistory = (repl, filename, maxSize) -> size = Math.min maxSize, stat.size # Read last `size` bytes from the file readFd = fs.openSync filename, 'r' - buffer = new Buffer(size) + buffer = new Buffer size fs.readSync readFd, buffer, 0, size, stat.size - size # Set the history on the interpreter repl.rli.history = buffer.toString().split('\n').reverse() diff --git a/src/rewriter.coffee b/src/rewriter.coffee index 9231d959..a6aee08f 100644 --- a/src/rewriter.coffee +++ b/src/rewriter.coffee @@ -171,7 +171,7 @@ class exports.Rewriter startImplicitObject = (j, startsLine = yes) -> idx = j ? i stack.push ['{', idx, sameLine: yes, startsLine: startsLine, ours: yes] - tokens.splice idx, 0, generate '{', generate(new String('{')) + tokens.splice idx, 0, generate '{', generate new String '{' i += 1 if not j? endImplicitObject = (j) -> @@ -202,7 +202,7 @@ class exports.Rewriter # Straightforward start of explicit expression if tag in EXPRESSION_START stack.push [tag, i] - return forward(1) + return forward 1 # Close all implicit expressions inside of explicitly closed expressions. if tag in EXPRESSION_END @@ -256,7 +256,7 @@ class exports.Rewriter 'SWITCH', 'LEADING_WHEN', 'FOR', 'WHILE', 'UNTIL']) startImplicitCall i + 1 stack.push ['INDENT', i + 2] - return forward(3) + return forward 3 # Implicit objects start here if tag is ':' @@ -270,10 +270,10 @@ class exports.Rewriter [stackTag, stackIdx] = stackTop() if (stackTag is '{' or stackTag is 'INDENT' and @tag(stackIdx - 1) is '{') and (startsLine or @tag(s - 1) is ',' or @tag(s - 1) is '{') - return forward(1) + return forward 1 - startImplicitObject(s, !!startsLine) - return forward(2) + startImplicitObject s, !!startsLine + return forward 2 # End implicit calls when chaining method calls # like e.g.: @@ -333,7 +333,7 @@ class exports.Rewriter offset = if nextTag is 'OUTDENT' then 1 else 0 while inImplicitObject() endImplicitObject i + offset - return forward(1) + return forward 1 # Add location data to all tokens generated by the rewriter. addLocationDataToGeneratedTokens: -> @@ -351,7 +351,7 @@ class exports.Rewriter first_column: column last_line: line last_column: column - 1 + return 1 # Because our grammar is LALR(1), it can't handle some single-line # expressions that lack ending delimiters. The **Rewriter** adds the implicit @@ -409,7 +409,7 @@ class exports.Rewriter return 1 unless token[0] is 'IF' original = token @detectEnd i + 1, condition, action - 1 + return 1 # Generate the indentation tokens, based on another token on the same line. indentation: (implicit = no) ->