diff --git a/Cakefile b/Cakefile index e693a58b5a..53df9b74df 100644 --- a/Cakefile +++ b/Cakefile @@ -20,8 +20,8 @@ task 'install', 'install CoffeeScript into /usr/local (or --prefix)', (options) "cp -rf bin lib LICENSE README package.json src vendor $lib" "ln -sf $lib/bin/coffee $base/bin/coffee" "ln -sf $lib/bin/cake $base/bin/cake" - "mkdir -p ~/.node_libraries" - "ln -sf $lib/lib ~/.node_libraries/coffee-script" + "mkdir -p ~/.nodeLibraries" + "ln -sf $lib/lib ~/.nodeLibraries/coffee-script" ].join(' && '), (err, stdout, stderr) -> if err then print stderr ) @@ -44,8 +44,8 @@ task 'build:parser', 'rebuild the Jison parser (run build first)', -> require.paths.unshift 'vendor/jison/lib' parser: require('./lib/grammar').parser js: parser.generate() - parser_path: 'lib/parser.js' - fs.writeFile parser_path, js + parserPath: 'lib/parser.js' + fs.writeFile parserPath, js task 'build:ultraviolet', 'build and install the Ultraviolet syntax highlighter', -> @@ -80,20 +80,20 @@ task 'loc', 'count the lines of source code in CoffeeScript', -> task 'test', 'run the CoffeeScript language test suite', -> helpers.extend global, require 'assert' - passed_tests: failed_tests: 0 - start_time: new Date() - original_ok: ok + passedTests: failedTests: 0 + startTime: new Date() + originalOk: ok helpers.extend global, { - ok: (args...) -> passed_tests += 1; original_ok(args...) + ok: (args...) -> passedTests += 1; originalOk(args...) CoffeeScript: CoffeeScript } red: '\033[0;31m' green: '\033[0;32m' reset: '\033[0m' process.addListener 'exit', -> - time: ((new Date() - start_time) / 1000).toFixed(2) - message: "passed $passed_tests tests in $time seconds$reset" - puts(if failed_tests then "${red}failed $failed_tests and $message" else "$green$message") + time: ((new Date() - startTime) / 1000).toFixed(2) + message: "passed $passedTests tests in $time seconds$reset" + puts(if failedTests then "${red}failed $failedTests and $message" else "$green$message") fs.readdir 'test', (err, files) -> files.forEach (file) -> return unless file.match(/\.coffee$/i) @@ -102,6 +102,6 @@ task 'test', 'run the CoffeeScript language test suite', -> try CoffeeScript.run code.toString(), {source: source} catch err - failed_tests += 1 + failedTests += 1 puts "${red}failed:${reset} $source" puts err.stack diff --git a/documentation/coffee/aliases.coffee b/documentation/coffee/aliases.coffee index e4a4399c0d..b3a9398271 100644 --- a/documentation/coffee/aliases.coffee +++ b/documentation/coffee/aliases.coffee @@ -1,9 +1,9 @@ launch() if ignition is on -volume: 10 if band isnt spinal_tap +volume: 10 if band isnt spinalTap -let_the_wild_rumpus_begin() unless answer is no +letTheWildRumpusBegin() unless answer is no -if car.speed < speed_limit then accelerate() +if car.speed < speedLimit then accelerate() print "My name is " + @name diff --git a/documentation/coffee/cake_tasks.coffee b/documentation/coffee/cake_tasks.coffee index 40b4640a61..64ec99ded3 100644 --- a/documentation/coffee/cake_tasks.coffee +++ b/documentation/coffee/cake_tasks.coffee @@ -1,3 +1,3 @@ task 'test', 'run each of the unit tests', -> - for test in test_files + for test in testFiles fs.readFile test, (err, code) -> eval coffee.compile code diff --git a/documentation/coffee/conditionals.coffee b/documentation/coffee/conditionals.coffee index 0e59bdd9b1..e99dc10c10 100644 --- a/documentation/coffee/conditionals.coffee +++ b/documentation/coffee/conditionals.coffee @@ -1,9 +1,9 @@ -mood: greatly_improved if singing +mood: greatlyImproved if singing -if happy and knows_it - claps_hands() - cha_cha_cha() +if happy and knowsIt + clapsHands() + chaChaCha() date: if friday then sue else jill -expensive: or do_the_math() \ No newline at end of file +expensive: or doTheMath() \ No newline at end of file diff --git a/documentation/coffee/expressions.coffee b/documentation/coffee/expressions.coffee index 74a02466df..0e184fd26b 100644 --- a/documentation/coffee/expressions.coffee +++ b/documentation/coffee/expressions.coffee @@ -1,8 +1,8 @@ grade: (student) -> - if student.excellent_work + if student.excellentWork "A+" - else if student.okay_stuff - if student.tried_hard then "B" else "B-" + else if student.okayStuff + if student.triedHard then "B" else "B-" else "C" diff --git a/documentation/coffee/fat_arrow.coffee b/documentation/coffee/fat_arrow.coffee index 28bbf12ab7..093197c87b 100644 --- a/documentation/coffee/fat_arrow.coffee +++ b/documentation/coffee/fat_arrow.coffee @@ -2,5 +2,5 @@ Account: (customer, cart) -> @customer: customer @cart: cart - $('.shopping_cart').bind 'click', (event) => + $('.shoppingCart').bind 'click', (event) => @customer.purchase @cart \ No newline at end of file diff --git a/documentation/coffee/multiple_return_values.coffee b/documentation/coffee/multiple_return_values.coffee index 3fe572b1d9..b6153f777f 100644 --- a/documentation/coffee/multiple_return_values.coffee +++ b/documentation/coffee/multiple_return_values.coffee @@ -1,5 +1,5 @@ -weather_report: (location) -> +weatherReport: (location) -> # Make an Ajax request to fetch the weather... [location, 72, "Mostly Sunny"] -[city, temp, forecast]: weather_report "Berkeley, CA" \ No newline at end of file +[city, temp, forecast]: weatherReport "Berkeley, CA" \ No newline at end of file diff --git a/documentation/coffee/object_comprehensions.coffee b/documentation/coffee/object_comprehensions.coffee index bf582af8a8..7dd549d09a 100644 --- a/documentation/coffee/object_comprehensions.coffee +++ b/documentation/coffee/object_comprehensions.coffee @@ -1,4 +1,4 @@ -years_old: {max: 10, ida: 9, tim: 11} +yearsOld: {max: 10, ida: 9, tim: 11} -ages: for child, age of years_old +ages: for child, age of yearsOld child + " is " + age \ No newline at end of file diff --git a/documentation/coffee/overview.coffee b/documentation/coffee/overview.coffee index 23bdb4bd85..7369f509be 100644 --- a/documentation/coffee/overview.coffee +++ b/documentation/coffee/overview.coffee @@ -1,9 +1,9 @@ # Assignment: number: 42 -opposite_day: true +oppositeDay: true # Conditions: -number: -42 if opposite_day +number: -42 if oppositeDay # Functions: square: (x) -> x * x @@ -26,4 +26,4 @@ race: (winner, runners...) -> alert "I knew it!" if elvis? # Array comprehensions: -cubed_list: math.cube num for num in list +cubedList: math.cube num for num in list diff --git a/documentation/coffee/parallel_assignment.coffee b/documentation/coffee/parallel_assignment.coffee index ea005b3b25..dadb6e64bf 100644 --- a/documentation/coffee/parallel_assignment.coffee +++ b/documentation/coffee/parallel_assignment.coffee @@ -1,4 +1,4 @@ bait: 1000 -and_switch: 0 +andSwitch: 0 -[bait, and_switch]: [and_switch, bait] \ No newline at end of file +[bait, andSwitch]: [andSwitch, bait] \ No newline at end of file diff --git a/documentation/coffee/range_comprehensions.coffee b/documentation/coffee/range_comprehensions.coffee index 33790f5a29..5c6a4e2696 100644 --- a/documentation/coffee/range_comprehensions.coffee +++ b/documentation/coffee/range_comprehensions.coffee @@ -1,6 +1,6 @@ countdown: num for num in [10..1] -egg_delivery: -> +eggDelivery: -> for i in [0...eggs.length] by 12 - dozen_eggs: eggs[i...i+12] - deliver new egg_carton(dozen) + dozenEggs: eggs[i...i+12] + deliver new eggCarton(dozen) diff --git a/documentation/coffee/scope.coffee b/documentation/coffee/scope.coffee index 30eedacf8a..2be0495722 100644 --- a/documentation/coffee/scope.coffee +++ b/documentation/coffee/scope.coffee @@ -1,5 +1,5 @@ num: 1 -change_numbers: -> - new_num: -1 +changeNumbers: -> + newNum: -1 num: 10 -new_num: change_numbers() \ No newline at end of file +newNum: changeNumbers() \ No newline at end of file diff --git a/documentation/coffee/slices.coffee b/documentation/coffee/slices.coffee index 7136e9544a..aa30e16ed2 100644 --- a/documentation/coffee/slices.coffee +++ b/documentation/coffee/slices.coffee @@ -1,6 +1,6 @@ numbers: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] -three_to_six: numbers[3..6] +threeToSix: numbers[3..6] -numbers_copy: numbers[0...numbers.length] +numbersCopy: numbers[0...numbers.length] diff --git a/documentation/coffee/soaks.coffee b/documentation/coffee/soaks.coffee index 964fef5b72..c0256e10ca 100644 --- a/documentation/coffee/soaks.coffee +++ b/documentation/coffee/soaks.coffee @@ -1 +1 @@ -lottery.draw_winner()?.address?.zipcode +lottery.drawWinner()?.address?.zipcode diff --git a/documentation/coffee/splats.coffee b/documentation/coffee/splats.coffee index 9faf40155e..cbcb034ba3 100644 --- a/documentation/coffee/splats.coffee +++ b/documentation/coffee/splats.coffee @@ -1,9 +1,9 @@ -gold: silver: the_field: "unknown" +gold: silver: theField: "unknown" -award_medals: (first, second, rest...) -> +awardMedals: (first, second, rest...) -> gold: first silver: second - the_field: rest + theField: rest contenders: [ "Michael Phelps" @@ -18,8 +18,8 @@ contenders: [ "Usain Bolt" ] -award_medals contenders... +awardMedals contenders... alert "Gold: " + gold alert "Silver: " + silver -alert "The Field: " + the_field \ No newline at end of file +alert "The Field: " + theField \ No newline at end of file diff --git a/documentation/coffee/strings.coffee b/documentation/coffee/strings.coffee index 1ec91081b6..1ec06723ab 100644 --- a/documentation/coffee/strings.coffee +++ b/documentation/coffee/strings.coffee @@ -1,4 +1,4 @@ -moby_dick: "Call me Ishmael. Some years ago -- +mobyDick: "Call me Ishmael. Some years ago -- never mind how long precisely -- having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail diff --git a/documentation/coffee/switch.coffee b/documentation/coffee/switch.coffee index 3478883d30..27f7315d8b 100644 --- a/documentation/coffee/switch.coffee +++ b/documentation/coffee/switch.coffee @@ -1,10 +1,10 @@ switch day - when "Mon" then go_to_work() - when "Tue" then go_to_the_park() - when "Thu" then go_ice_fishing() + when "Mon" then goToWork() + when "Tue" then goToThePark() + when "Thu" then goIceFishing() when "Fri", "Sat" - if day is bingo_day - go_to_bingo() - go_dancing() - when "Sun" then go_to_church() - else go_to_work() \ No newline at end of file + if day is bingoDay + goToBingo() + goDancing() + when "Sun" then goToChurch() + else goToWork() \ No newline at end of file diff --git a/documentation/coffee/try.coffee b/documentation/coffee/try.coffee index 67f4d19763..d424495c48 100644 --- a/documentation/coffee/try.coffee +++ b/documentation/coffee/try.coffee @@ -1,7 +1,7 @@ try - all_hell_breaks_loose() - cats_and_dogs_living_together() + allHellBreaksLoose() + catsAndDogsLivingTogether() catch error print error finally - clean_up() \ No newline at end of file + cleanUp() \ No newline at end of file diff --git a/documentation/coffee/while.coffee b/documentation/coffee/while.coffee index 20d77fe8b8..1c7614c1ca 100644 --- a/documentation/coffee/while.coffee +++ b/documentation/coffee/while.coffee @@ -1,5 +1,5 @@ # Econ 101 -if this.studying_economics +if this.studyingEconomics buy() while supply > demand sell() until supply > demand diff --git a/lib/cake.js b/lib/cake.js index 16b300d7f0..a3087ee05c 100755 --- a/lib/cake.js +++ b/lib/cake.js @@ -1,5 +1,5 @@ (function(){ - var CoffeeScript, fs, helpers, no_such_task, oparse, options, optparse, path, print_tasks, switches, tasks; + var CoffeeScript, fs, helpers, missingTask, oparse, options, optparse, path, printTasks, switches, tasks; var __hasProp = Object.prototype.hasOwnProperty; // `cake` is a simplified version of [Make](http://www.gnu.org/software/make/) // ([Rake](http://rake.rubyforge.org/), [Jake](http://github.com/280north/jake)) @@ -45,7 +45,7 @@ // Invoke another task in the current Cakefile. invoke: function(name) { if (!(tasks[name])) { - no_such_task(name); + missingTask(name); } return tasks[name].action(options); } @@ -65,7 +65,7 @@ }); oparse = new optparse.OptionParser(switches); if (!(args.length)) { - return print_tasks(); + return printTasks(); } options = oparse.parse(args); _a = []; _c = options.arguments; @@ -77,7 +77,7 @@ }); }; // Display the list of Cake tasks in a format similar to `rake -T` - print_tasks = function() { + printTasks = function() { var _a, _b, desc, i, name, spaces, task; puts(''); _a = tasks; @@ -99,7 +99,7 @@ } }; // Print an error and exit when attempting to all an undefined task. - no_such_task = function(task) { + missingTask = function(task) { puts(("No such task: \"" + task + "\"")); return process.exit(1); }; diff --git a/lib/coffee-script.js b/lib/coffee-script.js index daf56c34e4..75ee68b99d 100644 --- a/lib/coffee-script.js +++ b/lib/coffee-script.js @@ -1,5 +1,5 @@ (function(){ - var Lexer, compile, helpers, lexer, parser, path, process_scripts; + var Lexer, compile, helpers, lexer, parser, path, processScripts; // CoffeeScript can be used both on the server, as a command-line compiler based // on Node.js/V8, or to run CoffeeScripts directly in the browser. This module // contains the main entry functions for tokenzing, parsing, and compiling source @@ -90,7 +90,7 @@ // on page load. Unfortunately, the text contents of remote scripts cannot be // accessed from the browser, so only inline script tags will work. if ((typeof document !== "undefined" && document !== null) && document.getElementsByTagName) { - process_scripts = function() { + processScripts = function() { var _a, _b, _c, _d, tag; _a = []; _c = document.getElementsByTagName('script'); for (_b = 0, _d = _c.length; _b < _d; _b++) { @@ -100,9 +100,9 @@ return _a; }; if (window.addEventListener) { - window.addEventListener('load', process_scripts, false); + window.addEventListener('load', processScripts, false); } else if (window.attachEvent) { - window.attachEvent('onload', process_scripts); + window.attachEvent('onload', processScripts); } } })(); diff --git a/lib/command.js b/lib/command.js index 7258957a99..2954302169 100644 --- a/lib/command.js +++ b/lib/command.js @@ -1,5 +1,5 @@ (function(){ - var BANNER, CoffeeScript, SWITCHES, _a, compile_options, compile_script, compile_scripts, compile_stdio, exec, fs, lint, option_parser, options, optparse, parse_options, path, print_tokens, sources, spawn, usage, version, watch, write_js; + var BANNER, CoffeeScript, SWITCHES, _a, compileOptions, compileScript, compileScripts, compileStdio, exec, fs, lint, optionParser, options, optparse, parseOptions, path, printTokens, sources, spawn, usage, version, watch, writeJs; // The `coffee` utility. Handles command-line compilation of CoffeeScript // into various forms: saved into `.js` files or printed to stdout, piped to // [JSLint](http://javascriptlint.com/) or recompiled every time the source is @@ -20,13 +20,13 @@ // Top-level objects shared by all the functions. options = {}; sources = []; - option_parser = null; + optionParser = null; // Run `coffee` by parsing passed options and determining what action to take. // Many flags cause us to divert before compiling anything. Flags passed after // `--` will be passed verbatim to your script as arguments in `process.argv` exports.run = function() { var flags, separator; - parse_options(); + parseOptions(); if (options.help) { return usage(); } @@ -37,10 +37,10 @@ return require('./repl'); } if (options.stdio) { - return compile_stdio(); + return compileStdio(); } if (options.eval) { - return compile_script('console', sources[0]); + return compileScript('console', sources[0]); } if (!(sources.length)) { return require('./repl'); @@ -52,19 +52,19 @@ sources = sources.slice(0, separator); } process.ARGV = (process.argv = flags); - return compile_scripts(); + return compileScripts(); }; // Asynchronously read in each CoffeeScript in a list of source files and // compile them. If a directory is passed, recursively compile all // '.coffee' extension source files in it and all subdirectories. - compile_scripts = function() { + compileScripts = function() { var _b, _c, _d, _e, base, compile, source; _b = []; _d = sources; for (_c = 0, _e = _d.length; _c < _e; _c++) { source = _d[_c]; _b.push((function() { base = source; - compile = function(source, top_level) { + compile = function(source, topLevel) { return path.exists(source, function(exists) { if (!(exists)) { throw new Error(("File not found: " + source)); @@ -80,9 +80,9 @@ } return _f; }); - } else if (top_level || path.extname(source) === '.coffee') { + } else if (topLevel || path.extname(source) === '.coffee') { fs.readFile(source, function(err, code) { - return compile_script(source, code.toString(), base); + return compileScript(source, code.toString(), base); }); if (options.watch) { return watch(source, base); @@ -99,23 +99,23 @@ // Compile a single source script, containing the given code, according to the // requested options. If evaluating the script directly sets `__filename`, // `__dirname` and `module.filename` to be correct relative to the script's path. - compile_script = function(source, code, base) { - var code_opts, js, o; + compileScript = function(source, code, base) { + var codeOpts, js, o; o = options; - code_opts = compile_options(source); + codeOpts = compileOptions(source); try { if (o.tokens) { - return print_tokens(CoffeeScript.tokens(code)); + return printTokens(CoffeeScript.tokens(code)); } else if (o.nodes) { return puts(CoffeeScript.nodes(code).toString()); } else if (o.run) { - return CoffeeScript.run(code, code_opts); + return CoffeeScript.run(code, codeOpts); } else { - js = CoffeeScript.compile(code, code_opts); + js = CoffeeScript.compile(code, codeOpts); if (o.print) { return print(js); } else if (o.compile) { - return write_js(source, js, base); + return writeJs(source, js, base); } else if (o.lint) { return lint(js); } @@ -129,7 +129,7 @@ }; // Attach the appropriate listeners to compile scripts incoming over **stdin**, // and write them back to **stdout**. - compile_stdio = function() { + compileStdio = function() { var code, stdin; code = ''; stdin = process.openStdin(); @@ -139,7 +139,7 @@ } }); return stdin.addListener('end', function() { - return compile_script('stdio', code); + return compileScript('stdio', code); }); }; // Watch a source CoffeeScript file using `fs.watchFile`, recompiling it every @@ -157,22 +157,22 @@ puts(("Compiled " + source)); } return fs.readFile(source, function(err, code) { - return compile_script(source, code.toString(), base); + return compileScript(source, code.toString(), base); }); }); }; // Write out a JavaScript source file with the compiled code. By default, files // are written out in `cwd` as `.js` files with the same name, but the output // directory can be customized with `--output`. - write_js = function(source, js, base) { - var base_dir, compile, dir, filename, js_path, src_dir; + writeJs = function(source, js, base) { + var baseDir, compile, dir, filename, jsPath, srcDir; filename = path.basename(source, path.extname(source)) + '.js'; - src_dir = path.dirname(source); - base_dir = src_dir.substring(base.length); - dir = options.output ? path.join(options.output, base_dir) : src_dir; - js_path = path.join(dir, filename); + srcDir = path.dirname(source); + baseDir = srcDir.substring(base.length); + dir = options.output ? path.join(options.output, baseDir) : srcDir; + jsPath = path.join(dir, filename); compile = function() { - return fs.writeFile(js_path, js); + return fs.writeFile(jsPath, js); }; return path.exists(dir, function(exists) { if (exists) { @@ -185,18 +185,18 @@ // Pipe compiled JS through JSLint (requires a working `jsl` command), printing // any errors or warnings that arise. lint = function(js) { - var jsl, print_it; - print_it = function(buffer) { + var jsl, printIt; + printIt = function(buffer) { return print(buffer.toString()); }; jsl = spawn('jsl', ['-nologo', '-stdin']); - jsl.stdout.addListener('data', print_it); - jsl.stderr.addListener('data', print_it); + jsl.stdout.addListener('data', printIt); + jsl.stderr.addListener('data', printIt); jsl.stdin.write(js); return jsl.stdin.end(); }; // Pretty-print a stream of tokens. - print_tokens = function(tokens) { + printTokens = function(tokens) { var _b, _c, _d, _e, _f, strings, tag, token, value; strings = (function() { _b = []; _d = tokens; @@ -215,17 +215,17 @@ }; // Use the [OptionParser module](optparse.html) to extract all options from // `process.argv` that are specified in `SWITCHES`. - parse_options = function() { + parseOptions = function() { var o; - option_parser = new optparse.OptionParser(SWITCHES, BANNER); - o = (options = option_parser.parse(process.argv)); + optionParser = new optparse.OptionParser(SWITCHES, BANNER); + o = (options = optionParser.parse(process.argv)); options.run = !(o.compile || o.print || o.lint); options.print = !!(o.print || (o.eval || o.stdio && o.compile)); sources = options.arguments.slice(2, options.arguments.length); return sources; }; // The compile-time options to pass to the CoffeeScript compiler. - compile_options = function(source) { + compileOptions = function(source) { var o; o = { source: source @@ -235,7 +235,7 @@ }; // Print the `--help` usage message and exit. usage = function() { - puts(option_parser.help()); + puts(optionParser.help()); return process.exit(0); }; // Print the `--version` message and exit. diff --git a/lib/grammar.js b/lib/grammar.js index 0a2a542fcc..ca5d490c14 100644 --- a/lib/grammar.js +++ b/lib/grammar.js @@ -28,13 +28,13 @@ // we pass the pattern-defining string, the action to run, and extra options, // optionally. If no action is specified, we simply pass the value of the // previous nonterminal. - o = function(pattern_string, action, options) { + o = function(patternString, action, options) { var match; if (!(action)) { - return [pattern_string, '$$ = $1;', options]; + return [patternString, '$$ = $1;', options]; } action = (match = (action + '').match(unwrap)) ? match[1] : ("(" + action + "())"); - return [pattern_string, ("$$ = " + action + ";"), options]; + return [patternString, ("$$ = " + action + ";"), options]; }; // Grammatical Rules // ----------------- @@ -265,7 +265,7 @@ o("INDEX_START Expression INDEX_END", function() { return new IndexNode($2); }), o("INDEX_SOAK Index", function() { - $2.soak_node = true; + $2.soakNode = true; return $2; }), o("INDEX_PROTO Index", function() { $2.proto = true; @@ -328,7 +328,7 @@ // and calling `super()` Call: [ o("Invocation"), o("NEW Invocation", function() { - return $2.new_instance(); + return $2.newInstance(); }), o("Super") ], // Extending an object by setting its prototype chain to reference a parent @@ -479,20 +479,20 @@ // or postfix, with a single expression. There is no do..while. While: [ o("WhileSource Block", function() { - return $1.add_body($2); + return $1.addBody($2); }), o("Statement WhileSource", function() { - return $2.add_body(Expressions.wrap([$1])); + return $2.addBody(Expressions.wrap([$1])); }), o("Expression WhileSource", function() { - return $2.add_body(Expressions.wrap([$1])); + return $2.addBody(Expressions.wrap([$1])); }), o("Loop", function() { return $1; }) ], Loop: [ o("LOOP Block", function() { - return new WhileNode(new LiteralNode('true')).add_body($2); + return new WhileNode(new LiteralNode('true')).addBody($2); }), o("LOOP Expression", function() { - return new WhileNode(new LiteralNode('true')).add_body(Expressions.wrap([$2])); + return new WhileNode(new LiteralNode('true')).addBody(Expressions.wrap([$2])); }) ], // Array, object, and range comprehensions, at the most generic level. @@ -573,20 +573,20 @@ // switch/case/default by compiling into an if-else chain. Switch: [ o("SWITCH Expression INDENT Whens OUTDENT", function() { - return $4.switches_over($2); + return $4.switchesOver($2); }), o("SWITCH Expression INDENT Whens ELSE Block OUTDENT", function() { - return $4.switches_over($2).add_else($6, true); + return $4.switchesOver($2).addElse($6, true); }), o("SWITCH INDENT Whens OUTDENT", function() { return $3; }), o("SWITCH INDENT Whens ELSE Block OUTDENT", function() { - return $3.add_else($5, true); + return $3.addElse($5, true); }) ], // The inner list of whens is left recursive. At code-generation time, the // IfNode will rewrite them into a proper chain. Whens: [ o("When"), o("Whens When", function() { - return $1.add_else($2); + return $1.addElse($2); }) ], // An individual **When** clause, with action. @@ -615,13 +615,13 @@ invert: true }); }), o("IfStart ELSE IF Expression Block", function() { - return $1.add_else((new IfNode($4, $5)).force_statement()); + return $1.addElse((new IfNode($4, $5)).forceStatement()); }) ], // An **IfStart** can optionally be followed by an else block. IfBlock: [ o("IfStart"), o("IfStart ELSE Block", function() { - return $1.add_else($3); + return $1.addElse($3); }) ], // The full complement of *if* expressions, including postfix one-liner diff --git a/lib/helpers.js b/lib/helpers.js index cf3402f63f..708e74f2d9 100644 --- a/lib/helpers.js +++ b/lib/helpers.js @@ -1,5 +1,5 @@ (function(){ - var balanced_string, compact, count, del, extend, flatten, helpers, include, index_of, merge, starts; + var balancedString, compact, count, del, extend, flatten, helpers, include, indexOf, merge, starts; var __hasProp = Object.prototype.hasOwnProperty; // This file contains the common helper functions that we'd like to share among // the **Lexer**, **Rewriter**, and the **Nodes**. Merge objects, flatten @@ -10,7 +10,7 @@ } helpers = (exports.helpers = {}); // Cross-browser indexOf, so that IE can join the party. - helpers.index_of = (index_of = function(array, item, from) { + helpers.indexOf = (indexOf = function(array, item, from) { var _a, _b, index, other; if (array.indexOf) { return array.indexOf(item, from); @@ -26,7 +26,7 @@ }); // Does a list include a value? helpers.include = (include = function(list, value) { - return index_of(list, value) >= 0; + return indexOf(list, value) >= 0; }); // Peek at the beginning of a given string to see if it matches a sequence. helpers.starts = (starts = function(string, literal, start) { @@ -46,10 +46,10 @@ helpers.count = (count = function(string, letter) { var num, pos; num = 0; - pos = index_of(string, letter); + pos = indexOf(string, letter); while (pos !== -1) { num += 1; - pos = index_of(string, letter, pos + 1); + pos = indexOf(string, letter, pos + 1); } return num; }); @@ -108,7 +108,7 @@ // a series of delimiters, all of which must be nested correctly within the // contents of the string. This method allows us to have strings within // interpolations within strings, ad infinitum. - helpers.balanced_string = (balanced_string = function(str, delimited, options) { + helpers.balancedString = (balancedString = function(str, delimited, options) { var _a, _b, _c, _d, close, i, levels, open, pair, slash; options = options || {}; slash = delimited[0][0] === '/'; diff --git a/lib/lexer.js b/lib/lexer.js index 16f7b9e8db..5f2a37284c 100644 --- a/lib/lexer.js +++ b/lib/lexer.js @@ -1,11 +1,11 @@ (function(){ - var ASSIGNED, ASSIGNMENT, CALLABLE, CODE, COFFEE_ALIASES, COFFEE_KEYWORDS, COMMENT, COMMENT_CLEANER, CONVERSIONS, HALF_ASSIGNMENTS, HEREDOC, HEREDOC_INDENT, IDENTIFIER, INTERPOLATION, JS_CLEANER, JS_FORBIDDEN, JS_KEYWORDS, LAST_DENT, LAST_DENTS, LINE_BREAK, Lexer, MULTILINER, MULTI_DENT, NEXT_CHARACTER, NOT_REGEX, NO_NEWLINE, NUMBER, OPERATOR, REGEX_END, REGEX_ESCAPE, REGEX_INTERPOLATION, REGEX_START, RESERVED, Rewriter, STRING_NEWLINES, WHITESPACE, _a, _b, _c, balanced_string, compact, count, helpers, include, starts; + var ASSIGNED, ASSIGNMENT, CALLABLE, CODE, COFFEE_ALIASES, COFFEE_KEYWORDS, COMMENT, COMMENT_CLEANER, CONVERSIONS, HALF_ASSIGNMENTS, HEREDOC, HEREDOC_INDENT, IDENTIFIER, INTERPOLATION, JS_CLEANER, JS_FORBIDDEN, JS_KEYWORDS, LAST_DENT, LAST_DENTS, LINE_BREAK, Lexer, MULTILINER, MULTI_DENT, NEXT_CHARACTER, NOT_REGEX, NO_NEWLINE, NUMBER, OPERATOR, REGEX_END, REGEX_ESCAPE, REGEX_INTERPOLATION, REGEX_START, RESERVED, Rewriter, STRING_NEWLINES, WHITESPACE, _a, _b, _c, balancedString, compact, count, helpers, include, starts; var __slice = Array.prototype.slice; // The CoffeeScript Lexer. Uses a series of token-matching regexes to attempt // matches against the beginning of the source code. When a match is found, // a token is produced, we consume the match, and start again. Tokens are in the // form: - // [tag, value, line_number] + // [tag, value, lineNumber] // Which is a format that can be fed directly into [Jison](http://github.com/zaach/jison). // Set up the Lexer for both Node.js and the browser, depending on where we are. if ((typeof process !== "undefined" && process !== null)) { @@ -24,7 +24,7 @@ count = _c.count; starts = _c.starts; compact = _c.compact; - balanced_string = _c.balanced_string; + balancedString = _c.balancedString; // The Lexer Class // --------------- // The Lexer class reads a stream of CoffeeScript and divvys it up into tagged @@ -62,9 +62,9 @@ // Stream of parsed tokens in the form ['TYPE', value, line] while (this.i < this.code.length) { this.chunk = this.code.slice(this.i); - this.extract_next_token(); + this.extractNextToken(); } - this.close_indentation(); + this.closeIndentation(); if (o.rewrite === false) { return this.tokens; } @@ -72,45 +72,45 @@ }; // At every position, run through this list of attempted matches, // short-circuiting if any of them succeed. Their order determines precedence: - // `@literal_token` is the fallback catch-all. - Lexer.prototype.extract_next_token = function() { - if (this.extension_token()) { + // `@literalToken` is the fallback catch-all. + Lexer.prototype.extractNextToken = function() { + if (this.extensionToken()) { return null; } - if (this.identifier_token()) { + if (this.identifierToken()) { return null; } - if (this.number_token()) { + if (this.numberToken()) { return null; } - if (this.heredoc_token()) { + if (this.heredocToken()) { return null; } - if (this.regex_token()) { + if (this.regexToken()) { return null; } - if (this.comment_token()) { + if (this.commentToken()) { return null; } - if (this.line_token()) { + if (this.lineToken()) { return null; } - if (this.whitespace_token()) { + if (this.whitespaceToken()) { return null; } - if (this.js_token()) { + if (this.jsToken()) { return null; } - if (this.string_token()) { + if (this.stringToken()) { return null; } - return this.literal_token(); + return this.literalToken(); }; // Tokenizers // ---------- // Language extensions get the highest priority, first chance to tag tokens // as something else. - Lexer.prototype.extension_token = function() { + Lexer.prototype.extensionToken = function() { var _d, _e, _f, extension; _e = Lexer.extensions; for (_d = 0, _f = _e.length; _d < _f; _d++) { @@ -127,29 +127,29 @@ // allowed in JavaScript, we're careful not to tag them as keywords when // referenced as property names here, so you can still do `jQuery.is()` even // though `is` means `===` otherwise. - Lexer.prototype.identifier_token = function() { - var forced_identifier, id, tag; + Lexer.prototype.identifierToken = function() { + var forcedIdentifier, id, tag; if (!(id = this.match(IDENTIFIER, 1))) { return false; } - forced_identifier = this.tag_accessor() || this.match(ASSIGNED, 1); + forcedIdentifier = this.tagAccessor() || this.match(ASSIGNED, 1); tag = 'IDENTIFIER'; - if (include(JS_KEYWORDS, id) || (!forced_identifier && include(COFFEE_KEYWORDS, id))) { + if (include(JS_KEYWORDS, id) || (!forcedIdentifier && include(COFFEE_KEYWORDS, id))) { tag = id.toUpperCase(); } if (include(RESERVED, id)) { - this.identifier_error(id); + this.identifierError(id); } if (tag === 'WHEN' && include(LINE_BREAK, this.tag())) { tag = 'LEADING_WHEN'; } this.i += id.length; - if (!(forced_identifier)) { + if (!(forcedIdentifier)) { if (include(COFFEE_ALIASES, id)) { tag = (id = CONVERSIONS[id]); } if (this.prev() && this.prev()[0] === 'ASSIGN' && include(HALF_ASSIGNMENTS, tag)) { - return this.tag_half_assignment(tag); + return this.tagHalfAssignment(tag); } } this.token(tag, id); @@ -157,7 +157,7 @@ }; // Matches numbers, including decimals, hex, and exponential notation. // Be careful not to interfere with ranges-in-progress. - Lexer.prototype.number_token = function() { + Lexer.prototype.numberToken = function() { var number; if (!(number = this.match(NUMBER, 1))) { return false; @@ -171,44 +171,44 @@ }; // Matches strings, including multi-line strings. Ensures that quotation marks // are balanced within the string's contents, and within nested interpolations. - Lexer.prototype.string_token = function() { + Lexer.prototype.stringToken = function() { var string; if (!(starts(this.chunk, '"') || starts(this.chunk, "'"))) { return false; } - if (!(string = this.balanced_token(['"', '"'], ['${', '}']) || this.balanced_token(["'", "'"]))) { + if (!(string = this.balancedToken(['"', '"'], ['${', '}']) || this.balancedToken(["'", "'"]))) { return false; } - this.interpolate_string(string.replace(STRING_NEWLINES, " \\\n")); + this.interpolateString(string.replace(STRING_NEWLINES, " \\\n")); this.line += count(string, "\n"); this.i += string.length; return true; }; // Matches heredocs, adjusting indentation to the correct level, as heredocs // preserve whitespace, but ignore indentation to the left. - Lexer.prototype.heredoc_token = function() { + Lexer.prototype.heredocToken = function() { var doc, match, quote; if (!(match = this.chunk.match(HEREDOC))) { return false; } quote = match[1].substr(0, 1); - doc = this.sanitize_heredoc(match[2] || match[4], { + doc = this.sanitizeHeredoc(match[2] || match[4], { quote: quote }); - this.interpolate_string(("" + quote + doc + quote)); + this.interpolateString(("" + quote + doc + quote)); this.line += count(match[1], "\n"); this.i += match[1].length; return true; }; // Matches and conumes comments. We pass through comments into JavaScript, // so they're treated as real tokens, like any other part of the language. - Lexer.prototype.comment_token = function() { + Lexer.prototype.commentToken = function() { var comment, i, lines, match; if (!(match = this.chunk.match(COMMENT))) { return false; } if (match[3]) { - comment = this.sanitize_heredoc(match[3], { + comment = this.sanitizeHeredoc(match[3], { herecomment: true }); this.token('HERECOMMENT', comment.split(MULTILINER)); @@ -228,12 +228,12 @@ return true; }; // Matches JavaScript interpolated directly into the source via backticks. - Lexer.prototype.js_token = function() { + Lexer.prototype.jsToken = function() { var script; if (!(starts(this.chunk, '`'))) { return false; } - if (!(script = this.balanced_token(['`', '`']))) { + if (!(script = this.balancedToken(['`', '`']))) { return false; } this.token('JS', script.replace(JS_CLEANER, '')); @@ -242,9 +242,9 @@ }; // 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 `@balanced_token`, and - // borrow interpolation from `@interpolate_string`. - Lexer.prototype.regex_token = function() { + // JavaScript and Ruby, borrow slash balancing from `@balancedToken`, and + // borrow interpolation from `@interpolateString`. + Lexer.prototype.regexToken = function() { var end, flags, regex, str; if (!(this.chunk.match(REGEX_START))) { return false; @@ -252,7 +252,7 @@ if (include(NOT_REGEX, this.tag())) { return false; } - if (!(regex = this.balanced_token(['/', '/']))) { + if (!(regex = this.balancedToken(['/', '/']))) { return false; } if (!(end = this.chunk.substr(regex.length).match(REGEX_END))) { @@ -267,7 +267,7 @@ return '\\' + escaped; }); this.tokens = this.tokens.concat([['(', '('], ['NEW', 'new'], ['IDENTIFIER', 'RegExp'], ['CALL_START', '(']]); - this.interpolate_string(("\"" + str + "\""), true); + this.interpolateString(("\"" + str + "\""), true); this.tokens = this.tokens.concat([[',', ','], ['STRING', ("\"" + flags + "\"")], [')', ')'], [')', ')']]); } else { this.token('REGEX', regex); @@ -277,11 +277,11 @@ }; // Matches a token in which which the passed delimiter pairs must be correctly // balanced (ie. strings, JS literals). - Lexer.prototype.balanced_token = function() { + Lexer.prototype.balancedToken = function() { var delimited; var _d = arguments.length, _e = _d >= 1; delimited = __slice.call(arguments, 0, _d - 0); - return balanced_string(this.chunk, delimited); + return balancedString(this.chunk, delimited); }; // Matches newlines, indents, and outdents, and determines which is which. // If we can detect that the current line is continued onto the the next line, @@ -291,8 +291,8 @@ // .map( ... ) // Keeps track of the level of indentation, because a single outdent token // can close multiple indents, so we need to know how far in we happen to be. - Lexer.prototype.line_token = function() { - var diff, indent, next_character, no_newlines, prev, size; + Lexer.prototype.lineToken = function() { + var diff, indent, nextCharacter, noNewlines, prev, size; if (!(indent = this.match(MULTI_DENT, 1))) { return false; } @@ -300,50 +300,50 @@ this.i += indent.length; prev = this.prev(2); size = indent.match(LAST_DENTS).reverse()[0].match(LAST_DENT)[1].length; - next_character = this.chunk.match(NEXT_CHARACTER)[1]; - no_newlines = next_character === '.' || next_character === ',' || this.unfinished(); + nextCharacter = this.chunk.match(NEXT_CHARACTER)[1]; + noNewlines = nextCharacter === '.' || nextCharacter === ',' || this.unfinished(); if (size === this.indent) { - if (no_newlines) { - return this.suppress_newlines(); + if (noNewlines) { + return this.suppressNewlines(); } - return this.newline_token(indent); + return this.newlineToken(indent); } else if (size > this.indent) { - if (no_newlines) { - return this.suppress_newlines(); + if (noNewlines) { + return this.suppressNewlines(); } diff = size - this.indent; this.token('INDENT', diff); this.indents.push(diff); } else { - this.outdent_token(this.indent - size, no_newlines); + this.outdentToken(this.indent - size, noNewlines); } this.indent = size; return true; }; // Record an outdent token or multiple tokens, if we happen to be moving back // inwards past several recorded indents. - Lexer.prototype.outdent_token = function(move_out, no_newlines) { - var last_indent; - if (move_out > -this.outdebt) { - while (move_out > 0 && this.indents.length) { - last_indent = this.indents.pop(); - this.token('OUTDENT', last_indent); - move_out -= last_indent; + Lexer.prototype.outdentToken = function(moveOut, noNewlines) { + var lastIndent; + if (moveOut > -this.outdebt) { + while (moveOut > 0 && this.indents.length) { + lastIndent = this.indents.pop(); + this.token('OUTDENT', lastIndent); + moveOut -= lastIndent; } } else { - this.outdebt += move_out; + this.outdebt += moveOut; } - if (!(no_newlines)) { - this.outdebt = move_out; + if (!(noNewlines)) { + this.outdebt = moveOut; } - if (!(this.tag() === 'TERMINATOR' || no_newlines)) { + if (!(this.tag() === 'TERMINATOR' || noNewlines)) { this.token('TERMINATOR', "\n"); } return true; }; // Matches and consumes non-meaningful whitespace. Tag the previous token // as being "spaced", because there are some cases where it makes a difference. - Lexer.prototype.whitespace_token = function() { + Lexer.prototype.whitespaceToken = function() { var prev, space; if (!(space = this.match(WHITESPACE, 1))) { return false; @@ -356,7 +356,7 @@ return true; }; // Generate a newline token. Consecutive newlines get merged together. - Lexer.prototype.newline_token = function(newlines) { + Lexer.prototype.newlineToken = function(newlines) { if (!(this.tag() === 'TERMINATOR')) { this.token('TERMINATOR', "\n"); } @@ -364,7 +364,7 @@ }; // Use a `\` at a line-ending to suppress the newline. // The slash is removed here once its job is done. - Lexer.prototype.suppress_newlines = function() { + Lexer.prototype.suppressNewlines = function() { if (this.value() === "\\") { this.tokens.pop(); } @@ -375,25 +375,25 @@ // the proper order of operations. There are some symbols that we tag specially // here. `;` and newlines are both treated as a `TERMINATOR`, we distinguish // parentheses that indicate a method call from regular parentheses, and so on. - Lexer.prototype.literal_token = function() { - var match, prev_spaced, space, tag, value; + Lexer.prototype.literalToken = function() { + var match, prevSpaced, space, tag, value; match = this.chunk.match(OPERATOR); value = match && match[1]; space = match && match[2]; if (value && value.match(CODE)) { - this.tag_parameters(); + this.tagParameters(); } value = value || this.chunk.substr(0, 1); - prev_spaced = this.prev() && this.prev().spaced; + prevSpaced = this.prev() && this.prev().spaced; tag = value; if (value.match(ASSIGNMENT)) { tag = 'ASSIGN'; if (include(JS_FORBIDDEN, this.value)) { - this.assignment_error(); + this.assignmentError(); } } else if (value === ';') { tag = 'TERMINATOR'; - } else if (include(CALLABLE, this.tag()) && !prev_spaced) { + } else if (include(CALLABLE, this.tag()) && !prevSpaced) { if (value === '(') { tag = 'CALL_START'; } else if (value === '[') { @@ -407,8 +407,8 @@ } } this.i += value.length; - if (space && prev_spaced && this.prev()[0] === 'ASSIGN' && include(HALF_ASSIGNMENTS, tag)) { - return this.tag_half_assignment(tag); + if (space && prevSpaced && this.prev()[0] === 'ASSIGN' && include(HALF_ASSIGNMENTS, tag)) { + return this.tagHalfAssignment(tag); } this.token(tag, value); return true; @@ -418,7 +418,7 @@ // As we consume a new `IDENTIFIER`, look at the previous token to determine // if it's a special kind of accessor. Return `true` if any type of accessor // is the previous token. - Lexer.prototype.tag_accessor = function() { + Lexer.prototype.tagAccessor = function() { var prev; if ((!(prev = this.prev())) || (prev && prev.spaced)) { return false; @@ -438,7 +438,7 @@ }; // Sanitize a heredoc or herecomment by escaping internal double quotes and // erasing all external indentation on the left-hand side. - Lexer.prototype.sanitize_heredoc = function(doc, options) { + Lexer.prototype.sanitizeHeredoc = function(doc, options) { var _d, attempt, indent, match; while (match = HEREDOC_INDENT.exec(doc)) { attempt = (typeof (_d = match[2]) !== "undefined" && _d !== null) ? match[2] : match[3]; @@ -453,7 +453,7 @@ return doc.replace(MULTILINER, "\\n").replace(new RegExp(options.quote, 'g'), ("\\" + options.quote)); }; // Tag a half assignment. - Lexer.prototype.tag_half_assignment = function(tag) { + Lexer.prototype.tagHalfAssignment = function(tag) { var last; last = this.tokens.pop(); this.tokens.push([("" + tag + "="), ("" + tag + "="), last[2]]); @@ -462,7 +462,7 @@ // A source of ambiguity in our grammar used to be parameter lists in function // definitions versus argument lists in function calls. Walk backwards, tagging // parameters specially in order to make things easier for the parser. - Lexer.prototype.tag_parameters = function() { + Lexer.prototype.tagParameters = function() { var _d, i, tok; if (this.tag() !== ')') { return null; @@ -486,17 +486,17 @@ return true; }; // Close up all remaining open blocks at the end of the file. - Lexer.prototype.close_indentation = function() { - return this.outdent_token(this.indent); + Lexer.prototype.closeIndentation = function() { + return this.outdentToken(this.indent); }; // The error for when you try to use a forbidden word in JavaScript as // an identifier. - Lexer.prototype.identifier_error = function(word) { + Lexer.prototype.identifierError = function(word) { throw new Error(("SyntaxError: Reserved word \"" + word + "\" on line " + (this.line + 1))); }; // The error for when you try to assign to a reserved word in JavaScript, // like "function" or "default". - Lexer.prototype.assignment_error = function() { + Lexer.prototype.assignmentError = function() { throw new Error(("SyntaxError: Reserved word \"" + (this.value()) + "\" on line " + (this.line + 1) + " can't be assigned")); }; // Expand variables and expressions inside double-quoted strings using @@ -507,7 +507,7 @@ // If it encounters an interpolation, this method will recursively create a // new Lexer, tokenize the interpolated contents, and merge them into the // token stream. - Lexer.prototype.interpolate_string = function(str, escape_quotes) { + Lexer.prototype.interpolateString = function(str, escapeQuotes) { var _d, _e, _f, _g, _h, _i, _j, escaped, expr, group, i, idx, inner, interp, interpolated, lexer, match, nested, pi, quote, tag, tok, token, tokens, value; if (str.length < 3 || !starts(str, '"')) { return this.token('STRING', str); @@ -534,7 +534,7 @@ tokens.push(['IDENTIFIER', interp]); i += group.length - 1; pi = i + 1; - } else if ((expr = balanced_string(str.substring(i), [['${', '}']]))) { + } else if ((expr = balancedString(str.substring(i), [['${', '}']]))) { if (pi < i) { tokens.push(['STRING', ("" + quote + (str.substring(pi, i)) + quote)]); } @@ -576,7 +576,7 @@ value = _j[1]; if (tag === 'TOKENS') { this.tokens = this.tokens.concat(value); - } else if (tag === 'STRING' && escape_quotes) { + } else if (tag === 'STRING' && escapeQuotes) { escaped = value.substring(1, value.length - 1).replace(/"/g, '\\"'); this.token(tag, ("\"" + escaped + "\"")); } else { @@ -599,13 +599,13 @@ return this.tokens.push([tag, value, this.line]); }; // Peek at a tag in the current token stream. - Lexer.prototype.tag = function(index, new_tag) { + Lexer.prototype.tag = function(index, newTag) { var tok; if (!(tok = this.prev(index))) { return null; } - if ((typeof new_tag !== "undefined" && new_tag !== null)) { - tok[0] = new_tag; + if ((typeof newTag !== "undefined" && newTag !== null)) { + tok[0] = newTag; return tok[0]; } return tok[0]; diff --git a/lib/nodes.js b/lib/nodes.js index 19b96346fa..d4b19e9122 100644 --- a/lib/nodes.js +++ b/lib/nodes.js @@ -1,5 +1,5 @@ (function(){ - var AccessorNode, ArrayNode, AssignNode, BaseNode, CallNode, ClassNode, ClosureNode, CodeNode, CommentNode, ExistenceNode, Expressions, ExtendsNode, ForNode, IDENTIFIER, IS_STRING, IfNode, IndexNode, LiteralNode, NUMBER, ObjectNode, OpNode, ParentheticalNode, PushNode, RangeNode, ReturnNode, Scope, SliceNode, SplatNode, TAB, TRAILING_WHITESPACE, ThrowNode, TryNode, UTILITIES, ValueNode, WhileNode, _a, compact, del, flatten, helpers, include, index_of, literal, merge, starts, utility; + var AccessorNode, ArrayNode, AssignNode, BaseNode, CallNode, ClassNode, ClosureNode, CodeNode, CommentNode, ExistenceNode, Expressions, ExtendsNode, ForNode, IDENTIFIER, IS_STRING, IfNode, IndexNode, LiteralNode, NUMBER, ObjectNode, OpNode, ParentheticalNode, PushNode, RangeNode, ReturnNode, Scope, SliceNode, SplatNode, TAB, TRAILING_WHITESPACE, ThrowNode, TryNode, UTILITIES, ValueNode, WhileNode, _a, compact, del, flatten, helpers, include, indexOf, literal, merge, starts, utility; var __extends = function(child, parent) { var ctor = function(){ }; ctor.prototype = parent.prototype; @@ -28,13 +28,13 @@ merge = _a.merge; del = _a.del; include = _a.include; - index_of = _a.index_of; + indexOf = _a.indexOf; starts = _a.starts; //### BaseNode // The **BaseNode** is the abstract base class for all nodes in the syntax tree. - // Each subclass implements the `compile_node` method, which performs the + // Each subclass implements the `compileNode` method, which performs the // code generation for that node. To compile a node to JavaScript, - // call `compile` on it, which wraps `compile_node` in some generic extra smarts, + // call `compile` on it, which wraps `compileNode` in some generic extra smarts, // to know when the generated code needs to be wrapped up in a closure. // An options hash is passed and cloned throughout, containing information about // the environment from higher in the tree (such as if a returned value is @@ -44,11 +44,11 @@ BaseNode = function() { }; // Common logic for determining whether to wrap this node in a closure before // compiling it, or to compile directly. We need to wrap if this node is a - // *statement*, and it's not a *pure_statement*, and we're not at + // *statement*, and it's not a *pureStatement*, and we're not at // the top level of a block (which would be unnecessary), and we haven't // already been asked to return the result (because statements know how to // return results). - // If a Node is *top_sensitive*, that means that it needs to compile differently + // If a Node is *topSensitive*, that means that it needs to compile differently // depending on whether it's being used as part of a larger expression, or is a // top-level statement within the function body. BaseNode.prototype.compile = function(o) { @@ -58,33 +58,33 @@ if (!(this instanceof ValueNode || this instanceof CallNode)) { del(this.options, 'operation'); if (!(this instanceof AccessorNode || this instanceof IndexNode)) { - del(this.options, 'chain_root'); + del(this.options, 'chainRoot'); } } - top = this.top_sensitive() ? this.options.top : del(this.options, 'top'); - closure = this.is_statement() && !this.is_pure_statement() && !top && !this.options.as_statement && !(this instanceof CommentNode) && !this.contains_pure_statement(); + top = this.topSensitive() ? this.options.top : del(this.options, 'top'); + closure = this.isStatement() && !this.isPureStatement() && !top && !this.options.asStatement && !(this instanceof CommentNode) && !this.containsPureStatement(); if (closure) { - return this.compile_closure(this.options); + return this.compileClosure(this.options); } else { - return this.compile_node(this.options); + return this.compileNode(this.options); } }; // Statements converted into expressions via closure-wrapping share a scope // object with their parent closure, to preserve the expected lexical scope. - BaseNode.prototype.compile_closure = function(o) { + BaseNode.prototype.compileClosure = function(o) { this.tab = o.indent; - o.shared_scope = o.scope; + o.sharedScope = o.scope; return ClosureNode.wrap(this).compile(o); }; // If the code generation wishes to use the result of a complex expression // in multiple places, ensure that the expression is only ever evaluated once, // by assigning it to a temporary variable. - BaseNode.prototype.compile_reference = function(o, only_if_necessary) { + BaseNode.prototype.compileReference = function(o, onlyIfNecessary) { var compiled, reference; - if (only_if_necessary && !(this instanceof CallNode || this instanceof ValueNode && (!(this.base instanceof LiteralNode) || this.has_properties()))) { + if (onlyIfNecessary && !(this instanceof CallNode || this instanceof ValueNode && (!(this.base instanceof LiteralNode) || this.hasProperties()))) { return [this, this]; } - reference = literal(o.scope.free_variable()); + reference = literal(o.scope.freeVariable()); compiled = new AssignNode(reference, this); return [compiled, reference]; }; @@ -101,7 +101,7 @@ // Construct a node that returns the current node's result. // Note that this is overridden for smarter behavior for // many statement nodes (eg IfNode, ForNode)... - BaseNode.prototype.make_return = function() { + BaseNode.prototype.makeReturn = function() { return new ReturnNode(this); }; // Does this node, or any of its children, contain a node of a certain kind? @@ -111,7 +111,7 @@ BaseNode.prototype.contains = function(block) { var contains; contains = false; - this.traverse_children(false, function(node) { + this.traverseChildren(false, function(node) { if (block(node)) { contains = true; return false; @@ -120,21 +120,21 @@ return contains; }; // Is this node of a certain type, or does it contain the type? - BaseNode.prototype.contains_type = function(type) { + BaseNode.prototype.containsType = function(type) { return this instanceof type || this.contains(function(n) { return n instanceof type; }); }; // Convenience for the most common use of contains. Does the node contain // a pure statement? - BaseNode.prototype.contains_pure_statement = function() { - return this.is_pure_statement() || this.contains(function(n) { - return n.is_pure_statement(); + BaseNode.prototype.containsPureStatement = function() { + return this.isPureStatement() || this.contains(function(n) { + return n.isPureStatement(); }); }; // Perform an in-order traversal of the AST. Crosses scope boundaries. BaseNode.prototype.traverse = function(block) { - return this.traverse_children(true, block); + return this.traverseChildren(true, block); }; // `toString` representation of the node, for inspecting the parse tree. // This is what `coffee --nodes` prints out. @@ -142,7 +142,7 @@ var _b, _c, _d, _e, child; idt = idt || ''; return '\n' + idt + this.type + (function() { - _b = []; _d = this.collect_children(); + _b = []; _d = this.collectChildren(); for (_c = 0, _e = _d.length; _c < _e; _c++) { child = _d[_c]; _b.push(child.toString(idt + TAB)); @@ -150,7 +150,7 @@ return _b; }).call(this).join(''); }; - BaseNode.prototype.each_child = function(func) { + BaseNode.prototype.eachChild = function(func) { var _b, _c, _d, _e, _f, _g, attr, child; if (!(this.children)) { return null; @@ -169,19 +169,19 @@ } } }; - BaseNode.prototype.collect_children = function() { + BaseNode.prototype.collectChildren = function() { var nodes; nodes = []; - this.each_child(function(node) { + this.eachChild(function(node) { return nodes.push(node); }); return nodes; }; - BaseNode.prototype.traverse_children = function(cross_scope, func) { - return this.each_child(function(child) { + BaseNode.prototype.traverseChildren = function(crossScope, func) { + return this.eachChild(function(child) { func.apply(this, arguments); if (child instanceof BaseNode) { - return child.traverse_children(cross_scope, func); + return child.traverseChildren(crossScope, func); } }); }; @@ -192,13 +192,13 @@ BaseNode.prototype.unwrap = function() { return this; }; - BaseNode.prototype.is_statement = function() { + BaseNode.prototype.isStatement = function() { return false; }; - BaseNode.prototype.is_pure_statement = function() { + BaseNode.prototype.isPureStatement = function() { return false; }; - BaseNode.prototype.top_sensitive = function() { + BaseNode.prototype.topSensitive = function() { return false; }; return BaseNode; @@ -215,7 +215,7 @@ __extends(Expressions, BaseNode); Expressions.prototype.type = 'Expressions'; Expressions.prototype.children = ['expressions']; - Expressions.prototype.is_statement = function() { + Expressions.prototype.isStatement = function() { return true; }; // Tack an expression on to the end of this expression list. @@ -243,7 +243,7 @@ }; // An Expressions node does not return its entire body, rather it // ensures that the final expression is returned. - Expressions.prototype.make_return = function() { + Expressions.prototype.makeReturn = function() { var idx, last; idx = this.expressions.length - 1; last = this.expressions[idx]; @@ -253,8 +253,8 @@ if (!last || last instanceof ReturnNode) { return this; } - if (!(last.contains_pure_statement())) { - this.expressions[idx] = last.make_return(); + if (!(last.containsPureStatement())) { + this.expressions[idx] = last.makeReturn(); } return this; }; @@ -264,29 +264,29 @@ if (o.scope) { return Expressions.__superClass__.compile.call(this, o); } else { - return this.compile_root(o); + return this.compileRoot(o); } }; - Expressions.prototype.compile_node = function(o) { + Expressions.prototype.compileNode = function(o) { var _b, _c, _d, _e, node; return (function() { _b = []; _d = this.expressions; for (_c = 0, _e = _d.length; _c < _e; _c++) { node = _d[_c]; - _b.push(this.compile_expression(node, merge(o))); + _b.push(this.compileExpression(node, merge(o))); } return _b; }).call(this).join("\n"); }; // If we happen to be the top-level **Expressions**, wrap everything in // a safety closure, unless requested not to. - Expressions.prototype.compile_root = function(o) { + Expressions.prototype.compileRoot = function(o) { var code; - o.indent = (this.tab = o.no_wrap ? '' : TAB); + o.indent = (this.tab = o.noWrap ? '' : TAB); o.scope = new Scope(null, this, null); - code = o.globals ? this.compile_node(o) : this.compile_with_declarations(o); + code = o.globals ? this.compileNode(o) : this.compileWithDeclarations(o); code = code.replace(TRAILING_WHITESPACE, ''); - if (o.no_wrap) { + if (o.noWrap) { return code; } else { return "(function(){\n" + code + "\n})();\n"; @@ -294,30 +294,30 @@ }; // Compile the expressions body for the contents of a function, with // declarations of all inner variables pushed up to the top. - Expressions.prototype.compile_with_declarations = function(o) { + Expressions.prototype.compileWithDeclarations = function(o) { var code; - code = this.compile_node(o); - if (o.scope.has_assignments(this)) { - code = ("" + (this.tab) + "var " + (o.scope.compiled_assignments()) + ";\n" + code); + code = this.compileNode(o); + if (o.scope.hasAssignments(this)) { + code = ("" + (this.tab) + "var " + (o.scope.compiledAssignments()) + ";\n" + code); } - if (o.scope.has_declarations(this)) { - code = ("" + (this.tab) + "var " + (o.scope.compiled_declarations()) + ";\n" + code); + if (o.scope.hasDeclarations(this)) { + code = ("" + (this.tab) + "var " + (o.scope.compiledDeclarations()) + ";\n" + code); } return code; }; // Compiles a single expression within the expressions body. If we need to // return the result, and it's an expression, simply return it. If it's a // statement, ask the statement to do so. - Expressions.prototype.compile_expression = function(node, o) { - var compiled_node; + Expressions.prototype.compileExpression = function(node, o) { + var compiledNode; this.tab = o.indent; - compiled_node = node.compile(merge(o, { + compiledNode = node.compile(merge(o, { top: true })); - if (node.is_statement()) { - return compiled_node; + if (node.isStatement()) { + return compiledNode; } else { - return "" + (this.idt()) + compiled_node + ";"; + return "" + (this.idt()) + compiledNode + ";"; } }; return Expressions; @@ -343,14 +343,14 @@ LiteralNode.prototype.type = 'LiteralNode'; // Break and continue must be treated as pure statements -- they lose their // meaning when wrapped in a closure. - LiteralNode.prototype.is_statement = function() { + LiteralNode.prototype.isStatement = function() { return this.value === 'break' || this.value === 'continue'; }; - LiteralNode.prototype.is_pure_statement = LiteralNode.prototype.is_statement; - LiteralNode.prototype.compile_node = function(o) { + LiteralNode.prototype.isPureStatement = LiteralNode.prototype.isStatement; + LiteralNode.prototype.compileNode = function(o) { var end, idt; - idt = this.is_statement() ? this.idt() : ''; - end = this.is_statement() ? ';' : ''; + idt = this.isStatement() ? this.idt() : ''; + end = this.isStatement() ? ';' : ''; return "" + idt + this.value + end; }; LiteralNode.prototype.toString = function(idt) { @@ -359,7 +359,7 @@ return LiteralNode; })(); //### ReturnNode - // A `return` is a *pure_statement* -- wrapping it in a closure wouldn't + // A `return` is a *pureStatement* -- wrapping it in a closure wouldn't // make sense. exports.ReturnNode = (function() { ReturnNode = function(expression) { @@ -368,25 +368,25 @@ }; __extends(ReturnNode, BaseNode); ReturnNode.prototype.type = 'ReturnNode'; - ReturnNode.prototype.is_statement = function() { + ReturnNode.prototype.isStatement = function() { return true; }; - ReturnNode.prototype.is_pure_statement = function() { + ReturnNode.prototype.isPureStatement = function() { return true; }; ReturnNode.prototype.children = ['expression']; - ReturnNode.prototype.top_sensitive = function() { + ReturnNode.prototype.topSensitive = function() { return true; }; - ReturnNode.prototype.compile_node = function(o) { + ReturnNode.prototype.compileNode = function(o) { var expr; - expr = this.expression.make_return(); + expr = this.expression.makeReturn(); if (!(expr instanceof ReturnNode)) { return expr.compile(o); } del(o, 'top'); - if (this.expression.is_statement()) { - o.as_statement = true; + if (this.expression.isStatement()) { + o.asStatement = true; } return "" + (this.tab) + "return " + (this.expression.compile(o)) + ";"; }; @@ -411,24 +411,24 @@ this.properties.push(prop); return this; }; - ValueNode.prototype.has_properties = function() { + ValueNode.prototype.hasProperties = function() { return !!this.properties.length; }; // Some boolean checks for the benefit of other nodes. - ValueNode.prototype.is_array = function() { - return this.base instanceof ArrayNode && !this.has_properties(); + ValueNode.prototype.isArray = function() { + return this.base instanceof ArrayNode && !this.hasProperties(); }; - ValueNode.prototype.is_object = function() { - return this.base instanceof ObjectNode && !this.has_properties(); + ValueNode.prototype.isObject = function() { + return this.base instanceof ObjectNode && !this.hasProperties(); }; - ValueNode.prototype.is_splice = function() { - return this.has_properties() && this.properties[this.properties.length - 1] instanceof SliceNode; + ValueNode.prototype.isSplice = function() { + return this.hasProperties() && this.properties[this.properties.length - 1] instanceof SliceNode; }; - ValueNode.prototype.make_return = function() { - if (this.has_properties()) { - return ValueNode.__superClass__.make_return.call(this); + ValueNode.prototype.makeReturn = function() { + if (this.hasProperties()) { + return ValueNode.__superClass__.makeReturn.call(this); } else { - return this.base.make_return(); + return this.base.makeReturn(); } }; // The value can be unwrapped as its inner node, if there are no attached @@ -441,19 +441,19 @@ } }; // Values are considered to be statements if their base is a statement. - ValueNode.prototype.is_statement = function() { - return this.base.is_statement && this.base.is_statement() && !this.has_properties(); + ValueNode.prototype.isStatement = function() { + return this.base.isStatement && this.base.isStatement() && !this.hasProperties(); }; - ValueNode.prototype.is_number = function() { + ValueNode.prototype.isNumber = function() { return this.base instanceof LiteralNode && this.base.value.match(NUMBER); }; // Works out if the value is the start of a chain. - ValueNode.prototype.is_start = function(o) { + ValueNode.prototype.isStart = function(o) { var node; - if (this === o.chain_root && this.properties[0] instanceof AccessorNode) { + if (this === o.chainRoot && this.properties[0] instanceof AccessorNode) { return true; } - node = o.chain_root.base || o.chain_root.variable; + node = o.chainRoot.base || o.chainRoot.variable; while (node instanceof CallNode) { node = node.variable; } @@ -463,14 +463,14 @@ // Things get much more insteresting if the chain of properties has *soak* // operators `?.` interspersed. Then we have to take care not to accidentally // evaluate a anything twice when building the soak chain. - ValueNode.prototype.compile_node = function(o) { + ValueNode.prototype.compileNode = function(o) { var _b, _c, baseline, complete, i, only, op, part, prop, props, temp; - only = del(o, 'only_first'); + only = del(o, 'onlyFirst'); op = del(o, 'operation'); props = only ? this.properties.slice(0, this.properties.length - 1) : this.properties; - o.chain_root = o.chain_root || this; + o.chainRoot = o.chainRoot || this; baseline = this.base.compile(o); - if (this.has_properties() && (this.base instanceof ObjectNode || this.is_number())) { + if (this.hasProperties() && (this.base instanceof ObjectNode || this.isNumber())) { baseline = ("(" + baseline + ")"); } complete = (this.last = baseline); @@ -478,12 +478,12 @@ for (i = 0, _c = _b.length; i < _c; i++) { prop = _b[i]; this.source = baseline; - if (prop.soak_node) { + if (prop.soakNode) { if (this.base instanceof CallNode && i === 0) { - temp = o.scope.free_variable(); + temp = o.scope.freeVariable(); complete = ("(" + (baseline = temp) + " = (" + complete + "))"); } - if (i === 0 && this.is_start(o)) { + if (i === 0 && this.isStart(o)) { complete = ("typeof " + complete + " === \"undefined\" || " + baseline); } complete += this.SOAK + (baseline += prop.compile(o)); @@ -513,13 +513,13 @@ }; __extends(CommentNode, BaseNode); CommentNode.prototype.type = 'CommentNode'; - CommentNode.prototype.is_statement = function() { + CommentNode.prototype.isStatement = function() { return true; }; - CommentNode.prototype.make_return = function() { + CommentNode.prototype.makeReturn = function() { return this; }; - CommentNode.prototype.compile_node = function(o) { + CommentNode.prototype.compileNode = function(o) { var sep; if (this.kind === 'herecomment') { sep = '\n' + this.tab; @@ -535,12 +535,12 @@ // calls against the prototype's function of the same name. exports.CallNode = (function() { CallNode = function(variable, args) { - this.is_new = false; - this.is_super = variable === 'super'; - this.variable = this.is_super ? null : variable; + this.isNew = false; + this.isSuper = variable === 'super'; + this.variable = this.isSuper ? null : variable; this.args = (args || []); - this.compile_splat_arguments = function(o) { - return SplatNode.compile_mixed_array.call(this, this.args, o); + this.compileSplatArguments = function(o) { + return SplatNode.compileMixedArray.call(this, this.args, o); }; return this; }; @@ -548,19 +548,19 @@ CallNode.prototype.type = 'CallNode'; CallNode.prototype.children = ['variable', 'args']; // Tag this invocation as creating a new instance. - CallNode.prototype.new_instance = function() { - this.is_new = true; + CallNode.prototype.newInstance = function() { + this.isNew = true; return this; }; CallNode.prototype.prefix = function() { - if (this.is_new) { + if (this.isNew) { return 'new '; } else { return ''; } }; // Grab the reference to the superclass' implementation of the current method. - CallNode.prototype.super_reference = function(o) { + CallNode.prototype.superReference = function(o) { var meth, methname; methname = o.scope.method.name; meth = (function() { @@ -575,15 +575,15 @@ return meth; }; // Compile a vanilla function call. - CallNode.prototype.compile_node = function(o) { + CallNode.prototype.compileNode = function(o) { var _b, _c, _d, _e, _f, _g, _h, arg, args, compilation; - if (!(o.chain_root)) { - o.chain_root = this; + if (!(o.chainRoot)) { + o.chainRoot = this; } _c = this.args; for (_b = 0, _d = _c.length; _b < _d; _b++) { arg = _c[_b]; - arg instanceof SplatNode ? (compilation = this.compile_splat(o)) : null; + arg instanceof SplatNode ? (compilation = this.compileSplat(o)) : null; } if (!(compilation)) { args = (function() { @@ -594,7 +594,7 @@ } return _e; }).call(this).join(', '); - compilation = this.is_super ? this.compile_super(args, o) : ("" + (this.prefix()) + (this.variable.compile(o)) + "(" + args + ")"); + compilation = this.isSuper ? this.compileSuper(args, o) : ("" + (this.prefix()) + (this.variable.compile(o)) + "(" + args + ")"); } if (o.operation && this.wrapped) { return "(" + compilation + ")"; @@ -604,28 +604,28 @@ }; // `super()` is converted into a call against the superclass's implementation // of the current function. - CallNode.prototype.compile_super = function(args, o) { - return "" + (this.super_reference(o)) + ".call(this" + (args.length ? ', ' : '') + args + ")"; + CallNode.prototype.compileSuper = function(args, o) { + return "" + (this.superReference(o)) + ".call(this" + (args.length ? ', ' : '') + args + ")"; }; // If you call a function with a splat, it's converted into a JavaScript // `.apply()` call to allow an array of arguments to be passed. - CallNode.prototype.compile_splat = function(o) { + CallNode.prototype.compileSplat = function(o) { var meth, obj, temp; - meth = this.variable ? this.variable.compile(o) : this.super_reference(o); + meth = this.variable ? this.variable.compile(o) : this.superReference(o); obj = this.variable && this.variable.source || 'this'; if (obj.match(/\(/)) { - temp = o.scope.free_variable(); + temp = o.scope.freeVariable(); obj = temp; meth = ("(" + temp + " = " + (this.variable.source) + ")" + (this.variable.last)); } - return "" + (this.prefix()) + (meth) + ".apply(" + obj + ", " + (this.compile_splat_arguments(o)) + ")"; + return "" + (this.prefix()) + (meth) + ".apply(" + obj + ", " + (this.compileSplatArguments(o)) + ")"; }; return CallNode; })(); //### ExtendsNode // Node to extend an object's prototype with an ancestor object. // After `goog.inherits` from the - // [Closure Library](http://closure-library.googlecode.com/svn/docs/closure_goog_base.js.html). + // [Closure Library](http://closure-library.googlecode.com/svn/docs/closureGoogBase.js.html). exports.ExtendsNode = (function() { ExtendsNode = function(child, parent) { this.child = child; @@ -636,7 +636,7 @@ ExtendsNode.prototype.type = 'ExtendsNode'; ExtendsNode.prototype.children = ['child', 'parent']; // Hooks one constructor into another's prototype chain. - ExtendsNode.prototype.compile_node = function(o) { + ExtendsNode.prototype.compileNode = function(o) { var ref; ref = new ValueNode(literal(utility('extends'))); return (new CallNode(ref, [this.child, this.parent])).compile(o); @@ -650,17 +650,17 @@ AccessorNode = function(name, tag) { this.name = name; this.prototype = tag === 'prototype'; - this.soak_node = tag === 'soak'; + this.soakNode = tag === 'soak'; return this; }; __extends(AccessorNode, BaseNode); AccessorNode.prototype.type = 'AccessorNode'; AccessorNode.prototype.children = ['name']; - AccessorNode.prototype.compile_node = function(o) { - var proto_part; - o.chain_root.wrapped = o.chain_root.wrapped || this.soak_node; - proto_part = this.prototype ? 'prototype.' : ''; - return "." + proto_part + (this.name.compile(o)); + AccessorNode.prototype.compileNode = function(o) { + var protoPart; + o.chainRoot.wrapped = o.chainRoot.wrapped || this.soakNode; + protoPart = this.prototype ? 'prototype.' : ''; + return "." + protoPart + (this.name.compile(o)); }; return AccessorNode; })(); @@ -674,9 +674,9 @@ __extends(IndexNode, BaseNode); IndexNode.prototype.type = 'IndexNode'; IndexNode.prototype.children = ['index']; - IndexNode.prototype.compile_node = function(o) { + IndexNode.prototype.compileNode = function(o) { var idx, prefix; - o.chain_root.wrapped = o.chain_root.wrapped || this.soak_node; + o.chainRoot.wrapped = o.chainRoot.wrapped || this.soakNode; idx = this.index.compile(o); prefix = this.proto ? '.prototype' : ''; return "" + prefix + "[" + idx + "]"; @@ -699,19 +699,19 @@ RangeNode.prototype.children = ['from', 'to']; // Compiles the range's source variables -- where it starts and where it ends. // But only if they need to be cached to avoid double evaluation. - RangeNode.prototype.compile_variables = function(o) { + RangeNode.prototype.compileVariables = function(o) { var _b, _c, parts; - _b = this.from.compile_reference(o, true); + _b = this.from.compileReference(o, true); this.from = _b[0]; - this.from_var = _b[1]; - _c = this.to.compile_reference(o, true); + this.fromVar = _b[1]; + _c = this.to.compileReference(o, true); this.to = _c[0]; - this.to_var = _c[1]; + this.toVar = _c[1]; parts = []; - if (this.from !== this.from_var) { + if (this.from !== this.fromVar) { parts.push(this.from.compile(o)); } - if (this.to !== this.to_var) { + if (this.to !== this.toVar) { parts.push(this.to.compile(o)); } if (parts.length) { @@ -722,29 +722,29 @@ }; // When compiled normally, the range returns the contents of the *for loop* // needed to iterate over the values in the range. Used by comprehensions. - RangeNode.prototype.compile_node = function(o) { + RangeNode.prototype.compileNode = function(o) { var equals, idx, op, step, vars; if (!(o.index)) { - return this.compile_array(o); + return this.compileArray(o); } idx = del(o, 'index'); step = del(o, 'step'); - vars = ("" + idx + " = " + (this.from_var.compile(o))); + vars = ("" + idx + " = " + (this.fromVar.compile(o))); step = step ? step.compile(o) : '1'; equals = this.exclusive ? '' : '='; op = starts(step, '-') ? (">" + equals) : ("<" + equals); - return "" + vars + "; " + (idx) + " " + op + " " + (this.to_var.compile(o)) + "; " + idx + " += " + step; + return "" + vars + "; " + (idx) + " " + op + " " + (this.toVar.compile(o)) + "; " + idx + " += " + step; }; // When used as a value, expand the range into the equivalent array. - RangeNode.prototype.compile_array = function(o) { + RangeNode.prototype.compileArray = function(o) { var body, clause, equals, from, idt, post, pre, to, vars; idt = this.idt(1); - vars = this.compile_variables(merge(o, { + vars = this.compileVariables(merge(o, { indent: idt })); equals = this.exclusive ? '' : '='; - from = this.from_var.compile(o); - to = this.to_var.compile(o); + from = this.fromVar.compile(o); + to = this.toVar.compile(o); clause = ("" + from + " <= " + to + " ?"); pre = ("\n" + (idt) + "a = [];" + (vars)); body = ("var i = " + from + "; (" + clause + " i <" + equals + " " + to + " : i >" + equals + " " + to + "); (" + clause + " i += 1 : i -= 1)"); @@ -765,12 +765,12 @@ __extends(SliceNode, BaseNode); SliceNode.prototype.type = 'SliceNode'; SliceNode.prototype.children = ['range']; - SliceNode.prototype.compile_node = function(o) { - var from, plus_part, to; + SliceNode.prototype.compileNode = function(o) { + var from, plusPart, to; from = this.range.from.compile(o); to = this.range.to.compile(o); - plus_part = this.range.exclusive ? '' : ' + 1'; - return ".slice(" + from + ", " + to + plus_part + ")"; + plusPart = this.range.exclusive ? '' : ' + 1'; + return ".slice(" + from + ", " + to + plusPart + ")"; }; return SliceNode; })(); @@ -787,10 +787,10 @@ // All the mucking about with commas is to make sure that CommentNodes and // AssignNodes get interleaved correctly, with no trailing commas or // commas affixed to comments. - ObjectNode.prototype.compile_node = function(o) { - var _b, _c, _d, _e, _f, _g, _h, i, indent, inner, join, last_noncom, non_comments, prop, props; + ObjectNode.prototype.compileNode = function(o) { + var _b, _c, _d, _e, _f, _g, _h, i, indent, inner, join, lastNoncom, nonComments, prop, props; o.indent = this.idt(1); - non_comments = (function() { + nonComments = (function() { _b = []; _d = this.properties; for (_c = 0, _e = _d.length; _c < _e; _c++) { prop = _d[_c]; @@ -798,14 +798,14 @@ } return _b; }).call(this); - last_noncom = non_comments[non_comments.length - 1]; + lastNoncom = nonComments[nonComments.length - 1]; props = (function() { _f = []; _g = this.properties; for (i = 0, _h = _g.length; i < _h; i++) { prop = _g[i]; _f.push((function() { join = ",\n"; - if ((prop === last_noncom) || (prop instanceof CommentNode)) { + if ((prop === lastNoncom) || (prop instanceof CommentNode)) { join = "\n"; } if (i === this.properties.length - 1) { @@ -831,15 +831,15 @@ exports.ArrayNode = (function() { ArrayNode = function(objects) { this.objects = objects || []; - this.compile_splat_literal = function(o) { - return SplatNode.compile_mixed_array.call(this, this.objects, o); + this.compileSplatLiteral = function(o) { + return SplatNode.compileMixedArray.call(this, this.objects, o); }; return this; }; __extends(ArrayNode, BaseNode); ArrayNode.prototype.type = 'ArrayNode'; ArrayNode.prototype.children = ['objects']; - ArrayNode.prototype.compile_node = function(o) { + ArrayNode.prototype.compileNode = function(o) { var _b, _c, code, i, obj, objects; o.indent = this.idt(1); objects = []; @@ -848,7 +848,7 @@ obj = _b[i]; code = obj.compile(o); if (obj instanceof SplatNode) { - return this.compile_splat_literal(this.objects, o); + return this.compileSplatLiteral(this.objects, o); } else if (obj instanceof CommentNode) { objects.push(("\n" + code + "\n" + o.indent)); } else if (i === this.objects.length - 1) { @@ -858,7 +858,7 @@ } } objects = objects.join(''); - if (index_of(objects, '\n') >= 0) { + if (indexOf(objects, '\n') >= 0) { return "[\n" + (this.idt(1)) + objects + "\n" + this.tab + "]"; } else { return "[" + objects + "]"; @@ -879,19 +879,19 @@ __extends(ClassNode, BaseNode); ClassNode.prototype.type = 'ClassNode'; ClassNode.prototype.children = ['variable', 'parent', 'properties']; - ClassNode.prototype.is_statement = function() { + ClassNode.prototype.isStatement = function() { return true; }; // Initialize a **ClassNode** with its name, an optional superclass, and a // list of prototype property assignments. - ClassNode.prototype.make_return = function() { + ClassNode.prototype.makeReturn = function() { this.returns = true; return this; }; // Instead of generating the JavaScript string directly, we build up the // equivalent syntax tree and compile that, in pieces. You can see the // constructor, property assignments, and inheritance getting built out below. - ClassNode.prototype.compile_node = function(o) { + ClassNode.prototype.compileNode = function(o) { var _b, _c, _d, _e, access, applied, construct, extension, func, prop, props, pvar, returns, val; extension = this.parent && new ExtendsNode(this.variable, this.parent); constructor = null; @@ -950,34 +950,34 @@ AssignNode.prototype.LEADING_DOT = /^\.(prototype\.)?/; AssignNode.prototype.type = 'AssignNode'; AssignNode.prototype.children = ['variable', 'value']; - AssignNode.prototype.top_sensitive = function() { + AssignNode.prototype.topSensitive = function() { return true; }; - AssignNode.prototype.is_value = function() { + AssignNode.prototype.isValue = function() { return this.variable instanceof ValueNode; }; - AssignNode.prototype.make_return = function() { + AssignNode.prototype.makeReturn = function() { return new Expressions([this, new ReturnNode(this.variable)]); }; - AssignNode.prototype.is_statement = function() { - return this.is_value() && (this.variable.is_array() || this.variable.is_object()); + AssignNode.prototype.isStatement = function() { + return this.isValue() && (this.variable.isArray() || this.variable.isObject()); }; - // Compile an assignment, delegating to `compile_pattern_match` or - // `compile_splice` if appropriate. Keep track of the name of the base object + // Compile an assignment, delegating to `compilePatternMatch` or + // `compileSplice` if appropriate. Keep track of the name of the base object // we've been assigned to, for correct internal references. If the variable // has not been seen yet within the current scope, declare it. - AssignNode.prototype.compile_node = function(o) { + AssignNode.prototype.compileNode = function(o) { var last, match, name, proto, stmt, top, val; top = del(o, 'top'); - if (this.is_statement()) { - return this.compile_pattern_match(o); + if (this.isStatement()) { + return this.compilePatternMatch(o); } - if (this.is_value() && this.variable.is_splice()) { - return this.compile_splice(o); + if (this.isValue() && this.variable.isSplice()) { + return this.compileSplice(o); } - stmt = del(o, 'as_statement'); + stmt = del(o, 'asStatement'); name = this.variable.compile(o); - last = this.is_value() ? this.variable.last.replace(this.LEADING_DOT, '') : name; + last = this.isValue() ? this.variable.last.replace(this.LEADING_DOT, '') : name; match = name.match(this.PROTO_ASSIGN); proto = match && match[1]; if (this.value instanceof CodeNode) { @@ -992,7 +992,7 @@ if (this.context === 'object') { return ("" + name + ": " + val); } - if (!(this.is_value() && (this.variable.has_properties() || this.variable.namespaced))) { + if (!(this.isValue() && (this.variable.hasProperties() || this.variable.namespaced))) { o.scope.find(name); } val = ("" + name + " = " + val); @@ -1009,20 +1009,20 @@ // object literals to a value. Peeks at their properties to assign inner names. // See the [ECMAScript Harmony Wiki](http://wiki.ecmascript.org/doku.php?id=harmony:destructuring) // for details. - AssignNode.prototype.compile_pattern_match = function(o) { - var _b, _c, _d, access_class, assigns, code, i, idx, is_string, obj, oindex, olength, splat, val, val_var, value; - val_var = o.scope.free_variable(); - value = this.value.is_statement() ? ClosureNode.wrap(this.value) : this.value; - assigns = [("" + this.tab + val_var + " = " + (value.compile(o)) + ";")]; + AssignNode.prototype.compilePatternMatch = function(o) { + var _b, _c, _d, accessClass, assigns, code, i, idx, isString, obj, oindex, olength, splat, val, valVar, value; + valVar = o.scope.freeVariable(); + value = this.value.isStatement() ? ClosureNode.wrap(this.value) : this.value; + assigns = [("" + this.tab + valVar + " = " + (value.compile(o)) + ";")]; o.top = true; - o.as_statement = true; + o.asStatement = true; splat = false; _b = this.variable.base.objects; for (i = 0, _c = _b.length; i < _c; i++) { obj = _b[i]; // A regular array pattern-match. idx = i; - if (this.variable.is_object()) { + if (this.variable.isObject()) { if (obj instanceof AssignNode) { // A regular object pattern-match. _d = [obj.value, obj.variable.base]; @@ -1036,16 +1036,16 @@ if (!(obj instanceof ValueNode || obj instanceof SplatNode)) { throw new Error('pattern matching must use only identifiers on the left-hand side.'); } - is_string = idx.value && idx.value.match(IS_STRING); - access_class = is_string || this.variable.is_array() ? IndexNode : AccessorNode; + isString = idx.value && idx.value.match(IS_STRING); + accessClass = isString || this.variable.isArray() ? IndexNode : AccessorNode; if (obj instanceof SplatNode && !splat) { - val = literal(obj.compile_value(o, val_var, (oindex = index_of(this.variable.base.objects, obj)), (olength = this.variable.base.objects.length) - oindex - 1)); + val = literal(obj.compileValue(o, valVar, (oindex = indexOf(this.variable.base.objects, obj)), (olength = this.variable.base.objects.length) - oindex - 1)); splat = true; } else { if (typeof idx !== 'object') { - idx = literal(splat ? ("" + (val_var) + ".length - " + (olength - idx)) : idx); + idx = literal(splat ? ("" + (valVar) + ".length - " + (olength - idx)) : idx); } - val = new ValueNode(literal(val_var), [new access_class(idx)]); + val = new ValueNode(literal(valVar), [new accessClass(idx)]); } assigns.push(new AssignNode(obj, val).compile(o)); } @@ -1054,10 +1054,10 @@ }; // Compile the assignment from an array splice literal, using JavaScript's // `Array#splice` method. - AssignNode.prototype.compile_splice = function(o) { + AssignNode.prototype.compileSplice = function(o) { var from, l, name, plus, range, to, val; name = this.variable.compile(merge(o, { - only_first: true + onlyFirst: true })); l = this.variable.properties.length; range = this.variable.properties[l - 1].range; @@ -1088,14 +1088,14 @@ // the JavaScript `arguments` objects. If the function is bound with the `=>` // arrow, generates a wrapper that saves the current value of `this` through // a closure. - CodeNode.prototype.compile_node = function(o) { - var _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, code, func, i, inner, param, params, shared_scope, splat, top; - shared_scope = del(o, 'shared_scope'); + CodeNode.prototype.compileNode = function(o) { + var _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, code, func, i, inner, param, params, sharedScope, splat, top; + sharedScope = del(o, 'sharedScope'); top = del(o, 'top'); - o.scope = shared_scope || new Scope(o.scope, this.body, this); + o.scope = sharedScope || new Scope(o.scope, this.body, this); o.top = true; o.indent = this.idt(this.bound ? 2 : 1); - del(o, 'no_wrap'); + del(o, 'noWrap'); del(o, 'globals'); i = 0; splat = undefined; @@ -1124,13 +1124,13 @@ } return _e; })(); - this.body.make_return(); + this.body.makeReturn(); _j = params; for (_i = 0, _k = _j.length; _i < _k; _i++) { param = _j[_i]; (o.scope.parameter(param)); } - code = this.body.expressions.length ? ("\n" + (this.body.compile_with_declarations(o)) + "\n") : ''; + code = this.body.expressions.length ? ("\n" + (this.body.compileWithDeclarations(o)) + "\n") : ''; func = ("function(" + (params.join(', ')) + ") {" + code + (this.idt(this.bound ? 1 : 0)) + "}"); if (top && !this.bound) { func = ("(" + func + ")"); @@ -1141,21 +1141,21 @@ inner = ("(function() {\n" + (this.idt(2)) + "return __func.apply(__this, arguments);\n" + (this.idt(1)) + "});"); return "(function(__this) {\n" + (this.idt(1)) + "var __func = " + func + ";\n" + (this.idt(1)) + "return " + inner + "\n" + this.tab + "})(this)"; }; - CodeNode.prototype.top_sensitive = function() { + CodeNode.prototype.topSensitive = function() { return true; }; - // Short-circuit traverse_children method to prevent it from crossing scope boundaries - // unless cross_scope is true - CodeNode.prototype.traverse_children = function(cross_scope, func) { - if (cross_scope) { - return CodeNode.__superClass__.traverse_children.call(this, cross_scope, func); + // Short-circuit traverseChildren method to prevent it from crossing scope boundaries + // unless crossScope is true + CodeNode.prototype.traverseChildren = function(crossScope, func) { + if (crossScope) { + return CodeNode.__superClass__.traverseChildren.call(this, crossScope, func); } }; CodeNode.prototype.toString = function(idt) { var _b, _c, _d, _e, child, children; idt = idt || ''; children = (function() { - _b = []; _d = this.collect_children(); + _b = []; _d = this.collectChildren(); for (_c = 0, _e = _d.length; _c < _e; _c++) { child = _d[_c]; _b.push(child.toString(idt + TAB)); @@ -1180,23 +1180,23 @@ __extends(SplatNode, BaseNode); SplatNode.prototype.type = 'SplatNode'; SplatNode.prototype.children = ['name']; - SplatNode.prototype.compile_node = function(o) { + SplatNode.prototype.compileNode = function(o) { var _b; if ((typeof (_b = this.index) !== "undefined" && _b !== null)) { - return this.compile_param(o); + return this.compileParam(o); } else { return this.name.compile(o); } }; // Compiling a parameter splat means recovering the parameters that succeed // the splat in the parameter list, by slicing the arguments object. - SplatNode.prototype.compile_param = function(o) { + SplatNode.prototype.compileParam = function(o) { var _b, _c, idx, len, name, pos, trailing, variadic; name = this.name.compile(o); o.scope.find(name); - len = o.scope.free_variable(); + len = o.scope.freeVariable(); o.scope.assign(len, "arguments.length"); - variadic = o.scope.free_variable(); + variadic = o.scope.freeVariable(); o.scope.assign(variadic, ("" + len + " >= " + this.arglength)); _b = this.trailings; for (idx = 0, _c = _b.length; idx < _c; idx++) { @@ -1208,14 +1208,14 @@ }; // A compiling a splat as a destructuring assignment means slicing arguments // from the right-hand-side's corresponding array. - SplatNode.prototype.compile_value = function(o, name, index, trailings) { + SplatNode.prototype.compileValue = function(o, name, index, trailings) { var trail; trail = trailings ? (", " + (name) + ".length - " + trailings) : ''; return "" + (utility('slice')) + ".call(" + name + ", " + index + trail + ")"; }; // Utility function that converts arbitrary number of elements, mixed with // splats, to a proper array - SplatNode.compile_mixed_array = function(list, o) { + SplatNode.compileMixedArray = function(list, o) { var _b, _c, _d, arg, args, code, i, prev; args = []; i = 0; @@ -1261,24 +1261,24 @@ __extends(WhileNode, BaseNode); WhileNode.prototype.type = 'WhileNode'; WhileNode.prototype.children = ['condition', 'guard', 'body']; - WhileNode.prototype.is_statement = function() { + WhileNode.prototype.isStatement = function() { return true; }; - WhileNode.prototype.add_body = function(body) { + WhileNode.prototype.addBody = function(body) { this.body = body; return this; }; - WhileNode.prototype.make_return = function() { + WhileNode.prototype.makeReturn = function() { this.returns = true; return this; }; - WhileNode.prototype.top_sensitive = function() { + WhileNode.prototype.topSensitive = function() { return true; }; // The main difference from a JavaScript *while* is that the CoffeeScript // *while* can be used as a part of a larger expression -- while loops may // return an array containing the computed result of each iteration. - WhileNode.prototype.compile_node = function(o) { + WhileNode.prototype.compileNode = function(o) { var cond, post, pre, rvar, set, top; top = del(o, 'top') && !this.returns; o.indent = this.idt(1); @@ -1286,7 +1286,7 @@ cond = this.condition.compile(o); set = ''; if (!(top)) { - rvar = o.scope.free_variable(); + rvar = o.scope.freeVariable(); set = ("" + this.tab + rvar + " = [];\n"); if (this.body) { this.body = PushNode.wrap(rvar, this.body); @@ -1329,25 +1329,25 @@ OpNode.prototype.PREFIX_OPERATORS = ['typeof', 'delete']; OpNode.prototype.type = 'OpNode'; OpNode.prototype.children = ['first', 'second']; - OpNode.prototype.is_unary = function() { + OpNode.prototype.isUnary = function() { return !this.second; }; - OpNode.prototype.is_chainable = function() { - return index_of(this.CHAINABLE, this.operator) >= 0; + OpNode.prototype.isChainable = function() { + return indexOf(this.CHAINABLE, this.operator) >= 0; }; - OpNode.prototype.compile_node = function(o) { + OpNode.prototype.compileNode = function(o) { o.operation = true; - if (this.is_chainable() && this.first.unwrap() instanceof OpNode && this.first.unwrap().is_chainable()) { - return this.compile_chain(o); + if (this.isChainable() && this.first.unwrap() instanceof OpNode && this.first.unwrap().isChainable()) { + return this.compileChain(o); } - if (index_of(this.ASSIGNMENT, this.operator) >= 0) { - return this.compile_assignment(o); + if (indexOf(this.ASSIGNMENT, this.operator) >= 0) { + return this.compileAssignment(o); } - if (this.is_unary()) { - return this.compile_unary(o); + if (this.isUnary()) { + return this.compileUnary(o); } if (this.operator === '?') { - return this.compile_existence(o); + return this.compileExistence(o); } return [this.first.compile(o), this.operator, this.second.compile(o)].join(' '); }; @@ -1355,11 +1355,11 @@ // used sequentially. For example: // bin/coffee -e "puts 50 < 65 > 10" // true - OpNode.prototype.compile_chain = function(o) { + OpNode.prototype.compileChain = function(o) { var _b, _c, first, second, shared; shared = this.first.unwrap().second; - if (shared.contains_type(CallNode)) { - _b = shared.compile_reference(o); + if (shared.containsType(CallNode)) { + _b = shared.compileReference(o); this.first.second = _b[0]; shared = _b[1]; } @@ -1372,7 +1372,7 @@ // When compiling a conditional assignment, take care to ensure that the // operands are only evaluated once, even though we have to reference them // more than once. - OpNode.prototype.compile_assignment = function(o) { + OpNode.prototype.compileAssignment = function(o) { var _b, first, second; _b = [this.first.compile(o), this.second.compile(o)]; first = _b[0]; @@ -1381,24 +1381,24 @@ o.scope.find(first); } if (this.operator === '?=') { - return ("" + first + " = " + (ExistenceNode.compile_test(o, this.first)) + " ? " + first + " : " + second); + return ("" + first + " = " + (ExistenceNode.compileTest(o, this.first)) + " ? " + first + " : " + second); } return "" + first + " = " + first + " " + (this.operator.substr(0, 2)) + " " + second; }; - // If this is an existence operator, we delegate to `ExistenceNode.compile_test` + // If this is an existence operator, we delegate to `ExistenceNode.compileTest` // to give us the safe references for the variables. - OpNode.prototype.compile_existence = function(o) { + OpNode.prototype.compileExistence = function(o) { var _b, first, second, test; _b = [this.first.compile(o), this.second.compile(o)]; first = _b[0]; second = _b[1]; - test = ExistenceNode.compile_test(o, this.first); + test = ExistenceNode.compileTest(o, this.first); return "" + test + " ? " + first + " : " + second; }; // Compile a unary **OpNode**. - OpNode.prototype.compile_unary = function(o) { + OpNode.prototype.compileUnary = function(o) { var parts, space; - space = index_of(this.PREFIX_OPERATORS, this.operator) >= 0 ? ' ' : ''; + space = indexOf(this.PREFIX_OPERATORS, this.operator) >= 0 ? ' ' : ''; parts = [this.operator, space, this.first.compile(o)]; if (this.flip) { parts = parts.reverse(); @@ -1420,29 +1420,29 @@ __extends(TryNode, BaseNode); TryNode.prototype.type = 'TryNode'; TryNode.prototype.children = ['attempt', 'recovery', 'ensure']; - TryNode.prototype.is_statement = function() { + TryNode.prototype.isStatement = function() { return true; }; - TryNode.prototype.make_return = function() { + TryNode.prototype.makeReturn = function() { if (this.attempt) { - this.attempt = this.attempt.make_return(); + this.attempt = this.attempt.makeReturn(); } if (this.recovery) { - this.recovery = this.recovery.make_return(); + this.recovery = this.recovery.makeReturn(); } return this; }; // Compilation is more or less as you would expect -- the *finally* clause // is optional, the *catch* is not. - TryNode.prototype.compile_node = function(o) { - var attempt_part, catch_part, error_part, finally_part; + TryNode.prototype.compileNode = function(o) { + var attemptPart, catchPart, errorPart, finallyPart; o.indent = this.idt(1); o.top = true; - attempt_part = this.attempt.compile(o); - error_part = this.error ? (" (" + (this.error.compile(o)) + ") ") : ' '; - catch_part = this.recovery ? (" catch" + error_part + "{\n" + (this.recovery.compile(o)) + "\n" + this.tab + "}") : ''; - finally_part = (this.ensure || '') && ' finally {\n' + this.ensure.compile(merge(o)) + ("\n" + this.tab + "}"); - return "" + (this.tab) + "try {\n" + attempt_part + "\n" + this.tab + "}" + catch_part + finally_part; + 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; }; return TryNode; })(); @@ -1456,14 +1456,14 @@ __extends(ThrowNode, BaseNode); ThrowNode.prototype.type = 'ThrowNode'; ThrowNode.prototype.children = ['expression']; - ThrowNode.prototype.is_statement = function() { + ThrowNode.prototype.isStatement = function() { return true; }; // A **ThrowNode** is already a return, of sorts... - ThrowNode.prototype.make_return = function() { + ThrowNode.prototype.makeReturn = function() { return this; }; - ThrowNode.prototype.compile_node = function(o) { + ThrowNode.prototype.compileNode = function(o) { return "" + (this.tab) + "throw " + (this.expression.compile(o)) + ";"; }; return ThrowNode; @@ -1480,15 +1480,15 @@ __extends(ExistenceNode, BaseNode); ExistenceNode.prototype.type = 'ExistenceNode'; ExistenceNode.prototype.children = ['expression']; - ExistenceNode.prototype.compile_node = function(o) { - return ExistenceNode.compile_test(o, this.expression); + ExistenceNode.prototype.compileNode = function(o) { + return ExistenceNode.compileTest(o, this.expression); }; - // The meat of the **ExistenceNode** is in this static `compile_test` method + // The meat of the **ExistenceNode** is in this static `compileTest` method // because other nodes like to check the existence of their variables as well. // Be careful not to double-evaluate anything. - ExistenceNode.compile_test = function(o, variable) { + ExistenceNode.compileTest = function(o, variable) { var _b, first, second; - _b = variable.compile_reference(o, true); + _b = variable.compileReference(o, true); first = _b[0]; second = _b[1]; return "(typeof " + (first.compile(o)) + " !== \"undefined\" && " + (second.compile(o)) + " !== null)"; @@ -1508,16 +1508,16 @@ __extends(ParentheticalNode, BaseNode); ParentheticalNode.prototype.type = 'ParentheticalNode'; ParentheticalNode.prototype.children = ['expression']; - ParentheticalNode.prototype.is_statement = function() { - return this.expression.is_statement(); + ParentheticalNode.prototype.isStatement = function() { + return this.expression.isStatement(); }; - ParentheticalNode.prototype.make_return = function() { - return this.expression.make_return(); + ParentheticalNode.prototype.makeReturn = function() { + return this.expression.makeReturn(); }; - ParentheticalNode.prototype.compile_node = function(o) { + ParentheticalNode.prototype.compileNode = function(o) { var code, l; code = this.expression.compile(o); - if (this.is_statement()) { + if (this.isStatement()) { return code; } l = code.length; @@ -1564,17 +1564,17 @@ __extends(ForNode, BaseNode); ForNode.prototype.type = 'ForNode'; ForNode.prototype.children = ['body', 'source', 'guard']; - ForNode.prototype.is_statement = function() { + ForNode.prototype.isStatement = function() { return true; }; - ForNode.prototype.top_sensitive = function() { + ForNode.prototype.topSensitive = function() { return true; }; - ForNode.prototype.make_return = function() { + ForNode.prototype.makeReturn = function() { this.returns = true; return this; }; - ForNode.prototype.compile_return_value = function(val, o) { + ForNode.prototype.compileReturnValue = function(val, o) { if (this.returns) { return '\n' + new ReturnNode(literal(val)).compile(o); } @@ -1587,9 +1587,9 @@ // loop, filtering, stepping, and result saving for array, object, and range // comprehensions. Some of the generated code can be shared in common, and // some cannot. - ForNode.prototype.compile_node = function(o) { - var body, body_dent, close, for_part, index, ivar, lvar, name, range, return_result, rvar, scope, source, source_part, step_part, svar, top_level, var_part, vars; - top_level = del(o, 'top') && !this.returns; + ForNode.prototype.compileNode = function(o) { + var body, bodyDent, close, forPart, index, ivar, lvar, name, range, returnResult, rvar, scope, source, sourcePart, stepPart, svar, topLevel, varPart, vars; + topLevel = del(o, 'top') && !this.returns; range = this.source instanceof ValueNode && this.source.base instanceof RangeNode && !this.source.properties.length; source = range ? this.source.base : this.source; scope = o.scope; @@ -1601,58 +1601,58 @@ if (index) { scope.find(index); } - body_dent = this.idt(1); - if (!(top_level)) { - rvar = scope.free_variable(); + bodyDent = this.idt(1); + if (!(topLevel)) { + rvar = scope.freeVariable(); } - ivar = range ? name : index || scope.free_variable(); - var_part = ''; + ivar = range ? name : index || scope.freeVariable(); + varPart = ''; body = Expressions.wrap([this.body]); if (range) { - source_part = source.compile_variables(o); - for_part = source.compile(merge(o, { + sourcePart = source.compileVariables(o); + forPart = source.compile(merge(o, { index: ivar, step: this.step })); } else { - svar = scope.free_variable(); - source_part = ("" + svar + " = " + (this.source.compile(o)) + ";"); + svar = scope.freeVariable(); + sourcePart = ("" + svar + " = " + (this.source.compile(o)) + ";"); if (this.pattern) { - var_part = new AssignNode(this.name, literal(("" + svar + "[" + ivar + "]"))).compile(merge(o, { + varPart = new AssignNode(this.name, literal(("" + svar + "[" + ivar + "]"))).compile(merge(o, { indent: this.idt(1), top: true })) + "\n"; } else { if (name) { - var_part = ("" + body_dent + name + " = " + svar + "[" + ivar + "];\n"); + varPart = ("" + bodyDent + name + " = " + svar + "[" + ivar + "];\n"); } } if (!(this.object)) { - lvar = scope.free_variable(); - step_part = this.step ? ("" + ivar + " += " + (this.step.compile(o))) : ("" + ivar + "++"); - for_part = ("" + ivar + " = 0, " + lvar + " = " + (svar) + ".length; " + ivar + " < " + lvar + "; " + step_part); + lvar = scope.freeVariable(); + stepPart = this.step ? ("" + ivar + " += " + (this.step.compile(o))) : ("" + ivar + "++"); + forPart = ("" + ivar + " = 0, " + lvar + " = " + (svar) + ".length; " + ivar + " < " + lvar + "; " + stepPart); } } - source_part = (rvar ? ("" + rvar + " = []; ") : '') + source_part; - source_part = source_part ? ("" + this.tab + source_part + "\n" + this.tab) : this.tab; - return_result = this.compile_return_value(rvar, o); - if (top_level && body.contains(function(n) { + sourcePart = (rvar ? ("" + rvar + " = []; ") : '') + sourcePart; + sourcePart = sourcePart ? ("" + this.tab + sourcePart + "\n" + this.tab) : this.tab; + returnResult = this.compileReturnValue(rvar, o); + if (topLevel && body.contains(function(n) { return n instanceof CodeNode; })) { body = ClosureNode.wrap(body, true); } - if (!(top_level)) { + if (!(topLevel)) { body = PushNode.wrap(rvar, body); } this.guard ? (body = Expressions.wrap([new IfNode(this.guard, body)])) : null; - this.object ? (for_part = ("" + ivar + " in " + svar + ") { if (" + (utility('hasProp')) + ".call(" + svar + ", " + ivar + ")")) : null; + this.object ? (forPart = ("" + ivar + " in " + svar + ") { if (" + (utility('hasProp')) + ".call(" + svar + ", " + ivar + ")")) : null; body = body.compile(merge(o, { - indent: body_dent, + indent: bodyDent, top: true })); vars = range ? name : ("" + name + ", " + ivar); close = this.object ? '}}' : '}'; - return "" + (source_part) + "for (" + for_part + ") {\n" + var_part + body + "\n" + this.tab + close + return_result; + return "" + (sourcePart) + "for (" + forPart + ") {\n" + varPart + body + "\n" + this.tab + close + returnResult; }; return ForNode; })(); @@ -1665,42 +1665,42 @@ IfNode = function(condition, body, tags) { this.condition = condition; this.body = body; - this.else_body = null; + this.elseBody = null; this.tags = tags || {}; if (this.tags.invert) { this.condition = new OpNode('!', new ParentheticalNode(this.condition)); } - this.is_chain = false; + this.isChain = false; return this; }; __extends(IfNode, BaseNode); IfNode.prototype.type = 'IfNode'; - IfNode.prototype.children = ['condition', 'switch_subject', 'body', 'else_body', 'assigner']; - IfNode.prototype.body_node = function() { + IfNode.prototype.children = ['condition', 'switchSubject', 'body', 'elseBody', 'assigner']; + IfNode.prototype.bodyNode = function() { return this.body == undefined ? undefined : this.body.unwrap(); }; - IfNode.prototype.else_body_node = function() { - return this.else_body == undefined ? undefined : this.else_body.unwrap(); + IfNode.prototype.elseBodyNode = function() { + return this.elseBody == undefined ? undefined : this.elseBody.unwrap(); }; - IfNode.prototype.force_statement = function() { + IfNode.prototype.forceStatement = function() { this.tags.statement = true; return this; }; // Tag a chain of **IfNodes** with their object(s) to switch on for equality - // tests. `rewrite_switch` will perform the actual change at compile time. - IfNode.prototype.switches_over = function(expression) { - this.switch_subject = expression; + // tests. `rewriteSwitch` will perform the actual change at compile time. + IfNode.prototype.switchesOver = function(expression) { + this.switchSubject = expression; return this; }; // Rewrite a chain of **IfNodes** with their switch condition for equality. // Ensure that the switch expression isn't evaluated more than once. - IfNode.prototype.rewrite_switch = function(o) { + IfNode.prototype.rewriteSwitch = function(o) { var _b, _c, _d, cond, i, variable; - this.assigner = this.switch_subject; - if (!((this.switch_subject.unwrap() instanceof LiteralNode))) { - variable = literal(o.scope.free_variable()); - this.assigner = new AssignNode(variable, this.switch_subject); - this.switch_subject = variable; + this.assigner = this.switchSubject; + if (!((this.switchSubject.unwrap() instanceof LiteralNode))) { + variable = literal(o.scope.freeVariable()); + this.assigner = new AssignNode(variable, this.switchSubject); + this.switchSubject = variable; } this.condition = (function() { _b = []; _c = flatten([this.condition]); @@ -1710,34 +1710,34 @@ if (cond instanceof OpNode) { cond = new ParentheticalNode(cond); } - return new OpNode('==', (i === 0 ? this.assigner : this.switch_subject), cond); + return new OpNode('==', (i === 0 ? this.assigner : this.switchSubject), cond); }).call(this)); } return _b; }).call(this); - if (this.is_chain) { - this.else_body_node().switches_over(this.switch_subject); + if (this.isChain) { + this.elseBodyNode().switchesOver(this.switchSubject); } // prevent this rewrite from happening again - this.switch_subject = undefined; + this.switchSubject = undefined; return this; }; // Rewrite a chain of **IfNodes** to add a default case as the final *else*. - IfNode.prototype.add_else = function(else_body, statement) { - if (this.is_chain) { - this.else_body_node().add_else(else_body, statement); + IfNode.prototype.addElse = function(elseBody, statement) { + if (this.isChain) { + this.elseBodyNode().addElse(elseBody, statement); } else { - this.is_chain = else_body instanceof IfNode; - this.else_body = this.ensure_expressions(else_body); + this.isChain = elseBody instanceof IfNode; + this.elseBody = this.ensureExpressions(elseBody); } return this; }; // The **IfNode** only compiles into a statement if either of its bodies needs // to be a statement. Otherwise a ternary is safe. - IfNode.prototype.is_statement = function() { - return this.statement = this.statement || !!(this.comment || this.tags.statement || this.body_node().is_statement() || (this.else_body && this.else_body_node().is_statement())); + IfNode.prototype.isStatement = function() { + return this.statement = this.statement || !!(this.comment || this.tags.statement || this.bodyNode().isStatement() || (this.elseBody && this.elseBodyNode().isStatement())); }; - IfNode.prototype.compile_condition = function(o) { + IfNode.prototype.compileCondition = function(o) { var _b, _c, _d, _e, cond; return (function() { _b = []; _d = flatten([this.condition]); @@ -1748,19 +1748,19 @@ return _b; }).call(this).join(' || '); }; - IfNode.prototype.compile_node = function(o) { - if (this.is_statement()) { - return this.compile_statement(o); + IfNode.prototype.compileNode = function(o) { + if (this.isStatement()) { + return this.compileStatement(o); } else { - return this.compile_ternary(o); + return this.compileTernary(o); } }; - IfNode.prototype.make_return = function() { - this.body = this.body && this.ensure_expressions(this.body.make_return()); - this.else_body = this.else_body && this.ensure_expressions(this.else_body.make_return()); + IfNode.prototype.makeReturn = function() { + this.body = this.body && this.ensureExpressions(this.body.makeReturn()); + this.elseBody = this.elseBody && this.ensureExpressions(this.elseBody.makeReturn()); return this; }; - IfNode.prototype.ensure_expressions = function(node) { + IfNode.prototype.ensureExpressions = function(node) { if (!(node instanceof Expressions)) { node = new Expressions([node]); } @@ -1768,35 +1768,35 @@ }; // Compile the **IfNode** as a regular *if-else* statement. Flattened chains // force inner *else* bodies into statement form. - IfNode.prototype.compile_statement = function(o) { - var body, child, com_dent, cond_o, else_part, if_dent, if_part, prefix; - if (this.switch_subject) { - this.rewrite_switch(o); + IfNode.prototype.compileStatement = function(o) { + var body, child, comDent, condO, elsePart, ifDent, ifPart, prefix; + if (this.switchSubject) { + this.rewriteSwitch(o); } - child = del(o, 'chain_child'); - cond_o = merge(o); + child = del(o, 'chainChild'); + condO = merge(o); o.indent = this.idt(1); o.top = true; - if_dent = child ? '' : this.idt(); - com_dent = child ? this.idt() : ''; - prefix = this.comment ? ("" + (this.comment.compile(cond_o)) + "\n" + com_dent) : ''; + ifDent = child ? '' : this.idt(); + comDent = child ? this.idt() : ''; + prefix = this.comment ? ("" + (this.comment.compile(condO)) + "\n" + comDent) : ''; body = this.body.compile(o); - if_part = ("" + prefix + (if_dent) + "if (" + (this.compile_condition(cond_o)) + ") {\n" + body + "\n" + this.tab + "}"); - if (!(this.else_body)) { - return if_part; + ifPart = ("" + prefix + (ifDent) + "if (" + (this.compileCondition(condO)) + ") {\n" + body + "\n" + this.tab + "}"); + if (!(this.elseBody)) { + return ifPart; } - else_part = this.is_chain ? ' else ' + this.else_body_node().compile(merge(o, { + elsePart = this.isChain ? ' else ' + this.elseBodyNode().compile(merge(o, { indent: this.idt(), - chain_child: true - })) : (" else {\n" + (this.else_body.compile(o)) + "\n" + this.tab + "}"); - return "" + if_part + else_part; + chainChild: true + })) : (" else {\n" + (this.elseBody.compile(o)) + "\n" + this.tab + "}"); + return "" + ifPart + elsePart; }; // Compile the IfNode as a ternary operator. - IfNode.prototype.compile_ternary = function(o) { - var else_part, if_part; - if_part = this.condition.compile(o) + ' ? ' + this.body_node().compile(o); - else_part = this.else_body ? this.else_body_node().compile(o) : 'null'; - return "" + if_part + " : " + else_part; + IfNode.prototype.compileTernary = function(o) { + var elsePart, ifPart; + ifPart = this.condition.compile(o) + ' ? ' + this.bodyNode().compile(o); + elsePart = this.elseBody ? this.elseBodyNode().compile(o) : 'null'; + return "" + ifPart + " : " + elsePart; }; return IfNode; })(); @@ -1811,7 +1811,7 @@ wrap: function(array, expressions) { var expr; expr = expressions.unwrap(); - if (expr.is_pure_statement() || expr.contains_pure_statement()) { + if (expr.isPureStatement() || expr.containsPureStatement()) { return expressions; } return Expressions.wrap([new CallNode(new ValueNode(literal(array), [new AccessorNode(literal('push'))]), [expr])]); @@ -1824,22 +1824,22 @@ // in which case, no dice. If the body mentions `this` or `arguments`, // then make sure that the closure wrapper preserves the original values. wrap: function(expressions, statement) { - var args, call, func, mentions_args, mentions_this, meth; - if (expressions.contains_pure_statement()) { + var args, call, func, mentionsArgs, mentionsThis, meth; + if (expressions.containsPureStatement()) { return expressions; } func = new ParentheticalNode(new CodeNode([], Expressions.wrap([expressions]))); args = []; - mentions_args = expressions.contains(function(n) { + mentionsArgs = expressions.contains(function(n) { return (n instanceof LiteralNode) && (n.value === 'arguments'); }); - mentions_this = expressions.contains(function(n) { + mentionsThis = expressions.contains(function(n) { return (n instanceof LiteralNode) && (n.value === 'this'); }); - if (mentions_args || mentions_this) { - meth = literal(mentions_args ? 'apply' : 'call'); + if (mentionsArgs || mentionsThis) { + meth = literal(mentionsArgs ? 'apply' : 'call'); args = [literal('this')]; - if (mentions_args) { + if (mentionsArgs) { args.push(literal('arguments')); } func = new ValueNode(func, [new AccessorNode(meth)]); @@ -1857,7 +1857,7 @@ UTILITIES = { // Correctly set up a prototype chain for inheritance, including a reference // to the superclass for `super()` calls. See: - // [goog.inherits](http://closure-library.googlecode.com/svn/docs/closure_goog_base.js.source.html#line1206). + // [goog.inherits](http://closure-library.googlecode.com/svn/docs/closureGoogBase.js.source.html#line1206). __extends: "function(child, parent) {\n var ctor = function(){ };\n ctor.prototype = parent.prototype;\n child.__superClass__ = parent.prototype;\n child.prototype = new ctor();\n child.prototype.constructor = child;\n }", // Shortcuts to speed up the lookup time for native functions. __hasProp: 'Object.prototype.hasOwnProperty', diff --git a/lib/optparse.js b/lib/optparse.js index 07858476cf..5e1b65b48d 100755 --- a/lib/optparse.js +++ b/lib/optparse.js @@ -1,13 +1,13 @@ (function(){ - var LONG_FLAG, MULTI_FLAG, OPTIONAL, OptionParser, SHORT_FLAG, build_rule, build_rules, normalize_arguments; + var LONG_FLAG, MULTI_FLAG, OPTIONAL, OptionParser, SHORT_FLAG, buildRule, buildRules, normalizeArguments; // A simple **OptionParser** class to parse option flags from the command-line. // Use it like so: - // parser: new OptionParser switches, help_banner + // parser: new OptionParser switches, helpBanner // options: parser.parse process.argv exports.OptionParser = (function() { OptionParser = function(rules, banner) { this.banner = banner; - this.rules = build_rules(rules); + this.rules = buildRules(rules); return this; }; // Initialize with a list of valid options, in the form: @@ -19,27 +19,27 @@ // many option parsers that allow you to attach callback actions for every // flag. Instead, you're responsible for interpreting the options object. OptionParser.prototype.parse = function(args) { - var _a, _b, _c, arg, is_option, matched_rule, options, rule; + var _a, _b, _c, arg, isOption, matchedRule, options, rule; options = { arguments: [] }; - args = normalize_arguments(args); + args = normalizeArguments(args); while ((arg = args.shift())) { - is_option = !!(arg.match(LONG_FLAG) || arg.match(SHORT_FLAG)); - matched_rule = false; + isOption = !!(arg.match(LONG_FLAG) || arg.match(SHORT_FLAG)); + matchedRule = false; _b = this.rules; for (_a = 0, _c = _b.length; _a < _c; _a++) { rule = _b[_a]; - if (rule.short_flag === arg || rule.long_flag === arg) { - options[rule.name] = rule.has_argument ? args.shift() : true; - matched_rule = true; + if (rule.shortFlag === arg || rule.longFlag === arg) { + options[rule.name] = rule.hasArgument ? args.shift() : true; + matchedRule = true; break; } } - if (is_option && !matched_rule) { + if (isOption && !matchedRule) { throw new Error(("unrecognized option: " + arg)); } - if (!(is_option)) { + if (!(isOption)) { options.arguments.push(arg); } } @@ -48,7 +48,7 @@ // Return the help text for this **OptionParser**, listing and describing all // of the valid options, for `--help` and such. OptionParser.prototype.help = function() { - var _a, _b, _c, _d, i, let_part, lines, rule, spaces; + var _a, _b, _c, _d, i, letPart, lines, rule, spaces; lines = ['Available options:']; if (this.banner) { lines.unshift(("" + this.banner + "\n")); @@ -56,7 +56,7 @@ _b = this.rules; for (_a = 0, _c = _b.length; _a < _c; _a++) { rule = _b[_a]; - spaces = 15 - rule.long_flag.length; + spaces = 15 - rule.longFlag.length; spaces = spaces > 0 ? (function() { _d = []; for (i = 0; i <= spaces; i += 1) { @@ -64,8 +64,8 @@ } return _d; })().join('') : ''; - let_part = rule.short_flag ? rule.short_flag + ', ' : ' '; - lines.push((" " + let_part + rule.long_flag + spaces + rule.description)); + letPart = rule.shortFlag ? rule.shortFlag + ', ' : ' '; + lines.push((" " + letPart + rule.longFlag + spaces + rule.description)); } return "\n" + (lines.join('\n')) + "\n"; }; @@ -80,7 +80,7 @@ OPTIONAL = /\[(.+)\]/; // Build and return the list of option rules. If the optional *short-flag* is // unspecified, leave it out by padding with `null`. - build_rules = function(rules) { + buildRules = function(rules) { var _a, _b, _c, _d, tuple; _a = []; _c = rules; for (_b = 0, _d = _c.length; _b < _d; _b++) { @@ -89,28 +89,28 @@ if (tuple.length < 3) { tuple.unshift(null); } - return build_rule.apply(this, tuple); + return buildRule.apply(this, tuple); })()); } return _a; }; // Build a rule from a `-o` short flag, a `--output [DIR]` long flag, and the // description of what the option does. - build_rule = function(short_flag, long_flag, description) { + buildRule = function(shortFlag, longFlag, description) { var match; - match = long_flag.match(OPTIONAL); - long_flag = long_flag.match(LONG_FLAG)[1]; + match = longFlag.match(OPTIONAL); + longFlag = longFlag.match(LONG_FLAG)[1]; return { - name: long_flag.substr(2), - short_flag: short_flag, - long_flag: long_flag, + name: longFlag.substr(2), + shortFlag: shortFlag, + longFlag: longFlag, description: description, - has_argument: !!(match && match[1]) + hasArgument: !!(match && match[1]) }; }; // Normalize arguments by expanding merged flags into multiple flags. This allows // you to have `-wl` be the same as `--watch --lint`. - normalize_arguments = function(args) { + normalizeArguments = function(args) { var _a, _b, _c, _d, _e, _f, arg, l, match, result; args = args.slice(0); result = []; diff --git a/lib/parser.js b/lib/parser.js index d122b38244..8dd4c0c94a 100755 --- a/lib/parser.js +++ b/lib/parser.js @@ -184,7 +184,7 @@ break; case 87:this.$ = new IndexNode($$[$0-3+2-1]); break; case 88:this.$ = (function () { - $$[$0-2+2-1].soak_node = true; + $$[$0-2+2-1].soakNode = true; return $$[$0-2+2-1]; }()); break; @@ -225,7 +225,7 @@ case 104:this.$ = $$[$0-3+1-1].concat($$[$0-3+3-1]); break; case 105:this.$ = $$[$0-1+1-1]; break; -case 106:this.$ = $$[$0-2+2-1].new_instance(); +case 106:this.$ = $$[$0-2+2-1].newInstance(); break; case 107:this.$ = $$[$0-1+1-1]; break; @@ -304,17 +304,17 @@ case 138:this.$ = new WhileNode($$[$0-4+2-1], { guard: $$[$0-4+4-1] }); break; -case 139:this.$ = $$[$0-2+1-1].add_body($$[$0-2+2-1]); +case 139:this.$ = $$[$0-2+1-1].addBody($$[$0-2+2-1]); break; -case 140:this.$ = $$[$0-2+2-1].add_body(Expressions.wrap([$$[$0-2+1-1]])); +case 140:this.$ = $$[$0-2+2-1].addBody(Expressions.wrap([$$[$0-2+1-1]])); break; -case 141:this.$ = $$[$0-2+2-1].add_body(Expressions.wrap([$$[$0-2+1-1]])); +case 141:this.$ = $$[$0-2+2-1].addBody(Expressions.wrap([$$[$0-2+1-1]])); break; case 142:this.$ = $$[$0-1+1-1]; break; -case 143:this.$ = new WhileNode(new LiteralNode('true')).add_body($$[$0-2+2-1]); +case 143:this.$ = new WhileNode(new LiteralNode('true')).addBody($$[$0-2+2-1]); break; -case 144:this.$ = new WhileNode(new LiteralNode('true')).add_body(Expressions.wrap([$$[$0-2+2-1]])); +case 144:this.$ = new WhileNode(new LiteralNode('true')).addBody(Expressions.wrap([$$[$0-2+2-1]])); break; case 145:this.$ = new ForNode($$[$0-4+1-1], $$[$0-4+4-1], $$[$0-4+3-1][0], $$[$0-4+3-1][1]); break; @@ -369,17 +369,17 @@ case 159:this.$ = { guard: $$[$0-6+6-1] }; break; -case 160:this.$ = $$[$0-5+4-1].switches_over($$[$0-5+2-1]); +case 160:this.$ = $$[$0-5+4-1].switchesOver($$[$0-5+2-1]); break; -case 161:this.$ = $$[$0-7+4-1].switches_over($$[$0-7+2-1]).add_else($$[$0-7+6-1], true); +case 161:this.$ = $$[$0-7+4-1].switchesOver($$[$0-7+2-1]).addElse($$[$0-7+6-1], true); break; case 162:this.$ = $$[$0-4+3-1]; break; -case 163:this.$ = $$[$0-6+3-1].add_else($$[$0-6+5-1], true); +case 163:this.$ = $$[$0-6+3-1].addElse($$[$0-6+5-1], true); break; case 164:this.$ = $$[$0-1+1-1]; break; -case 165:this.$ = $$[$0-2+1-1].add_else($$[$0-2+2-1]); +case 165:this.$ = $$[$0-2+1-1].addElse($$[$0-2+2-1]); break; case 166:this.$ = new IfNode($$[$0-3+2-1], $$[$0-3+3-1], { statement: true @@ -400,11 +400,11 @@ case 170:this.$ = new IfNode($$[$0-3+2-1], $$[$0-3+3-1], { invert: true }); break; -case 171:this.$ = $$[$0-5+1-1].add_else((new IfNode($$[$0-5+4-1], $$[$0-5+5-1])).force_statement()); +case 171:this.$ = $$[$0-5+1-1].addElse((new IfNode($$[$0-5+4-1], $$[$0-5+5-1])).forceStatement()); break; case 172:this.$ = $$[$0-1+1-1]; break; -case 173:this.$ = $$[$0-3+1-1].add_else($$[$0-3+3-1]); +case 173:this.$ = $$[$0-3+1-1].addElse($$[$0-3+3-1]); break; case 174:this.$ = $$[$0-1+1-1]; break; diff --git a/lib/repl.js b/lib/repl.js index a9842d3a3c..04a728725f 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -23,7 +23,7 @@ var val; try { val = CoffeeScript.run(buffer.toString(), { - no_wrap: true, + noWrap: true, globals: true, source: 'repl' }); diff --git a/lib/rewriter.js b/lib/rewriter.js index e1e580dea5..5da03e03f3 100644 --- a/lib/rewriter.js +++ b/lib/rewriter.js @@ -29,14 +29,14 @@ // corrected before implicit parentheses can be wrapped around blocks of code. Rewriter.prototype.rewrite = function(tokens) { this.tokens = tokens; - this.adjust_comments(); - this.remove_leading_newlines(); - this.remove_mid_expression_newlines(); - this.close_open_calls_and_indexes(); - this.add_implicit_indentation(); - this.add_implicit_parentheses(); - this.ensure_balance(BALANCED_PAIRS); - this.rewrite_closing_parens(); + this.adjustComments(); + this.removeLeadingNewlines(); + this.removeMidExpressionNewlines(); + this.closeOpenCallsAndIndexes(); + this.addImplicitIndentation(); + this.addImplicitParentheses(); + this.ensureBalance(BALANCED_PAIRS); + this.rewriteClosingParens(); return this.tokens; }; // Rewrite the token stream, looking one token ahead and behind. @@ -44,7 +44,7 @@ // forwards (or backwards) in the stream, to make sure we don't miss anything // as tokens are inserted and removed, and the stream changes length under // our feet. - Rewriter.prototype.scan_tokens = function(block) { + Rewriter.prototype.scanTokens = function(block) { var i, move; i = 0; while (true) { @@ -58,8 +58,8 @@ }; // Massage newlines and indentations so that comments don't have to be // correctly indented, or appear on a line of their own. - Rewriter.prototype.adjust_comments = function() { - return this.scan_tokens((function(__this) { + Rewriter.prototype.adjustComments = function() { + return this.scanTokens((function(__this) { var __func = function(prev, token, post, i) { var _c, after, before; if (!(include(COMMENTS, token[0]))) { @@ -86,7 +86,7 @@ }; // Leading newlines would introduce an ambiguity in the grammar, so we // dispatch them here. - Rewriter.prototype.remove_leading_newlines = function() { + Rewriter.prototype.removeLeadingNewlines = function() { var _c; _c = []; while (this.tokens[0] && this.tokens[0][0] === 'TERMINATOR') { @@ -96,8 +96,8 @@ }; // Some blocks occur in the middle of expressions -- when we're expecting // this, remove their trailing newlines. - Rewriter.prototype.remove_mid_expression_newlines = function() { - return this.scan_tokens((function(__this) { + Rewriter.prototype.removeMidExpressionNewlines = function() { + return this.scanTokens((function(__this) { var __func = function(prev, token, post, i) { if (!(post && include(EXPRESSION_CLOSE, post[0]) && token[0] === 'TERMINATOR')) { return 1; @@ -113,11 +113,11 @@ // The lexer has tagged the opening parenthesis of a method call, and the // opening bracket of an indexing operation. Match them with their paired // close. - Rewriter.prototype.close_open_calls_and_indexes = function() { + Rewriter.prototype.closeOpenCallsAndIndexes = function() { var brackets, parens; parens = [0]; brackets = [0]; - return this.scan_tokens((function(__this) { + return this.scanTokens((function(__this) { var __func = function(prev, token, post, i) { var _c; if ((_c = token[0]) === 'CALL_START') { @@ -153,10 +153,10 @@ // Methods may be optionally called without parentheses, for simple cases. // Insert the implicit parentheses here, so that the parser doesn't have to // deal with them. - Rewriter.prototype.add_implicit_parentheses = function() { - var close_calls, stack; + Rewriter.prototype.addImplicitParentheses = function() { + var closeCalls, stack; stack = [0]; - close_calls = (function(__this) { + closeCalls = (function(__this) { var __func = function(i) { var _c, size, tmp; (_c = stack[stack.length - 1]); @@ -172,7 +172,7 @@ return __func.apply(__this, arguments); }); })(this); - return this.scan_tokens((function(__this) { + return this.scanTokens((function(__this) { var __func = function(prev, token, post, i) { var _c, j, nx, open, size, tag; tag = token[0]; @@ -190,7 +190,7 @@ } if (include(EXPRESSION_START, tag)) { if (tag === 'INDENT' && !token.generated && open && !(prev && include(IMPLICIT_BLOCK, prev[0]))) { - size = close_calls(i); + size = closeCalls(i); stack.push(0); return size; } @@ -207,7 +207,7 @@ this.tokens.splice(i, 1); } } else { - size = close_calls(i); + size = closeCalls(i); if (tag !== 'OUTDENT' && include(EXPRESSION_END, tag)) { stack.pop(); } @@ -229,8 +229,8 @@ // expressions that lack ending delimiters. The **Rewriter** adds the implicit // blocks, so it doesn't need to. ')' can close a single-line block, // but we need to make sure it's balanced. - Rewriter.prototype.add_implicit_indentation = function() { - return this.scan_tokens((function(__this) { + Rewriter.prototype.addImplicitIndentation = function() { + return this.scanTokens((function(__this) { var __func = function(prev, token, post, i) { var idx, indent, insertion, outdent, parens, pre, starter, tok; if (!(include(SINGLE_LINERS, token[0]) && post[0] !== 'INDENT' && !(token[0] === 'ELSE' && post[0] === 'IF'))) { @@ -273,11 +273,11 @@ }; // Ensure that all listed pairs of tokens are correctly balanced throughout // the course of the token stream. - Rewriter.prototype.ensure_balance = function(pairs) { - var _c, _d, key, levels, line, open, open_line, unclosed, value; + Rewriter.prototype.ensureBalance = function(pairs) { + var _c, _d, key, levels, line, open, openLine, unclosed, value; levels = {}; - open_line = {}; - this.scan_tokens((function(__this) { + openLine = {}; + this.scanTokens((function(__this) { var __func = function(prev, token, post, i) { var _c, _d, _e, _f, close, open, pair; _d = pairs; @@ -289,7 +289,7 @@ levels[open] = levels[open] || 0; if (token[0] === open) { if (levels[open] === 0) { - open_line[open] = token[2]; + openLine[open] = token[2]; } levels[open] += 1; } @@ -316,7 +316,7 @@ })(); if (unclosed.length) { open = unclosed[0]; - line = open_line[open] + 1; + line = openLine[open] + 1; throw new Error(("unclosed " + open + " on line " + line)); } }; @@ -333,7 +333,7 @@ // up balanced in the end. // 4. Be careful not to alter array or parentheses delimiters with overzealous // rewriting. - Rewriter.prototype.rewrite_closing_parens = function() { + Rewriter.prototype.rewriteClosingParens = function() { var _c, debt, key, stack, val; stack = []; debt = {}; @@ -342,7 +342,7 @@ val = _c[key]; (debt[key] = 0); }} - return this.scan_tokens((function(__this) { + return this.scanTokens((function(__this) { var __func = function(prev, token, post, i) { var inv, match, mtag, oppos, tag; tag = token[0]; diff --git a/lib/scope.js b/lib/scope.js index 73067e2470..9e03b5fa02 100644 --- a/lib/scope.js +++ b/lib/scope.js @@ -20,10 +20,10 @@ this.method = _a[2]; this.variables = {}; if (this.parent) { - this.temp_var = this.parent.temp_var; + this.tempVar = this.parent.tempVar; } else { Scope.root = this; - this.temp_var = '_a'; + this.tempVar = '_a'; } return this; }; @@ -69,14 +69,14 @@ }; // If we need to store an intermediate result, find an available name for a // compiler-generated variable. `_a`, `_b`, and so on... - Scope.prototype.free_variable = function() { + Scope.prototype.freeVariable = function() { var ordinal; - while (this.check(this.temp_var)) { - ordinal = 1 + parseInt(this.temp_var.substr(1), 36); - this.temp_var = '_' + ordinal.toString(36).replace(/\d/g, 'a'); + while (this.check(this.tempVar)) { + ordinal = 1 + parseInt(this.tempVar.substr(1), 36); + this.tempVar = '_' + ordinal.toString(36).replace(/\d/g, 'a'); } - this.variables[this.temp_var] = 'var'; - return this.temp_var; + this.variables[this.tempVar] = 'var'; + return this.tempVar; }; // Ensure that an assignment is made at the top of this scope // (or at the top-level scope, if requested). @@ -89,20 +89,20 @@ }; // Does this scope reference any variables that need to be declared in the // given function body? - Scope.prototype.has_declarations = function(body) { + Scope.prototype.hasDeclarations = function(body) { return body === this.expressions && this.any(function(k, val) { return val === 'var'; }); }; // Does this scope reference any assignments that need to be declared at the // top of the given function body? - Scope.prototype.has_assignments = function(body) { + Scope.prototype.hasAssignments = function(body) { return body === this.expressions && this.any(function(k, val) { return val.assigned; }); }; // Return the list of variables first declared in this scope. - Scope.prototype.declared_variables = function() { + Scope.prototype.declaredVariables = function() { var _a, _b, key, val; return (function() { _a = []; _b = this.variables; @@ -115,7 +115,7 @@ }; // Return the list of assignments that are supposed to be made at the top // of this scope. - Scope.prototype.assigned_variables = function() { + Scope.prototype.assignedVariables = function() { var _a, _b, key, val; _a = []; _b = this.variables; for (key in _b) { if (__hasProp.call(_b, key)) { @@ -125,12 +125,12 @@ return _a; }; // Compile the JavaScript for all of the variable declarations in this scope. - Scope.prototype.compiled_declarations = function() { - return this.declared_variables().join(', '); + Scope.prototype.compiledDeclarations = function() { + return this.declaredVariables().join(', '); }; // Compile the JavaScript for all of the variable assignments in this scope. - Scope.prototype.compiled_assignments = function() { - return this.assigned_variables().join(', '); + Scope.prototype.compiledAssignments = function() { + return this.assignedVariables().join(', '); }; return Scope; }).call(this); diff --git a/src/cake.coffee b/src/cake.coffee index c1e285f4a7..b26aef6bb6 100644 --- a/src/cake.coffee +++ b/src/cake.coffee @@ -36,7 +36,7 @@ helpers.extend global, { # Invoke another task in the current Cakefile. invoke: (name) -> - no_such_task name unless tasks[name] + missingTask name unless tasks[name] tasks[name].action options } @@ -50,12 +50,12 @@ exports.run: -> args: process.argv[2...process.argv.length] CoffeeScript.run fs.readFileSync('Cakefile').toString(), {source: 'Cakefile'} oparse: new optparse.OptionParser switches - return print_tasks() unless args.length + return printTasks() unless args.length options: oparse.parse(args) invoke arg for arg in options.arguments # Display the list of Cake tasks in a format similar to `rake -T` -print_tasks: -> +printTasks: -> puts '' for name, task of tasks spaces: 20 - name.length @@ -65,6 +65,6 @@ print_tasks: -> puts oparse.help() if switches.length # Print an error and exit when attempting to all an undefined task. -no_such_task: (task) -> +missingTask: (task) -> puts "No such task: \"$task\"" process.exit 1 diff --git a/src/coffee-script.coffee b/src/coffee-script.coffee index 99a3939283..bc26437188 100644 --- a/src/coffee-script.coffee +++ b/src/coffee-script.coffee @@ -83,10 +83,10 @@ parser.lexer: { # on page load. Unfortunately, the text contents of remote scripts cannot be # accessed from the browser, so only inline script tags will work. if document? and document.getElementsByTagName - process_scripts: -> + processScripts: -> for tag in document.getElementsByTagName('script') when tag.type is 'text/coffeescript' eval exports.compile tag.innerHTML if window.addEventListener - window.addEventListener 'load', process_scripts, false + window.addEventListener 'load', processScripts, false else if window.attachEvent - window.attachEvent 'onload', process_scripts + window.attachEvent 'onload', processScripts diff --git a/src/command.coffee b/src/command.coffee index 93abc9f11a..36769f8b54 100644 --- a/src/command.coffee +++ b/src/command.coffee @@ -39,18 +39,18 @@ SWITCHES: [ # Top-level objects shared by all the functions. options: {} sources: [] -option_parser: null +optionParser: null # Run `coffee` by parsing passed options and determining what action to take. # Many flags cause us to divert before compiling anything. Flags passed after # `--` will be passed verbatim to your script as arguments in `process.argv` exports.run: -> - parse_options() + parseOptions() return usage() if options.help return version() if options.version return require './repl' if options.interactive - return compile_stdio() if options.stdio - return compile_script 'console', sources[0] if options.eval + return compileStdio() if options.stdio + return compileScript 'console', sources[0] if options.eval return require './repl' unless sources.length separator: sources.indexOf '--' flags: [] @@ -58,15 +58,15 @@ exports.run: -> flags: sources[(separator + 1)...sources.length] sources: sources[0...separator] process.ARGV: process.argv: flags - compile_scripts() + compileScripts() # Asynchronously read in each CoffeeScript in a list of source files and # compile them. If a directory is passed, recursively compile all # '.coffee' extension source files in it and all subdirectories. -compile_scripts: -> +compileScripts: -> for source in sources base: source - compile: (source, top_level) -> + compile: (source, topLevel) -> path.exists source, (exists) -> throw new Error "File not found: $source" unless exists fs.stat source, (err, stats) -> @@ -74,25 +74,25 @@ compile_scripts: -> fs.readdir source, (err, files) -> for file in files compile path.join(source, file) - else if top_level or path.extname(source) is '.coffee' - fs.readFile source, (err, code) -> compile_script(source, code.toString(), base) + else if topLevel or path.extname(source) is '.coffee' + fs.readFile source, (err, code) -> compileScript(source, code.toString(), base) watch source, base if options.watch compile source, true # Compile a single source script, containing the given code, according to the # requested options. If evaluating the script directly sets `__filename`, # `__dirname` and `module.filename` to be correct relative to the script's path. -compile_script: (source, code, base) -> +compileScript: (source, code, base) -> o: options - code_opts: compile_options source + codeOpts: compileOptions source try - if o.tokens then print_tokens CoffeeScript.tokens code + if o.tokens then printTokens CoffeeScript.tokens code else if o.nodes then puts CoffeeScript.nodes(code).toString() - else if o.run then CoffeeScript.run code, code_opts + else if o.run then CoffeeScript.run code, codeOpts else - js: CoffeeScript.compile code, code_opts + js: CoffeeScript.compile code, codeOpts if o.print then print js - else if o.compile then write_js source, js, base + else if o.compile then writeJs source, js, base else if o.lint then lint js catch err error(err.stack) and process.exit 1 unless o.watch @@ -100,13 +100,13 @@ compile_script: (source, code, base) -> # Attach the appropriate listeners to compile scripts incoming over **stdin**, # and write them back to **stdout**. -compile_stdio: -> +compileStdio: -> code: '' stdin: process.openStdin() stdin.addListener 'data', (buffer) -> code: + buffer.toString() if buffer stdin.addListener 'end', -> - compile_script 'stdio', code + compileScript 'stdio', code # Watch a source CoffeeScript file using `fs.watchFile`, recompiling it every # time the file is updated. May be used in combination with other options, @@ -115,33 +115,33 @@ watch: (source, base) -> fs.watchFile source, {persistent: true, interval: 500}, (curr, prev) -> return if curr.mtime.getTime() is prev.mtime.getTime() puts "Compiled $source" if options.compile - fs.readFile source, (err, code) -> compile_script(source, code.toString(), base) + fs.readFile source, (err, code) -> compileScript(source, code.toString(), base) # Write out a JavaScript source file with the compiled code. By default, files # are written out in `cwd` as `.js` files with the same name, but the output # directory can be customized with `--output`. -write_js: (source, js, base) -> +writeJs: (source, js, base) -> filename: path.basename(source, path.extname(source)) + '.js' - src_dir: path.dirname source - base_dir: src_dir.substring base.length - dir: if options.output then path.join options.output, base_dir else src_dir - js_path: path.join dir, filename - compile: -> fs.writeFile js_path, js + srcDir: path.dirname source + baseDir: srcDir.substring base.length + dir: if options.output then path.join options.output, baseDir else srcDir + jsPath: path.join dir, filename + compile: -> fs.writeFile jsPath, js path.exists dir, (exists) -> if exists then compile() else exec "mkdir -p $dir", compile # Pipe compiled JS through JSLint (requires a working `jsl` command), printing # any errors or warnings that arise. lint: (js) -> - print_it: (buffer) -> print buffer.toString() + printIt: (buffer) -> print buffer.toString() jsl: spawn 'jsl', ['-nologo', '-stdin'] - jsl.stdout.addListener 'data', print_it - jsl.stderr.addListener 'data', print_it + jsl.stdout.addListener 'data', printIt + jsl.stderr.addListener 'data', printIt jsl.stdin.write js jsl.stdin.end() # Pretty-print a stream of tokens. -print_tokens: (tokens) -> +printTokens: (tokens) -> strings: for token in tokens [tag, value]: [token[0], token[1].toString().replace(/\n/, '\\n')] "[$tag $value]" @@ -149,22 +149,22 @@ print_tokens: (tokens) -> # Use the [OptionParser module](optparse.html) to extract all options from # `process.argv` that are specified in `SWITCHES`. -parse_options: -> - option_parser: new optparse.OptionParser SWITCHES, BANNER - o: options: option_parser.parse(process.argv) +parseOptions: -> + optionParser: new optparse.OptionParser SWITCHES, BANNER + o: options: optionParser.parse(process.argv) options.run: not (o.compile or o.print or o.lint) options.print: !! (o.print or (o.eval or o.stdio and o.compile)) sources: options.arguments[2...options.arguments.length] # The compile-time options to pass to the CoffeeScript compiler. -compile_options: (source) -> +compileOptions: (source) -> o: {source: source} o['no_wrap']: options['no-wrap'] o # Print the `--help` usage message and exit. usage: -> - puts option_parser.help() + puts optionParser.help() process.exit 0 # Print the `--version` message and exit. diff --git a/src/grammar.coffee b/src/grammar.coffee index bb2d812c41..6b9604ea3d 100644 --- a/src/grammar.coffee +++ b/src/grammar.coffee @@ -30,10 +30,10 @@ unwrap: /function\s*\(\)\s*\{\s*return\s*([\s\S]*);\s*\}/ # we pass the pattern-defining string, the action to run, and extra options, # optionally. If no action is specified, we simply pass the value of the # previous nonterminal. -o: (pattern_string, action, options) -> - return [pattern_string, '$$ = $1;', options] unless action +o: (patternString, action, options) -> + return [patternString, '$$ = $1;', options] unless action action: if match: (action + '').match(unwrap) then match[1] else "($action())" - [pattern_string, "$$ = $action;", options] + [patternString, "$$ = $action;", options] # Grammatical Rules # ----------------- @@ -252,7 +252,7 @@ grammar: { # Indexing into an object or array using bracket notation. Index: [ o "INDEX_START Expression INDEX_END", -> new IndexNode $2 - o "INDEX_SOAK Index", -> $2.soak_node: yes; $2 + o "INDEX_SOAK Index", -> $2.soakNode: yes; $2 o "INDEX_PROTO Index", -> $2.proto: yes; $2 ] @@ -297,7 +297,7 @@ grammar: { # and calling `super()` Call: [ o "Invocation" - o "NEW Invocation", -> $2.new_instance() + o "NEW Invocation", -> $2.newInstance() o "Super" ] @@ -413,15 +413,15 @@ grammar: { # The while loop can either be normal, with a block of expressions to execute, # or postfix, with a single expression. There is no do..while. While: [ - o "WhileSource Block", -> $1.add_body $2 - o "Statement WhileSource", -> $2.add_body Expressions.wrap [$1] - o "Expression WhileSource", -> $2.add_body Expressions.wrap [$1] + o "WhileSource Block", -> $1.addBody $2 + o "Statement WhileSource", -> $2.addBody Expressions.wrap [$1] + o "Expression WhileSource", -> $2.addBody Expressions.wrap [$1] o "Loop", -> $1 ] Loop: [ - o "LOOP Block", -> new WhileNode(new LiteralNode 'true').add_body $2 - o "LOOP Expression", -> new WhileNode(new LiteralNode 'true').add_body Expressions.wrap [$2] + o "LOOP Block", -> new WhileNode(new LiteralNode 'true').addBody $2 + o "LOOP Expression", -> new WhileNode(new LiteralNode 'true').addBody Expressions.wrap [$2] ] # Array, object, and range comprehensions, at the most generic level. @@ -465,17 +465,17 @@ grammar: { # The CoffeeScript switch/when/else block replaces the JavaScript # switch/case/default by compiling into an if-else chain. Switch: [ - o "SWITCH Expression INDENT Whens OUTDENT", -> $4.switches_over $2 - o "SWITCH Expression INDENT Whens ELSE Block OUTDENT", -> $4.switches_over($2).add_else $6, true + o "SWITCH Expression INDENT Whens OUTDENT", -> $4.switchesOver $2 + o "SWITCH Expression INDENT Whens ELSE Block OUTDENT", -> $4.switchesOver($2).addElse $6, true o "SWITCH INDENT Whens OUTDENT", -> $3 - o "SWITCH INDENT Whens ELSE Block OUTDENT", -> $3.add_else $5, true + o "SWITCH INDENT Whens ELSE Block OUTDENT", -> $3.addElse $5, true ] # The inner list of whens is left recursive. At code-generation time, the # IfNode will rewrite them into a proper chain. Whens: [ o "When" - o "Whens When", -> $1.add_else $2 + o "Whens When", -> $1.addElse $2 ] # An individual **When** clause, with action. @@ -491,13 +491,13 @@ grammar: { IfStart: [ o "IF Expression Block", -> new IfNode $2, $3 o "UNLESS Expression Block", -> new IfNode $2, $3, {invert: true} - o "IfStart ELSE IF Expression Block", -> $1.add_else (new IfNode($4, $5)).force_statement() + o "IfStart ELSE IF Expression Block", -> $1.addElse (new IfNode($4, $5)).forceStatement() ] # An **IfStart** can optionally be followed by an else block. IfBlock: [ o "IfStart" - o "IfStart ELSE Block", -> $1.add_else $3 + o "IfStart ELSE Block", -> $1.addElse $3 ] # The full complement of *if* expressions, including postfix one-liner diff --git a/src/helpers.coffee b/src/helpers.coffee index f75c633cb9..00c1281401 100644 --- a/src/helpers.coffee +++ b/src/helpers.coffee @@ -7,7 +7,7 @@ this.exports: this unless process? helpers: exports.helpers: {} # Cross-browser indexOf, so that IE can join the party. -helpers.index_of: index_of: (array, item, from) -> +helpers.indexOf: indexOf: (array, item, from) -> return array.indexOf item, from if array.indexOf for other, index in array if other is item and (not from or (from <= index)) @@ -16,7 +16,7 @@ helpers.index_of: index_of: (array, item, from) -> # Does a list include a value? helpers.include: include: (list, value) -> - index_of(list, value) >= 0 + indexOf(list, value) >= 0 # Peek at the beginning of a given string to see if it matches a sequence. helpers.starts: starts: (string, literal, start) -> @@ -28,10 +28,10 @@ helpers.compact: compact: (array) -> item for item in array when item # Count the number of occurences of a character in a string. helpers.count: count: (string, letter) -> num: 0 - pos: index_of string, letter + pos: indexOf string, letter while pos isnt -1 num: + 1 - pos: index_of string, letter, pos + 1 + pos: indexOf string, letter, pos + 1 num # Merge objects, returning a fresh copy with attributes from both sides. @@ -67,7 +67,7 @@ helpers.del: del: (obj, key) -> # a series of delimiters, all of which must be nested correctly within the # contents of the string. This method allows us to have strings within # interpolations within strings, ad infinitum. -helpers.balanced_string: balanced_string: (str, delimited, options) -> +helpers.balancedString: balancedString: (str, delimited, options) -> options: or {} slash: delimited[0][0] is '/' levels: [] diff --git a/src/lexer.coffee b/src/lexer.coffee index 917d71ba48..fe2cbe39ef 100644 --- a/src/lexer.coffee +++ b/src/lexer.coffee @@ -3,7 +3,7 @@ # a token is produced, we consume the match, and start again. Tokens are in the # form: # -# [tag, value, line_number] +# [tag, value, lineNumber] # # Which is a format that can be fed directly into [Jison](http://github.com/zaach/jison). @@ -17,7 +17,7 @@ else helpers: this.helpers # Import the helpers we need. -{include, count, starts, compact, balanced_string}: helpers +{include, count, starts, compact, balancedString}: helpers # The Lexer Class # --------------- @@ -51,33 +51,33 @@ exports.Lexer: class Lexer @tokens : [] # Stream of parsed tokens in the form ['TYPE', value, line] while @i < @code.length @chunk: @code.slice @i - @extract_next_token() - @close_indentation() + @extractNextToken() + @closeIndentation() return @tokens if o.rewrite is off (new Rewriter()).rewrite @tokens # At every position, run through this list of attempted matches, # short-circuiting if any of them succeed. Their order determines precedence: - # `@literal_token` is the fallback catch-all. - extract_next_token: -> - return if @extension_token() - return if @identifier_token() - return if @number_token() - return if @heredoc_token() - return if @regex_token() - return if @comment_token() - return if @line_token() - return if @whitespace_token() - return if @js_token() - return if @string_token() - return @literal_token() + # `@literalToken` is the fallback catch-all. + extractNextToken: -> + return if @extensionToken() + return if @identifierToken() + return if @numberToken() + return if @heredocToken() + return if @regexToken() + return if @commentToken() + return if @lineToken() + return if @whitespaceToken() + return if @jsToken() + return if @stringToken() + return @literalToken() # Tokenizers # ---------- # Language extensions get the highest priority, first chance to tag tokens # as something else. - extension_token: -> + extensionToken: -> for extension in Lexer.extensions return true if extension.call this false @@ -88,23 +88,23 @@ exports.Lexer: class Lexer # allowed in JavaScript, we're careful not to tag them as keywords when # referenced as property names here, so you can still do `jQuery.is()` even # though `is` means `===` otherwise. - identifier_token: -> + identifierToken: -> return false unless id: @match IDENTIFIER, 1 - forced_identifier: @tag_accessor() or @match ASSIGNED, 1 + forcedIdentifier: @tagAccessor() or @match ASSIGNED, 1 tag: 'IDENTIFIER' - tag: id.toUpperCase() if include(JS_KEYWORDS, id) or (not forced_identifier and include(COFFEE_KEYWORDS, id)) - @identifier_error id if include RESERVED, id + tag: id.toUpperCase() if include(JS_KEYWORDS, id) or (not forcedIdentifier and include(COFFEE_KEYWORDS, id)) + @identifierError id if include RESERVED, id tag: 'LEADING_WHEN' if tag is 'WHEN' and include LINE_BREAK, @tag() @i: + id.length - unless forced_identifier + unless forcedIdentifier tag: id: CONVERSIONS[id] if include COFFEE_ALIASES, id - return @tag_half_assignment tag if @prev() and @prev()[0] is 'ASSIGN' and include HALF_ASSIGNMENTS, tag + return @tagHalfAssignment tag if @prev() and @prev()[0] is 'ASSIGN' and include HALF_ASSIGNMENTS, tag @token tag, id true # Matches numbers, including decimals, hex, and exponential notation. # Be careful not to interfere with ranges-in-progress. - number_token: -> + numberToken: -> return false unless number: @match NUMBER, 1 return false if @tag() is '.' and starts number, '.' @i: + number.length @@ -113,33 +113,33 @@ exports.Lexer: class Lexer # Matches strings, including multi-line strings. Ensures that quotation marks # are balanced within the string's contents, and within nested interpolations. - string_token: -> + stringToken: -> return false unless starts(@chunk, '"') or starts(@chunk, "'") return false unless string: - @balanced_token(['"', '"'], ['${', '}']) or - @balanced_token ["'", "'"] - @interpolate_string string.replace STRING_NEWLINES, " \\\n" + @balancedToken(['"', '"'], ['${', '}']) or + @balancedToken ["'", "'"] + @interpolateString string.replace STRING_NEWLINES, " \\\n" @line: + count string, "\n" @i: + string.length true # Matches heredocs, adjusting indentation to the correct level, as heredocs # preserve whitespace, but ignore indentation to the left. - heredoc_token: -> + heredocToken: -> return false unless match: @chunk.match(HEREDOC) quote: match[1].substr 0, 1 - doc: @sanitize_heredoc match[2] or match[4], {quote} - @interpolate_string "$quote$doc$quote" + doc: @sanitizeHeredoc match[2] or match[4], {quote} + @interpolateString "$quote$doc$quote" @line: + count match[1], "\n" @i: + match[1].length true # Matches and conumes comments. We pass through comments into JavaScript, # so they're treated as real tokens, like any other part of the language. - comment_token: -> + commentToken: -> return false unless match: @chunk.match(COMMENT) if match[3] - comment: @sanitize_heredoc match[3], {herecomment: true} + comment: @sanitizeHeredoc match[3], {herecomment: true} @token 'HERECOMMENT', comment.split MULTILINER @token 'TERMINATOR', '\n' else @@ -153,28 +153,28 @@ exports.Lexer: class Lexer true # Matches JavaScript interpolated directly into the source via backticks. - js_token: -> + jsToken: -> return false unless starts @chunk, '`' - return false unless script: @balanced_token ['`', '`'] + return false unless script: @balancedToken ['`', '`'] @token 'JS', script.replace JS_CLEANER, '' @i: + script.length true # 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 `@balanced_token`, and - # borrow interpolation from `@interpolate_string`. - regex_token: -> + # JavaScript and Ruby, borrow slash balancing from `@balancedToken`, and + # borrow interpolation from `@interpolateString`. + regexToken: -> return false unless @chunk.match REGEX_START return false if include NOT_REGEX, @tag() - return false unless regex: @balanced_token ['/', '/'] + return false unless regex: @balancedToken ['/', '/'] return false unless end: @chunk.substr(regex.length).match REGEX_END regex: + flags: end[2] if end[2] if regex.match REGEX_INTERPOLATION str: regex.substring(1).split('/')[0] str: str.replace REGEX_ESCAPE, (escaped) -> '\\' + escaped @tokens: @tokens.concat [['(', '('], ['NEW', 'new'], ['IDENTIFIER', 'RegExp'], ['CALL_START', '(']] - @interpolate_string "\"$str\"", yes + @interpolateString "\"$str\"", yes @tokens: @tokens.concat [[',', ','], ['STRING', "\"$flags\""], [')', ')'], [')', ')']] else @token 'REGEX', regex @@ -183,8 +183,8 @@ exports.Lexer: class Lexer # Matches a token in which which the passed delimiter pairs must be correctly # balanced (ie. strings, JS literals). - balanced_token: (delimited...) -> - balanced_string @chunk, delimited + balancedToken: (delimited...) -> + balancedString @chunk, delimited # Matches newlines, indents, and outdents, and determines which is which. # If we can detect that the current line is continued onto the the next line, @@ -196,44 +196,44 @@ exports.Lexer: class Lexer # # Keeps track of the level of indentation, because a single outdent token # can close multiple indents, so we need to know how far in we happen to be. - line_token: -> + lineToken: -> return false unless indent: @match MULTI_DENT, 1 @line: + count indent, "\n" @i : + indent.length prev: @prev(2) size: indent.match(LAST_DENTS).reverse()[0].match(LAST_DENT)[1].length - next_character: @chunk.match(NEXT_CHARACTER)[1] - no_newlines: next_character is '.' or next_character is ',' or @unfinished() + nextCharacter: @chunk.match(NEXT_CHARACTER)[1] + noNewlines: nextCharacter is '.' or nextCharacter is ',' or @unfinished() if size is @indent - return @suppress_newlines() if no_newlines - return @newline_token indent + return @suppressNewlines() if noNewlines + return @newlineToken indent else if size > @indent - return @suppress_newlines() if no_newlines + return @suppressNewlines() if noNewlines diff: size - @indent @token 'INDENT', diff @indents.push diff else - @outdent_token @indent - size, no_newlines + @outdentToken @indent - size, noNewlines @indent: size true # Record an outdent token or multiple tokens, if we happen to be moving back # inwards past several recorded indents. - outdent_token: (move_out, no_newlines) -> - if move_out > -@outdebt - while move_out > 0 and @indents.length - last_indent: @indents.pop() - @token 'OUTDENT', last_indent - move_out: - last_indent + outdentToken: (moveOut, noNewlines) -> + if moveOut > -@outdebt + while moveOut > 0 and @indents.length + lastIndent: @indents.pop() + @token 'OUTDENT', lastIndent + moveOut: - lastIndent else - @outdebt: + move_out - @outdebt: move_out unless no_newlines - @token 'TERMINATOR', "\n" unless @tag() is 'TERMINATOR' or no_newlines + @outdebt: + moveOut + @outdebt: moveOut unless noNewlines + @token 'TERMINATOR', "\n" unless @tag() is 'TERMINATOR' or noNewlines true # Matches and consumes non-meaningful whitespace. Tag the previous token # as being "spaced", because there are some cases where it makes a difference. - whitespace_token: -> + whitespaceToken: -> return false unless space: @match WHITESPACE, 1 prev: @prev() prev.spaced: true if prev @@ -241,13 +241,13 @@ exports.Lexer: class Lexer true # Generate a newline token. Consecutive newlines get merged together. - newline_token: (newlines) -> + newlineToken: (newlines) -> @token 'TERMINATOR', "\n" unless @tag() is 'TERMINATOR' true # Use a `\` at a line-ending to suppress the newline. # The slash is removed here once its job is done. - suppress_newlines: -> + suppressNewlines: -> @tokens.pop() if @value() is "\\" true @@ -256,20 +256,20 @@ exports.Lexer: class Lexer # the proper order of operations. There are some symbols that we tag specially # here. `;` and newlines are both treated as a `TERMINATOR`, we distinguish # parentheses that indicate a method call from regular parentheses, and so on. - literal_token: -> + literalToken: -> match: @chunk.match OPERATOR value: match and match[1] space: match and match[2] - @tag_parameters() if value and value.match CODE + @tagParameters() if value and value.match CODE value: or @chunk.substr 0, 1 - prev_spaced: @prev() and @prev().spaced + prevSpaced: @prev() and @prev().spaced tag: value if value.match ASSIGNMENT tag: 'ASSIGN' - @assignment_error() if include JS_FORBIDDEN, @value + @assignmentError() if include JS_FORBIDDEN, @value else if value is ';' tag: 'TERMINATOR' - else if include(CALLABLE, @tag()) and not prev_spaced + else if include(CALLABLE, @tag()) and not prevSpaced if value is '(' tag: 'CALL_START' else if value is '[' @@ -277,7 +277,7 @@ exports.Lexer: class Lexer @tag 1, 'INDEX_SOAK' if @tag() is '?' @tag 1, 'INDEX_PROTO' if @tag() is '::' @i: + value.length - return @tag_half_assignment tag if space and prev_spaced and @prev()[0] is 'ASSIGN' and include HALF_ASSIGNMENTS, tag + return @tagHalfAssignment tag if space and prevSpaced and @prev()[0] is 'ASSIGN' and include HALF_ASSIGNMENTS, tag @token tag, value true @@ -287,7 +287,7 @@ exports.Lexer: class Lexer # As we consume a new `IDENTIFIER`, look at the previous token to determine # if it's a special kind of accessor. Return `true` if any type of accessor # is the previous token. - tag_accessor: -> + tagAccessor: -> return false if (not prev: @prev()) or (prev and prev.spaced) if prev[1] is '::' @tag 1, 'PROTOTYPE_ACCESS' @@ -302,7 +302,7 @@ exports.Lexer: class Lexer # Sanitize a heredoc or herecomment by escaping internal double quotes and # erasing all external indentation on the left-hand side. - sanitize_heredoc: (doc, options) -> + sanitizeHeredoc: (doc, options) -> while match: HEREDOC_INDENT.exec doc attempt: if match[2]? then match[2] else match[3] indent: attempt if not indent or attempt.length < indent.length @@ -312,7 +312,7 @@ exports.Lexer: class Lexer .replace(new RegExp(options.quote, 'g'), "\\$options.quote") # Tag a half assignment. - tag_half_assignment: (tag) -> + tagHalfAssignment: (tag) -> last: @tokens.pop() @tokens.push ["$tag=", "$tag=", last[2]] true @@ -320,7 +320,7 @@ exports.Lexer: class Lexer # A source of ambiguity in our grammar used to be parameter lists in function # definitions versus argument lists in function calls. Walk backwards, tagging # parameters specially in order to make things easier for the parser. - tag_parameters: -> + tagParameters: -> return if @tag() isnt ')' i: 0 loop @@ -334,17 +334,17 @@ exports.Lexer: class Lexer true # Close up all remaining open blocks at the end of the file. - close_indentation: -> - @outdent_token @indent + closeIndentation: -> + @outdentToken @indent # The error for when you try to use a forbidden word in JavaScript as # an identifier. - identifier_error: (word) -> + identifierError: (word) -> throw new Error "SyntaxError: Reserved word \"$word\" on line ${@line + 1}" # The error for when you try to assign to a reserved word in JavaScript, # like "function" or "default". - assignment_error: -> + assignmentError: -> throw new Error "SyntaxError: Reserved word \"${@value()}\" on line ${@line + 1} can't be assigned" # Expand variables and expressions inside double-quoted strings using @@ -357,7 +357,7 @@ exports.Lexer: class Lexer # If it encounters an interpolation, this method will recursively create a # new Lexer, tokenize the interpolated contents, and merge them into the # token stream. - interpolate_string: (str, escape_quotes) -> + interpolateString: (str, escapeQuotes) -> if str.length < 3 or not starts str, '"' @token 'STRING', str else @@ -375,7 +375,7 @@ exports.Lexer: class Lexer tokens.push ['IDENTIFIER', interp] i: + group.length - 1 pi: i + 1 - else if (expr: balanced_string str.substring(i), [['${', '}']]) + else if (expr: balancedString str.substring(i), [['${', '}']]) tokens.push ['STRING', "$quote${ str.substring(pi, i) }$quote"] if pi < i inner: expr.substring(2, expr.length - 1) if inner.length @@ -396,7 +396,7 @@ exports.Lexer: class Lexer [tag, value]: token if tag is 'TOKENS' @tokens: @tokens.concat value - else if tag is 'STRING' and escape_quotes + else if tag is 'STRING' and escapeQuotes escaped: value.substring(1, value.length - 1).replace(/"/g, '\\"') @token tag, "\"$escaped\"" else @@ -413,9 +413,9 @@ exports.Lexer: class Lexer @tokens.push [tag, value, @line] # Peek at a tag in the current token stream. - tag: (index, new_tag) -> + tag: (index, newTag) -> return unless tok: @prev index - return tok[0]: new_tag if new_tag? + return tok[0]: newTag if newTag? tok[0] # Peek at a value in the current token stream. diff --git a/src/nodes.coffee b/src/nodes.coffee index 45157bc968..08fb8ceaef 100644 --- a/src/nodes.coffee +++ b/src/nodes.coffee @@ -14,14 +14,14 @@ else Scope: this.Scope # Import the helpers we plan to use. -{compact, flatten, merge, del, include, index_of, starts}: helpers +{compact, flatten, merge, del, include, indexOf, starts}: helpers #### BaseNode # The **BaseNode** is the abstract base class for all nodes in the syntax tree. -# Each subclass implements the `compile_node` method, which performs the +# Each subclass implements the `compileNode` method, which performs the # code generation for that node. To compile a node to JavaScript, -# call `compile` on it, which wraps `compile_node` in some generic extra smarts, +# call `compile` on it, which wraps `compileNode` in some generic extra smarts, # to know when the generated code needs to be wrapped up in a closure. # An options hash is passed and cloned throughout, containing information about # the environment from higher in the tree (such as if a returned value is @@ -31,12 +31,12 @@ exports.BaseNode: class BaseNode # Common logic for determining whether to wrap this node in a closure before # compiling it, or to compile directly. We need to wrap if this node is a - # *statement*, and it's not a *pure_statement*, and we're not at + # *statement*, and it's not a *pureStatement*, and we're not at # the top level of a block (which would be unnecessary), and we haven't # already been asked to return the result (because statements know how to # return results). # - # If a Node is *top_sensitive*, that means that it needs to compile differently + # If a Node is *topSensitive*, that means that it needs to compile differently # depending on whether it's being used as part of a larger expression, or is a # top-level statement within the function body. compile: (o) -> @@ -44,29 +44,29 @@ exports.BaseNode: class BaseNode @tab: o.indent unless this instanceof ValueNode or this instanceof CallNode del @options, 'operation' - del @options, 'chain_root' unless this instanceof AccessorNode or this instanceof IndexNode - top: if @top_sensitive() then @options.top else del @options, 'top' - closure: @is_statement() and not @is_pure_statement() and not top and - not @options.as_statement and not (this instanceof CommentNode) and - not @contains_pure_statement() - if closure then @compile_closure(@options) else @compile_node(@options) + del @options, 'chainRoot' unless this instanceof AccessorNode or this instanceof IndexNode + top: if @topSensitive() then @options.top else del @options, 'top' + closure: @isStatement() and not @isPureStatement() and not top and + not @options.asStatement and not (this instanceof CommentNode) and + not @containsPureStatement() + if closure then @compileClosure(@options) else @compileNode(@options) # Statements converted into expressions via closure-wrapping share a scope # object with their parent closure, to preserve the expected lexical scope. - compile_closure: (o) -> + compileClosure: (o) -> @tab: o.indent - o.shared_scope: o.scope + o.sharedScope: o.scope ClosureNode.wrap(this).compile o # If the code generation wishes to use the result of a complex expression # in multiple places, ensure that the expression is only ever evaluated once, # by assigning it to a temporary variable. - compile_reference: (o, only_if_necessary) -> - if only_if_necessary and not + compileReference: (o, onlyIfNecessary) -> + if onlyIfNecessary and not (this instanceof CallNode or - this instanceof ValueNode and (not (@base instanceof LiteralNode) or @has_properties())) + this instanceof ValueNode and (not (@base instanceof LiteralNode) or @hasProperties())) return [this, this] - reference: literal o.scope.free_variable() + reference: literal o.scope.freeVariable() compiled: new AssignNode reference, this [compiled, reference] @@ -80,7 +80,7 @@ exports.BaseNode: class BaseNode # Construct a node that returns the current node's result. # Note that this is overridden for smarter behavior for # many statement nodes (eg IfNode, ForNode)... - make_return: -> + makeReturn: -> new ReturnNode this # Does this node, or any of its children, contain a node of a certain kind? @@ -89,45 +89,45 @@ exports.BaseNode: class BaseNode # scope boundaries. contains: (block) -> contains: false - @traverse_children false, (node) -> + @traverseChildren false, (node) -> if block(node) contains: true return false contains # Is this node of a certain type, or does it contain the type? - contains_type: (type) -> + containsType: (type) -> this instanceof type or @contains (n) -> n instanceof type # Convenience for the most common use of contains. Does the node contain # a pure statement? - contains_pure_statement: -> - @is_pure_statement() or @contains (n) -> n.is_pure_statement() + containsPureStatement: -> + @isPureStatement() or @contains (n) -> n.isPureStatement() # Perform an in-order traversal of the AST. Crosses scope boundaries. - traverse: (block) -> @traverse_children true, block + traverse: (block) -> @traverseChildren true, block # `toString` representation of the node, for inspecting the parse tree. # This is what `coffee --nodes` prints out. toString: (idt) -> idt: or '' - '\n' + idt + @type + (child.toString(idt + TAB) for child in @collect_children()).join('') + '\n' + idt + @type + (child.toString(idt + TAB) for child in @collectChildren()).join('') - each_child: (func) -> + eachChild: (func) -> return unless @children for attr in @children when this[attr] for child in flatten [this[attr]] return if func(child) is false - collect_children: -> + collectChildren: -> nodes: [] - @each_child (node) -> nodes.push node + @eachChild (node) -> nodes.push node nodes - traverse_children: (cross_scope, func) -> - @each_child (child) -> + traverseChildren: (crossScope, func) -> + @eachChild (child) -> func.apply(this, arguments) - child.traverse_children(cross_scope, func) if child instanceof BaseNode + child.traverseChildren(crossScope, func) if child instanceof BaseNode # Default implementations of the common node properties and methods. Nodes # will override these with custom logic, if needed. @@ -135,9 +135,9 @@ exports.BaseNode: class BaseNode children: [] unwrap: -> this - is_statement: -> no - is_pure_statement: -> no - top_sensitive: -> no + isStatement: -> no + isPureStatement: -> no + topSensitive: -> no #### Expressions @@ -148,7 +148,7 @@ exports.Expressions: class Expressions extends BaseNode type: 'Expressions' children: ['expressions'] - is_statement: -> yes + isStatement: -> yes constructor: (nodes) -> @expressions: compact flatten nodes or [] @@ -174,46 +174,46 @@ exports.Expressions: class Expressions extends BaseNode # An Expressions node does not return its entire body, rather it # ensures that the final expression is returned. - make_return: -> + makeReturn: -> idx: @expressions.length - 1 last: @expressions[idx] last: @expressions[idx: - 1] if last instanceof CommentNode return this if not last or last instanceof ReturnNode - @expressions[idx]: last.make_return() unless last.contains_pure_statement() + @expressions[idx]: last.makeReturn() unless last.containsPureStatement() this # An **Expressions** is the only node that can serve as the root. compile: (o) -> o: or {} - if o.scope then super(o) else @compile_root(o) + if o.scope then super(o) else @compileRoot(o) - compile_node: (o) -> - (@compile_expression(node, merge(o)) for node in @expressions).join("\n") + compileNode: (o) -> + (@compileExpression(node, merge(o)) for node in @expressions).join("\n") # If we happen to be the top-level **Expressions**, wrap everything in # a safety closure, unless requested not to. - compile_root: (o) -> - o.indent: @tab: if o.no_wrap then '' else TAB + compileRoot: (o) -> + o.indent: @tab: if o.noWrap then '' else TAB o.scope: new Scope(null, this, null) - code: if o.globals then @compile_node(o) else @compile_with_declarations(o) + code: if o.globals then @compileNode(o) else @compileWithDeclarations(o) code: code.replace(TRAILING_WHITESPACE, '') - if o.no_wrap then code else "(function(){\n$code\n})();\n" + if o.noWrap then code else "(function(){\n$code\n})();\n" # Compile the expressions body for the contents of a function, with # declarations of all inner variables pushed up to the top. - compile_with_declarations: (o) -> - code: @compile_node(o) - code: "${@tab}var ${o.scope.compiled_assignments()};\n$code" if o.scope.has_assignments(this) - code: "${@tab}var ${o.scope.compiled_declarations()};\n$code" if o.scope.has_declarations(this) + compileWithDeclarations: (o) -> + code: @compileNode(o) + code: "${@tab}var ${o.scope.compiledAssignments()};\n$code" if o.scope.hasAssignments(this) + code: "${@tab}var ${o.scope.compiledDeclarations()};\n$code" if o.scope.hasDeclarations(this) code # Compiles a single expression within the expressions body. If we need to # return the result, and it's an expression, simply return it. If it's a # statement, ask the statement to do so. - compile_expression: (node, o) -> + compileExpression: (node, o) -> @tab: o.indent - compiled_node: node.compile merge o, {top: true} - if node.is_statement() then compiled_node else "${@idt()}$compiled_node;" + compiledNode: node.compile merge o, {top: true} + if node.isStatement() then compiledNode else "${@idt()}$compiledNode;" # Wrap up the given nodes as an **Expressions**, unless it already happens # to be one. @@ -235,13 +235,13 @@ exports.LiteralNode: class LiteralNode extends BaseNode # Break and continue must be treated as pure statements -- they lose their # meaning when wrapped in a closure. - is_statement: -> + isStatement: -> @value is 'break' or @value is 'continue' - is_pure_statement: LiteralNode::is_statement + isPureStatement: LiteralNode::isStatement - compile_node: (o) -> - idt: if @is_statement() then @idt() else '' - end: if @is_statement() then ';' else '' + compileNode: (o) -> + idt: if @isStatement() then @idt() else '' + end: if @isStatement() then ';' else '' "$idt$@value$end" toString: (idt) -> @@ -249,26 +249,26 @@ exports.LiteralNode: class LiteralNode extends BaseNode #### ReturnNode -# A `return` is a *pure_statement* -- wrapping it in a closure wouldn't +# A `return` is a *pureStatement* -- wrapping it in a closure wouldn't # make sense. exports.ReturnNode: class ReturnNode extends BaseNode type: 'ReturnNode' - is_statement: -> yes - is_pure_statement: -> yes + isStatement: -> yes + isPureStatement: -> yes children: ['expression'] constructor: (expression) -> @expression: expression - top_sensitive: -> + topSensitive: -> true - compile_node: (o) -> - expr: @expression.make_return() + compileNode: (o) -> + expr: @expression.makeReturn() return expr.compile(o) unless expr instanceof ReturnNode del o, 'top' - o.as_statement: true if @expression.is_statement() + o.asStatement: true if @expression.isStatement() "${@tab}return ${@expression.compile(o)};" #### ValueNode @@ -292,22 +292,22 @@ exports.ValueNode: class ValueNode extends BaseNode @properties.push(prop) this - has_properties: -> + hasProperties: -> !!@properties.length # Some boolean checks for the benefit of other nodes. - is_array: -> - @base instanceof ArrayNode and not @has_properties() + isArray: -> + @base instanceof ArrayNode and not @hasProperties() - is_object: -> - @base instanceof ObjectNode and not @has_properties() + isObject: -> + @base instanceof ObjectNode and not @hasProperties() - is_splice: -> - @has_properties() and @properties[@properties.length - 1] instanceof SliceNode + isSplice: -> + @hasProperties() and @properties[@properties.length - 1] instanceof SliceNode - make_return: -> - if @has_properties() then super() else @base.make_return() + makeReturn: -> + if @hasProperties() then super() else @base.makeReturn() # The value can be unwrapped as its inner node, if there are no attached # properties. @@ -315,16 +315,16 @@ exports.ValueNode: class ValueNode extends BaseNode if @properties.length then this else @base # Values are considered to be statements if their base is a statement. - is_statement: -> - @base.is_statement and @base.is_statement() and not @has_properties() + isStatement: -> + @base.isStatement and @base.isStatement() and not @hasProperties() - is_number: -> + isNumber: -> @base instanceof LiteralNode and @base.value.match NUMBER # Works out if the value is the start of a chain. - is_start: (o) -> - return true if this is o.chain_root and @properties[0] instanceof AccessorNode - node: o.chain_root.base or o.chain_root.variable + isStart: (o) -> + return true if this is o.chainRoot and @properties[0] instanceof AccessorNode + node: o.chainRoot.base or o.chainRoot.variable while node instanceof CallNode then node: node.variable node is this @@ -332,22 +332,22 @@ exports.ValueNode: class ValueNode extends BaseNode # Things get much more insteresting if the chain of properties has *soak* # operators `?.` interspersed. Then we have to take care not to accidentally # evaluate a anything twice when building the soak chain. - compile_node: (o) -> - only: del(o, 'only_first') + compileNode: (o) -> + only: del(o, 'onlyFirst') op: del(o, 'operation') props: if only then @properties[0...@properties.length - 1] else @properties - o.chain_root: or this + o.chainRoot: or this baseline: @base.compile o - baseline: "($baseline)" if @has_properties() and (@base instanceof ObjectNode or @is_number()) + baseline: "($baseline)" if @hasProperties() and (@base instanceof ObjectNode or @isNumber()) complete: @last: baseline for prop, i in props @source: baseline - if prop.soak_node + if prop.soakNode if @base instanceof CallNode and i is 0 - temp: o.scope.free_variable() + temp: o.scope.freeVariable() complete: "(${ baseline: temp } = ($complete))" - complete: "typeof $complete === \"undefined\" || $baseline" if i is 0 and @is_start(o) + complete: "typeof $complete === \"undefined\" || $baseline" if i is 0 and @isStart(o) complete: + @SOAK + (baseline: + prop.compile(o)) else part: prop.compile(o) @@ -364,16 +364,16 @@ exports.ValueNode: class ValueNode extends BaseNode exports.CommentNode: class CommentNode extends BaseNode type: 'CommentNode' - is_statement: -> yes + isStatement: -> yes constructor: (lines, kind) -> @lines: lines @kind: kind - make_return: -> + makeReturn: -> this - compile_node: (o) -> + compileNode: (o) -> if @kind is 'herecomment' sep: '\n' + @tab "$@tab/*$sep${ @lines.join(sep) }\n$@tab*/" @@ -390,23 +390,23 @@ exports.CallNode: class CallNode extends BaseNode children: ['variable', 'args'] constructor: (variable, args) -> - @is_new: false - @is_super: variable is 'super' - @variable: if @is_super then null else variable + @isNew: false + @isSuper: variable is 'super' + @variable: if @isSuper then null else variable @args: (args or []) - @compile_splat_arguments: (o) -> - SplatNode.compile_mixed_array.call(this, @args, o) + @compileSplatArguments: (o) -> + SplatNode.compileMixedArray.call(this, @args, o) # Tag this invocation as creating a new instance. - new_instance: -> - @is_new: true + newInstance: -> + @isNew: true this prefix: -> - if @is_new then 'new ' else '' + if @isNew then 'new ' else '' # Grab the reference to the superclass' implementation of the current method. - super_reference: (o) -> + superReference: (o) -> methname: o.scope.method.name meth: if o.scope.method.proto "${o.scope.method.proto}.__superClass__.$methname" @@ -415,37 +415,37 @@ exports.CallNode: class CallNode extends BaseNode else throw new Error "cannot call super on an anonymous function." # Compile a vanilla function call. - compile_node: (o) -> - o.chain_root: this unless o.chain_root + compileNode: (o) -> + o.chainRoot: this unless o.chainRoot for arg in @args when arg instanceof SplatNode - compilation: @compile_splat(o) + compilation: @compileSplat(o) unless compilation args: (arg.compile(o) for arg in @args).join(', ') - compilation: if @is_super then @compile_super(args, o) + compilation: if @isSuper then @compileSuper(args, o) else "${@prefix()}${@variable.compile(o)}($args)" if o.operation and @wrapped then "($compilation)" else compilation # `super()` is converted into a call against the superclass's implementation # of the current function. - compile_super: (args, o) -> - "${@super_reference(o)}.call(this${ if args.length then ', ' else '' }$args)" + compileSuper: (args, o) -> + "${@superReference(o)}.call(this${ if args.length then ', ' else '' }$args)" # If you call a function with a splat, it's converted into a JavaScript # `.apply()` call to allow an array of arguments to be passed. - compile_splat: (o) -> - meth: if @variable then @variable.compile(o) else @super_reference(o) + compileSplat: (o) -> + meth: if @variable then @variable.compile(o) else @superReference(o) obj: @variable and @variable.source or 'this' if obj.match(/\(/) - temp: o.scope.free_variable() + temp: o.scope.freeVariable() obj: temp meth: "($temp = ${ @variable.source })${ @variable.last }" - "${@prefix()}${meth}.apply($obj, ${ @compile_splat_arguments(o) })" + "${@prefix()}${meth}.apply($obj, ${ @compileSplatArguments(o) })" #### ExtendsNode # Node to extend an object's prototype with an ancestor object. # After `goog.inherits` from the -# [Closure Library](http://closure-library.googlecode.com/svn/docs/closure_goog_base.js.html). +# [Closure Library](http://closure-library.googlecode.com/svn/docs/closureGoogBase.js.html). exports.ExtendsNode: class ExtendsNode extends BaseNode type: 'ExtendsNode' @@ -456,7 +456,7 @@ exports.ExtendsNode: class ExtendsNode extends BaseNode @parent: parent # Hooks one constructor into another's prototype chain. - compile_node: (o) -> + compileNode: (o) -> ref: new ValueNode literal utility 'extends' (new CallNode ref, [@child, @parent]).compile o @@ -472,12 +472,12 @@ exports.AccessorNode: class AccessorNode extends BaseNode constructor: (name, tag) -> @name: name @prototype: tag is 'prototype' - @soak_node: tag is 'soak' + @soakNode: tag is 'soak' - compile_node: (o) -> - o.chain_root.wrapped: or @soak_node - proto_part: if @prototype then 'prototype.' else '' - ".$proto_part${@name.compile(o)}" + compileNode: (o) -> + o.chainRoot.wrapped: or @soakNode + protoPart: if @prototype then 'prototype.' else '' + ".$protoPart${@name.compile(o)}" #### IndexNode @@ -490,8 +490,8 @@ exports.IndexNode: class IndexNode extends BaseNode constructor: (index) -> @index: index - compile_node: (o) -> - o.chain_root.wrapped: or @soak_node + compileNode: (o) -> + o.chainRoot.wrapped: or @soakNode idx: @index.compile o prefix: if @proto then '.prototype' else '' "$prefix[$idx]" @@ -513,33 +513,33 @@ exports.RangeNode: class RangeNode extends BaseNode # Compiles the range's source variables -- where it starts and where it ends. # But only if they need to be cached to avoid double evaluation. - compile_variables: (o) -> - [@from, @from_var]: @from.compile_reference o, true - [@to, @to_var]: @to.compile_reference o, true + compileVariables: (o) -> + [@from, @fromVar]: @from.compileReference o, true + [@to, @toVar]: @to.compileReference o, true parts: [] - parts.push @from.compile o if @from isnt @from_var - parts.push @to.compile o if @to isnt @to_var + parts.push @from.compile o if @from isnt @fromVar + parts.push @to.compile o if @to isnt @toVar if parts.length then "${parts.join('; ')};\n$o.indent" else '' # When compiled normally, the range returns the contents of the *for loop* # needed to iterate over the values in the range. Used by comprehensions. - compile_node: (o) -> - return @compile_array(o) unless o.index + compileNode: (o) -> + return @compileArray(o) unless o.index idx: del o, 'index' step: del o, 'step' - vars: "$idx = ${@from_var.compile(o)}" + vars: "$idx = ${@fromVar.compile(o)}" step: if step then step.compile(o) else '1' equals: if @exclusive then '' else '=' op: if starts(step, '-') then ">$equals" else "<$equals" - "$vars; ${idx} $op ${@to_var.compile(o)}; $idx += $step" + "$vars; ${idx} $op ${@toVar.compile(o)}; $idx += $step" # When used as a value, expand the range into the equivalent array. - compile_array: (o) -> + compileArray: (o) -> idt: @idt 1 - vars: @compile_variables(merge(o, {indent: idt})) + vars: @compileVariables(merge(o, {indent: idt})) equals: if @exclusive then '' else '=' - from: @from_var.compile o - to: @to_var.compile o + from: @fromVar.compile o + to: @toVar.compile o clause: "$from <= $to ?" pre: "\n${idt}a = [];${vars}" body: "var i = $from; ($clause i <$equals $to : i >$equals $to); ($clause i += 1 : i -= 1)" @@ -559,11 +559,11 @@ exports.SliceNode: class SliceNode extends BaseNode constructor: (range) -> @range: range - compile_node: (o) -> + compileNode: (o) -> from: @range.from.compile(o) to: @range.to.compile(o) - plus_part: if @range.exclusive then '' else ' + 1' - ".slice($from, $to$plus_part)" + plusPart: if @range.exclusive then '' else ' + 1' + ".slice($from, $to$plusPart)" #### ObjectNode @@ -579,13 +579,13 @@ exports.ObjectNode: class ObjectNode extends BaseNode # All the mucking about with commas is to make sure that CommentNodes and # AssignNodes get interleaved correctly, with no trailing commas or # commas affixed to comments. - compile_node: (o) -> + compileNode: (o) -> o.indent: @idt 1 - non_comments: prop for prop in @properties when not (prop instanceof CommentNode) - last_noncom: non_comments[non_comments.length - 1] + nonComments: prop for prop in @properties when not (prop instanceof CommentNode) + lastNoncom: nonComments[nonComments.length - 1] props: for prop, i in @properties join: ",\n" - join: "\n" if (prop is last_noncom) or (prop instanceof CommentNode) + join: "\n" if (prop is lastNoncom) or (prop instanceof CommentNode) join: '' if i is @properties.length - 1 indent: if prop instanceof CommentNode then '' else @idt 1 prop: new AssignNode prop, prop, 'object' unless prop instanceof AssignNode or prop instanceof CommentNode @@ -604,16 +604,16 @@ exports.ArrayNode: class ArrayNode extends BaseNode constructor: (objects) -> @objects: objects or [] - @compile_splat_literal: (o) -> - SplatNode.compile_mixed_array.call(this, @objects, o) + @compileSplatLiteral: (o) -> + SplatNode.compileMixedArray.call(this, @objects, o) - compile_node: (o) -> + compileNode: (o) -> o.indent: @idt 1 objects: [] for obj, i in @objects code: obj.compile(o) if obj instanceof SplatNode - return @compile_splat_literal @objects, o + return @compileSplatLiteral @objects, o else if obj instanceof CommentNode objects.push "\n$code\n$o.indent" else if i is @objects.length - 1 @@ -621,7 +621,7 @@ exports.ArrayNode: class ArrayNode extends BaseNode else objects.push "$code, " objects: objects.join('') - if index_of(objects, '\n') >= 0 + if indexOf(objects, '\n') >= 0 "[\n${@idt(1)}$objects\n$@tab]" else "[$objects]" @@ -633,7 +633,7 @@ exports.ClassNode: class ClassNode extends BaseNode type: 'ClassNode' children: ['variable', 'parent', 'properties'] - is_statement: -> yes + isStatement: -> yes # Initialize a **ClassNode** with its name, an optional superclass, and a # list of prototype property assignments. @@ -643,14 +643,14 @@ exports.ClassNode: class ClassNode extends BaseNode @properties: props or [] @returns: false - make_return: -> + makeReturn: -> @returns: true this # Instead of generating the JavaScript string directly, we build up the # equivalent syntax tree and compile that, in pieces. You can see the # constructor, property assignments, and inheritance getting built out below. - compile_node: (o) -> + compileNode: (o) -> extension: @parent and new ExtendsNode(@variable, @parent) constructor: null props: new Expressions() @@ -704,29 +704,29 @@ exports.AssignNode: class AssignNode extends BaseNode @value: value @context: context - top_sensitive: -> + topSensitive: -> true - is_value: -> + isValue: -> @variable instanceof ValueNode - make_return: -> + makeReturn: -> return new Expressions [this, new ReturnNode(@variable)] - is_statement: -> - @is_value() and (@variable.is_array() or @variable.is_object()) + isStatement: -> + @isValue() and (@variable.isArray() or @variable.isObject()) - # Compile an assignment, delegating to `compile_pattern_match` or - # `compile_splice` if appropriate. Keep track of the name of the base object + # Compile an assignment, delegating to `compilePatternMatch` or + # `compileSplice` if appropriate. Keep track of the name of the base object # we've been assigned to, for correct internal references. If the variable # has not been seen yet within the current scope, declare it. - compile_node: (o) -> + compileNode: (o) -> top: del o, 'top' - return @compile_pattern_match(o) if @is_statement() - return @compile_splice(o) if @is_value() and @variable.is_splice() - stmt: del o, 'as_statement' + return @compilePatternMatch(o) if @isStatement() + return @compileSplice(o) if @isValue() and @variable.isSplice() + stmt: del o, 'asStatement' name: @variable.compile(o) - last: if @is_value() then @variable.last.replace(@LEADING_DOT, '') else name + last: if @isValue() then @variable.last.replace(@LEADING_DOT, '') else name match: name.match(@PROTO_ASSIGN) proto: match and match[1] if @value instanceof CodeNode @@ -734,7 +734,7 @@ exports.AssignNode: class AssignNode extends BaseNode @value.proto: proto if proto val: @value.compile o return "$name: $val" if @context is 'object' - o.scope.find name unless @is_value() and (@variable.has_properties() or @variable.namespaced) + o.scope.find name unless @isValue() and (@variable.hasProperties() or @variable.namespaced) val: "$name = $val" return "$@tab$val;" if stmt if top then val else "($val)" @@ -743,17 +743,17 @@ exports.AssignNode: class AssignNode extends BaseNode # object literals to a value. Peeks at their properties to assign inner names. # See the [ECMAScript Harmony Wiki](http://wiki.ecmascript.org/doku.php?id=harmony:destructuring) # for details. - compile_pattern_match: (o) -> - val_var: o.scope.free_variable() - value: if @value.is_statement() then ClosureNode.wrap(@value) else @value - assigns: ["$@tab$val_var = ${ value.compile(o) };"] + compilePatternMatch: (o) -> + valVar: o.scope.freeVariable() + value: if @value.isStatement() then ClosureNode.wrap(@value) else @value + assigns: ["$@tab$valVar = ${ value.compile(o) };"] o.top: true - o.as_statement: true + o.asStatement: true splat: false for obj, i in @variable.base.objects # A regular array pattern-match. idx: i - if @variable.is_object() + if @variable.isObject() if obj instanceof AssignNode # A regular object pattern-match. [obj, idx]: [obj.value, obj.variable.base] @@ -762,24 +762,24 @@ exports.AssignNode: class AssignNode extends BaseNode idx: obj if not (obj instanceof ValueNode or obj instanceof SplatNode) throw new Error 'pattern matching must use only identifiers on the left-hand side.' - is_string: idx.value and idx.value.match IS_STRING - access_class: if is_string or @variable.is_array() then IndexNode else AccessorNode + isString: idx.value and idx.value.match IS_STRING + accessClass: if isString or @variable.isArray() then IndexNode else AccessorNode if obj instanceof SplatNode and not splat - val: literal(obj.compile_value(o, val_var, - (oindex: index_of(@variable.base.objects, obj)), + val: literal(obj.compileValue(o, valVar, + (oindex: indexOf(@variable.base.objects, obj)), (olength: @variable.base.objects.length) - oindex - 1)) splat: true else - idx: literal(if splat then "${val_var}.length - ${olength - idx}" else idx) if typeof idx isnt 'object' - val: new ValueNode(literal(val_var), [new access_class(idx)]) + idx: literal(if splat then "${valVar}.length - ${olength - idx}" else idx) if typeof idx isnt 'object' + val: new ValueNode(literal(valVar), [new accessClass(idx)]) assigns.push(new AssignNode(obj, val).compile(o)) code: assigns.join("\n") code # Compile the assignment from an array splice literal, using JavaScript's # `Array#splice` method. - compile_splice: (o) -> - name: @variable.compile merge o, {only_first: true} + compileSplice: (o) -> + name: @variable.compile merge o, {onlyFirst: true} l: @variable.properties.length range: @variable.properties[l - 1].range plus: if range.exclusive then '' else ' + 1' @@ -808,13 +808,13 @@ exports.CodeNode: class CodeNode extends BaseNode # the JavaScript `arguments` objects. If the function is bound with the `=>` # arrow, generates a wrapper that saves the current value of `this` through # a closure. - compile_node: (o) -> - shared_scope: del o, 'shared_scope' + compileNode: (o) -> + sharedScope: del o, 'sharedScope' top: del o, 'top' - o.scope: shared_scope or new Scope(o.scope, @body, this) + o.scope: sharedScope or new Scope(o.scope, @body, this) o.top: true o.indent: @idt(if @bound then 2 else 1) - del o, 'no_wrap' + del o, 'noWrap' del o, 'globals' i: 0 splat: undefined @@ -832,25 +832,25 @@ exports.CodeNode: class CodeNode extends BaseNode params.push(param) i: + 1 params: (param.compile(o) for param in params) - @body.make_return() + @body.makeReturn() (o.scope.parameter(param)) for param in params - code: if @body.expressions.length then "\n${ @body.compile_with_declarations(o) }\n" else '' + code: if @body.expressions.length then "\n${ @body.compileWithDeclarations(o) }\n" else '' func: "function(${ params.join(', ') }) {$code${@idt(if @bound then 1 else 0)}}" func: "($func)" if top and not @bound return func unless @bound inner: "(function() {\n${@idt(2)}return __func.apply(__this, arguments);\n${@idt(1)}});" "(function(__this) {\n${@idt(1)}var __func = $func;\n${@idt(1)}return $inner\n$@tab})(this)" - top_sensitive: -> + topSensitive: -> true - # Short-circuit traverse_children method to prevent it from crossing scope boundaries - # unless cross_scope is true - traverse_children: (cross_scope, func) -> super(cross_scope, func) if cross_scope + # Short-circuit traverseChildren method to prevent it from crossing scope boundaries + # unless crossScope is true + traverseChildren: (crossScope, func) -> super(crossScope, func) if crossScope toString: (idt) -> idt: or '' - children: (child.toString(idt + TAB) for child in @collect_children()).join('') + children: (child.toString(idt + TAB) for child in @collectChildren()).join('') "\n$idt$children" #### SplatNode @@ -866,17 +866,17 @@ exports.SplatNode: class SplatNode extends BaseNode name: literal(name) unless name.compile @name: name - compile_node: (o) -> - if @index? then @compile_param(o) else @name.compile(o) + compileNode: (o) -> + if @index? then @compileParam(o) else @name.compile(o) # Compiling a parameter splat means recovering the parameters that succeed # the splat in the parameter list, by slicing the arguments object. - compile_param: (o) -> + compileParam: (o) -> name: @name.compile(o) o.scope.find name - len: o.scope.free_variable() + len: o.scope.freeVariable() o.scope.assign len, "arguments.length" - variadic: o.scope.free_variable() + variadic: o.scope.freeVariable() o.scope.assign variadic, "$len >= $@arglength" for trailing, idx in @trailings pos: @trailings.length - idx @@ -885,13 +885,13 @@ exports.SplatNode: class SplatNode extends BaseNode # A compiling a splat as a destructuring assignment means slicing arguments # from the right-hand-side's corresponding array. - compile_value: (o, name, index, trailings) -> + compileValue: (o, name, index, trailings) -> trail: if trailings then ", ${name}.length - $trailings" else '' "${utility 'slice'}.call($name, $index$trail)" # Utility function that converts arbitrary number of elements, mixed with # splats, to a proper array - @compile_mixed_array: (list, o) -> + @compileMixedArray: (list, o) -> args: [] i: 0 for arg in list @@ -919,7 +919,7 @@ exports.WhileNode: class WhileNode extends BaseNode type: 'WhileNode' children: ['condition', 'guard', 'body'] - is_statement: -> yes + isStatement: -> yes constructor: (condition, opts) -> if opts and opts.invert @@ -928,28 +928,28 @@ exports.WhileNode: class WhileNode extends BaseNode @condition: condition @guard: opts and opts.guard - add_body: (body) -> + addBody: (body) -> @body: body this - make_return: -> + makeReturn: -> @returns: true this - top_sensitive: -> + topSensitive: -> true # The main difference from a JavaScript *while* is that the CoffeeScript # *while* can be used as a part of a larger expression -- while loops may # return an array containing the computed result of each iteration. - compile_node: (o) -> + compileNode: (o) -> top: del(o, 'top') and not @returns o.indent: @idt 1 o.top: true cond: @condition.compile(o) set: '' unless top - rvar: o.scope.free_variable() + rvar: o.scope.freeVariable() set: "$@tab$rvar = [];\n" @body: PushNode.wrap(rvar, @body) if @body pre: "$set${@tab}while ($cond)" @@ -991,18 +991,18 @@ exports.OpNode: class OpNode extends BaseNode @operator: @CONVERSIONS[operator] or operator @flip: !!flip - is_unary: -> + isUnary: -> not @second - is_chainable: -> - index_of(@CHAINABLE, @operator) >= 0 + isChainable: -> + indexOf(@CHAINABLE, @operator) >= 0 - compile_node: (o) -> + compileNode: (o) -> o.operation: true - return @compile_chain(o) if @is_chainable() and @first.unwrap() instanceof OpNode and @first.unwrap().is_chainable() - return @compile_assignment(o) if index_of(@ASSIGNMENT, @operator) >= 0 - return @compile_unary(o) if @is_unary() - return @compile_existence(o) if @operator is '?' + return @compileChain(o) if @isChainable() and @first.unwrap() instanceof OpNode and @first.unwrap().isChainable() + return @compileAssignment(o) if indexOf(@ASSIGNMENT, @operator) >= 0 + return @compileUnary(o) if @isUnary() + return @compileExistence(o) if @operator is '?' [@first.compile(o), @operator, @second.compile(o)].join ' ' # Mimic Python's chained comparisons when multiple comparison operators are @@ -1010,31 +1010,31 @@ exports.OpNode: class OpNode extends BaseNode # # bin/coffee -e "puts 50 < 65 > 10" # true - compile_chain: (o) -> + compileChain: (o) -> shared: @first.unwrap().second - [@first.second, shared]: shared.compile_reference(o) if shared.contains_type CallNode + [@first.second, shared]: shared.compileReference(o) if shared.containsType CallNode [first, second, shared]: [@first.compile(o), @second.compile(o), shared.compile(o)] "($first) && ($shared $@operator $second)" # When compiling a conditional assignment, take care to ensure that the # operands are only evaluated once, even though we have to reference them # more than once. - compile_assignment: (o) -> + compileAssignment: (o) -> [first, second]: [@first.compile(o), @second.compile(o)] o.scope.find(first) if first.match(IDENTIFIER) - return "$first = ${ ExistenceNode.compile_test(o, @first) } ? $first : $second" if @operator is '?=' + return "$first = ${ ExistenceNode.compileTest(o, @first) } ? $first : $second" if @operator is '?=' "$first = $first ${ @operator.substr(0, 2) } $second" - # If this is an existence operator, we delegate to `ExistenceNode.compile_test` + # If this is an existence operator, we delegate to `ExistenceNode.compileTest` # to give us the safe references for the variables. - compile_existence: (o) -> + compileExistence: (o) -> [first, second]: [@first.compile(o), @second.compile(o)] - test: ExistenceNode.compile_test(o, @first) + test: ExistenceNode.compileTest(o, @first) "$test ? $first : $second" # Compile a unary **OpNode**. - compile_unary: (o) -> - space: if index_of(@PREFIX_OPERATORS, @operator) >= 0 then ' ' else '' + compileUnary: (o) -> + space: if indexOf(@PREFIX_OPERATORS, @operator) >= 0 then ' ' else '' parts: [@operator, space, @first.compile(o)] parts: parts.reverse() if @flip parts.join('') @@ -1046,7 +1046,7 @@ exports.TryNode: class TryNode extends BaseNode type: 'TryNode' children: ['attempt', 'recovery', 'ensure'] - is_statement: -> yes + isStatement: -> yes constructor: (attempt, error, recovery, ensure) -> @attempt: attempt @@ -1054,21 +1054,21 @@ exports.TryNode: class TryNode extends BaseNode @ensure: ensure @error: error - make_return: -> - @attempt: @attempt.make_return() if @attempt - @recovery: @recovery.make_return() if @recovery + makeReturn: -> + @attempt: @attempt.makeReturn() if @attempt + @recovery: @recovery.makeReturn() if @recovery this # Compilation is more or less as you would expect -- the *finally* clause # is optional, the *catch* is not. - compile_node: (o) -> + compileNode: (o) -> o.indent: @idt 1 o.top: true - attempt_part: @attempt.compile(o) - error_part: if @error then " (${ @error.compile(o) }) " else ' ' - catch_part: if @recovery then " catch$error_part{\n${ @recovery.compile(o) }\n$@tab}" else '' - finally_part: (@ensure or '') and ' finally {\n' + @ensure.compile(merge(o)) + "\n$@tab}" - "${@tab}try {\n$attempt_part\n$@tab}$catch_part$finally_part" + attemptPart: @attempt.compile(o) + errorPart: if @error then " (${ @error.compile(o) }) " else ' ' + catchPart: if @recovery then " catch$errorPart{\n${ @recovery.compile(o) }\n$@tab}" else '' + finallyPart: (@ensure or '') and ' finally {\n' + @ensure.compile(merge(o)) + "\n$@tab}" + "${@tab}try {\n$attemptPart\n$@tab}$catchPart$finallyPart" #### ThrowNode @@ -1077,16 +1077,16 @@ exports.ThrowNode: class ThrowNode extends BaseNode type: 'ThrowNode' children: ['expression'] - is_statement: -> yes + isStatement: -> yes constructor: (expression) -> @expression: expression # A **ThrowNode** is already a return, of sorts... - make_return: -> + makeReturn: -> return this - compile_node: (o) -> + compileNode: (o) -> "${@tab}throw ${@expression.compile(o)};" #### ExistenceNode @@ -1102,14 +1102,14 @@ exports.ExistenceNode: class ExistenceNode extends BaseNode constructor: (expression) -> @expression: expression - compile_node: (o) -> - ExistenceNode.compile_test(o, @expression) + compileNode: (o) -> + ExistenceNode.compileTest(o, @expression) - # The meat of the **ExistenceNode** is in this static `compile_test` method + # The meat of the **ExistenceNode** is in this static `compileTest` method # because other nodes like to check the existence of their variables as well. # Be careful not to double-evaluate anything. - @compile_test: (o, variable) -> - [first, second]: variable.compile_reference o, true + @compileTest: (o, variable) -> + [first, second]: variable.compileReference o, true "(typeof ${first.compile(o)} !== \"undefined\" && ${second.compile(o)} !== null)" #### ParentheticalNode @@ -1127,15 +1127,15 @@ exports.ParentheticalNode: class ParentheticalNode extends BaseNode constructor: (expression) -> @expression: expression - is_statement: -> - @expression.is_statement() + isStatement: -> + @expression.isStatement() - make_return: -> - @expression.make_return() + makeReturn: -> + @expression.makeReturn() - compile_node: (o) -> + compileNode: (o) -> code: @expression.compile(o) - return code if @is_statement() + return code if @isStatement() l: code.length code: code.substr(o, l-1) if code.substr(l-1, 1) is ';' if @expression instanceof AssignNode then code else "($code)" @@ -1153,7 +1153,7 @@ exports.ForNode: class ForNode extends BaseNode type: 'ForNode' children: ['body', 'source', 'guard'] - is_statement: -> yes + isStatement: -> yes constructor: (body, source, name, index) -> @body: body @@ -1168,14 +1168,14 @@ exports.ForNode: class ForNode extends BaseNode throw new Error('index cannot be a pattern matching expression') if @index instanceof ValueNode @returns: false - top_sensitive: -> + topSensitive: -> true - make_return: -> + makeReturn: -> @returns: true this - compile_return_value: (val, o) -> + compileReturnValue: (val, o) -> return '\n' + new ReturnNode(literal(val)).compile(o) if @returns return '\n' + val if val '' @@ -1184,8 +1184,8 @@ exports.ForNode: class ForNode extends BaseNode # loop, filtering, stepping, and result saving for array, object, and range # comprehensions. Some of the generated code can be shared in common, and # some cannot. - compile_node: (o) -> - top_level: del(o, 'top') and not @returns + compileNode: (o) -> + topLevel: del(o, 'top') and not @returns range: @source instanceof ValueNode and @source.base instanceof RangeNode and not @source.properties.length source: if range then @source.base else @source scope: o.scope @@ -1193,39 +1193,39 @@ exports.ForNode: class ForNode extends BaseNode index: @index and @index.compile o scope.find name if name and not @pattern scope.find index if index - body_dent: @idt 1 - rvar: scope.free_variable() unless top_level - ivar: if range then name else index or scope.free_variable() - var_part: '' + bodyDent: @idt 1 + rvar: scope.freeVariable() unless topLevel + ivar: if range then name else index or scope.freeVariable() + varPart: '' body: Expressions.wrap([@body]) if range - source_part: source.compile_variables o - for_part: source.compile merge o, {index: ivar, step: @step} + sourcePart: source.compileVariables o + forPart: source.compile merge o, {index: ivar, step: @step} else - svar: scope.free_variable() - source_part: "$svar = ${ @source.compile(o) };" + svar: scope.freeVariable() + sourcePart: "$svar = ${ @source.compile(o) };" if @pattern - var_part: new AssignNode(@name, literal("$svar[$ivar]")).compile(merge o, {indent: @idt(1), top: true}) + "\n" + varPart: new AssignNode(@name, literal("$svar[$ivar]")).compile(merge o, {indent: @idt(1), top: true}) + "\n" else - var_part: "$body_dent$name = $svar[$ivar];\n" if name + varPart: "$bodyDent$name = $svar[$ivar];\n" if name unless @object - lvar: scope.free_variable() - step_part: if @step then "$ivar += ${ @step.compile(o) }" else "$ivar++" - for_part: "$ivar = 0, $lvar = ${svar}.length; $ivar < $lvar; $step_part" - source_part: (if rvar then "$rvar = []; " else '') + source_part - source_part: if source_part then "$@tab$source_part\n$@tab" else @tab - return_result: @compile_return_value(rvar, o) - - body: ClosureNode.wrap(body, true) if top_level and body.contains (n) -> n instanceof CodeNode - body: PushNode.wrap(rvar, body) unless top_level + lvar: scope.freeVariable() + stepPart: if @step then "$ivar += ${ @step.compile(o) }" else "$ivar++" + forPart: "$ivar = 0, $lvar = ${svar}.length; $ivar < $lvar; $stepPart" + sourcePart: (if rvar then "$rvar = []; " else '') + sourcePart + sourcePart: if sourcePart then "$@tab$sourcePart\n$@tab" else @tab + returnResult: @compileReturnValue(rvar, o) + + body: ClosureNode.wrap(body, true) if topLevel and body.contains (n) -> n instanceof CodeNode + body: PushNode.wrap(rvar, body) unless topLevel if @guard body: Expressions.wrap([new IfNode(@guard, body)]) if @object - for_part: "$ivar in $svar) { if (${utility('hasProp')}.call($svar, $ivar)" - body: body.compile(merge(o, {indent: body_dent, top: true})) + forPart: "$ivar in $svar) { if (${utility('hasProp')}.call($svar, $ivar)" + body: body.compile(merge(o, {indent: bodyDent, top: true})) vars: if range then name else "$name, $ivar" close: if @object then '}}' else '}' - "${source_part}for ($for_part) {\n$var_part$body\n$@tab$close$return_result" + "${sourcePart}for ($forPart) {\n$varPart$body\n$@tab$close$returnResult" #### IfNode @@ -1237,99 +1237,99 @@ exports.ForNode: class ForNode extends BaseNode exports.IfNode: class IfNode extends BaseNode type: 'IfNode' - children: ['condition', 'switch_subject', 'body', 'else_body', 'assigner'] + children: ['condition', 'switchSubject', 'body', 'elseBody', 'assigner'] constructor: (condition, body, tags) -> @condition: condition @body: body - @else_body: null + @elseBody: null @tags: tags or {} @condition: new OpNode('!', new ParentheticalNode(@condition)) if @tags.invert - @is_chain: false + @isChain: false - body_node: -> @body?.unwrap() - else_body_node: -> @else_body?.unwrap() + bodyNode: -> @body?.unwrap() + elseBodyNode: -> @elseBody?.unwrap() - force_statement: -> + forceStatement: -> @tags.statement: true this # Tag a chain of **IfNodes** with their object(s) to switch on for equality - # tests. `rewrite_switch` will perform the actual change at compile time. - switches_over: (expression) -> - @switch_subject: expression + # tests. `rewriteSwitch` will perform the actual change at compile time. + switchesOver: (expression) -> + @switchSubject: expression this # Rewrite a chain of **IfNodes** with their switch condition for equality. # Ensure that the switch expression isn't evaluated more than once. - rewrite_switch: (o) -> - @assigner: @switch_subject - unless (@switch_subject.unwrap() instanceof LiteralNode) - variable: literal(o.scope.free_variable()) - @assigner: new AssignNode(variable, @switch_subject) - @switch_subject: variable + rewriteSwitch: (o) -> + @assigner: @switchSubject + unless (@switchSubject.unwrap() instanceof LiteralNode) + variable: literal(o.scope.freeVariable()) + @assigner: new AssignNode(variable, @switchSubject) + @switchSubject: variable @condition: for cond, i in flatten [@condition] cond: new ParentheticalNode(cond) if cond instanceof OpNode - new OpNode('==', (if i is 0 then @assigner else @switch_subject), cond) - @else_body_node().switches_over(@switch_subject) if @is_chain + new OpNode('==', (if i is 0 then @assigner else @switchSubject), cond) + @elseBodyNode().switchesOver(@switchSubject) if @isChain # prevent this rewrite from happening again - @switch_subject: undefined + @switchSubject: undefined this # Rewrite a chain of **IfNodes** to add a default case as the final *else*. - add_else: (else_body, statement) -> - if @is_chain - @else_body_node().add_else else_body, statement + addElse: (elseBody, statement) -> + if @isChain + @elseBodyNode().addElse elseBody, statement else - @is_chain: else_body instanceof IfNode - @else_body: @ensure_expressions else_body + @isChain: elseBody instanceof IfNode + @elseBody: @ensureExpressions elseBody this # The **IfNode** only compiles into a statement if either of its bodies needs # to be a statement. Otherwise a ternary is safe. - is_statement: -> - @statement: or !!(@comment or @tags.statement or @body_node().is_statement() or (@else_body and @else_body_node().is_statement())) + isStatement: -> + @statement: or !!(@comment or @tags.statement or @bodyNode().isStatement() or (@elseBody and @elseBodyNode().isStatement())) - compile_condition: (o) -> + compileCondition: (o) -> (cond.compile(o) for cond in flatten([@condition])).join(' || ') - compile_node: (o) -> - if @is_statement() then @compile_statement(o) else @compile_ternary(o) + compileNode: (o) -> + if @isStatement() then @compileStatement(o) else @compileTernary(o) - make_return: -> - @body: and @ensure_expressions(@body.make_return()) - @else_body: and @ensure_expressions(@else_body.make_return()) + makeReturn: -> + @body: and @ensureExpressions(@body.makeReturn()) + @elseBody: and @ensureExpressions(@elseBody.makeReturn()) this - ensure_expressions: (node) -> + ensureExpressions: (node) -> node: new Expressions([node]) unless node instanceof Expressions node # Compile the **IfNode** as a regular *if-else* statement. Flattened chains # force inner *else* bodies into statement form. - compile_statement: (o) -> - @rewrite_switch(o) if @switch_subject - child: del o, 'chain_child' - cond_o: merge o + compileStatement: (o) -> + @rewriteSwitch(o) if @switchSubject + child: del o, 'chainChild' + condO: merge o o.indent: @idt 1 o.top: true - if_dent: if child then '' else @idt() - com_dent: if child then @idt() else '' - prefix: if @comment then "${ @comment.compile(cond_o) }\n$com_dent" else '' + ifDent: if child then '' else @idt() + comDent: if child then @idt() else '' + prefix: if @comment then "${ @comment.compile(condO) }\n$comDent" else '' body: @body.compile(o) - if_part: "$prefix${if_dent}if (${ @compile_condition(cond_o) }) {\n$body\n$@tab}" - return if_part unless @else_body - else_part: if @is_chain - ' else ' + @else_body_node().compile(merge(o, {indent: @idt(), chain_child: true})) + ifPart: "$prefix${ifDent}if (${ @compileCondition(condO) }) {\n$body\n$@tab}" + return ifPart unless @elseBody + elsePart: if @isChain + ' else ' + @elseBodyNode().compile(merge(o, {indent: @idt(), chainChild: true})) else - " else {\n${ @else_body.compile(o) }\n$@tab}" - "$if_part$else_part" + " else {\n${ @elseBody.compile(o) }\n$@tab}" + "$ifPart$elsePart" # Compile the IfNode as a ternary operator. - compile_ternary: (o) -> - if_part: @condition.compile(o) + ' ? ' + @body_node().compile(o) - else_part: if @else_body then @else_body_node().compile(o) else 'null' - "$if_part : $else_part" + compileTernary: (o) -> + ifPart: @condition.compile(o) + ' ? ' + @bodyNode().compile(o) + elsePart: if @elseBody then @elseBodyNode().compile(o) else 'null' + "$ifPart : $elsePart" # Faux-Nodes # ---------- @@ -1344,7 +1344,7 @@ PushNode: exports.PushNode: { wrap: (array, expressions) -> expr: expressions.unwrap() - return expressions if expr.is_pure_statement() or expr.contains_pure_statement() + return expressions if expr.isPureStatement() or expr.containsPureStatement() Expressions.wrap([new CallNode( new ValueNode(literal(array), [new AccessorNode(literal('push'))]), [expr] )]) @@ -1360,15 +1360,15 @@ ClosureNode: exports.ClosureNode: { # in which case, no dice. If the body mentions `this` or `arguments`, # then make sure that the closure wrapper preserves the original values. wrap: (expressions, statement) -> - return expressions if expressions.contains_pure_statement() + return expressions if expressions.containsPureStatement() func: new ParentheticalNode(new CodeNode([], Expressions.wrap([expressions]))) args: [] - mentions_args: expressions.contains (n) -> (n instanceof LiteralNode) and (n.value is 'arguments') - mentions_this: expressions.contains (n) -> (n instanceof LiteralNode) and (n.value is 'this') - if mentions_args or mentions_this - meth: literal(if mentions_args then 'apply' else 'call') + mentionsArgs: expressions.contains (n) -> (n instanceof LiteralNode) and (n.value is 'arguments') + mentionsThis: expressions.contains (n) -> (n instanceof LiteralNode) and (n.value is 'this') + if mentionsArgs or mentionsThis + meth: literal(if mentionsArgs then 'apply' else 'call') args: [literal('this')] - args.push literal 'arguments' if mentions_args + args.push literal 'arguments' if mentionsArgs func: new ValueNode func, [new AccessorNode(meth)] call: new CallNode(func, args) if statement then Expressions.wrap([call]) else call @@ -1382,7 +1382,7 @@ UTILITIES: { # Correctly set up a prototype chain for inheritance, including a reference # to the superclass for `super()` calls. See: - # [goog.inherits](http://closure-library.googlecode.com/svn/docs/closure_goog_base.js.source.html#line1206). + # [goog.inherits](http://closure-library.googlecode.com/svn/docs/closureGoogBase.js.source.html#line1206). __extends: """ function(child, parent) { var ctor = function(){ }; diff --git a/src/optparse.coffee b/src/optparse.coffee index 2f177c5f11..94645e6077 100644 --- a/src/optparse.coffee +++ b/src/optparse.coffee @@ -1,7 +1,7 @@ # A simple **OptionParser** class to parse option flags from the command-line. # Use it like so: # -# parser: new OptionParser switches, help_banner +# parser: new OptionParser switches, helpBanner # options: parser.parse process.argv exports.OptionParser: class OptionParser @@ -12,7 +12,7 @@ exports.OptionParser: class OptionParser # Along with an an optional banner for the usage help. constructor: (rules, banner) -> @banner: banner - @rules: build_rules(rules) + @rules: buildRules(rules) # Parse the list of arguments, populating an `options` object with all of the # specified options, and returning it. `options.arguments` will be an array @@ -21,17 +21,17 @@ exports.OptionParser: class OptionParser # flag. Instead, you're responsible for interpreting the options object. parse: (args) -> options: {arguments: []} - args: normalize_arguments args + args: normalizeArguments args while (arg: args.shift()) - is_option: !!(arg.match(LONG_FLAG) or arg.match(SHORT_FLAG)) - matched_rule: no + isOption: !!(arg.match(LONG_FLAG) or arg.match(SHORT_FLAG)) + matchedRule: no for rule in @rules - if rule.short_flag is arg or rule.long_flag is arg - options[rule.name]: if rule.has_argument then args.shift() else true - matched_rule: yes + if rule.shortFlag is arg or rule.longFlag is arg + options[rule.name]: if rule.hasArgument then args.shift() else true + matchedRule: yes break - throw new Error "unrecognized option: $arg" if is_option and not matched_rule - options.arguments.push arg unless is_option + throw new Error "unrecognized option: $arg" if isOption and not matchedRule + options.arguments.push arg unless isOption options # Return the help text for this **OptionParser**, listing and describing all @@ -40,10 +40,10 @@ exports.OptionParser: class OptionParser lines: ['Available options:'] lines.unshift "$@banner\n" if @banner for rule in @rules - spaces: 15 - rule.long_flag.length + spaces: 15 - rule.longFlag.length spaces: if spaces > 0 then (' ' for i in [0..spaces]).join('') else '' - let_part: if rule.short_flag then rule.short_flag + ', ' else ' ' - lines.push " $let_part$rule.long_flag$spaces$rule.description" + letPart: if rule.shortFlag then rule.shortFlag + ', ' else ' ' + lines.push " $letPart$rule.longFlag$spaces$rule.description" "\n${ lines.join('\n') }\n" # Helpers @@ -57,27 +57,27 @@ OPTIONAL: /\[(.+)\]/ # Build and return the list of option rules. If the optional *short-flag* is # unspecified, leave it out by padding with `null`. -build_rules: (rules) -> +buildRules: (rules) -> for tuple in rules tuple.unshift null if tuple.length < 3 - build_rule tuple... + buildRule tuple... # Build a rule from a `-o` short flag, a `--output [DIR]` long flag, and the # description of what the option does. -build_rule: (short_flag, long_flag, description) -> - match: long_flag.match(OPTIONAL) - long_flag: long_flag.match(LONG_FLAG)[1] +buildRule: (shortFlag, longFlag, description) -> + match: longFlag.match(OPTIONAL) + longFlag: longFlag.match(LONG_FLAG)[1] { - name: long_flag.substr 2 - short_flag: short_flag - long_flag: long_flag + name: longFlag.substr 2 + shortFlag: shortFlag + longFlag: longFlag description: description - has_argument: !!(match and match[1]) + hasArgument: !!(match and match[1]) } # Normalize arguments by expanding merged flags into multiple flags. This allows # you to have `-wl` be the same as `--watch --lint`. -normalize_arguments: (args) -> +normalizeArguments: (args) -> args: args.slice 0 result: [] for arg in args diff --git a/src/repl.coffee b/src/repl.coffee index 7bb2454344..1b2bdb64ba 100644 --- a/src/repl.coffee +++ b/src/repl.coffee @@ -22,7 +22,7 @@ helpers.extend global, { # of exiting. run: (buffer) -> try - val: CoffeeScript.run buffer.toString(), {no_wrap: true, globals: true, source: 'repl'} + val: CoffeeScript.run buffer.toString(), {noWrap: true, globals: true, source: 'repl'} puts inspect val if val isnt undefined catch err puts err.stack or err.toString() diff --git a/src/rewriter.coffee b/src/rewriter.coffee index 017a2b0722..de9b5c9883 100644 --- a/src/rewriter.coffee +++ b/src/rewriter.coffee @@ -26,14 +26,14 @@ exports.Rewriter: class Rewriter # corrected before implicit parentheses can be wrapped around blocks of code. rewrite: (tokens) -> @tokens: tokens - @adjust_comments() - @remove_leading_newlines() - @remove_mid_expression_newlines() - @close_open_calls_and_indexes() - @add_implicit_indentation() - @add_implicit_parentheses() - @ensure_balance BALANCED_PAIRS - @rewrite_closing_parens() + @adjustComments() + @removeLeadingNewlines() + @removeMidExpressionNewlines() + @closeOpenCallsAndIndexes() + @addImplicitIndentation() + @addImplicitParentheses() + @ensureBalance BALANCED_PAIRS + @rewriteClosingParens() @tokens # Rewrite the token stream, looking one token ahead and behind. @@ -41,7 +41,7 @@ exports.Rewriter: class Rewriter # forwards (or backwards) in the stream, to make sure we don't miss anything # as tokens are inserted and removed, and the stream changes length under # our feet. - scan_tokens: (block) -> + scanTokens: (block) -> i: 0 loop break unless @tokens[i] @@ -51,8 +51,8 @@ exports.Rewriter: class Rewriter # Massage newlines and indentations so that comments don't have to be # correctly indented, or appear on a line of their own. - adjust_comments: -> - @scan_tokens (prev, token, post, i) => + adjustComments: -> + @scanTokens (prev, token, post, i) => return 1 unless include COMMENTS, token[0] [before, after]: [@tokens[i - 2], @tokens[i + 2]] if after and after[0] is 'INDENT' @@ -74,13 +74,13 @@ exports.Rewriter: class Rewriter # Leading newlines would introduce an ambiguity in the grammar, so we # dispatch them here. - remove_leading_newlines: -> + removeLeadingNewlines: -> @tokens.shift() while @tokens[0] and @tokens[0][0] is 'TERMINATOR' # Some blocks occur in the middle of expressions -- when we're expecting # this, remove their trailing newlines. - remove_mid_expression_newlines: -> - @scan_tokens (prev, token, post, i) => + removeMidExpressionNewlines: -> + @scanTokens (prev, token, post, i) => return 1 unless post and include(EXPRESSION_CLOSE, post[0]) and token[0] is 'TERMINATOR' @tokens.splice i, 1 return 0 @@ -88,10 +88,10 @@ exports.Rewriter: class Rewriter # The lexer has tagged the opening parenthesis of a method call, and the # opening bracket of an indexing operation. Match them with their paired # close. - close_open_calls_and_indexes: -> + closeOpenCallsAndIndexes: -> parens: [0] brackets: [0] - @scan_tokens (prev, token, post, i) => + @scanTokens (prev, token, post, i) => switch token[0] when 'CALL_START' then parens.push 0 when 'INDEX_START' then brackets.push 0 @@ -114,15 +114,15 @@ exports.Rewriter: class Rewriter # Methods may be optionally called without parentheses, for simple cases. # Insert the implicit parentheses here, so that the parser doesn't have to # deal with them. - add_implicit_parentheses: -> + addImplicitParentheses: -> stack: [0] - close_calls: (i) => + closeCalls: (i) => for tmp in [0...stack[stack.length - 1]] @tokens.splice(i, 0, ['CALL_END', ')', @tokens[i][2]]) size: stack[stack.length - 1] + 1 stack[stack.length - 1]: 0 size - @scan_tokens (prev, token, post, i) => + @scanTokens (prev, token, post, i) => tag: token[0] stack[stack.length - 2]: + stack.pop() if tag is 'OUTDENT' open: stack[stack.length - 1] > 0 @@ -133,7 +133,7 @@ exports.Rewriter: class Rewriter return 2 if include(EXPRESSION_START, tag) if tag is 'INDENT' and !token.generated and open and not (prev and include(IMPLICIT_BLOCK, prev[0])) - size: close_calls(i) + size: closeCalls(i) stack.push 0 return size stack.push 0 @@ -143,7 +143,7 @@ exports.Rewriter: class Rewriter if nx? and nx[0] is ',' @tokens.splice(i, 1) if tag is 'TERMINATOR' else - size: close_calls(i) + size: closeCalls(i) stack.pop() if tag isnt 'OUTDENT' and include EXPRESSION_END, tag return size if tag isnt 'OUTDENT' and include EXPRESSION_END, tag @@ -155,8 +155,8 @@ exports.Rewriter: class Rewriter # expressions that lack ending delimiters. The **Rewriter** adds the implicit # blocks, so it doesn't need to. ')' can close a single-line block, # but we need to make sure it's balanced. - add_implicit_indentation: -> - @scan_tokens (prev, token, post, i) => + addImplicitIndentation: -> + @scanTokens (prev, token, post, i) => return 1 unless include(SINGLE_LINERS, token[0]) and post[0] isnt 'INDENT' and not (token[0] is 'ELSE' and post[0] is 'IF') @@ -187,15 +187,15 @@ exports.Rewriter: class Rewriter # Ensure that all listed pairs of tokens are correctly balanced throughout # the course of the token stream. - ensure_balance: (pairs) -> + ensureBalance: (pairs) -> levels: {} - open_line: {} - @scan_tokens (prev, token, post, i) => + openLine: {} + @scanTokens (prev, token, post, i) => for pair in pairs [open, close]: pair levels[open]: or 0 if token[0] is open - open_line[open]: token[2] if levels[open] == 0 + openLine[open]: token[2] if levels[open] == 0 levels[open]: + 1 levels[open]: - 1 if token[0] is close throw new Error("too many ${token[1]} on line ${token[2] + 1}") if levels[open] < 0 @@ -203,7 +203,7 @@ exports.Rewriter: class Rewriter unclosed: key for key, value of levels when value > 0 if unclosed.length open: unclosed[0] - line: open_line[open] + 1 + line: openLine[open] + 1 throw new Error "unclosed $open on line $line" # We'd like to support syntax like this: @@ -222,11 +222,11 @@ exports.Rewriter: class Rewriter # up balanced in the end. # 4. Be careful not to alter array or parentheses delimiters with overzealous # rewriting. - rewrite_closing_parens: -> + rewriteClosingParens: -> stack: [] debt: {} (debt[key]: 0) for key, val of INVERSES - @scan_tokens (prev, token, post, i) => + @scanTokens (prev, token, post, i) => tag: token[0] inv: INVERSES[token[0]] if include EXPRESSION_START, tag diff --git a/src/scope.coffee b/src/scope.coffee index ec96ac5c47..5cc10dbf18 100644 --- a/src/scope.coffee +++ b/src/scope.coffee @@ -21,10 +21,10 @@ exports.Scope: class Scope [@parent, @expressions, @method]: [parent, expressions, method] @variables: {} if @parent - @temp_var: @parent.temp_var + @tempVar: @parent.tempVar else Scope.root: this - @temp_var: '_a' + @tempVar: '_a' # Look up a variable name in lexical scope, and declare it if it does not # already exist. @@ -51,12 +51,12 @@ exports.Scope: class Scope # If we need to store an intermediate result, find an available name for a # compiler-generated variable. `_a`, `_b`, and so on... - free_variable: -> - while @check @temp_var - ordinal: 1 + parseInt @temp_var.substr(1), 36 - @temp_var: '_' + ordinal.toString(36).replace(/\d/g, 'a') - @variables[@temp_var]: 'var' - @temp_var + freeVariable: -> + while @check @tempVar + ordinal: 1 + parseInt @tempVar.substr(1), 36 + @tempVar: '_' + ordinal.toString(36).replace(/\d/g, 'a') + @variables[@tempVar]: 'var' + @tempVar # Ensure that an assignment is made at the top of this scope # (or at the top-level scope, if requested). @@ -65,27 +65,27 @@ exports.Scope: class Scope # Does this scope reference any variables that need to be declared in the # given function body? - has_declarations: (body) -> + hasDeclarations: (body) -> body is @expressions and @any (k, val) -> val is 'var' # Does this scope reference any assignments that need to be declared at the # top of the given function body? - has_assignments: (body) -> + hasAssignments: (body) -> body is @expressions and @any (k, val) -> val.assigned # Return the list of variables first declared in this scope. - declared_variables: -> + declaredVariables: -> (key for key, val of @variables when val is 'var').sort() # Return the list of assignments that are supposed to be made at the top # of this scope. - assigned_variables: -> + assignedVariables: -> "$key = $val.value" for key, val of @variables when val.assigned # Compile the JavaScript for all of the variable declarations in this scope. - compiled_declarations: -> - @declared_variables().join ', ' + compiledDeclarations: -> + @declaredVariables().join ', ' # Compile the JavaScript for all of the variable assignments in this scope. - compiled_assignments: -> - @assigned_variables().join ', ' + compiledAssignments: -> + @assignedVariables().join ', ' diff --git a/test/test_arguments.coffee b/test/test_arguments.coffee index f53c9e2218..1fccb7ef74 100644 --- a/test/test_arguments.coffee +++ b/test/test_arguments.coffee @@ -17,9 +17,9 @@ ok(area( ) is 100) -sum_of_args: -> +sumOfArgs: -> sum: 0 sum: + val for val in arguments sum -ok sum_of_args(1, 2, 3, 4, 5) is 15 \ No newline at end of file +ok sumOfArgs(1, 2, 3, 4, 5) is 15 \ No newline at end of file diff --git a/test/test_assignment.coffee b/test/test_assignment.coffee index 383c40e5a3..9144d38cf6 100644 --- a/test/test_assignment.coffee +++ b/test/test_assignment.coffee @@ -10,13 +10,13 @@ ok result is true and result2 is true # Can assign a conditional statement. -get_x: -> 10 +getX: -> 10 -if x: get_x() then 100 +if x: getX() then 100 ok x is 10 -x: if get_x() then 100 +x: if getX() then 100 ok x is 100 diff --git a/test/test_break.coffee b/test/test_break.coffee index 303a7f722a..53ac158b80 100644 --- a/test/test_break.coffee +++ b/test/test_break.coffee @@ -1,8 +1,8 @@ # Test with break at the top level. array: [1,2,3] -call_with_lambda: (l) -> null +callWithLambda: (l) -> null for i in array - result: call_with_lambda(->) + result: callWithLambda(->) if i == 2 puts "i = 2" else @@ -12,10 +12,10 @@ ok result is null # Test with break *not* at the top level. -some_func: (input) -> - takes_lambda: (l) -> null +someFunc: (input) -> + takesLambda: (l) -> null for i in [1,2] - result: takes_lambda(->) + result: takesLambda(->) if input == 1 return 1 else @@ -23,6 +23,6 @@ some_func: (input) -> return 2 -ok some_func(1) is 1 -ok some_func(2) is 2 +ok someFunc(1) is 1 +ok someFunc(2) is 2 diff --git a/test/test_chaining.coffee b/test/test_chaining.coffee index 040418d7f5..f9c1436dcb 100644 --- a/test/test_chaining.coffee +++ b/test/test_chaining.coffee @@ -1,8 +1,8 @@ # Basic chained function calls. -identity_wrap: (x) -> +identityWrap: (x) -> -> x -result: identity_wrap(identity_wrap(true))()() +result: identityWrap(identityWrap(true))()() ok result diff --git a/test/test_classes.coffee b/test/test_classes.coffee index ae1a5f0dc9..16150dc06e 100644 --- a/test/test_classes.coffee +++ b/test/test_classes.coffee @@ -102,11 +102,11 @@ ok (new SubClass()).prop is 'top-super-sub' # '@' referring to the current instance, and not being coerced into a call. class ClassName - am_i: -> + amI: -> @ instanceof ClassName obj: new ClassName() -ok obj.am_i() +ok obj.amI() # super() calls in constructors of classes that are defined as object properties. diff --git a/test/test_comments.coffee b/test/test_comments.coffee index 582ab64cf1..dcd8981967 100644 --- a/test/test_comments.coffee +++ b/test/test_comments.coffee @@ -13,7 +13,7 @@ switch 'string' when false then something() # comment when null - something_else() + somethingElse() -> code() diff --git a/test/test_compilation.coffee b/test/test_compilation.coffee index 7163c638d8..2c39511701 100644 --- a/test/test_compilation.coffee +++ b/test/test_compilation.coffee @@ -2,7 +2,7 @@ CoffeeScript: require('./../lib/coffee-script') Lexer: require('./../lib/lexer') -js: CoffeeScript.compile("one\r\ntwo", {no_wrap: on}) +js: CoffeeScript.compile("one\r\ntwo", {noWrap: on}) ok js is "one;\ntwo;" @@ -17,7 +17,7 @@ class SplitNode extends BaseNode constructor: (variable) -> @variable: variable - compile_node: (o) -> + compileNode: (o) -> "'${@variable}'.split('')" # Extend CoffeeScript with our lexing function that matches --wordgoeshere-- @@ -29,7 +29,7 @@ CoffeeScript.extend -> true # Compile with the extension. -js: CoffeeScript.compile 'return --tobesplit--', {no_wrap: on} +js: CoffeeScript.compile 'return --tobesplit--', {noWrap: on} ok js is "return 'tobesplit'.split('');" @@ -42,7 +42,7 @@ class WordArrayNode extends BaseNode constructor: (words) -> @words: words - compile_node: (o) -> + compileNode: (o) -> strings = ("\"$word\"" for word in @words).join ', ' "[$strings]" @@ -52,7 +52,7 @@ CoffeeScript.extend -> @token 'EXTENSION', new WordArrayNode(words[1].split(/\s+/)) true -js: CoffeeScript.compile 'puts %w{one two three}', {no_wrap: on} +js: CoffeeScript.compile 'puts %w{one two three}', {noWrap: on} ok js is 'puts(["one", "two", "three"]);' @@ -65,7 +65,7 @@ CoffeeScript.extend -> @token 'PROPERTY_ACCESS', '.' @token 'IDENTIFIER', 'push' -js: CoffeeScript.compile 'a << b', {no_wrap: on} +js: CoffeeScript.compile 'a << b', {noWrap: on} ok js is 'a.push(b);' diff --git a/test/test_comprehensions.coffee b/test/test_comprehensions.coffee index b5c7ed3097..3c11196306 100644 --- a/test/test_comprehensions.coffee +++ b/test/test_comprehensions.coffee @@ -80,17 +80,17 @@ ok(num % 2 is 0 for num in array by 2) # Nested comprehensions. -multi_liner: +multiLiner: for x in [3..5] for y in [3..5] [x, y] -single_liner: +singleLiner: [x, y] for y in [3..5] for x in [3..5] -ok multi_liner.length is single_liner.length -ok 5 is multi_liner[2][2][1] -ok 5 is single_liner[2][2][1] +ok multiLiner.length is singleLiner.length +ok 5 is multiLiner[2][2][1] +ok 5 is singleLiner[2][2][1] # Comprehensions within parentheses. diff --git a/test/test_existence.coffee b/test/test_existence.coffee index 481d25639d..0843c9c43a 100644 --- a/test/test_existence.coffee +++ b/test/test_existence.coffee @@ -1,8 +1,8 @@ -ok(if my_special_variable? then false else true) +ok(if mySpecialVariable? then false else true) -my_special_variable: false +mySpecialVariable: false -ok(if my_special_variable? then true else false) +ok(if mySpecialVariable? then true else false) # Existential assignment. @@ -23,11 +23,11 @@ ok z is null and x is "EX" # Only evaluate once. counter: 0 -get_next_node: -> +getNextNode: -> throw "up" if counter counter++ -ok(if get_next_node()? then true else false) +ok(if getNextNode()? then true else false) # Existence chains, soaking up undefined properties: diff --git a/test/test_expressions.coffee b/test/test_expressions.coffee index 4836119f2d..c787463040 100644 --- a/test/test_expressions.coffee +++ b/test/test_expressions.coffee @@ -1,4 +1,4 @@ -# Ensure that we don't wrap Nodes that are "pure_statement" in a closure. +# Ensure that we don't wrap Nodes that are "pureStatement" in a closure. items: [1, 2, 3, "bacon", 4, 5] for item in items diff --git a/test/test_functions.coffee b/test/test_functions.coffee index 600dc540e7..c0ac6ea002 100644 --- a/test/test_functions.coffee +++ b/test/test_functions.coffee @@ -57,8 +57,8 @@ ok 100 > 1 if 1 > 0 ok true unless false ok true for i in [1..3] -ok_func: (f) -> ok(f()) -ok_func -> true +okFunc: (f) -> ok(f()) +okFunc -> true # Optional parens can be used in a nested fashion. call: (func) -> func() diff --git a/test/test_literals.coffee b/test/test_literals.coffee index 2f6ded0a9f..960d5f5119 100644 --- a/test/test_literals.coffee +++ b/test/test_literals.coffee @@ -40,18 +40,18 @@ reg: /\\/ ok reg(str) and str is '\\' -trailing_comma: [1, 2, 3,] -ok (trailing_comma[0] is 1) and (trailing_comma[2] is 3) and (trailing_comma.length is 3) +trailingComma: [1, 2, 3,] +ok (trailingComma[0] is 1) and (trailingComma[2] is 3) and (trailingComma.length is 3) -trailing_comma: [ +trailingComma: [ 1, 2, 3, 4, 5, 6 7, 8, 9, ] -(sum: (sum or 0) + n) for n in trailing_comma +(sum: (sum or 0) + n) for n in trailingComma -trailing_comma: {k1: "v1", k2: 4, k3: (-> true),} -ok trailing_comma.k3() and (trailing_comma.k2 is 4) and (trailing_comma.k1 is "v1") +trailingComma: {k1: "v1", k2: 4, k3: (-> true),} +ok trailingComma.k3() and (trailingComma.k2 is 4) and (trailingComma.k1 is "v1") multiline: {a: 15, b: 26} diff --git a/test/test_module.coffee b/test/test_module.coffee index e776984787..97ebef20c5 100644 --- a/test/test_module.coffee +++ b/test/test_module.coffee @@ -1,4 +1,4 @@ -# This file is imported by `test_importing.coffee` +# This file is imported by `testImporting.coffee` local: "from over there" diff --git a/test/test_splats.coffee b/test/test_splats.coffee index 5b89e77387..d4073704fe 100644 --- a/test/test_splats.coffee +++ b/test/test_splats.coffee @@ -6,13 +6,13 @@ result: func 1, 2, 3, 4, 5 ok result is "3 4 5" -gold: silver: bronze: the_field: last: null +gold: silver: bronze: theField: last: null medalists: (first, second, third, rest..., unlucky) -> gold: first silver: second bronze: third - the_field: rest.concat([last]) + theField: rest.concat([last]) last: unlucky contenders: [ @@ -34,7 +34,7 @@ ok gold is "Mighty Mouse" ok silver is "Michael Phelps" ok bronze is "Liu Xiang" ok last is "Usain Bolt" -ok the_field.length is 8 +ok theField.length is 8 contenders.reverse() medalists contenders[0...2]..., "Mighty Mouse", contenders[2...contenders.length]... @@ -43,7 +43,7 @@ ok gold is "Usain Bolt" ok silver is "Asafa Powell" ok bronze is "Mighty Mouse" ok last is "Michael Phelps" -ok the_field.length is 8 +ok theField.length is 8 medalists contenders..., 'Tim', 'Moe', 'Jim' ok last is 'Jim' diff --git a/test/test_switch.coffee b/test/test_switch.coffee index 5b8b4bfa6b..baa82ee504 100644 --- a/test/test_switch.coffee +++ b/test/test_switch.coffee @@ -46,7 +46,7 @@ ok result result: false switch "word" when "one thing" - do_something() + doSomething() else result: true unless false @@ -55,9 +55,9 @@ ok result result: false switch "word" when "one thing" - do_something() + doSomething() when "other thing" - do_something() + doSomething() else result: true unless false