mirror of
https://github.com/jashkenas/coffeescript.git
synced 2026-01-13 08:47:55 -05:00
Compare commits
271 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1e024b5c8 | ||
|
|
4895e6ddc9 | ||
|
|
3d43c41a67 | ||
|
|
0e645cce41 | ||
|
|
4f564dec60 | ||
|
|
20144abe25 | ||
|
|
a8631dcbaf | ||
|
|
f5cd6578b8 | ||
|
|
f1af50ee33 | ||
|
|
ad5e69d303 | ||
|
|
7d800b5e5b | ||
|
|
f150011d9d | ||
|
|
a09f807ce0 | ||
|
|
6082b9dc36 | ||
|
|
326904826d | ||
|
|
3f30712ca1 | ||
|
|
e9b72ee955 | ||
|
|
7be3b8edac | ||
|
|
3daac200e5 | ||
|
|
f77877d7eb | ||
|
|
536bdd2107 | ||
|
|
0093455d29 | ||
|
|
67d34ec40b | ||
|
|
d8603dbff2 | ||
|
|
6b6cb3ab12 | ||
|
|
10f53bac15 | ||
|
|
15f12423c3 | ||
|
|
885dbaf7e4 | ||
|
|
0d0df09c6d | ||
|
|
7df7ff26c8 | ||
|
|
841258b360 | ||
|
|
f715393b06 | ||
|
|
abfe3c35f8 | ||
|
|
8517455746 | ||
|
|
0e86fa534e | ||
|
|
1dbf257df7 | ||
|
|
5cbd94bf14 | ||
|
|
fa3f3e41d4 | ||
|
|
94bab256b4 | ||
|
|
dfa2f50076 | ||
|
|
e2de88544d | ||
|
|
010a2dde11 | ||
|
|
2fb8f48e75 | ||
|
|
271ea24b20 | ||
|
|
792fd359bd | ||
|
|
acf4a5ee47 | ||
|
|
d9afe2cf44 | ||
|
|
ee304485b8 | ||
|
|
5957ba624a | ||
|
|
2b40607b57 | ||
|
|
8da4185bbf | ||
|
|
e8df8abf7a | ||
|
|
b7ef9510c9 | ||
|
|
fba131c5a4 | ||
|
|
4985a400e6 | ||
|
|
2ed041b5e1 | ||
|
|
5bcb2b2629 | ||
|
|
adca8183de | ||
|
|
c187f2160f | ||
|
|
959c9a31cb | ||
|
|
9f6233473e | ||
|
|
32b0f9fa4f | ||
|
|
f7e49eaae4 | ||
|
|
3042a50f87 | ||
|
|
c8e820e851 | ||
|
|
66f92e770d | ||
|
|
f3472b7437 | ||
|
|
fdf2a76c53 | ||
|
|
d11569b434 | ||
|
|
86be82f3ae | ||
|
|
bcc5aa2bc3 | ||
|
|
5658b2b41f | ||
|
|
34bf4ce325 | ||
|
|
4251aa30c6 | ||
|
|
3ad9316fd0 | ||
|
|
e4ae324e8f | ||
|
|
370d05148d | ||
|
|
3f27b0ff72 | ||
|
|
71cf6ab031 | ||
|
|
f3e9a18c3c | ||
|
|
d2176acf25 | ||
|
|
62725c5a52 | ||
|
|
cc66b31e69 | ||
|
|
199d314903 | ||
|
|
f2a805db24 | ||
|
|
b7e29aac4d | ||
|
|
2ee04b8421 | ||
|
|
65ce74fbcb | ||
|
|
4b520d04e3 | ||
|
|
4eb10f9d43 | ||
|
|
7e58d1d914 | ||
|
|
4097a81456 | ||
|
|
c4413b933b | ||
|
|
e3da53e3df | ||
|
|
675a5f5d7c | ||
|
|
02c19b3170 | ||
|
|
96859e749b | ||
|
|
622ddea343 | ||
|
|
8e8efe4288 | ||
|
|
df5c5d9fe2 | ||
|
|
cf7ce8a1af | ||
|
|
b3cd5721cf | ||
|
|
893908b8fe | ||
|
|
6821660905 | ||
|
|
bc0214730a | ||
|
|
57d0f25054 | ||
|
|
f456d1b78e | ||
|
|
332f499c31 | ||
|
|
92cdeb093e | ||
|
|
f2bdd555fa | ||
|
|
5c7dee556a | ||
|
|
8c6e5d0b37 | ||
|
|
1128beb49b | ||
|
|
0963eea60e | ||
|
|
c1cdedd260 | ||
|
|
3b0b93ec06 | ||
|
|
9c2f66ff13 | ||
|
|
1b688d7077 | ||
|
|
df1f9c27eb | ||
|
|
e227a3bc69 | ||
|
|
e4c6119550 | ||
|
|
6c9e8f28b6 | ||
|
|
cc7e685428 | ||
|
|
4abd88f2a9 | ||
|
|
a44fe402a1 | ||
|
|
350cb623ae | ||
|
|
42c9c53a4c | ||
|
|
5a49c22121 | ||
|
|
2bc4cbbdcc | ||
|
|
8fe6fa1cd7 | ||
|
|
835db4b279 | ||
|
|
f89c864911 | ||
|
|
542726911a | ||
|
|
575dc7d12e | ||
|
|
ff0062b088 | ||
|
|
78589f5db1 | ||
|
|
903331f3ff | ||
|
|
6aa247f73d | ||
|
|
da71735066 | ||
|
|
47b45c4494 | ||
|
|
d6ac6a3535 | ||
|
|
c322d77b86 | ||
|
|
7aa69579ff | ||
|
|
5f3e2b7fc7 | ||
|
|
c4844abb28 | ||
|
|
96ae6d80f3 | ||
|
|
60342e8cd9 | ||
|
|
f9c3d3fc14 | ||
|
|
b1e25eea88 | ||
|
|
1486bbab9f | ||
|
|
59d912cc26 | ||
|
|
9adf2e2d30 | ||
|
|
cf46fa8c2c | ||
|
|
16ca3d1608 | ||
|
|
476a251c80 | ||
|
|
274152aff7 | ||
|
|
00659e5f76 | ||
|
|
88fe4f6fd1 | ||
|
|
03a90928e1 | ||
|
|
67865d3341 | ||
|
|
0337513172 | ||
|
|
1ee2c53391 | ||
|
|
4b7c965101 | ||
|
|
11c394fb7e | ||
|
|
54a7c405e7 | ||
|
|
781f3b5fa4 | ||
|
|
2393472924 | ||
|
|
859ab7583f | ||
|
|
3eedd5bb50 | ||
|
|
5b7e695f6c | ||
|
|
1e3182727b | ||
|
|
e595dbfcee | ||
|
|
12b830893d | ||
|
|
cca80342aa | ||
|
|
4412f590cf | ||
|
|
0cd2d78027 | ||
|
|
be672ebfc1 | ||
|
|
9047c87567 | ||
|
|
31d630bb91 | ||
|
|
7a2f5a333f | ||
|
|
66303636dc | ||
|
|
9dc932e380 | ||
|
|
a71de4b5b6 | ||
|
|
ada8dfc6d4 | ||
|
|
4112595368 | ||
|
|
c281db7730 | ||
|
|
5e6b49ad1e | ||
|
|
ec1a527575 | ||
|
|
7f066aa168 | ||
|
|
166ea578f9 | ||
|
|
dc0ab1afca | ||
|
|
ae72fbfd0d | ||
|
|
ad0735f765 | ||
|
|
d49c178f1d | ||
|
|
cb3b47690a | ||
|
|
cf6060bdb3 | ||
|
|
8f8ba255b3 | ||
|
|
a4bc24817d | ||
|
|
9eeac9b272 | ||
|
|
f859eb6cec | ||
|
|
b29afc2c09 | ||
|
|
95b79973f9 | ||
|
|
1f79733a33 | ||
|
|
cfc29f7830 | ||
|
|
34486039e1 | ||
|
|
53e8ea7d9e | ||
|
|
9841b78ed8 | ||
|
|
065cfddd0d | ||
|
|
6882a3d36c | ||
|
|
85c595e84c | ||
|
|
b8f563d49e | ||
|
|
3b3d57e84a | ||
|
|
a1ee622aa6 | ||
|
|
64733981fd | ||
|
|
7833b11724 | ||
|
|
a7032d0964 | ||
|
|
f2c872230e | ||
|
|
8d26488748 | ||
|
|
d92ed46503 | ||
|
|
777eac045a | ||
|
|
37e2f3b944 | ||
|
|
3902a8b268 | ||
|
|
63a910d7ce | ||
|
|
3cee51cc37 | ||
|
|
45b559a721 | ||
|
|
7c59eb2c36 | ||
|
|
40f633b8d0 | ||
|
|
4e3d7cb974 | ||
|
|
d14b127b60 | ||
|
|
0d566ed1ec | ||
|
|
d86f92c6f2 | ||
|
|
efc5150144 | ||
|
|
7474ed1a5e | ||
|
|
2f4433af71 | ||
|
|
91303efd2c | ||
|
|
d73ff9a79f | ||
|
|
7ec6300a48 | ||
|
|
42c84fc54b | ||
|
|
f0a790d624 | ||
|
|
fdcff7aaf0 | ||
|
|
ab2362e372 | ||
|
|
98cf9f5af2 | ||
|
|
e74af51a7d | ||
|
|
35b5d8c630 | ||
|
|
8575d91c66 | ||
|
|
8338f124be | ||
|
|
be19f7ad4f | ||
|
|
5c737d29ab | ||
|
|
92c59ea4a5 | ||
|
|
dd28074436 | ||
|
|
f8ab30fa42 | ||
|
|
581ad8ba1e | ||
|
|
5703c1ed6d | ||
|
|
a71a3cdf3f | ||
|
|
f5d31b78e6 | ||
|
|
e1e6bb72c6 | ||
|
|
d89ca33cdb | ||
|
|
58ecfeb815 | ||
|
|
955d01a302 | ||
|
|
f8a5f7595d | ||
|
|
9f33cf19ad | ||
|
|
6deb85e083 | ||
|
|
9ad108281e | ||
|
|
cd0091c045 | ||
|
|
01ecae2c55 | ||
|
|
cef4bcd756 | ||
|
|
ad50bd7154 | ||
|
|
b97f9cf5ec | ||
|
|
2d65d3d73b | ||
|
|
733a76fdba | ||
|
|
fd63698005 |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -1,6 +1,4 @@
|
||||
presentation
|
||||
test.coffee
|
||||
parser.output
|
||||
test/fixtures/underscore
|
||||
examples/beautiful_code/parse.coffee
|
||||
*.gem
|
||||
57
Cakefile
57
Cakefile
@@ -1,57 +0,0 @@
|
||||
fs: require 'fs'
|
||||
coffee: require 'coffee-script'
|
||||
|
||||
# Run a CoffeeScript through our node/coffee interpreter.
|
||||
run: (args) ->
|
||||
proc: process.createChildProcess 'bin/coffee', args
|
||||
proc.addListener 'error', (err) -> if err then puts err
|
||||
|
||||
|
||||
task 'install', 'install CoffeeScript into /usr/local', ->
|
||||
exec([
|
||||
'mkdir -p /usr/local/lib/coffee-script'
|
||||
'cp -rf bin lib LICENSE README package.json src vendor /usr/local/lib/coffee-script'
|
||||
'ln -sf /usr/local/lib/coffee-script/lib/bin/coffee /usr/local/bin/coffee'
|
||||
'ln -sf /usr/local/lib/coffee-script/lib/bin/cake /usr/local/bin/cake'
|
||||
].join(' && '))
|
||||
|
||||
|
||||
task 'build', 'build the CoffeeScript language from source', ->
|
||||
fs.readdir 'src', (err, files) ->
|
||||
files: 'src/' + file for file in files when file.match(/\.coffee$/)
|
||||
run ['-o', 'lib'].concat(files)
|
||||
|
||||
|
||||
task 'build:parser', 'rebuild the Jison parser (run build first)', ->
|
||||
parser: require('grammar').parser
|
||||
js: parser.generate()
|
||||
parser_path: 'lib/parser.js'
|
||||
fs.writeFile parser_path, js
|
||||
|
||||
|
||||
task 'build:ultraviolet', 'build and install the Ultraviolet syntax highlighter', ->
|
||||
exec('plist2syntax extras/CoffeeScript.tmbundle/Syntaxes/CoffeeScript.tmLanguage').addCallback ->
|
||||
exec 'sudo mv coffeescript.yaml /usr/local/lib/ruby/gems/1.8/gems/ultraviolet-0.10.2/syntax/coffeescript.syntax'
|
||||
|
||||
|
||||
task 'build:underscore', 'rebuild the Underscore.coffee documentation page', ->
|
||||
exec 'uv -s coffeescript -t idle -h examples/underscore.coffee > documentation/underscore.html'
|
||||
|
||||
|
||||
task 'test', 'run the CoffeeScript language test suite', ->
|
||||
process.mixin require 'assert'
|
||||
test_count: 0
|
||||
start_time: new Date()
|
||||
[original_ok, original_throws]: [ok, throws]
|
||||
process.mixin {
|
||||
ok: (args...) -> test_count += 1; original_ok(args...)
|
||||
throws: (args...) -> test_count += 1; original_throws(args...)
|
||||
}
|
||||
process.addListener 'exit', ->
|
||||
time: ((new Date() - start_time) / 1000).toFixed(2)
|
||||
puts '\033[0;32mpassed ' + test_count + ' tests in ' + time + ' seconds\033[0m'
|
||||
fs.readdir 'test', (err, files) ->
|
||||
for file in files
|
||||
fs.readFile 'test/' + file, (err, source) ->
|
||||
js: coffee.compile source
|
||||
process.compile js, file
|
||||
2
LICENSE
2
LICENSE
@@ -1,4 +1,4 @@
|
||||
Copyright (c) 2010 Jeremy Ashkenas
|
||||
Copyright (c) 2009 Jeremy Ashkenas
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation
|
||||
|
||||
11
README
11
README
@@ -22,20 +22,17 @@
|
||||
|
||||
CoffeeScript is a little language that compiles into JavaScript.
|
||||
|
||||
Install Node.js, and then the CoffeeScript compiler:
|
||||
sudo bin/cake install
|
||||
Install the compiler:
|
||||
gem install coffee-script
|
||||
|
||||
Compile a script:
|
||||
coffee /path/to/script.coffee
|
||||
|
||||
For documentation, usage, and examples, see:
|
||||
http://coffeescript.org/
|
||||
http://jashkenas.github.com/coffee-script/
|
||||
|
||||
To suggest a feature, report a bug, or general discussion:
|
||||
To suggest a feature or report a bug:
|
||||
http://github.com/jashkenas/coffee-script/issues/
|
||||
|
||||
If you'd like to chat, drop by #coffeescript on Freenode.
|
||||
|
||||
The source repository:
|
||||
git://github.com/jashkenas/coffee-script.git
|
||||
|
||||
|
||||
47
Rakefile
47
Rakefile
@@ -2,12 +2,42 @@ require 'erb'
|
||||
require 'fileutils'
|
||||
require 'rake/testtask'
|
||||
|
||||
desc "Run all tests"
|
||||
task :test do
|
||||
$LOAD_PATH.unshift(File.expand_path('test'))
|
||||
require 'redgreen' if Gem.available?('redgreen')
|
||||
require 'test/unit'
|
||||
Dir['test/*/**/test_*.rb'].each {|test| require test }
|
||||
end
|
||||
|
||||
namespace :build do
|
||||
|
||||
desc "Recompile the Racc parser (pass -v and -g for verbose debugging)"
|
||||
task :parser, :racc_args do |t, args|
|
||||
sh "racc #{args[:racc_args]} -o lib/coffee_script/parser.rb lib/coffee_script/grammar.y"
|
||||
end
|
||||
|
||||
desc "Compile the Narwhal interface for --interactive and --run"
|
||||
task :narwhal do
|
||||
sh "bin/coffee lib/coffee_script/narwhal/*.coffee -o lib/coffee_script/narwhal/lib/coffee-script"
|
||||
sh "mv lib/coffee_script/narwhal/lib/coffee-script/coffee-script.js lib/coffee_script/narwhal/lib/coffee-script.js"
|
||||
end
|
||||
|
||||
desc "Compile and install the Ultraviolet syntax highlighter"
|
||||
task :ultraviolet do
|
||||
sh "plist2syntax lib/coffee_script/CoffeeScript.tmbundle/Syntaxes/CoffeeScript.tmLanguage"
|
||||
sh "sudo mv coffeescript.yaml /usr/local/lib/ruby/gems/1.8/gems/ultraviolet-0.10.2/syntax/coffeescript.syntax"
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
desc "Build the documentation page"
|
||||
task :doc do
|
||||
source = 'documentation/index.html.erb'
|
||||
child = fork { exec "bin/coffee documentation/coffee/*.coffee -o documentation/js -w" }
|
||||
at_exit { Process.kill("INT", child) }
|
||||
Signal.trap("INT") { exit }
|
||||
# `uv -t idle -s coffeescript -h examples/underscore.coffee > documentation/underscore.html`
|
||||
loop do
|
||||
mtime = File.stat(source).mtime
|
||||
if !@mtime || mtime > @mtime
|
||||
@@ -18,3 +48,20 @@ task :doc do
|
||||
sleep 1
|
||||
end
|
||||
end
|
||||
|
||||
namespace :gem do
|
||||
|
||||
desc 'Build and install the coffee-script gem'
|
||||
task :install do
|
||||
sh "gem build coffee-script.gemspec"
|
||||
sh "sudo gem install #{Dir['*.gem'].join(' ')} --local --no-ri --no-rdoc"
|
||||
end
|
||||
|
||||
desc 'Uninstall the coffee-script gem'
|
||||
task :uninstall do
|
||||
sh "sudo gem uninstall -x coffee-script"
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
task :default => :test
|
||||
7
bin/cake
7
bin/cake
@@ -1,7 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
process.mixin(require('sys'));
|
||||
|
||||
require.paths.unshift('./lib');
|
||||
|
||||
require('cake').run();
|
||||
@@ -1,7 +1,5 @@
|
||||
#!/usr/bin/env node
|
||||
#!/usr/bin/env ruby
|
||||
|
||||
process.mixin(require('sys'));
|
||||
require "#{File.dirname(__FILE__)}/../lib/coffee_script/command_line.rb"
|
||||
|
||||
require.paths.unshift('./lib');
|
||||
|
||||
require('command_line').run();
|
||||
CoffeeScript::CommandLine.new
|
||||
26
coffee-script.gemspec
Normal file
26
coffee-script.gemspec
Normal file
@@ -0,0 +1,26 @@
|
||||
Gem::Specification.new do |s|
|
||||
s.name = 'coffee-script'
|
||||
s.version = '0.2.1' # Keep version in sync with coffee-script.rb
|
||||
s.date = '2010-1-5'
|
||||
|
||||
s.homepage = "http://jashkenas.github.com/coffee-script/"
|
||||
s.summary = "The CoffeeScript Compiler"
|
||||
s.description = <<-EOS
|
||||
CoffeeScript is a little language that compiles into JavaScript. Think
|
||||
of it as JavaScript's less ostentatious kid brother -- the same genes,
|
||||
roughly the same height, but a different sense of style. Apart from a
|
||||
handful of bonus goodies, statements in CoffeeScript correspond
|
||||
one-to-one with their equivalent in JavaScript, it's just another
|
||||
way of saying it.
|
||||
EOS
|
||||
|
||||
s.authors = ['Jeremy Ashkenas']
|
||||
s.email = 'jashkenas@gmail.com'
|
||||
s.rubyforge_project = 'coffee-script'
|
||||
s.has_rdoc = false
|
||||
|
||||
s.require_paths = ['lib']
|
||||
s.executables = ['coffee']
|
||||
|
||||
s.files = Dir['bin/*', 'examples/*', 'lib/**/*', 'coffee-script.gemspec', 'LICENSE', 'README', 'package.json']
|
||||
end
|
||||
@@ -5,5 +5,3 @@ volume: 10 if band isnt spinal_tap
|
||||
let_the_wild_rumpus_begin() unless answer is no
|
||||
|
||||
if car.speed < speed_limit then accelerate()
|
||||
|
||||
print "My name is " + @name
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
backwards: ->
|
||||
alert arguments.reverse()
|
||||
backwards: =>
|
||||
alert(arguments.reverse())
|
||||
|
||||
backwards "stairway", "to", "heaven"
|
||||
backwards("stairway", "to", "heaven")
|
||||
@@ -4,4 +4,4 @@ lunch: eat(food) for food in ['toast', 'cheese', 'wine']
|
||||
# Naive collision detection.
|
||||
for roid in asteroids
|
||||
for roid2 in asteroids when roid isnt roid2
|
||||
roid.explode() if roid.overlaps roid2
|
||||
roid.explode() if roid.overlaps(roid2)
|
||||
4
documentation/coffee/blocks.coffee
Normal file
4
documentation/coffee/blocks.coffee
Normal file
@@ -0,0 +1,4 @@
|
||||
$('table.list').each() table =>
|
||||
$('tr.account', table).each() row =>
|
||||
row.show()
|
||||
row.highlight()
|
||||
@@ -1,5 +0,0 @@
|
||||
process.mixin require 'assert'
|
||||
|
||||
task 'test', 'run each of the unit tests', ->
|
||||
for test in test_files
|
||||
fs.readFile test, (err, code) -> eval coffee.compile code
|
||||
@@ -1,5 +0,0 @@
|
||||
cholesterol: 127
|
||||
|
||||
healthy: 200 > cholesterol > 60
|
||||
|
||||
|
||||
@@ -1,8 +1 @@
|
||||
solipsism: true if mind? and not world?
|
||||
|
||||
speed ?= 140
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
solipsism: true if mind? and not world?
|
||||
@@ -1,4 +1,4 @@
|
||||
grade: (student) ->
|
||||
grade: student =>
|
||||
if student.excellent_work
|
||||
"A+"
|
||||
else if student.okay_stuff
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
# The first ten global properties.
|
||||
|
||||
globals: (name for name of window)[0...10]
|
||||
globals: (name for property, name in window)[0...10]
|
||||
@@ -2,5 +2,5 @@ alert(
|
||||
try
|
||||
nonexistent / undefined
|
||||
catch error
|
||||
"And the error is ... " + error
|
||||
"The error is: " + error
|
||||
)
|
||||
@@ -1,6 +0,0 @@
|
||||
Account: (customer, cart) ->
|
||||
@customer: customer
|
||||
@cart: cart
|
||||
|
||||
$('.shopping_cart').bind 'click', (event) =>
|
||||
@customer.purchase @cart
|
||||
@@ -1,2 +1,2 @@
|
||||
square: (x) -> x * x
|
||||
cube: (x) -> square(x) * x
|
||||
square: x => x * x
|
||||
cube: x => square(x) * x
|
||||
@@ -1,5 +0,0 @@
|
||||
html: '''
|
||||
<strong>
|
||||
cup of coffeescript
|
||||
</strong>
|
||||
'''
|
||||
@@ -1,5 +0,0 @@
|
||||
weather_report: (location) ->
|
||||
# Make an Ajax request to fetch the weather...
|
||||
[location, 72, "Mostly Sunny"]
|
||||
|
||||
[city, temp, forecast]: weather_report "Berkeley, CA"
|
||||
@@ -1,4 +1,3 @@
|
||||
years_old: {max: 10, ida: 9, tim: 11}
|
||||
|
||||
ages: for child, age of years_old
|
||||
child + " is " + age
|
||||
ages: child + " is " + age for age, child in years_old
|
||||
@@ -1,13 +0,0 @@
|
||||
futurists: {
|
||||
sculptor: "Umberto Boccioni"
|
||||
painter: "Vladimir Burliuk"
|
||||
poet: {
|
||||
name: "F.T. Marinetti"
|
||||
address: [
|
||||
"Via Roma 42R"
|
||||
"Bellagio, Italy 22021"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
{poet: {name: poet, address: [street, city]}}: futurists
|
||||
@@ -6,7 +6,7 @@ opposite_day: true
|
||||
number: -42 if opposite_day
|
||||
|
||||
# Functions:
|
||||
square: (x) -> x * x
|
||||
square: x => x * x
|
||||
|
||||
# Arrays:
|
||||
list: [1, 2, 3, 4, 5]
|
||||
@@ -15,15 +15,15 @@ list: [1, 2, 3, 4, 5]
|
||||
math: {
|
||||
root: Math.sqrt
|
||||
square: square
|
||||
cube: (x) -> x * square x
|
||||
cube: x => x * square(x)
|
||||
}
|
||||
|
||||
# Splats:
|
||||
race: (winner, runners...) ->
|
||||
print winner, runners
|
||||
race: winner, *runners =>
|
||||
print(winner, runners)
|
||||
|
||||
# Existence:
|
||||
alert "I knew it!" if elvis?
|
||||
alert("I knew it!") if elvis?
|
||||
|
||||
# Array comprehensions:
|
||||
cubed_list: math.cube num for num in list
|
||||
cubed_list: math.cube(num) for num in list
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
bait: 1000
|
||||
and_switch: 0
|
||||
|
||||
[bait, and_switch]: [and_switch, bait]
|
||||
@@ -1,6 +1,3 @@
|
||||
countdown: num for num in [10..1]
|
||||
|
||||
egg_delivery: ->
|
||||
for i in [0...eggs.length] by 12
|
||||
dozen_eggs: eggs[i...i+12]
|
||||
deliver new egg_carton(dozen)
|
||||
for i in [0...eggs.length] by 12
|
||||
dozen_eggs: eggs[i...i+12]
|
||||
deliver(new egg_carton(dozen))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
num: 1
|
||||
change_numbers: ->
|
||||
change_numbers: =>
|
||||
new_num: -1
|
||||
num: 10
|
||||
new_num: change_numbers()
|
||||
@@ -1 +0,0 @@
|
||||
lottery.draw_winner()?.address?.zipcode
|
||||
@@ -1,6 +1,6 @@
|
||||
gold: silver: the_field: "unknown"
|
||||
|
||||
award_medals: (first, second, rest...) ->
|
||||
medalists: first, second, *rest =>
|
||||
gold: first
|
||||
silver: second
|
||||
the_field: rest
|
||||
@@ -18,8 +18,8 @@ contenders: [
|
||||
"Usain Bolt"
|
||||
]
|
||||
|
||||
award_medals contenders...
|
||||
medalists(*contenders)
|
||||
|
||||
alert "Gold: " + gold
|
||||
alert "Silver: " + silver
|
||||
alert "The Field: " + the_field
|
||||
alert("Gold: " + gold)
|
||||
alert("Silver: " + silver)
|
||||
alert("The Field: " + the_field)
|
||||
@@ -1,30 +1,21 @@
|
||||
Animal: ->
|
||||
|
||||
Animal::move: (meters) ->
|
||||
alert @name + " moved " + meters + "m."
|
||||
|
||||
Snake: (name) ->
|
||||
@name: name
|
||||
this
|
||||
Animal: =>
|
||||
Animal.prototype.move: meters =>
|
||||
alert(this.name + " moved " + meters + "m.")
|
||||
|
||||
Snake: name => this.name: name
|
||||
Snake extends Animal
|
||||
Snake.prototype.move: =>
|
||||
alert("Slithering...")
|
||||
super(5)
|
||||
|
||||
Snake::move: ->
|
||||
alert "Slithering..."
|
||||
super 5
|
||||
|
||||
Horse: (name) ->
|
||||
@name: name
|
||||
this
|
||||
|
||||
Horse: name => this.name: name
|
||||
Horse extends Animal
|
||||
Horse.prototype.move: =>
|
||||
alert("Galloping...")
|
||||
super(45)
|
||||
|
||||
Horse::move: ->
|
||||
alert "Galloping..."
|
||||
super 45
|
||||
|
||||
sam: new Snake "Sammy the Python"
|
||||
tom: new Horse "Tommy the Palomino"
|
||||
sam: new Snake("Sammy the Python")
|
||||
tom: new Horse("Tommy the Palomino")
|
||||
|
||||
sam.move()
|
||||
tom.move()
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
switch day
|
||||
when "Mon" then go_to_work()
|
||||
when "Tue" then go_to_the_park()
|
||||
when "Thu" then go_ice_fishing()
|
||||
when "Fri", "Sat"
|
||||
when "Tuesday" then eat_breakfast()
|
||||
when "Wednesday" then go_to_the_park()
|
||||
when "Saturday"
|
||||
if day is bingo_day
|
||||
go_to_bingo()
|
||||
go_dancing()
|
||||
when "Sun" then go_to_church()
|
||||
when "Sunday" then go_to_church()
|
||||
else go_to_work()
|
||||
@@ -2,6 +2,6 @@ try
|
||||
all_hell_breaks_loose()
|
||||
cats_and_dogs_living_together()
|
||||
catch error
|
||||
print error
|
||||
print(error)
|
||||
finally
|
||||
clean_up()
|
||||
@@ -1,10 +1,5 @@
|
||||
# Econ 101
|
||||
if this.studying_economics
|
||||
while supply > demand then buy()
|
||||
while supply < demand then sell()
|
||||
while demand > supply
|
||||
sell()
|
||||
restock()
|
||||
|
||||
# Nursery Rhyme
|
||||
num: 6
|
||||
lyrics: while num -= 1
|
||||
num + " little monkeys, jumping on the bed.
|
||||
One fell out and bumped his head."
|
||||
while supply > demand then buy()
|
||||
147
documentation/css/amy.css
Normal file
147
documentation/css/amy.css
Normal file
@@ -0,0 +1,147 @@
|
||||
pre.amy .PolymorphicVariants {
|
||||
color: #60B0FF;
|
||||
font-style: italic;
|
||||
}
|
||||
pre.amy .KeywordDecorator {
|
||||
color: #D0D0FF;
|
||||
}
|
||||
pre.amy .Punctuation {
|
||||
color: #805080;
|
||||
}
|
||||
pre.amy .InheritedClass {
|
||||
}
|
||||
pre.amy .InvalidDepricated {
|
||||
background-color: #CC66FF;
|
||||
color: #200020;
|
||||
}
|
||||
pre.amy .LibraryVariable {
|
||||
}
|
||||
pre.amy .TokenReferenceOcamlyacc {
|
||||
color: #3CB0D0;
|
||||
}
|
||||
pre.amy .Storage {
|
||||
color: #B0FFF0;
|
||||
}
|
||||
pre.amy .KeywordOperator {
|
||||
color: #A0A0FF;
|
||||
}
|
||||
pre.amy .CharacterConstant {
|
||||
color: #666666;
|
||||
}
|
||||
pre.amy .line-numbers {
|
||||
background-color: #800000;
|
||||
color: #000000;
|
||||
}
|
||||
pre.amy .ClassName {
|
||||
color: #70E080;
|
||||
}
|
||||
pre.amy .Int64Constant {
|
||||
font-style: italic;
|
||||
}
|
||||
pre.amy .NonTerminalReferenceOcamlyacc {
|
||||
color: #C0F0F0;
|
||||
}
|
||||
pre.amy .TokenDefinitionOcamlyacc {
|
||||
color: #3080A0;
|
||||
}
|
||||
pre.amy .ClassType {
|
||||
color: #70E0A0;
|
||||
}
|
||||
pre.amy .ControlKeyword {
|
||||
color: #80A0FF;
|
||||
}
|
||||
pre.amy .LineNumberDirectives {
|
||||
text-decoration: underline;
|
||||
color: #C080C0;
|
||||
}
|
||||
pre.amy .FloatingPointConstant {
|
||||
text-decoration: underline;
|
||||
}
|
||||
pre.amy .Int32Constant {
|
||||
font-weight: bold;
|
||||
}
|
||||
pre.amy .TagName {
|
||||
color: #009090;
|
||||
}
|
||||
pre.amy .ModuleTypeDefinitions {
|
||||
text-decoration: underline;
|
||||
color: #B000B0;
|
||||
}
|
||||
pre.amy .Integer {
|
||||
color: #7090B0;
|
||||
}
|
||||
pre.amy .Camlp4TempParser {
|
||||
}
|
||||
pre.amy .InvalidIllegal {
|
||||
font-weight: bold;
|
||||
background-color: #FFFF00;
|
||||
color: #400080;
|
||||
}
|
||||
pre.amy .LibraryConstant {
|
||||
background-color: #200020;
|
||||
}
|
||||
pre.amy .ModuleDefinitions {
|
||||
color: #B000B0;
|
||||
}
|
||||
pre.amy .Variants {
|
||||
color: #60B0FF;
|
||||
}
|
||||
pre.amy .CompilerDirectives {
|
||||
color: #C080C0;
|
||||
}
|
||||
pre.amy .FloatingPointInfixOperator {
|
||||
text-decoration: underline;
|
||||
}
|
||||
pre.amy .BuiltInConstant1 {
|
||||
}
|
||||
pre.amy {
|
||||
background-color: #200020;
|
||||
color: #D0D0FF;
|
||||
}
|
||||
pre.amy .FunctionArgument {
|
||||
color: #80B0B0;
|
||||
}
|
||||
pre.amy .FloatingPointPrefixOperator {
|
||||
text-decoration: underline;
|
||||
}
|
||||
pre.amy .NativeintConstant {
|
||||
font-weight: bold;
|
||||
}
|
||||
pre.amy .BuiltInConstant {
|
||||
color: #707090;
|
||||
}
|
||||
pre.amy .BooleanConstant {
|
||||
color: #8080A0;
|
||||
}
|
||||
pre.amy .LibraryClassType {
|
||||
}
|
||||
pre.amy .TagAttribute {
|
||||
}
|
||||
pre.amy .Keyword {
|
||||
color: #A080FF;
|
||||
}
|
||||
pre.amy .UserDefinedConstant {
|
||||
}
|
||||
pre.amy .String {
|
||||
color: #999999;
|
||||
}
|
||||
pre.amy .Camlp4Code {
|
||||
background-color: #350060;
|
||||
}
|
||||
pre.amy .NonTerminalDefinitionOcamlyacc {
|
||||
color: #90E0E0;
|
||||
}
|
||||
pre.amy .FunctionName {
|
||||
color: #50A0A0;
|
||||
}
|
||||
pre.amy .SupportModules {
|
||||
color: #A00050;
|
||||
}
|
||||
pre.amy .Variable {
|
||||
color: #008080;
|
||||
}
|
||||
pre.amy .Comment {
|
||||
background-color: #200020;
|
||||
color: #404080;
|
||||
font-style: italic;
|
||||
}
|
||||
@@ -1,29 +1,29 @@
|
||||
body {
|
||||
font-size: 14px;
|
||||
line-height: 20px;
|
||||
background: #f3f3f9;
|
||||
color: #191933;
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
}
|
||||
div.container {
|
||||
width: 950px;
|
||||
margin: 100px 0 50px 50px;
|
||||
width: 850px;
|
||||
margin: 50px 0 50px 50px;
|
||||
}
|
||||
p {
|
||||
padding-left: 13px;
|
||||
width: 625px;
|
||||
}
|
||||
a {
|
||||
color: #000055;
|
||||
}
|
||||
h1, h2, h3, h4, h5, h6 {
|
||||
padding-left: 13px;
|
||||
margin-top: 40px;
|
||||
}
|
||||
br.clear {
|
||||
height: 0;
|
||||
clear: both;
|
||||
}
|
||||
ul {
|
||||
padding-left: 20px;
|
||||
}
|
||||
b.header {
|
||||
color: #000055;
|
||||
display: block;
|
||||
@@ -31,7 +31,7 @@ b.header {
|
||||
font-size: 16px;
|
||||
}
|
||||
li {
|
||||
margin-bottom: 10px;
|
||||
margin-bottom: 7px;
|
||||
}
|
||||
table {
|
||||
margin: 16px 0 0 13px; padding: 0;
|
||||
@@ -43,7 +43,7 @@ table {
|
||||
td {
|
||||
padding: 9px 15px 9px 0;
|
||||
}
|
||||
code, pre, tt, textarea {
|
||||
code, pre, tt {
|
||||
font-family: Monaco, Consolas, "Lucida Console", monospace;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
@@ -66,7 +66,7 @@ code, pre, tt, textarea {
|
||||
div.code {
|
||||
position: relative;
|
||||
border: 1px solid #cacaca;
|
||||
background: #fafaff;
|
||||
background: #fff;
|
||||
padding: 7px 0 10px 0;
|
||||
-moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px;
|
||||
-webkit-box-shadow: 0px 0px 7px #cacaca;
|
||||
@@ -75,133 +75,13 @@ div.code {
|
||||
position: absolute;
|
||||
right: 8px; bottom: 8px;
|
||||
}
|
||||
div.code pre, div.code textarea {
|
||||
div.code pre {
|
||||
float: left;
|
||||
width: 450px;
|
||||
background: #fafaff;
|
||||
width: 410px;
|
||||
border-left: 1px dotted #559;
|
||||
padding: 0 0 0 12px;
|
||||
margin: 0;
|
||||
}
|
||||
div.code pre:first-child {
|
||||
border-left: 0;
|
||||
}
|
||||
|
||||
#fadeout {
|
||||
z-index: 50;
|
||||
position: fixed;
|
||||
left: 0; top: 0; right: 0;
|
||||
height: 100px;
|
||||
background: -webkit-gradient(linear, left top, left bottom, from(rgba(255, 255, 255, 255)), to(rgba(255, 255, 255, 0)));
|
||||
background: -moz-linear-gradient(top, rgba(255, 255, 255, 255), rgba(255, 255, 255, 0));
|
||||
}
|
||||
|
||||
#flybar {
|
||||
position: fixed;
|
||||
z-index: 100;
|
||||
height: 50px;
|
||||
left: 40px; right: 40px; top: 25px;
|
||||
background: #ddd;
|
||||
padding-left: 235px;
|
||||
background: -webkit-gradient(linear, left top, left bottom, from(#f5f5f5), to(#d0d0d0));
|
||||
background: -moz-linear-gradient(top, #f5f5f5, #d0d0d0);
|
||||
filter: progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr='#F5F5F5', EndColorStr='#D0D0D0');
|
||||
-webkit-border-radius: 20px; -moz-border-radius: 20px; border-radius: 20px;
|
||||
-webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777;
|
||||
}
|
||||
#logo {
|
||||
display: block;
|
||||
width: 215px; height: 50px;
|
||||
background: url('logo.png');
|
||||
position: absolute;
|
||||
top: 0px; left: 10px;
|
||||
}
|
||||
.navigation {
|
||||
height: 50px;
|
||||
font: bold 11px/50px Arial;
|
||||
text-transform: uppercase;
|
||||
position: relative;
|
||||
float: left;
|
||||
padding: 0 20px;
|
||||
border: 1px solid #bbb;
|
||||
border-top: 0; border-bottom: 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
.navigation.try {
|
||||
border-left: 0;
|
||||
}
|
||||
.navigation:hover {
|
||||
background: #d0d0d0;
|
||||
background: -webkit-gradient(linear, left top, left bottom, from(#f0f0f0), to(#c0c0c0));
|
||||
background: -moz-linear-gradient(top, #f0f0f0, #c0c0c0);
|
||||
filter: progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr='#F0F0F0', EndColorStr='#C0C0C0');
|
||||
}
|
||||
.navigation .contents {
|
||||
display: none;
|
||||
position: absolute;
|
||||
background: #fff;
|
||||
top: 50px; left: 0;
|
||||
padding: 5px 0;
|
||||
-webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px;
|
||||
-webkit-border-top-left-radius: 0; -moz-border-radius-topleft: 0;
|
||||
-webkit-border-top-right-radius: 0; -moz-border-radius-topright: 0;
|
||||
-webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777;
|
||||
}
|
||||
.navigation:hover .contents {
|
||||
display: block;
|
||||
}
|
||||
.navigation .contents.repl_wrapper {
|
||||
left: -162px;
|
||||
width: 700px;
|
||||
padding: 0;
|
||||
}
|
||||
.navigation .contents.repl_wrapper .code {
|
||||
-webkit-box-shadow: none; -moz-box-shadow: none;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
}
|
||||
.navigation .code button {
|
||||
bottom: 10px;
|
||||
}
|
||||
.navigation .compile {
|
||||
left: 240px; right: auto;
|
||||
}
|
||||
.navigation .contents a {
|
||||
display: block;
|
||||
width: 300px;
|
||||
text-transform: none;
|
||||
text-decoration: none;
|
||||
font-weight: normal;
|
||||
height: 12px;
|
||||
line-height: 12px;
|
||||
padding: 4px 10px;
|
||||
}
|
||||
.navigation .contents a:hover {
|
||||
background: #f0f0f0;
|
||||
}
|
||||
|
||||
.bookmark {
|
||||
display: block;
|
||||
width: 0; height: 0;
|
||||
position: relative;
|
||||
top: -90px;
|
||||
}
|
||||
|
||||
#repl_source, #repl_results {
|
||||
background: transparent;
|
||||
}
|
||||
#repl_source {
|
||||
border: 0;
|
||||
padding: 5px 7px;
|
||||
margin-left: 5px;
|
||||
min-height: 250px;
|
||||
resize: none;
|
||||
width: 295px;
|
||||
}
|
||||
#repl_results {
|
||||
font-family: Monaco, Consolas, "Lucida Console", monospace;
|
||||
text-transform: none;
|
||||
font-weight: normal;
|
||||
min-height: 260px;
|
||||
width: 355px;
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,6 @@ pre.idle .LibraryConstant {
|
||||
color: #A535AE;
|
||||
}
|
||||
pre.idle .FunctionArgument {
|
||||
color: #0076ad;
|
||||
}
|
||||
pre.idle .BuiltInConstant {
|
||||
color: #A535AE;
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 5.9 KiB |
@@ -1,3 +1,18 @@
|
||||
<%#
|
||||
TODO:
|
||||
Multiline and nested array comprehensions (and filters with 'when').
|
||||
Range comprehension examples (expression endpoints), with steps.
|
||||
Object comprehension examples.
|
||||
Significant Whitespace Rules.
|
||||
Newline-delimited Matrix.
|
||||
Automatic newline escaping.
|
||||
All functions are named functions.
|
||||
Splats in function definitions.
|
||||
(Multiple) splats as arguments to a function call.
|
||||
Exists?
|
||||
Array assignment splice literals.
|
||||
%>
|
||||
|
||||
<%
|
||||
require 'uv'
|
||||
def code_for(file, executable=false)
|
||||
@@ -25,66 +40,9 @@
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div id="fadeout"></div>
|
||||
|
||||
<div id="flybar">
|
||||
<a id="logo" href="#top"> </a>
|
||||
<div class="navigation">
|
||||
<div class="button">
|
||||
Table of Contents
|
||||
</div>
|
||||
<div class="contents">
|
||||
<a href="#overview">Mini Overview</a>
|
||||
<a href="#installation">Installation and Usage</a>
|
||||
<a href="#language">Language Reference</a>
|
||||
<a href="#whitespace">Significant Whitespace</a>
|
||||
<a href="#functions">Functions and Invocation</a>
|
||||
<a href="#assignment">Assignment</a>
|
||||
<a href="#objects_and_arrays">Objects and Arrays</a>
|
||||
<a href="#lexical_scope">Lexical Scoping and Variable Safety</a>
|
||||
<a href="#conditionals">Conditionals, Ternaries, and Conditional Assignment</a>
|
||||
<a href="#aliases">Aliases</a>
|
||||
<a href="#splats">Splats...</a>
|
||||
<a href="#arguments">Arguments are Arrays</a>
|
||||
<a href="#while">While Loops</a>
|
||||
<a href="#comprehensions">Comprehensions (Arrays, Objects, and Ranges)</a>
|
||||
<a href="#slice_splice">Array Slicing and Splicing with Ranges</a>
|
||||
<a href="#expressions">Everything is an Expression</a>
|
||||
<a href="#existence">The Existential Operator</a>
|
||||
<a href="#inheritance">Inheritance, and Calling Super from a Subclass</a>
|
||||
<a href="#pattern_matching">Pattern Matching</a>
|
||||
<a href="#fat_arrow">Function Binding</a>
|
||||
<a href="#embedded">Embedded JavaScript</a>
|
||||
<a href="#switch">Switch/When/Else</a>
|
||||
<a href="#try">Try/Catch/Finally</a>
|
||||
<a href="#comparisons">Chained Comparisons</a>
|
||||
<a href="#strings">Multiline Strings and Heredocs</a>
|
||||
<a href="#cake">Cake, and Cakefiles</a>
|
||||
<a href="#resources">Resources</a>
|
||||
<a href="#change_log">Change Log</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="navigation try">
|
||||
<div class="button">
|
||||
Try CoffeeScript
|
||||
</div>
|
||||
<div class="contents repl_wrapper">
|
||||
<div class="code">
|
||||
<textarea id="repl_source">reverse: (string) ->
|
||||
string.split('').reverse().join ''
|
||||
|
||||
alert reverse '!tpircseeffoC'</textarea>
|
||||
<pre id="repl_results"></pre>
|
||||
<button class="compile" onclick="javascript: repl_compile();">compile</button>
|
||||
<button class="run" onclick="javascript: repl_run();">run</button>
|
||||
<br class="clear" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
<span class="bookmark" id="top"></span>
|
||||
|
||||
<h1><sub style="font-size: 100px;">☕</sub> CoffeeScript</h1>
|
||||
|
||||
<p>
|
||||
CoffeeScript is a little language that compiles into JavaScript. Think
|
||||
@@ -96,8 +54,9 @@ alert reverse '!tpircseeffoC'</textarea>
|
||||
|
||||
<p>
|
||||
<b>Disclaimer:</b>
|
||||
CoffeeScript is just for fun. Until it reaches 1.0, <i>there are no guarantees
|
||||
that the syntax won't change between versions.</i> That said,
|
||||
CoffeeScript is just for fun and seriously alpha. I'm sure that there are still
|
||||
plenty of holes in the lexer and leaks in the syntax. <i>There is no guarantee,
|
||||
explicit or implied, of its suitability for any purpose.</i> That said,
|
||||
it compiles into clean JavaScript (the good parts) that can use existing
|
||||
JavaScript libraries seamlessly, and passes through
|
||||
<a href="http://www.jslint.com/">JSLint</a> without warnings. The compiled
|
||||
@@ -107,13 +66,40 @@ alert reverse '!tpircseeffoC'</textarea>
|
||||
|
||||
<p>
|
||||
<b>Latest Version:</b>
|
||||
<a href="http://github.com/jashkenas/coffee-script/tarball/0.5.0">0.5.0</a>
|
||||
<a href="http://gemcutter.org/gems/coffee-script">0.2.1</a>
|
||||
</p>
|
||||
|
||||
<h2>
|
||||
<span id="overview" class="bookmark"></span>
|
||||
Mini Overview
|
||||
</h2>
|
||||
<h2>Table of Contents</h2>
|
||||
|
||||
<p>
|
||||
<a href="#overview">Mini Overview</a><br />
|
||||
<a href="#installation">Installation and Usage</a><br />
|
||||
<a href="#whitespace">Significant Whitespace</a><br />
|
||||
<a href="#functions">Functions and Invocation</a><br />
|
||||
<a href="#assignment">Assignment</a><br />
|
||||
<a href="#objects_and_arrays">Objects and Arrays</a><br />
|
||||
<a href="#lexical_scope">Lexical Scoping and Variable Safety</a><br />
|
||||
<a href="#conditionals">Conditionals, Ternaries, and Conditional Assignment</a><br />
|
||||
<a href="#existence">The Existence Operator</a><br />
|
||||
<a href="#aliases">Aliases</a><br />
|
||||
<a href="#splats">Splats</a><br />
|
||||
<a href="#arguments">Arguments are Arrays</a><br />
|
||||
<a href="#while">While Loops</a><br />
|
||||
<a href="#comprehensions">Comprehensions (Arrays, Objects, and Ranges)</a><br />
|
||||
<a href="#slice_splice">Array Slicing and Splicing with Ranges</a><br />
|
||||
<a href="#expressions">Everything is an Expression</a><br />
|
||||
<a href="#inheritance">Inheritance, and Calling Super from a Subclass</a><br />
|
||||
<a href="#blocks">Blocks</a><br />
|
||||
<a href="#embedded">Embedded JavaScript</a><br />
|
||||
<a href="#switch">Switch/When/Else</a><br />
|
||||
<a href="#try">Try/Catch/Finally</a><br />
|
||||
<a href="#strings">Multiline Strings</a><br />
|
||||
<a href="#resources">Resources</a><br />
|
||||
<a href="#contributing">Contributing</a><br />
|
||||
<a href="#change_log">Change Log</a><br />
|
||||
</p>
|
||||
|
||||
<h2 id="overview">Mini Overview</h2>
|
||||
|
||||
<p><i>CoffeeScript on the left, compiled JavaScript output on the right.</i></p>
|
||||
|
||||
@@ -122,45 +108,27 @@ alert reverse '!tpircseeffoC'</textarea>
|
||||
<p>
|
||||
For a longer CoffeeScript example, check out
|
||||
<a href="documentation/underscore.html">Underscore.coffee</a>, a port
|
||||
of the <a href="http://documentcloud.github.com/underscore/">Underscore.js</a>
|
||||
library of helper functions. Underscore.coffee can pass the entire Underscore.js
|
||||
test suite. The CoffeeScript version is faster than the original for a number
|
||||
of methods (in general, due to the speed of CoffeeScript's array comprehensions), and
|
||||
after being minified and gzipped, is only 241 bytes larger than the original
|
||||
JavaScript version.
|
||||
Additional examples are included in the source repository, inside the
|
||||
of <a href="http://documentcloud.github.com/underscore/">Underscore.js</a>
|
||||
to CoffeeScript, which, when compiled, can pass the complete Underscore test suite.
|
||||
Or, clone the source and take a look in the
|
||||
<a href="http://github.com/jashkenas/coffee-script/tree/master/examples/">examples</a> folder.
|
||||
</p>
|
||||
|
||||
<h2>
|
||||
<span id="installation" class="bookmark"></span>
|
||||
Installation and Usage
|
||||
</h2>
|
||||
<h2 id="installation">Installation and Usage</h2>
|
||||
|
||||
<p>
|
||||
The CoffeeScript compiler is written in pure CoffeeScript, and is available
|
||||
as a <a href="http://nodejs.org/">Node.js</a> utility. The core compiler however,
|
||||
does not depend on Node, and can be run in other server-side-JavaScript environments,
|
||||
or in the browser (see "Try CoffeeScript", above).
|
||||
</p>
|
||||
|
||||
<p>
|
||||
To install, first make sure you have a working version of
|
||||
<a href="http://nodejs.org/">Node.js</a>, 0.1.30 or higher. Then clone the CoffeeScript
|
||||
<a href="http://github.com/jashkenas/coffee-script">source repository</a>
|
||||
from GitHub, or download the latest
|
||||
release: <a href="http://github.com/jashkenas/coffee-script/tarball/0.5.0">0.5.0</a>.
|
||||
To install the CoffeeScript compiler system-wide
|
||||
under <tt>/usr/local</tt>, open the directory and run:
|
||||
The CoffeeScript compiler is written in pure Ruby, and is available
|
||||
as a Ruby Gem.
|
||||
</p>
|
||||
|
||||
<pre>
|
||||
sudo bin/cake install</pre>
|
||||
gem install coffee-script</pre>
|
||||
|
||||
<p>
|
||||
This provides the <tt>coffee</tt> command, which can
|
||||
Installing the gem provides the <tt>coffee</tt> command, which can
|
||||
be used to compile CoffeeScript <tt>.coffee</tt> files into JavaScript, as
|
||||
well as debug them. The <tt>coffee</tt>
|
||||
well as debug them. In conjunction with
|
||||
<a href="http://narwhaljs.org/">Narwhal</a>, the <tt>coffee</tt>
|
||||
command also provides direct evaluation and an interactive REPL.
|
||||
When compiling to JavaScript, <tt>coffee</tt> writes the output
|
||||
as <tt>.js</tt> files in the same directory by default, but output
|
||||
@@ -171,14 +139,15 @@ sudo bin/cake install</pre>
|
||||
<tr>
|
||||
<td width="25%"><code>-i, --interactive</code></td>
|
||||
<td>
|
||||
Launch an interactive CoffeeScript session to try short snippets.
|
||||
Launch an interactive CoffeeScript session.
|
||||
Requires <a href="http://narwhaljs.org/">Narwhal</a>.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>-r, --run</code></td>
|
||||
<td>
|
||||
Compile and execute a given CoffeeScript without saving the intermediate
|
||||
JavaScript.
|
||||
Compile and execute scripts without saving the intermediate
|
||||
JavaScript. Requires <a href="http://narwhaljs.org/">Narwhal</a>.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
@@ -204,9 +173,7 @@ sudo bin/cake install</pre>
|
||||
<tr>
|
||||
<td><code>-l, --lint</code></td>
|
||||
<td>
|
||||
If the <tt>jsl</tt>
|
||||
(<a href="http://www.javascriptlint.com/">JavaScript Lint</a>)
|
||||
command is installed, use it
|
||||
If the <tt>jsl</tt> (JavaScript Lint) command is installed, use it
|
||||
to check the compilation of a CoffeeScript file. (Handy in
|
||||
conjunction with <tt>--watch</tt>)
|
||||
</td>
|
||||
@@ -215,36 +182,36 @@ sudo bin/cake install</pre>
|
||||
<td><code>-e, --eval</code></td>
|
||||
<td>
|
||||
Compile and print a little snippet of CoffeeScript directly from the
|
||||
command line. For example:<br /><tt>coffee -e "square: (x) -> x * x"</tt>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>-n, --no-wrap</code></td>
|
||||
<td>
|
||||
Compile the JavaScript without the top-level function safety wrapper.
|
||||
(Used for CoffeeScript as a Node.js module.)
|
||||
command line (or from <b>stdin</b>). For example:<br /><tt>coffee -e "square: x => x * x"</tt>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>-t, --tokens</code></td>
|
||||
<td>
|
||||
Instead of parsing the CoffeeScript, just lex it, and print out the
|
||||
token stream: <tt>[IDENTIFIER square] [ASSIGN :] [PARAM_START (]</tt> ...
|
||||
token stream: <tt>[:IDENTIFIER, "square"], [":", ":"], [:PARAM, "x"]</tt> ...
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>-tr, --tree</code></td>
|
||||
<td><code>-v, --verbose</code></td>
|
||||
<td>
|
||||
Instead of compiling the CoffeeScript, just lex and parse it, and print
|
||||
out the parse tree:
|
||||
<pre>
|
||||
Expressions
|
||||
Assign
|
||||
Value "square"
|
||||
Code "x"
|
||||
Op *
|
||||
Value "x"
|
||||
Value "x"</pre>
|
||||
As the JavaScript is being generated, print out every step of code
|
||||
generation, including lexical scope and the node in the
|
||||
AST.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>-n, --no-wrap</code></td>
|
||||
<td>
|
||||
Compile the JavaScript without the top-level function safety wrapper
|
||||
or var declarations, for situations where you want to add every
|
||||
variable to global scope.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>--install-bundle</code></td>
|
||||
<td>
|
||||
Install the TextMate bundle for CoffeeScript syntax highlighting.
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
@@ -259,10 +226,7 @@ coffee --interactive
|
||||
coffee --watch --lint experimental.coffee
|
||||
coffee --print app/scripts/*.coffee > concatenation.js</pre>
|
||||
|
||||
<h2>
|
||||
<span id="language" class="bookmark"></span>
|
||||
Language Reference
|
||||
</h2>
|
||||
<h2>Language Reference</h2>
|
||||
|
||||
<p>
|
||||
<i>
|
||||
@@ -274,14 +238,7 @@ coffee --print app/scripts/*.coffee > concatenation.js</pre>
|
||||
</i>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<i>
|
||||
Many of the examples can be run (where it makes sense) by pressing the "run"
|
||||
button towards the bottom right. You can also paste examples into
|
||||
"Try CoffeeScript" in the toolbar, and play with them from there.
|
||||
</i>
|
||||
<p>
|
||||
<span id="whitespace" class="bookmark"></span>
|
||||
<p id="whitespace">
|
||||
<b class="header">Significant Whitespace</b>
|
||||
CoffeeScript uses Python-style significant whitespace: You don't need to
|
||||
use semicolons <tt>;</tt> to terminate expressions, ending
|
||||
@@ -293,58 +250,37 @@ coffee --print app/scripts/*.coffee > concatenation.js</pre>
|
||||
use indentation.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
You don't need to use parentheses to invoke a function if you're passing
|
||||
arguments:<br /><tt>print "coffee"</tt>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
You can use newlines to break up your expression into smaller pieces,
|
||||
as long as CoffeeScript can determine that the line hasn't finished yet,
|
||||
because it ends with an operator or a dot.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<span id="functions" class="bookmark"></span>
|
||||
<p id="functions">
|
||||
<b class="header">Functions and Invocation</b>
|
||||
Functions are defined by a list of parameters, an arrow, and the
|
||||
function body. The empty function looks like this: <tt>-></tt> All
|
||||
functions in CoffeeScript are named by default, for easier debugging.
|
||||
function body. The empty function looks like this: <tt>=></tt>. All
|
||||
functions in CoffeeScript are named, for the benefit of debug messages.
|
||||
</p>
|
||||
<%= code_for('functions', 'cube(5)') %>
|
||||
<p>
|
||||
If you'd like to assign a function literal to a variable, but not have
|
||||
it be named, just wrap the function definition in parentheses:
|
||||
<tt>((x) -> x * x)</tt>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<span id="assignment" class="bookmark"></span>
|
||||
<p id="assignment">
|
||||
<b class="header">Assignment</b>
|
||||
Use a colon <tt>:</tt> to assign, as in
|
||||
<a href="http://json.org">JSON</a>. Equal signs are only needed for
|
||||
mathy things. While colons are preferred, the two may be used interchangeably,
|
||||
even within object literals.
|
||||
mathy things.
|
||||
</p>
|
||||
<%= code_for('assignment', 'greeting') %>
|
||||
<p>
|
||||
All declaration of new variables is pushed up to the top of the nearest
|
||||
Declarations of new variables are pushed up to the top of the nearest
|
||||
lexical scope, so that assignment may always be performed within expressions.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<span id="objects_and_arrays" class="bookmark"></span>
|
||||
<p id="objects_and_arrays">
|
||||
<b class="header">Objects and Arrays</b>
|
||||
Object and Array literals look very similar to their JavaScript cousins.
|
||||
When you spread out each assignment on a separate line, the commas are
|
||||
optional. In this way, assigning object properties looks the same as
|
||||
assigning local variables, and can be moved around freely. Feel free to mix
|
||||
assigning local variables, and can be moved around freely. You can mix
|
||||
and match the two styles.
|
||||
</p>
|
||||
<%= code_for('objects_and_arrays', 'song.join(",")') %>
|
||||
|
||||
<p>
|
||||
<span id="lexical_scope" class="bookmark"></span>
|
||||
<p id="lexical_scope">
|
||||
<b class="header">Lexical Scoping and Variable Safety</b>
|
||||
The CoffeeScript compiler takes care to make sure that all of your variables
|
||||
are properly declared within lexical scope — you never need to write
|
||||
@@ -364,18 +300,12 @@ coffee --print app/scripts/*.coffee > concatenation.js</pre>
|
||||
CoffeeScript output is wrapped in an anonymous function:
|
||||
<tt>(function(){ ... })();</tt> This safety wrapper, combined with the
|
||||
automatic generation of the <tt>var</tt> keyword, make it exceedingly difficult
|
||||
to pollute the global namespace by accident.
|
||||
</p>
|
||||
<p>
|
||||
If you'd like to create top-level variables for other scripts to use,
|
||||
attach them as properties on <b>window</b>, or on the <b>exports</b>
|
||||
object in CommonJS. The <b>existential operator</b> (below), gives you a
|
||||
reliable way to figure out where to add them, if you're targeting both
|
||||
CommonJS and the browser: <tt>root: exports ? this</tt>
|
||||
to pollute the global namespace by accident. If you'd like to create
|
||||
global variables, attach them as properties on <b>window</b>,
|
||||
or on the <b>exports</b> object in CommonJS.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<span id="conditionals" class="bookmark"></span>
|
||||
<p id="conditionals">
|
||||
<b class="header">Conditionals, Ternaries, and Conditional Assignment</b>
|
||||
<b>If/else</b> statements can be written without the use of parentheses and
|
||||
curly brackets. As with functions and other block expressions,
|
||||
@@ -394,8 +324,17 @@ coffee --print app/scripts/*.coffee > concatenation.js</pre>
|
||||
truthy variables.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<span id="aliases" class="bookmark"></span>
|
||||
<p id="existence">
|
||||
<b class="header">The Existence Operator</b>
|
||||
It's a little difficult to check for the existence of a variable in
|
||||
JavaScript. <tt>if (variable) ...</tt> comes close, but fails for zero,
|
||||
the empty string, and false. The existence operator <tt>?</tt> returns true unless
|
||||
a variable is <b>null</b> or <b>undefined</b>, which makes it analogous
|
||||
to Ruby's <tt>nil?</tt>
|
||||
</p>
|
||||
<%= code_for('existence') %>
|
||||
|
||||
<p id="aliases">
|
||||
<b class="header">Aliases</b>
|
||||
Because the <tt>==</tt> operator frequently causes undesirable coercion,
|
||||
is intransitive, and has a different meaning than in other languages,
|
||||
@@ -423,40 +362,31 @@ coffee --print app/scripts/*.coffee > concatenation.js</pre>
|
||||
<p>
|
||||
For single-line statements, <tt>unless</tt> can be used as the inverse of <tt>if</tt>.
|
||||
</p>
|
||||
<p>
|
||||
As a shortcut for <tt>this.property</tt>, you can use <tt>@property</tt>.
|
||||
</p>
|
||||
<%= code_for('aliases') %>
|
||||
|
||||
<p>
|
||||
<span id="splats" class="bookmark"></span>
|
||||
<b class="header">Splats...</b>
|
||||
<p id="splats">
|
||||
<b class="header">Splats</b>
|
||||
The JavaScript <b>arguments object</b> is a useful way to work with
|
||||
functions that accept variable numbers of arguments. CoffeeScript provides
|
||||
splats <tt>...</tt>, both for function definition as well as invocation,
|
||||
making variable numbers of arguments a little bit more palatable.
|
||||
splats <tt>*</tt>, both for function definition as well as invocation,
|
||||
making variable arguments a little bit more palatable.
|
||||
</p>
|
||||
<%= code_for('splats', true) %>
|
||||
|
||||
<p>
|
||||
<span id="arguments" class="bookmark"></span>
|
||||
<p id="arguments">
|
||||
<b class="header">Arguments are Arrays</b>
|
||||
If you reference the <b>arguments object</b> directly, it will be converted
|
||||
into a real Array, making all of the
|
||||
<a href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array">Array methods</a>
|
||||
into a real Array, making all of the
|
||||
<a href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array">Array methods</a>
|
||||
available.
|
||||
</p>
|
||||
<%= code_for('arguments', true) %>
|
||||
|
||||
<p>
|
||||
<span id="while" class="bookmark"></span>
|
||||
<p id="while">
|
||||
<b class="header">While Loops</b>
|
||||
The only low-level loop that CoffeeScript provides is the <b>while</b> loop. The
|
||||
main difference from JavaScript is that the <b>while</b> loop can be used
|
||||
as an expression, returning an array containing the result of each iteration
|
||||
through the loop.
|
||||
The only low-level loop that CoffeeScript provides is the while loop.
|
||||
</p>
|
||||
<%= code_for('while', 'lyrics.join("\n")') %>
|
||||
<%= code_for('while') %>
|
||||
<p>
|
||||
Other JavaScript loops, such as <b>for</b> loops and <b>do-while</b> loops
|
||||
can be mimicked by variations on <b>while</b>, but the hope is that you
|
||||
@@ -464,8 +394,7 @@ coffee --print app/scripts/*.coffee > concatenation.js</pre>
|
||||
<b>each</b> (<b>forEach</b>) style iterators, or...
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<span id="comprehensions" class="bookmark"></span>
|
||||
<p id="comprehensions">
|
||||
<b class="header">Comprehensions (Arrays, Objects, and Ranges)</b>
|
||||
For your looping needs, CoffeeScript provides array comprehensions
|
||||
similar to Python's. They replace (and compile into) <b>for</b> loops, with
|
||||
@@ -478,19 +407,16 @@ coffee --print app/scripts/*.coffee > concatenation.js</pre>
|
||||
<p>
|
||||
If you know the start and end of your loop, or would like to step through
|
||||
in fixed-size increments, you can use a range to specify the start and
|
||||
end of your comprehension. (The long line-breaking "for" definitions in
|
||||
the compiled JS below allow ranges to count downwards, as well as upwards).
|
||||
end of your comprehension:
|
||||
</p>
|
||||
<%= code_for('range_comprehensions', 'countdown') %>
|
||||
<%= code_for('range_comprehensions') %>
|
||||
<p>
|
||||
Comprehensions can also be used to iterate over the keys and values in
|
||||
an object. Use <tt>of</tt> to signal comprehension over the properties of
|
||||
an object instead of the values in an array.
|
||||
Comprehensions can also be used to iterate over the values and keys in
|
||||
an object:
|
||||
</p>
|
||||
<%= code_for('object_comprehensions', 'ages.join(", ")') %>
|
||||
|
||||
<p>
|
||||
<span id="slice_splice" class="bookmark"></span>
|
||||
<p id="slice_splice">
|
||||
<b class="header">Array Slicing and Splicing with Ranges</b>
|
||||
CoffeeScript borrows Ruby's
|
||||
<a href="http://ruby-doc.org/core/classes/Range.html">range syntax</a>
|
||||
@@ -506,8 +432,7 @@ coffee --print app/scripts/*.coffee > concatenation.js</pre>
|
||||
</p>
|
||||
<%= code_for('splices', 'numbers') %>
|
||||
|
||||
<p>
|
||||
<span id="expressions" class="bookmark"></span>
|
||||
<p id="expressions">
|
||||
<b class="header">Everything is an Expression (at least, as much as possible)</b>
|
||||
You might have noticed how even though we don't add return statements
|
||||
to CoffeeScript functions, they nonetheless return their final value.
|
||||
@@ -517,11 +442,6 @@ coffee --print app/scripts/*.coffee > concatenation.js</pre>
|
||||
below.
|
||||
</p>
|
||||
<%= code_for('expressions', 'eldest') %>
|
||||
<p>
|
||||
Even though functions will always return their final value, it's both possible
|
||||
and encouraged to return early from a function body writing out the explicit
|
||||
return (<tt>return value</tt>), when you know that you're done.
|
||||
</p>
|
||||
<p>
|
||||
Because variable declarations occur at the top of scope, assignment can
|
||||
be used within expressions, even for variables that haven't been seen before:
|
||||
@@ -539,45 +459,8 @@ coffee --print app/scripts/*.coffee > concatenation.js</pre>
|
||||
into a function call:
|
||||
</p>
|
||||
<%= code_for('expressions_try', true) %>
|
||||
<p>
|
||||
There are a handful of statements in JavaScript that can't be meaningfully
|
||||
converted into expressions, namely <tt>break</tt>, <tt>continue</tt>,
|
||||
and <tt>return</tt>. If you make use of them within a block of code,
|
||||
CoffeeScript won't try to perform the conversion.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<span id="existence" class="bookmark"></span>
|
||||
<b class="header">The Existential Operator</b>
|
||||
It's a little difficult to check for the existence of a variable in
|
||||
JavaScript. <tt>if (variable) ...</tt> comes close, but fails for zero,
|
||||
the empty string, and false. CoffeeScript's existential operator <tt>?</tt> returns true unless
|
||||
a variable is <b>null</b> or <b>undefined</b>, which makes it analogous
|
||||
to Ruby's <tt>nil?</tt>
|
||||
</p>
|
||||
<p>
|
||||
It can also be used for safer conditional assignment than <tt>||=</tt>
|
||||
provides, for cases where you may be handling numbers or strings.
|
||||
</p>
|
||||
<%= code_for('existence', 'speed') %>
|
||||
<p>
|
||||
The accessor variant of the existential operator <tt>?.</tt> can be used to soak
|
||||
up null references in a chain of properties. Use it instead
|
||||
of the dot accessor <tt>.</tt> in cases where the base value may be <b>null</b>
|
||||
or <b>undefined</b>. If all of the properties exist then you'll get the expected
|
||||
result, if the chain is broken, <b>undefined</b> is returned instead of
|
||||
the <b>TypeError</b> that would be raised otherwise.
|
||||
</p>
|
||||
<%= code_for('soaks') %>
|
||||
<p>
|
||||
Soaking up nulls is similar to Ruby's
|
||||
<a href="http://andand.rubyforge.org/">andand gem</a>, and to the
|
||||
<a href="http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator%28%3F.%29">safe navigation operator</a>
|
||||
in Groovy.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<span id="inheritance" class="bookmark"></span>
|
||||
<p id="inheritance">
|
||||
<b class="header">Inheritance, and Calling Super from a Subclass</b>
|
||||
JavaScript's prototypal inheritance has always been a bit of a
|
||||
brain-bender, with a whole family tree of libraries that provide a cleaner
|
||||
@@ -589,62 +472,30 @@ coffee --print app/scripts/*.coffee > concatenation.js</pre>
|
||||
be completely usable if it weren't for a couple of small exceptions:
|
||||
it's awkward to call <b>super</b> (the prototype object's
|
||||
implementation of the current function), and it's awkward to correctly
|
||||
set the prototype chain.
|
||||
</p>
|
||||
<p>
|
||||
CoffeeScript provides <tt>extends</tt>
|
||||
to help with prototype setup, <tt>::</tt> for quick access to an
|
||||
object's prototype, and converts <tt>super()</tt> into a call against
|
||||
the immediate ancestor's method of the same name.
|
||||
set the prototype chain. CoffeeScript provides <tt>extends</tt>
|
||||
to help with prototype setup, and converts
|
||||
<tt>super()</tt> calls into calls against the immediate ancestor's
|
||||
method of the same name.
|
||||
</p>
|
||||
<%= code_for('super', true) %>
|
||||
|
||||
<p>
|
||||
<span id="pattern_matching" class="bookmark"></span>
|
||||
<b class="header">Pattern Matching (Destructuring Assignment)</b>
|
||||
To make extracting values from complex arrays and objects more convenient,
|
||||
CoffeeScript implements ECMAScript Harmony's proposed
|
||||
<a href="http://wiki.ecmascript.org/doku.php?id=harmony:destructuring">destructuring assignment</a>
|
||||
syntax. When you assign an array or object literal to a value, CoffeeScript
|
||||
breaks up and matches both sides against each other, assigning the values
|
||||
on the right to the variables on the left. In the simplest case, it can be
|
||||
used for parallel assignment:
|
||||
<p id="blocks">
|
||||
<b class="header">Blocks</b>
|
||||
Many common looping functions (in Prototype, jQuery, and Underscore,
|
||||
for example) take a single function as their final argument. To make
|
||||
final functions easier to pass, CoffeeScript includes block syntax,
|
||||
so you don't have to close the parentheses on the other side.
|
||||
</p>
|
||||
<%= code_for('parallel_assignment', 'bait') %>
|
||||
<p>
|
||||
But it's also helpful for dealing with functions that return multiple
|
||||
values.
|
||||
</p>
|
||||
<%= code_for('multiple_return_values', 'forecast') %>
|
||||
<p>
|
||||
Pattern matching can be used with any depth of array and object nesting,
|
||||
to help pull out deeply nested properties.
|
||||
</p>
|
||||
<%= code_for('object_extraction', 'poet + " — " + street') %>
|
||||
<%= code_for('blocks') %>
|
||||
|
||||
<p>
|
||||
<span id="fat_arrow" class="bookmark"></span>
|
||||
<b class="header">Function binding</b>
|
||||
The fat arrow <tt>=></tt> can be used to both define a function, and to bind
|
||||
it to the current value of <tt>this</tt>, right on the spot. This is helpful
|
||||
when using callback-based libraries like Prototype or jQuery, for creating
|
||||
iterator functions to pass to <tt>each</tt>, or event-handler functions
|
||||
to use with <tt>bind</tt>. Functions created with the fat arrow are able to access
|
||||
properties of the <tt>this</tt> where they're defined.
|
||||
</p>
|
||||
<%= code_for('fat_arrow') %>
|
||||
|
||||
<p>
|
||||
<span id="embedded" class="bookmark"></span>
|
||||
<p id="embedded">
|
||||
<b class="header">Embedded JavaScript</b>
|
||||
Hopefully, you'll never need to use it, but if you ever need to intersperse
|
||||
snippets of JavaScript within your CoffeeScript, you can
|
||||
use backticks to pass it straight through.
|
||||
If you ever need to interpolate literal JavaScript snippets, you can
|
||||
use backticks to pass JavaScript straight through.
|
||||
</p>
|
||||
<%= code_for('embedded', 'hi()') %>
|
||||
|
||||
<p>
|
||||
<span id="switch" class="bookmark"></span>
|
||||
<p id="switch">
|
||||
<b class="header">Switch/When/Else</b>
|
||||
<b>Switch</b> statements in JavaScript are rather broken. You can only
|
||||
do comparisons based on string equality, and need to remember to <b>break</b> at the end of
|
||||
@@ -654,174 +505,79 @@ coffee --print app/scripts/*.coffee > concatenation.js</pre>
|
||||
in a returnable, assignable expression. The format is: <tt>switch</tt> condition,
|
||||
<tt>when</tt> clauses, <tt>else</tt> the default case.
|
||||
</p>
|
||||
<p>
|
||||
As in Ruby, <b>switch</b> statements in CoffeeScript can take multiple
|
||||
values for each <b>when</b> clause. If any of the values match, the clause
|
||||
runs.
|
||||
</p>
|
||||
<%= code_for('switch') %>
|
||||
|
||||
<p>
|
||||
<span id="try" class="bookmark"></span>
|
||||
<p id="try">
|
||||
<b class="header">Try/Catch/Finally</b>
|
||||
Try/catch statements are just about the same as JavaScript (although
|
||||
they work as expressions).
|
||||
</p>
|
||||
<%= code_for('try') %>
|
||||
|
||||
<p>
|
||||
<span id="comparisons" class="bookmark"></span>
|
||||
<b class="header">Chained Comparisons</b>
|
||||
CoffeeScript borrows
|
||||
<a href="http://docs.python.org/reference/expressions.html#notin">chained comparisons</a>
|
||||
from Python — making it easy to test if a value falls within a
|
||||
certain range.
|
||||
</p>
|
||||
<%= code_for('comparisons', 'healthy') %>
|
||||
|
||||
<p>
|
||||
<span id="strings" class="bookmark"></span>
|
||||
<b class="header">Multiline Strings and Heredocs</b>
|
||||
<p id="strings">
|
||||
<b class="header">Multiline Strings</b>
|
||||
Multiline strings are allowed in CoffeeScript.
|
||||
</p>
|
||||
<%= code_for('strings', 'moby_dick') %>
|
||||
<p>
|
||||
Heredocs can be used to hold formatted or indentation-sensitive text
|
||||
(or, if you just don't feel like escaping quotes and apostrophes). The
|
||||
indentation level that begins the heredoc is maintained throughout, so
|
||||
you can keep it all aligned with the body of your code.
|
||||
</p>
|
||||
<%= code_for('heredocs') %>
|
||||
|
||||
<h2>
|
||||
<span id="cake" class="bookmark"></span>
|
||||
Cake, and Cakefiles
|
||||
</h2>
|
||||
|
||||
<p>
|
||||
CoffeeScript includes a simple build system similar to Make and Rake. Naturally,
|
||||
it's called Cake, and is used for the build and test tasks for the CoffeeScript
|
||||
language itself. Tasks are defined in a file named <tt>Cakefile</tt>, and
|
||||
can be invoked by running <tt>cake taskname</tt> from within the directory.
|
||||
To print a list of all the tasks, just run <tt>cake</tt>.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Task definitions are written in CoffeeScript, so you can put arbitrary code
|
||||
in your Cakefile. Define a task with a name, a long description, and the
|
||||
function to invoke when the task is run. Here's a hypothetical task
|
||||
that uses the Node.js API.
|
||||
</p>
|
||||
<%= code_for('cake_tasks') %>
|
||||
|
||||
<h2>
|
||||
<span id="resources" class="bookmark"></span>
|
||||
Resources
|
||||
</h2>
|
||||
<h2 id="resources">Resources</h2>
|
||||
|
||||
<ul>
|
||||
<li>
|
||||
<a href="http://github.com/jashkenas/coffee-script/">Source Code</a><br />
|
||||
Use <tt>bin/coffee</tt> to test your changes,<br />
|
||||
<tt>bin/cake test</tt> to run the test suite,<br />
|
||||
<tt>bin/cake build</tt> to rebuild the CoffeeScript compiler, and <br />
|
||||
<tt>bin/cake build:parser</tt> to regenerate the Jison parser if you're
|
||||
working on the grammar.
|
||||
Use <tt>bin/coffee</tt> to test your changes, or <tt>rake gem:install</tt> to
|
||||
create and install a custom version of the gem. If you're hacking on the
|
||||
parser, use <tt>rake build:parser</tt> to rebuild it.
|
||||
</li>
|
||||
<li>
|
||||
<a href="http://github.com/jashkenas/coffee-script/issues">CoffeeScript Issues</a><br />
|
||||
Bugs reports, feature requests, and general discussion all belong here.
|
||||
<a href="http://github.com/jashkenas/coffee-script/issues">Bugs and Feature Requests</a>
|
||||
</li>
|
||||
<li>
|
||||
If you'd like to chat, stop by <tt>#coffeescript</tt> on Freenode.
|
||||
<a href="http://github.com/jnicklas/bistro_car">BistroCar</a><br />
|
||||
A Rails plugin by
|
||||
<a href="http://github.com/jnicklas">Jonas Nicklas</a>
|
||||
that includes CoffeeScript helpers,
|
||||
bundling and minification.
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<h2>
|
||||
<span id="change_log" class="bookmark"></span>
|
||||
Change Log
|
||||
</h2>
|
||||
|
||||
<p>
|
||||
<b class="header" style="margin-top: 20px;">0.5.0</b>
|
||||
CoffeeScript 0.5.0 is a major release, While there are no language changes,
|
||||
the Ruby compiler has been removed in favor of a self-hosting
|
||||
compiler written in pure CoffeeScript.
|
||||
</p>
|
||||
<h2 id="contributing">Contributing</h2>
|
||||
|
||||
<p>
|
||||
<b class="header" style="margin-top: 20px;">0.3.2</b>
|
||||
<tt>@property</tt> is now a shorthand for <tt>this.property</tt>.<br />
|
||||
Switched the default JavaScript engine from Narwhal to Node.js. Pass
|
||||
the <tt>--narwhal</tt> flag if you'd like to continue using it.
|
||||
Here's a wish list of things that would be wonderful to have in
|
||||
CoffeeScript:
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<b class="header" style="margin-top: 20px;">0.3.0</b>
|
||||
CoffeeScript 0.3 includes major syntax changes:
|
||||
<br />
|
||||
The function symbol was changed to
|
||||
<tt>-></tt>, and the bound function symbol is now <tt>=></tt>.
|
||||
<br />
|
||||
Parameter lists in function definitions must now be wrapped in parentheses.
|
||||
<br />
|
||||
Added property soaking, with the <tt>?.</tt> operator.
|
||||
<br />
|
||||
Made parentheses optional, when invoking functions with arguments.
|
||||
<br />
|
||||
Removed the obsolete block literal syntax.
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
A clean, safe syntax for manipulating the prototype chain, and performing
|
||||
inheritance. <a href="#inheritance"><b>extends</b> and <b>super</b></a> are the start of this, but
|
||||
aren't a complete answer.
|
||||
</li>
|
||||
<li>
|
||||
A CoffeeScript version of the compiler, perhaps using Alessandro Warth's
|
||||
<a href="http://tinlizzie.org/ometa/">OMeta</a>.
|
||||
</li>
|
||||
<li>
|
||||
Test cases for any syntax errors you encounter that you think CoffeeScript
|
||||
should be able to compile properly.
|
||||
</li>
|
||||
<li>
|
||||
A tutorial that introduces CoffeeScript from the ground up for folks
|
||||
without knowledge of JavaScript.
|
||||
</li>
|
||||
<li>
|
||||
Integration with Processing.js's JavaScript API (this would depend on
|
||||
having a JavaScript version of the compiler).
|
||||
</li>
|
||||
<li>
|
||||
A lot of the code generation in <tt>nodes.rb</tt> gets into messy
|
||||
string manipulation. Techniques for cleaning this up across the board
|
||||
would be appreciated.
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<p>
|
||||
<b class="header" style="margin-top: 20px;">0.2.6</b>
|
||||
Added Python-style chained comparisons, the conditional existence
|
||||
operator <tt>?=</tt>, and some examples from <i>Beautiful Code</i>.
|
||||
Bugfixes relating to statement-to-expression conversion, arguments-to-array
|
||||
conversion, and the TextMate syntax highlighter.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<b class="header" style="margin-top: 20px;">0.2.5</b>
|
||||
The conditions in switch statements can now take multiple values at once —
|
||||
If any of them are true, the case will run. Added the long arrow <tt>==></tt>,
|
||||
which defines and immediately binds a function to <tt>this</tt>. While loops can
|
||||
now be used as expressions, in the same way that comprehensions can. Splats
|
||||
can be used within pattern matches to soak up the rest of an array.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<b class="header" style="margin-top: 20px;">0.2.4</b>
|
||||
Added ECMAScript Harmony style destructuring assignment, for dealing with
|
||||
extracting values from nested arrays and objects. Added indentation-sensitive
|
||||
heredocs for nicely formatted strings or chunks of code.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<b class="header" style="margin-top: 20px;">0.2.3</b>
|
||||
Axed the unsatisfactory <tt>ino</tt> keyword, replacing it with <tt>of</tt> for
|
||||
object comprehensions. They now look like: <tt>for prop, value of object</tt>.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<b class="header" style="margin-top: 20px;">0.2.2</b>
|
||||
When performing a comprehension over an object, use <tt>ino</tt>, instead
|
||||
of <tt>in</tt>, which helps us generate smaller, more efficient code at
|
||||
compile time.
|
||||
<br />
|
||||
Added <tt>::</tt> as a shorthand for saying <tt>.prototype.</tt>
|
||||
<br />
|
||||
The "splat" symbol has been changed from a prefix asterisk <tt>*</tt>, to
|
||||
a postfix ellipsis <tt>...</tt>
|
||||
<br />
|
||||
Added JavaScript's <tt>in</tt> operator,
|
||||
empty <tt>return</tt> statements, and empty <tt>while</tt> loops.
|
||||
<br />
|
||||
Constructor functions that start with capital letters now include a
|
||||
safety check to make sure that the new instance of the object is returned.
|
||||
<br />
|
||||
The <tt>extends</tt> keyword now functions identically to <tt>goog.inherits</tt>
|
||||
in Google's Closure Library.
|
||||
</p>
|
||||
<h2 id="change_log">Change Log</h2>
|
||||
|
||||
<p>
|
||||
<b class="header" style="margin-top: 20px;">0.2.1</b>
|
||||
@@ -832,7 +588,7 @@ coffee --print app/scripts/*.coffee > concatenation.js</pre>
|
||||
<b class="header" style="margin-top: 20px;">0.2.0</b>
|
||||
Major release. Significant whitespace. Better statement-to-expression
|
||||
conversion. Splats. Splice literals. Object comprehensions. Blocks.
|
||||
The existential operator. Many thanks to all the folks who posted issues,
|
||||
The existence operator. Many thanks to all the folks who posted issues,
|
||||
with special thanks to
|
||||
<a href="http://github.com/kamatsu">Liam O'Connor-Davis</a> for whitespace
|
||||
and expression help.
|
||||
@@ -904,32 +660,5 @@ coffee --print app/scripts/*.coffee > concatenation.js</pre>
|
||||
|
||||
</div>
|
||||
|
||||
<script type="text/javascript" src="lib/rewriter.js"></script>
|
||||
<script type="text/javascript" src="lib/lexer.js"></script>
|
||||
<script type="text/javascript" src="lib/parser.js"></script>
|
||||
<script type="text/javascript" src="lib/scope.js"></script>
|
||||
<script type="text/javascript" src="lib/nodes.js"></script>
|
||||
<script type="text/javascript" src="lib/coffee-script.js"></script>
|
||||
|
||||
<script type="text/javascript">
|
||||
window.repl_compile = function() {
|
||||
var source = document.getElementById('repl_source').value;
|
||||
window.compiled_js = '';
|
||||
try {
|
||||
window.compiled_js = CoffeeScript.compile(source, {no_wrap: true});
|
||||
} catch(error) {
|
||||
alert(error);
|
||||
}
|
||||
document.getElementById('repl_results').innerHTML = window.compiled_js;
|
||||
}
|
||||
window.repl_run = function() {
|
||||
try {
|
||||
eval(window.compiled_js);
|
||||
} catch(error) {
|
||||
alert(error);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -10,5 +10,4 @@
|
||||
let_the_wild_rumpus_begin();
|
||||
}
|
||||
car.speed < speed_limit ? accelerate() : null;
|
||||
print("My name is " + this.name);
|
||||
})();
|
||||
@@ -1,8 +1,7 @@
|
||||
(function(){
|
||||
var backwards;
|
||||
backwards = function backwards() {
|
||||
arguments = Array.prototype.slice.call(arguments, 0);
|
||||
return alert(arguments.reverse());
|
||||
return alert(Array.prototype.slice.call(arguments, 0).reverse());
|
||||
};
|
||||
backwards("stairway", "to", "heaven");
|
||||
})();
|
||||
@@ -1,24 +1,32 @@
|
||||
(function(){
|
||||
var _a, _b, _c, _d, _e, _f, _g, food, lunch, roid, roid2;
|
||||
var __a, __b, __c, __d, __e, __f, __g, __h, __i, __j, food, lunch, roid, roid2;
|
||||
// Eat lunch.
|
||||
lunch = (function() {
|
||||
_a = []; _b = ['toast', 'cheese', 'wine'];
|
||||
for (_c = 0; _c < _b.length; _c++) {
|
||||
food = _b[_c];
|
||||
_a.push(eat(food));
|
||||
__a = ['toast', 'cheese', 'wine'];
|
||||
__c = [];
|
||||
for (__b in __a) {
|
||||
if (__a.hasOwnProperty(__b)) {
|
||||
food = __a[__b];
|
||||
__d = eat(food);
|
||||
__c.push(__d);
|
||||
}
|
||||
}
|
||||
return _a;
|
||||
}).call(this);
|
||||
return __c;
|
||||
})();
|
||||
// Naive collision detection.
|
||||
_d = asteroids;
|
||||
for (_e = 0; _e < _d.length; _e++) {
|
||||
roid = _d[_e];
|
||||
_f = asteroids;
|
||||
for (_g = 0; _g < _f.length; _g++) {
|
||||
roid2 = _f[_g];
|
||||
if (roid !== roid2) {
|
||||
if (roid.overlaps(roid2)) {
|
||||
roid.explode();
|
||||
__e = asteroids;
|
||||
for (__f in __e) {
|
||||
if (__e.hasOwnProperty(__f)) {
|
||||
roid = __e[__f];
|
||||
__h = asteroids;
|
||||
for (__i in __h) {
|
||||
if (__h.hasOwnProperty(__i)) {
|
||||
roid2 = __h[__i];
|
||||
if (roid !== roid2) {
|
||||
if (roid.overlaps(roid2)) {
|
||||
roid.explode();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
8
documentation/js/blocks.js
Normal file
8
documentation/js/blocks.js
Normal file
@@ -0,0 +1,8 @@
|
||||
(function(){
|
||||
$('table.list').each(function(table) {
|
||||
return $('tr.account', table).each(function(row) {
|
||||
row.show();
|
||||
return row.highlight();
|
||||
});
|
||||
});
|
||||
})();
|
||||
@@ -1,14 +0,0 @@
|
||||
(function(){
|
||||
process.mixin(require('assert'));
|
||||
task('test', 'run each of the unit tests', function() {
|
||||
var _a, _b, _c, test;
|
||||
_a = []; _b = test_files;
|
||||
for (_c = 0; _c < _b.length; _c++) {
|
||||
test = _b[_c];
|
||||
_a.push(fs.readFile(test, function(err, code) {
|
||||
return eval(coffee.compile(code));
|
||||
}));
|
||||
}
|
||||
return _a;
|
||||
});
|
||||
})();
|
||||
@@ -1,5 +0,0 @@
|
||||
(function(){
|
||||
var cholesterol, healthy;
|
||||
cholesterol = 127;
|
||||
healthy = (200 > cholesterol) && (cholesterol > 60);
|
||||
})();
|
||||
@@ -1,5 +1,5 @@
|
||||
(function(){
|
||||
var date, expensive, mood;
|
||||
var date, mood;
|
||||
if (singing) {
|
||||
mood = greatly_improved;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
(function(){
|
||||
var solipsism, speed;
|
||||
var solipsism;
|
||||
if ((typeof mind !== "undefined" && mind !== null) && !(typeof world !== "undefined" && world !== null)) {
|
||||
solipsism = true;
|
||||
}
|
||||
speed = (typeof speed !== "undefined" && speed !== null) ? speed : 140;
|
||||
})();
|
||||
@@ -1,4 +1,4 @@
|
||||
(function(){
|
||||
var one, six, three, two;
|
||||
six = ((one = 1)) + ((two = 2)) + ((three = 3));
|
||||
six = (one = 1) + (two = 2) + (three = 3);
|
||||
})();
|
||||
@@ -1,12 +1,16 @@
|
||||
(function(){
|
||||
var _a, _b, globals, name;
|
||||
var __hasProp = Object.prototype.hasOwnProperty;
|
||||
var __a, __b, __c, globals, name, property;
|
||||
// The first ten global properties.
|
||||
globals = (function() {
|
||||
_a = []; _b = window;
|
||||
for (name in _b) { if (__hasProp.call(_b, name)) {
|
||||
_a.push(name);
|
||||
}}
|
||||
return _a;
|
||||
}).call(this).slice(0, 10);
|
||||
globals = ((function() {
|
||||
__a = window;
|
||||
__b = [];
|
||||
for (name in __a) {
|
||||
if (__a.hasOwnProperty(name)) {
|
||||
property = __a[name];
|
||||
__c = name;
|
||||
__b.push(__c);
|
||||
}
|
||||
}
|
||||
return __b;
|
||||
})()).slice(0, 10);
|
||||
})();
|
||||
@@ -3,7 +3,7 @@
|
||||
try {
|
||||
return nonexistent / undefined;
|
||||
} catch (error) {
|
||||
return "And the error is ... " + error;
|
||||
return "The error is: " + error;
|
||||
}
|
||||
}).call(this));
|
||||
})());
|
||||
})();
|
||||
@@ -1,15 +0,0 @@
|
||||
(function(){
|
||||
var Account;
|
||||
Account = function Account(customer, cart) {
|
||||
this.customer = customer;
|
||||
this.cart = cart;
|
||||
return $('.shopping_cart').bind('click', (function(__this) {
|
||||
var __func = function(event) {
|
||||
return this.customer.purchase(this.cart);
|
||||
};
|
||||
return (function() {
|
||||
return __func.apply(__this, arguments);
|
||||
});
|
||||
})(this));
|
||||
};
|
||||
})();
|
||||
@@ -1,4 +0,0 @@
|
||||
(function(){
|
||||
var html;
|
||||
html = "<strong>\n cup of coffeescript\n</strong>";
|
||||
})();
|
||||
@@ -1,11 +0,0 @@
|
||||
(function(){
|
||||
var _a, city, forecast, temp, weather_report;
|
||||
weather_report = function weather_report(location) {
|
||||
// Make an Ajax request to fetch the weather...
|
||||
return [location, 72, "Mostly Sunny"];
|
||||
};
|
||||
_a = weather_report("Berkeley, CA");
|
||||
city = _a[0];
|
||||
temp = _a[1];
|
||||
forecast = _a[2];
|
||||
})();
|
||||
@@ -1,17 +1,20 @@
|
||||
(function(){
|
||||
var _a, _b, age, ages, child, years_old;
|
||||
var __hasProp = Object.prototype.hasOwnProperty;
|
||||
var __a, __b, __c, age, ages, child, years_old;
|
||||
years_old = {
|
||||
max: 10,
|
||||
ida: 9,
|
||||
tim: 11
|
||||
};
|
||||
ages = (function() {
|
||||
_a = []; _b = years_old;
|
||||
for (child in _b) { if (__hasProp.call(_b, child)) {
|
||||
age = _b[child];
|
||||
_a.push(child + " is " + age);
|
||||
}}
|
||||
return _a;
|
||||
}).call(this);
|
||||
__a = years_old;
|
||||
__b = [];
|
||||
for (child in __a) {
|
||||
if (__a.hasOwnProperty(child)) {
|
||||
age = __a[child];
|
||||
__c = child + " is " + age;
|
||||
__b.push(__c);
|
||||
}
|
||||
}
|
||||
return __b;
|
||||
})();
|
||||
})();
|
||||
@@ -1,17 +0,0 @@
|
||||
(function(){
|
||||
var _a, _b, _c, city, futurists, poet, street;
|
||||
futurists = {
|
||||
sculptor: "Umberto Boccioni",
|
||||
painter: "Vladimir Burliuk",
|
||||
poet: {
|
||||
name: "F.T. Marinetti",
|
||||
address: ["Via Roma 42R", "Bellagio, Italy 22021"]
|
||||
}
|
||||
};
|
||||
_a = futurists;
|
||||
_b = _a.poet;
|
||||
poet = _b.name;
|
||||
_c = _b.address;
|
||||
street = _c[0];
|
||||
city = _c[1];
|
||||
})();
|
||||
@@ -1,5 +1,5 @@
|
||||
(function(){
|
||||
var _a, _b, _c, cubed_list, list, math, num, number, opposite_day, race, square;
|
||||
var __a, __b, __c, __d, cubed_list, list, math, num, number, opposite_day, race, square;
|
||||
// Assignment:
|
||||
number = 42;
|
||||
opposite_day = true;
|
||||
@@ -33,11 +33,15 @@
|
||||
}
|
||||
// Array comprehensions:
|
||||
cubed_list = (function() {
|
||||
_a = []; _b = list;
|
||||
for (_c = 0; _c < _b.length; _c++) {
|
||||
num = _b[_c];
|
||||
_a.push(math.cube(num));
|
||||
__a = list;
|
||||
__c = [];
|
||||
for (__b in __a) {
|
||||
if (__a.hasOwnProperty(__b)) {
|
||||
num = __a[__b];
|
||||
__d = math.cube(num);
|
||||
__c.push(__d);
|
||||
}
|
||||
}
|
||||
return _a;
|
||||
}).call(this);
|
||||
return __c;
|
||||
})();
|
||||
})();
|
||||
@@ -1,8 +0,0 @@
|
||||
(function(){
|
||||
var _a, and_switch, bait;
|
||||
bait = 1000;
|
||||
and_switch = 0;
|
||||
_a = [and_switch, bait];
|
||||
bait = _a[0];
|
||||
and_switch = _a[1];
|
||||
})();
|
||||
@@ -1,21 +1,9 @@
|
||||
(function(){
|
||||
var _a, _b, _c, _d, _e, countdown, egg_delivery, num;
|
||||
countdown = (function() {
|
||||
_a = []; _d = 10; _e = 1;
|
||||
for (_c=0, num=_d; (_d <= _e ? num <= _e : num >= _e); (_d <= _e ? num += 1 : num -= 1), _c++) {
|
||||
_a.push(num);
|
||||
}
|
||||
return _a;
|
||||
}).call(this);
|
||||
egg_delivery = function egg_delivery() {
|
||||
var _f, _g, _h, _i, _j, dozen_eggs, i;
|
||||
_f = []; _i = 0; _j = eggs.length;
|
||||
for (_h=0, i=_i; (_i <= _j ? i < _j : i > _j); (_i <= _j ? i += 12 : i -= 12), _h++) {
|
||||
_f.push((function() {
|
||||
dozen_eggs = eggs.slice(i, i + 12);
|
||||
return deliver(new egg_carton(dozen));
|
||||
}).call(this));
|
||||
}
|
||||
return _f;
|
||||
};
|
||||
var __a, __b, __c, __d, __e, dozen_eggs, i;
|
||||
__d = 0;
|
||||
__e = eggs.length;
|
||||
for (__c=0, i=__d; (__d <= __e ? i < __e : i > __e); (__d <= __e ? i += 12 : i -= 12), __c++) {
|
||||
dozen_eggs = eggs.slice(i, i + 12);
|
||||
deliver(new egg_carton(dozen));
|
||||
}
|
||||
})();
|
||||
@@ -1,4 +0,0 @@
|
||||
(function(){
|
||||
var _a;
|
||||
(_a = lottery.draw_winner()) == null ? undefined : _a.address == null ? undefined : _a.address.zipcode;
|
||||
})();
|
||||
@@ -1,7 +1,7 @@
|
||||
(function(){
|
||||
var award_medals, contenders, gold, silver, the_field;
|
||||
gold = (silver = (the_field = "unknown"));
|
||||
award_medals = function award_medals(first, second) {
|
||||
var contenders, gold, medalists, silver, the_field;
|
||||
gold = silver = the_field = "unknown";
|
||||
medalists = function medalists(first, second) {
|
||||
var rest;
|
||||
rest = Array.prototype.slice.call(arguments, 2);
|
||||
gold = first;
|
||||
@@ -9,7 +9,7 @@
|
||||
return the_field = rest;
|
||||
};
|
||||
contenders = ["Michael Phelps", "Liu Xiang", "Yao Ming", "Allyson Felix", "Shawn Johnson", "Roman Sebrle", "Guo Jingjing", "Tyson Gay", "Asafa Powell", "Usain Bolt"];
|
||||
award_medals.apply(this, contenders);
|
||||
medalists.apply(this, contenders);
|
||||
alert("Gold: " + gold);
|
||||
alert("Silver: " + silver);
|
||||
alert("The Field: " + the_field);
|
||||
|
||||
@@ -1,30 +1,25 @@
|
||||
(function(){
|
||||
var Animal, Horse, Snake, _a, _b, sam, tom;
|
||||
Animal = function Animal() { };
|
||||
var Animal, Horse, Snake, sam, tom;
|
||||
Animal = function Animal() {
|
||||
};
|
||||
Animal.prototype.move = function move(meters) {
|
||||
return alert(this.name + " moved " + meters + "m.");
|
||||
};
|
||||
Snake = function Snake(name) {
|
||||
this.name = name;
|
||||
return this;
|
||||
return this.name = name;
|
||||
};
|
||||
_a = function(){};
|
||||
_a.prototype = Animal.prototype;
|
||||
Snake.__superClass__ = Animal.prototype;
|
||||
Snake.prototype = new _a();
|
||||
Snake.prototype = new Animal();
|
||||
Snake.prototype.constructor = Snake;
|
||||
Snake.prototype.move = function move() {
|
||||
alert("Slithering...");
|
||||
return Snake.__superClass__.move.call(this, 5);
|
||||
};
|
||||
Horse = function Horse(name) {
|
||||
this.name = name;
|
||||
return this;
|
||||
return this.name = name;
|
||||
};
|
||||
_b = function(){};
|
||||
_b.prototype = Animal.prototype;
|
||||
Horse.__superClass__ = Animal.prototype;
|
||||
Horse.prototype = new _b();
|
||||
Horse.prototype = new Animal();
|
||||
Horse.prototype.constructor = Horse;
|
||||
Horse.prototype.move = function move() {
|
||||
alert("Galloping...");
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
(function(){
|
||||
if (day === "Mon") {
|
||||
go_to_work();
|
||||
} else if (day === "Tue") {
|
||||
if (day === "Tuesday") {
|
||||
eat_breakfast();
|
||||
} else if (day === "Wednesday") {
|
||||
go_to_the_park();
|
||||
} else if (day === "Thu") {
|
||||
go_ice_fishing();
|
||||
} else if (day === "Fri" || day === "Sat") {
|
||||
} else if (day === "Saturday") {
|
||||
if (day === bingo_day) {
|
||||
go_to_bingo();
|
||||
go_dancing();
|
||||
}
|
||||
} else if (day === "Sun") {
|
||||
} else if (day === "Sunday") {
|
||||
go_to_church();
|
||||
} else {
|
||||
go_to_work();
|
||||
|
||||
@@ -1,22 +1,9 @@
|
||||
(function(){
|
||||
var _a, lyrics, num;
|
||||
// Econ 101
|
||||
if (this.studying_economics) {
|
||||
while (supply > demand) {
|
||||
buy();
|
||||
}
|
||||
while (supply < demand) {
|
||||
sell();
|
||||
}
|
||||
while (demand > supply) {
|
||||
sell();
|
||||
restock();
|
||||
}
|
||||
while (supply > demand) {
|
||||
buy();
|
||||
}
|
||||
// Nursery Rhyme
|
||||
num = 6;
|
||||
lyrics = (function() {
|
||||
_a = [];
|
||||
while (num -= 1) {
|
||||
_a.push(num + " little monkeys, jumping on the bed. \
|
||||
One fell out and bumped his head.");
|
||||
}
|
||||
return _a;
|
||||
}).call(this);
|
||||
})();
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,16 +0,0 @@
|
||||
# Beautiful Code, Chapter 6.
|
||||
# The implementation of binary search that is tested.
|
||||
|
||||
# Return the index of an element in a sorted list. (or -1, if not present)
|
||||
index: (list, target) ->
|
||||
[low, high]: [0, list.length]
|
||||
while low < high
|
||||
mid: (low + high) >> 1
|
||||
val: list[mid]
|
||||
return mid if val is target
|
||||
if val < target then low: mid + 1 else high: mid
|
||||
return -1
|
||||
|
||||
puts 2 is index([10, 20, 30, 40, 50], 30)
|
||||
puts 4 is index([-97, 35, 67, 88, 1200], 1200)
|
||||
puts 0 is index([0, 45, 70], 0)
|
||||
@@ -1,13 +0,0 @@
|
||||
# Beautiful Code, Chapter 3.
|
||||
# Produces the expected runtime of Quicksort, for every integer from 1 to N.
|
||||
|
||||
runtime: (N) ->
|
||||
[sum, t]: [0, 0]
|
||||
for n in [1..N]
|
||||
sum += 2 * t
|
||||
t: n - 1 + sum / n
|
||||
t
|
||||
|
||||
puts runtime(3) is 2.6666666666666665
|
||||
puts runtime(5) is 7.4
|
||||
puts runtime(8) is 16.92142857142857
|
||||
@@ -1,34 +0,0 @@
|
||||
# Beautiful Code, Chapter 1.
|
||||
# Implements a regular expression matcher that supports character matches,
|
||||
# '.', '^', '$', and '*'.
|
||||
|
||||
# Search for the regexp anywhere in the text.
|
||||
match: (regexp, text) ->
|
||||
return match_here(regexp.slice(1), text) if regexp[0] is '^'
|
||||
while text
|
||||
return true if match_here(regexp, text)
|
||||
text: text.slice(1)
|
||||
false
|
||||
|
||||
# Search for the regexp at the beginning of the text.
|
||||
match_here: (regexp, text) ->
|
||||
[cur, next]: [regexp[0], regexp[1]]
|
||||
if regexp.length is 0 then return true
|
||||
if next is '*' then return match_star(cur, regexp.slice(2), text)
|
||||
if cur is '$' and not next then return text.length is 0
|
||||
if text and (cur is '.' or cur is text[0]) then return match_here(regexp.slice(1), text.slice(1))
|
||||
false
|
||||
|
||||
# Search for a kleene star match at the beginning of the text.
|
||||
match_star: (c, regexp, text) ->
|
||||
while true
|
||||
return true if match_here(regexp, text)
|
||||
return false unless text and (text[0] is c or c is '.')
|
||||
text: text.slice(1)
|
||||
|
||||
puts match("ex", "some text")
|
||||
puts match("s..t", "spit")
|
||||
puts match("^..t", "buttercup")
|
||||
puts match("i..$", "cherries")
|
||||
puts match("o*m", "vrooooommm!")
|
||||
puts match("^hel*o$", "hellllllo")
|
||||
@@ -1,57 +0,0 @@
|
||||
# After wycats' http://yehudakatz.com/2010/02/07/the-building-blocks-of-ruby/
|
||||
|
||||
# Sinatra.
|
||||
get '/hello', ->
|
||||
'Hello World'
|
||||
|
||||
|
||||
# Append.
|
||||
append: (location, data) ->
|
||||
path: new Pathname location
|
||||
throw "Location does not exist" unless path.exists()
|
||||
|
||||
File.open path, 'a', (file) ->
|
||||
file.puts YAML.dump data
|
||||
|
||||
data
|
||||
|
||||
|
||||
# Rubinius' File.open implementation.
|
||||
File.open: (path, mode, block) ->
|
||||
io: new File path, mode
|
||||
|
||||
return io unless block
|
||||
|
||||
try
|
||||
block io
|
||||
finally
|
||||
try
|
||||
io.close() unless io.closed()
|
||||
catch error
|
||||
# nothing, just swallow them.
|
||||
|
||||
|
||||
# Write.
|
||||
write: (location, data) ->
|
||||
path = new Pathname location
|
||||
raise "Location does not exist" unless path.exists()
|
||||
|
||||
File.open path, 'w', (file) ->
|
||||
return false if Digest.MD5.hexdigest(file.read()) is data.hash()
|
||||
file.puts YAML.dump data
|
||||
true
|
||||
|
||||
|
||||
# Rails' respond_to.
|
||||
index: ->
|
||||
people: Person.find 'all'
|
||||
|
||||
respond_to (format) ->
|
||||
format.html()
|
||||
format.xml -> render { xml: people.xml() }
|
||||
|
||||
|
||||
# Synchronization.
|
||||
synchronize: (block) ->
|
||||
lock()
|
||||
try block() finally unlock()
|
||||
@@ -1,14 +1,14 @@
|
||||
# Functions:
|
||||
square: (x) -> x * x
|
||||
square: x => x * x
|
||||
|
||||
sum: (x, y) -> x + y
|
||||
sum: x, y => x + y
|
||||
|
||||
odd: (x) -> x % 2 isnt 0
|
||||
odd: x => x % 2 is 0
|
||||
|
||||
even: (x) -> x % 2 is 0
|
||||
even: x => x % 2 isnt 0
|
||||
|
||||
run_loop: ->
|
||||
fire_events((e) -> e.stopPropagation())
|
||||
run_loop: =>
|
||||
fire_events(e => e.stopPropagation())
|
||||
listen()
|
||||
wait()
|
||||
|
||||
@@ -22,14 +22,14 @@ spaced_out_multiline_object: {
|
||||
three: new Idea()
|
||||
|
||||
inner_obj: {
|
||||
freedom: -> _.freedom()
|
||||
freedom: => _.freedom()
|
||||
}
|
||||
}
|
||||
|
||||
# Arrays:
|
||||
stooges: [{moe: 45}, {curly: 43}, {larry: 46}]
|
||||
|
||||
exponents: [(x) -> x, (x) -> x * x, (x) -> x * x * x]
|
||||
exponents: [(x => x), (x => x * x), (x => x * x * x)]
|
||||
|
||||
empty: []
|
||||
|
||||
@@ -54,7 +54,7 @@ decoration: medal_of_honor if war_hero
|
||||
go_to_sleep() unless coffee
|
||||
|
||||
# Returning early:
|
||||
race: ->
|
||||
race: =>
|
||||
run()
|
||||
walk()
|
||||
crawl()
|
||||
@@ -103,7 +103,7 @@ while true
|
||||
|
||||
# Lexical scoping.
|
||||
v_1: 5
|
||||
change_a_and_set_b: ->
|
||||
change_a_and_set_b: =>
|
||||
v_1: 10
|
||||
v_2: 15
|
||||
v_2: 20
|
||||
@@ -128,7 +128,7 @@ activity: switch day
|
||||
else go_to_work()
|
||||
|
||||
# Semicolons can optionally be used instead of newlines.
|
||||
wednesday: -> eat_breakfast(); go_to_work(); eat_dinner()
|
||||
wednesday: => eat_breakfast(); go_to_work(); eat_dinner()
|
||||
|
||||
# Array slice literals.
|
||||
zero_to_nine: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
@@ -140,19 +140,19 @@ sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna
|
||||
aliquam erat volutpat. Ut wisi enim ad."
|
||||
|
||||
# Inheritance and calling super.
|
||||
Animal: ->
|
||||
Animal::move: (meters) ->
|
||||
Animal: =>
|
||||
Animal.prototype.move: meters =>
|
||||
alert(this.name + " moved " + meters + "m.")
|
||||
|
||||
Snake: (name) -> this.name: name
|
||||
Snake: name => this.name: name
|
||||
Snake extends Animal
|
||||
Snake::move: ->
|
||||
Snake.prototype.move: =>
|
||||
alert('Slithering...')
|
||||
super(5)
|
||||
|
||||
Horse: (name) -> this.name: name
|
||||
Horse: name => this.name: name
|
||||
Horse extends Animal
|
||||
Horse::move: ->
|
||||
Horse.prototype.move: =>
|
||||
alert('Galloping...')
|
||||
super(45)
|
||||
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
Ported from Nicholas Zakas' collection of computer science fundamentals, written
|
||||
in JavaScript. Originals available here:
|
||||
|
||||
http://github.com/nzakas/computer-science-in-javascript
|
||||
@@ -1,25 +0,0 @@
|
||||
# Uses a binary search algorithm to locate a value in the specified array.
|
||||
binary_search: (items, value) ->
|
||||
|
||||
start: 0
|
||||
stop: items.length - 1
|
||||
pivot: Math.floor((start + stop) / 2)
|
||||
|
||||
while items[pivot] isnt value and start < stop
|
||||
|
||||
# Adjust the search area.
|
||||
stop: pivot - 1 if value < items[pivot]
|
||||
start: pivot + 1 if value > items[pivot]
|
||||
|
||||
# Recalculate the pivot.
|
||||
pivot: Math.floor((stop + start) / 2)
|
||||
|
||||
# Make sure we've found the correct value.
|
||||
if items[pivot] is value then pivot else -1
|
||||
|
||||
|
||||
# Test the function.
|
||||
puts(2 is binary_search([10, 20, 30, 40, 50], 30))
|
||||
puts(4 is binary_search([-97, 35, 67, 88, 1200], 1200))
|
||||
puts(0 is binary_search([0, 45, 70], 0))
|
||||
puts(-1 is binary_search([0, 45, 70], 10))
|
||||
@@ -1,11 +0,0 @@
|
||||
# A bubble sort implementation, sorting the given array in-place.
|
||||
bubble_sort: (list) ->
|
||||
for i in [0...list.length]
|
||||
for j in [0...list.length - i]
|
||||
[list[j], list[j+1]]: [list[j+1], list[j]] if list[j] > list[j+1]
|
||||
list
|
||||
|
||||
|
||||
# Test the function.
|
||||
puts(bubble_sort([3, 2, 1]).join(' ') is '1 2 3')
|
||||
puts(bubble_sort([9, 2, 7, 0, 1]).join(' ') is '0 1 2 7 9')
|
||||
@@ -1,106 +0,0 @@
|
||||
# "Classic" linked list implementation that doesn't keep track of its size.
|
||||
LinkedList: ->
|
||||
this._head: null # Pointer to the first item in the list.
|
||||
|
||||
|
||||
# Appends some data to the end of the list. This method traverses the existing
|
||||
# list and places the value at the end in a new node.
|
||||
LinkedList::add: (data) ->
|
||||
|
||||
# Create a new node object to wrap the data.
|
||||
node: {data: data, next: null}
|
||||
|
||||
current: this._head ||= node
|
||||
|
||||
if this._head isnt node
|
||||
current: current.next while current.next
|
||||
current.next: node
|
||||
|
||||
this
|
||||
|
||||
|
||||
# Retrieves the data at the given position in the list.
|
||||
LinkedList::item: (index) ->
|
||||
|
||||
# Check for out-of-bounds values.
|
||||
return null if index < 0
|
||||
|
||||
current: this._head or null
|
||||
i: -1
|
||||
|
||||
# Advance through the list.
|
||||
current: current.next while current and index > (i += 1)
|
||||
|
||||
# Return null if we've reached the end.
|
||||
current and current.data
|
||||
|
||||
|
||||
# Remove the item from the given location in the list.
|
||||
LinkedList::remove: (index) ->
|
||||
|
||||
# Check for out-of-bounds values.
|
||||
return null if index < 0
|
||||
|
||||
current: this._head or null
|
||||
i: -1
|
||||
|
||||
# Special case: removing the first item.
|
||||
if index is 0
|
||||
this._head: current.next
|
||||
else
|
||||
|
||||
# Find the right location.
|
||||
[previous, current]: [current, current.next] while index > (i += 1)
|
||||
|
||||
# Skip over the item to remove.
|
||||
previous.next: current.next
|
||||
|
||||
# Return the value.
|
||||
current and current.data
|
||||
|
||||
|
||||
# Calculate the number of items in the list.
|
||||
LinkedList::size: ->
|
||||
current: this._head
|
||||
count: 0
|
||||
|
||||
while current
|
||||
count += 1
|
||||
current: current.next
|
||||
|
||||
count
|
||||
|
||||
|
||||
# Convert the list into an array.
|
||||
LinkedList::toArray: ->
|
||||
result: []
|
||||
current: this._head
|
||||
|
||||
while current
|
||||
result.push(current.data)
|
||||
current: current.next
|
||||
|
||||
result
|
||||
|
||||
|
||||
# The string representation of the linked list.
|
||||
LinkedList::toString: -> this.toArray().toString()
|
||||
|
||||
|
||||
# Tests.
|
||||
list: new LinkedList()
|
||||
|
||||
list.add("Hi")
|
||||
puts(list.size() is 1)
|
||||
puts(list.item(0) is "Hi")
|
||||
puts(list.item(1) is null)
|
||||
|
||||
list: new LinkedList()
|
||||
list.add("zero").add("one").add("two")
|
||||
puts(list.size() is 3)
|
||||
puts(list.item(2) is "two")
|
||||
puts(list.remove(1) is "one")
|
||||
puts(list.item(0) is "zero")
|
||||
puts(list.item(1) is "two")
|
||||
puts(list.size() is 2)
|
||||
puts(list.item(-10) is null)
|
||||
@@ -1,36 +0,0 @@
|
||||
# Use the Luhn algorithm to validate a numeric identifier, such as credit card
|
||||
# numbers, national insurance numbers, etc.
|
||||
# See: http://en.wikipedia.org/wiki/Luhn_algorithm
|
||||
|
||||
is_valid_identifier: (identifier) ->
|
||||
|
||||
sum: 0
|
||||
alt: false
|
||||
|
||||
for i in [(identifier.length - 1)..0]
|
||||
|
||||
# Get the next digit.
|
||||
num: parseInt(identifier.charAt(i), 10)
|
||||
|
||||
# If it's not a valid number, abort.
|
||||
return false if isNaN(num)
|
||||
|
||||
# If it's an alternate number...
|
||||
if alt
|
||||
num *= 2
|
||||
num: (num % 10) + 1 if num > 9
|
||||
|
||||
# Flip the alternate bit.
|
||||
alt: !alt
|
||||
|
||||
# Add to the rest of the sum.
|
||||
sum += num
|
||||
|
||||
# Determine if it's valid.
|
||||
sum % 10 is 0
|
||||
|
||||
|
||||
# Tests.
|
||||
puts(is_valid_identifier("49927398716") is true)
|
||||
puts(is_valid_identifier("4408041234567893") is true)
|
||||
puts(is_valid_identifier("4408041234567890") is false)
|
||||
@@ -1,19 +0,0 @@
|
||||
# Sorts an array in ascending natural order using merge sort.
|
||||
merge_sort: (list) ->
|
||||
|
||||
return list if list.length is 1
|
||||
|
||||
result: []
|
||||
pivot: Math.floor(list.length / 2)
|
||||
left: merge_sort(list.slice(0, pivot))
|
||||
right: merge_sort(list.slice(pivot))
|
||||
|
||||
while left.length and right.length
|
||||
result.push(if left[0] < right[0] then left.shift() else right.shift())
|
||||
|
||||
result.concat(left).concat(right)
|
||||
|
||||
|
||||
# Test the function.
|
||||
puts(merge_sort([3, 2, 1]).join(' ') is '1 2 3')
|
||||
puts(merge_sort([9, 2, 7, 0, 1]).join(' ') is '0 1 2 7 9')
|
||||
@@ -1,23 +0,0 @@
|
||||
# An in-place selection sort.
|
||||
selection_sort: (list) ->
|
||||
len: list.length
|
||||
|
||||
# For each item in the list.
|
||||
for i in [0...len]
|
||||
|
||||
# Set the minimum to this position.
|
||||
min: i
|
||||
|
||||
# Check the rest of the array to see if anything is smaller.
|
||||
(min: j if list[j] < list[min]) for j in [(i+1)...len]
|
||||
|
||||
# Swap if a smaller item has been found.
|
||||
[list[i], list[min]]: [list[min], list[i]] if i isnt min
|
||||
|
||||
# The list is now sorted.
|
||||
list
|
||||
|
||||
|
||||
# Test the function.
|
||||
puts(selection_sort([3, 2, 1]).join(' ') is '1 2 3')
|
||||
puts(selection_sort([9, 2, 7, 0, 1]).join(' ') is '0 1 2 7 9')
|
||||
72
examples/documents.coffee
Normal file
72
examples/documents.coffee
Normal file
@@ -0,0 +1,72 @@
|
||||
# Document Model
|
||||
dc.model.Document: dc.Model.extend({
|
||||
|
||||
constructor: attributes => this.base(attributes)
|
||||
|
||||
# For display, show either the highlighted search results, or the summary,
|
||||
# if no highlights are available.
|
||||
# The import process will take care of this in the future, but the inline
|
||||
# version of the summary has all runs of whitespace squeezed out.
|
||||
displaySummary: =>
|
||||
text: this.get('highlight') or this.get('summary') or ''
|
||||
text and text.replace(/\s+/g, ' ')
|
||||
|
||||
# Return a list of the document's metadata. Think about caching this on the
|
||||
# document by binding to Metadata, instead of on-the-fly.
|
||||
metadata: =>
|
||||
docId: this.id
|
||||
_.select(Metadata.models(), (meta =>
|
||||
_.any(meta.get('instances'), instance =>
|
||||
instance.document_id is docId)))
|
||||
|
||||
bookmark: pageNumber =>
|
||||
bookmark: new dc.model.Bookmark({title: this.get('title'), page_number: pageNumber, document_id: this.id})
|
||||
Bookmarks.create(bookmark)
|
||||
|
||||
# Inspect.
|
||||
toString: => 'Document ' + this.id + ' "' + this.get('title') + '"'
|
||||
|
||||
})
|
||||
|
||||
# Document Set
|
||||
dc.model.DocumentSet: dc.model.RESTfulSet.extend({
|
||||
|
||||
resource: 'documents'
|
||||
|
||||
SELECTION_CHANGED: 'documents:selection_changed'
|
||||
|
||||
constructor: options =>
|
||||
this.base(options)
|
||||
_.bindAll(this, 'downloadSelectedViewers', 'downloadSelectedPDF', 'downloadSelectedFullText')
|
||||
|
||||
selected: => _.select(this.models(), m => m.get('selected'))
|
||||
|
||||
selectedIds: => _.pluck(this.selected(), 'id')
|
||||
|
||||
countSelected: => this.selected().length
|
||||
|
||||
downloadSelectedViewers: =>
|
||||
dc.app.download('/download/' + this.selectedIds().join('/') + '/document_viewer.zip')
|
||||
|
||||
downloadSelectedPDF: =>
|
||||
if this.countSelected() <= 1 then return window.open(this.selected()[0].get('pdf_url'))
|
||||
dc.app.download('/download/' + this.selectedIds().join('/') + '/document_pdfs.zip')
|
||||
|
||||
downloadSelectedFullText: =>
|
||||
if this.countSelected() <= 1 then return window.open(this.selected()[0].get('full_text_url'))
|
||||
dc.app.download('/download/' + this.selectedIds().join('/') + '/document_text.zip')
|
||||
|
||||
# We override "_onModelEvent" to fire selection changed events when documents
|
||||
# change their selected state.
|
||||
_onModelEvent: e, model =>
|
||||
this.base(e, model)
|
||||
fire: e == dc.Model.CHANGED and model.hasChanged('selected')
|
||||
if fire then _.defer(_(this.fire).bind(this, this.SELECTION_CHANGED, this))
|
||||
|
||||
})
|
||||
|
||||
# The main set of Documents, used by the search tab.
|
||||
window.Documents: new dc.model.DocumentSet()
|
||||
|
||||
# The set of documents that is used to look at a particular label.
|
||||
dc.app.LabeledDocuments: new dc.model.DocumentSet()
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
# ['toast', 'cheese', 'wine'].each { |food| print food.capitalize }
|
||||
|
||||
['toast', 'wine', 'cheese'].each (food) -> print(food.capitalize())
|
||||
['toast', 'wine', 'cheese'].each(food => print(food.capitalize()))
|
||||
|
||||
|
||||
|
||||
@@ -14,43 +14,10 @@
|
||||
# end
|
||||
|
||||
LotteryTicket: {
|
||||
get_picks: -> this.picks
|
||||
set_picks: (nums) -> this.picks: nums
|
||||
get_purchase: -> this.purchase
|
||||
set_purchase: (amount) -> this.purchase: amount
|
||||
}
|
||||
|
||||
|
||||
|
||||
# class << LotteryDraw
|
||||
# def play
|
||||
# result = LotteryTicket.new_random
|
||||
# winners = {}
|
||||
# @@tickets.each do |buyer, ticket_list|
|
||||
# ticket_list.each do |ticket|
|
||||
# score = ticket.score( result )
|
||||
# next if score.zero?
|
||||
# winners[buyer] ||= []
|
||||
# winners[buyer] << [ ticket, score ]
|
||||
# end
|
||||
# end
|
||||
# @@tickets.clear
|
||||
# winners
|
||||
# end
|
||||
# end
|
||||
|
||||
LotteryDraw: {
|
||||
play: ->
|
||||
result: LotteryTicket.new_random()
|
||||
winners: {}
|
||||
this.tickets.each (buyer, ticket_list) ->
|
||||
ticket_list.each (ticket) ->
|
||||
score: ticket.score(result)
|
||||
return if score is 0
|
||||
winners[buyer] ||= []
|
||||
winners[buyer].push([ticket, score])
|
||||
this.tickets: {}
|
||||
winners
|
||||
get_picks: => this.picks
|
||||
set_picks: nums => this.picks: nums
|
||||
get_purchase: => this.purchase
|
||||
set_purchase: amount => this.purchase: amount
|
||||
}
|
||||
|
||||
|
||||
@@ -65,8 +32,8 @@ LotteryDraw: {
|
||||
# end
|
||||
|
||||
WishScanner: {
|
||||
scan_for_a_wish: ->
|
||||
wish: this.read().detect((thought) -> thought.index('wish: ') is 0)
|
||||
scan_for_a_wish: =>
|
||||
wish: this.read().detect(thought => thought.index('wish: ') is 0)
|
||||
wish.replace('wish: ', '')
|
||||
}
|
||||
|
||||
@@ -111,7 +78,7 @@ WishScanner: {
|
||||
Creature : {
|
||||
|
||||
# This method applies a hit taken during a fight.
|
||||
hit: (damage) ->
|
||||
hit: damage =>
|
||||
p_up: Math.rand(this.charisma)
|
||||
if p_up % 9 is 7
|
||||
this.life += p_up / 4
|
||||
@@ -120,7 +87,7 @@ Creature : {
|
||||
if this.life <= 0 then puts("[" + this.name + " has died.]")
|
||||
|
||||
# This method takes one turn in a fight.
|
||||
fight: (enemy, weapon) ->
|
||||
fight: enemy, weapon =>
|
||||
if this.life <= 0 then return puts("[" + this.name + "is too dead to fight!]")
|
||||
|
||||
# Attack the opponent.
|
||||
@@ -156,12 +123,12 @@ Creature : {
|
||||
# Get evil idea and swap in code words
|
||||
print("Enter your new idea: ")
|
||||
idea: gets()
|
||||
code_words.each((real, code) -> idea.replace(real, code))
|
||||
code_words.each(real, code => idea.replace(real, code))
|
||||
|
||||
# Save the jibberish to a new file
|
||||
print("File encoded. Please enter a name for this idea: ")
|
||||
idea_name: gets().strip()
|
||||
File.open("idea-" + idea_name + '.txt', 'w', (file) -> file.write(idea))
|
||||
File.open("idea-" + idea_name + '.txt', 'w', file => file.write(idea))
|
||||
|
||||
|
||||
|
||||
@@ -177,7 +144,7 @@ File.open("idea-" + idea_name + '.txt', 'w', (file) -> file.write(idea))
|
||||
# end
|
||||
# end
|
||||
|
||||
wipe_mutterings_from: (sentence) ->
|
||||
wipe_mutterings_from: sentence =>
|
||||
throw new Error("cannot wipe mutterings") unless sentence.indexOf
|
||||
while sentence.indexOf('(') >= 0
|
||||
open: sentence.indexOf('(') - 1
|
||||
|
||||
@@ -1,205 +0,0 @@
|
||||
# Examples from _why's Potion, the Readme and "Potion: A Short Pamphlet".
|
||||
|
||||
# 5 times: "Odelay!" print.
|
||||
|
||||
print("Odelay!") for i in [1..5]
|
||||
|
||||
|
||||
# add = (x, y): x + y.
|
||||
# add(2, 4) string print
|
||||
|
||||
add: (x, y) -> x + y
|
||||
print(add(2, 4))
|
||||
|
||||
|
||||
# loop: 'quaff' print.
|
||||
|
||||
while true
|
||||
print('quaff')
|
||||
|
||||
|
||||
# ('cheese', 'bread', 'mayo') at (1) print
|
||||
|
||||
print(['cheese', 'bread', 'mayo'][1])
|
||||
|
||||
|
||||
# (language='Potion', pointless=true) at (key='language') print
|
||||
|
||||
print({language: 'Potion', pointless: true}['language'])
|
||||
|
||||
|
||||
# minus = (x, y): x - y.
|
||||
# minus (y=10, x=6)
|
||||
|
||||
minus: (x, y) -> x - y
|
||||
minus(6, 10)
|
||||
|
||||
|
||||
# foods = ('cheese', 'bread', 'mayo')
|
||||
# foods (2)
|
||||
|
||||
foods: ['cheese', 'bread', 'mayo']
|
||||
foods[2]
|
||||
|
||||
|
||||
# (dog='canine', cat='feline', fox='vulpine') each (key, val):
|
||||
# (key, ' is a ', val) join print.
|
||||
|
||||
for key, val of {dog: 'canine', cat: 'feline', fox: 'vulpine'}
|
||||
print(key + ' is a ' + val)
|
||||
|
||||
|
||||
# Person = class: /name, /age, /sex.
|
||||
# Person print = ():
|
||||
# ('My name is ', /name, '.') join print.
|
||||
|
||||
Person: ->
|
||||
Person::print: ->
|
||||
print('My name is ' + this.name + '.')
|
||||
|
||||
|
||||
# p = Person ()
|
||||
# p /name string print
|
||||
|
||||
p: new Person()
|
||||
print(p.name)
|
||||
|
||||
|
||||
# Policeman = Person class (rank): /rank = rank.
|
||||
# Policeman print = ():
|
||||
# ('My name is ', /name, ' and I'm a ', /rank, '.') join print.
|
||||
#
|
||||
# Policeman ('Constable') print
|
||||
|
||||
Policeman: (rank) -> this.rank: rank
|
||||
Policeman extends Person
|
||||
Policeman::print: ->
|
||||
print('My name is ' + this.name + " and I'm a " + this.rank + '.')
|
||||
|
||||
print(new Policeman('Constable'))
|
||||
|
||||
|
||||
# app = [window (width=200, height=400)
|
||||
# [para 'Welcome.', button 'OK']]
|
||||
# app first name
|
||||
|
||||
app = {
|
||||
window: {width: 200, height: 200}
|
||||
para: 'Welcome.'
|
||||
button: 'OK'
|
||||
}
|
||||
app.window
|
||||
|
||||
|
||||
# x = 1
|
||||
# y = 2
|
||||
#
|
||||
# x = 1, y = 2
|
||||
|
||||
x: 1
|
||||
y: 2
|
||||
|
||||
x: 1; y: 2
|
||||
|
||||
|
||||
# table = (language='Potion'
|
||||
# pointless=true)
|
||||
|
||||
table: {
|
||||
language: 'Potion'
|
||||
pointless: yes
|
||||
}
|
||||
|
||||
|
||||
# # this foul business...
|
||||
# String length = (): 10.
|
||||
|
||||
# this foul business...
|
||||
String::length: -> 10
|
||||
|
||||
|
||||
# block = :
|
||||
# 'potion' print.
|
||||
|
||||
block: ->
|
||||
print('potion')
|
||||
|
||||
|
||||
# if (age > 100): 'ancient'.
|
||||
|
||||
if age > 100 then 'ancient'
|
||||
|
||||
|
||||
# author =
|
||||
# if (title == 'Jonathan Strange & Mr. Norrell'):
|
||||
# 'Susanna Clarke'.
|
||||
# elsif (title == 'The Star Diaries'):
|
||||
# 'Stanislaw Lem'.
|
||||
# elsif (title == 'The Slynx'):
|
||||
# 'Tatyana Tolstaya'.
|
||||
# else:
|
||||
# '... probably Philip K. Dick'.
|
||||
|
||||
switch author
|
||||
when 'Jonathan Strange & Mr. Norrell'
|
||||
'Susanna Clarke'
|
||||
when 'The Star Diaries'
|
||||
'Stanislaw Lem'
|
||||
when 'The Slynx'
|
||||
'Tatyana Tolstaya'
|
||||
else
|
||||
'... probably Philip K. Dick'
|
||||
|
||||
|
||||
# count = 8
|
||||
# while (count > 0):
|
||||
# 'quaff' print
|
||||
# count--.
|
||||
|
||||
count: 8
|
||||
while count > 0
|
||||
print('quaff')
|
||||
count--
|
||||
|
||||
|
||||
# 1 to 5 (a):
|
||||
# a string print.
|
||||
|
||||
print(a) for a in [1..5]
|
||||
|
||||
|
||||
# if (3 ?gender):
|
||||
# "Huh? Numbers are sexed? That's amazing." print.
|
||||
|
||||
if (3).gender?
|
||||
print("Huh? Numbers are sexed? That's amazing.")
|
||||
|
||||
|
||||
# HomePage get = (url):
|
||||
# session = url query ? at ('session').
|
||||
|
||||
HomePage::get: (url) ->
|
||||
session: url.query.session if url.query?
|
||||
|
||||
|
||||
# BTree = class: /left, /right.
|
||||
# b = BTree ()
|
||||
# b /left = BTree ()
|
||||
# b /right = BTree ()
|
||||
|
||||
BTree: ->
|
||||
b: new BTree()
|
||||
b.left: new BTree()
|
||||
b.right: new BTree()
|
||||
|
||||
|
||||
# BTree = class: /left, /right.
|
||||
# b = BTree ()
|
||||
#
|
||||
# if (b ? /left):
|
||||
# 'left path found!' print.
|
||||
|
||||
BTree: ->
|
||||
b: new BTree()
|
||||
|
||||
print('left path found!') if b.left?
|
||||
20
examples/syntax_errors.coffee
Normal file
20
examples/syntax_errors.coffee
Normal file
@@ -0,0 +1,20 @@
|
||||
# Identifiers run together:
|
||||
# a b c
|
||||
|
||||
# Trailing comma in array:
|
||||
# array: [1, 2, 3, 4, 5,]
|
||||
|
||||
# Unterminated object literal:
|
||||
# obj: { one: 1, two: 2
|
||||
|
||||
# Numbers run together:
|
||||
# 101 202
|
||||
|
||||
# Strings run together:
|
||||
# str: "broken" "words"
|
||||
|
||||
# Forgot to terminate a function:
|
||||
# obj: {
|
||||
# first: a => a[0].
|
||||
# last: a => a[a.length-1]
|
||||
# }
|
||||
@@ -1,6 +1,6 @@
|
||||
|
||||
# Underscore.coffee
|
||||
# (c) 2010 Jeremy Ashkenas, DocumentCloud Inc.
|
||||
# (c) 2009 Jeremy Ashkenas, DocumentCloud Inc.
|
||||
# Underscore is freely distributable under the terms of the MIT license.
|
||||
# Portions of Underscore are inspired by or borrowed from Prototype.js,
|
||||
# Oliver Steele's Functional, and John Resig's Micro-Templating.
|
||||
@@ -21,7 +21,7 @@
|
||||
# If Underscore is called as a function, it returns a wrapped object that
|
||||
# can be used OO-style. This wrapper holds altered versions of all the
|
||||
# underscore functions. Wrapped objects may be chained.
|
||||
wrapper: (obj) ->
|
||||
wrapper: obj =>
|
||||
this._wrapped: obj
|
||||
this
|
||||
|
||||
@@ -30,8 +30,8 @@
|
||||
breaker: if typeof(StopIteration) is 'undefined' then '__break__' else StopIteration
|
||||
|
||||
|
||||
# Create a safe reference to the Underscore object forreference below.
|
||||
_: root._: (obj) -> new wrapper(obj)
|
||||
# Create a safe reference to the Underscore object for reference below.
|
||||
_: root._: obj => new wrapper(obj)
|
||||
|
||||
|
||||
# Export the Underscore object for CommonJS.
|
||||
@@ -39,28 +39,28 @@
|
||||
|
||||
|
||||
# Create quick reference variables for speed access to core prototypes.
|
||||
slice: Array::slice
|
||||
unshift: Array::unshift
|
||||
toString: Object::toString
|
||||
hasOwnProperty: Object::hasOwnProperty
|
||||
propertyIsEnumerable: Object::propertyIsEnumerable
|
||||
slice: Array.prototype.slice
|
||||
unshift: Array.prototype.unshift
|
||||
toString: Object.prototype.toString
|
||||
hasOwnProperty: Object.prototype.hasOwnProperty
|
||||
propertyIsEnumerable: Object.prototype.propertyIsEnumerable
|
||||
|
||||
|
||||
# Current version.
|
||||
_.VERSION: '0.5.8'
|
||||
_.VERSION: '0.5.3'
|
||||
|
||||
|
||||
# ------------------------ Collection Functions: ---------------------------
|
||||
|
||||
# The cornerstone, an each implementation.
|
||||
# Handles objects implementing forEach, arrays, and raw objects.
|
||||
_.each: (obj, iterator, context) ->
|
||||
_.each: obj, iterator, context =>
|
||||
index: 0
|
||||
try
|
||||
return obj.forEach(iterator, context) if obj.forEach
|
||||
if _.isNumber(obj.length)
|
||||
if _.isArray(obj) or _.isArguments(obj)
|
||||
return iterator.call(context, obj[i], i, obj) for i in [0...obj.length]
|
||||
iterator.call(context, val, key, obj) for key, val of obj
|
||||
iterator.call(context, val, key, obj) for val, key in obj
|
||||
catch e
|
||||
throw e if e isnt breaker
|
||||
obj
|
||||
@@ -68,36 +68,36 @@
|
||||
|
||||
# Return the results of applying the iterator to each element. Use JavaScript
|
||||
# 1.6's version of map, if possible.
|
||||
_.map: (obj, iterator, context) ->
|
||||
_.map: obj, iterator, context =>
|
||||
return obj.map(iterator, context) if (obj and _.isFunction(obj.map))
|
||||
results: []
|
||||
_.each obj, (value, index, list) ->
|
||||
_.each(obj) value, index, list =>
|
||||
results.push(iterator.call(context, value, index, list))
|
||||
results
|
||||
|
||||
|
||||
# Reduce builds up a single result from a list of values. Also known as
|
||||
# inject, or foldl. Uses JavaScript 1.8's version of reduce, if possible.
|
||||
_.reduce: (obj, memo, iterator, context) ->
|
||||
_.reduce: obj, memo, iterator, context =>
|
||||
return obj.reduce(_.bind(iterator, context), memo) if (obj and _.isFunction(obj.reduce))
|
||||
_.each obj, (value, index, list) ->
|
||||
_.each(obj) value, index, list =>
|
||||
memo: iterator.call(context, memo, value, index, list)
|
||||
memo
|
||||
|
||||
|
||||
# The right-associative version of reduce, also known as foldr. Uses
|
||||
# JavaScript 1.8's version of reduceRight, if available.
|
||||
_.reduceRight: (obj, memo, iterator, context) ->
|
||||
_.reduceRight: obj, memo, iterator, context =>
|
||||
return obj.reduceRight(_.bind(iterator, context), memo) if (obj and _.isFunction(obj.reduceRight))
|
||||
_.each _.clone(_.toArray(obj)).reverse(), (value, index) ->
|
||||
_.each(_.clone(_.toArray(obj)).reverse()) value, index =>
|
||||
memo: iterator.call(context, memo, value, index, obj)
|
||||
memo
|
||||
|
||||
|
||||
# Return the first value which passes a truth test.
|
||||
_.detect: (obj, iterator, context) ->
|
||||
_.detect: obj, iterator, context =>
|
||||
result: null
|
||||
_.each obj, (value, index, list) ->
|
||||
_.each(obj) value, index, list =>
|
||||
if iterator.call(context, value, index, list)
|
||||
result: value
|
||||
_.breakLoop()
|
||||
@@ -106,97 +106,97 @@
|
||||
|
||||
# Return all the elements that pass a truth test. Use JavaScript 1.6's
|
||||
# filter(), if it exists.
|
||||
_.select: (obj, iterator, context) ->
|
||||
_.select: obj, iterator, context =>
|
||||
if obj and _.isFunction(obj.filter) then return obj.filter(iterator, context)
|
||||
results: []
|
||||
_.each obj, (value, index, list) ->
|
||||
_.each(obj) value, index, list =>
|
||||
results.push(value) if iterator.call(context, value, index, list)
|
||||
results
|
||||
|
||||
|
||||
# Return all the elements for which a truth test fails.
|
||||
_.reject: (obj, iterator, context) ->
|
||||
_.reject: obj, iterator, context =>
|
||||
results: []
|
||||
_.each obj, (value, index, list) ->
|
||||
_.each(obj) value, index, list =>
|
||||
results.push(value) if not iterator.call(context, value, index, list)
|
||||
results
|
||||
|
||||
|
||||
# Determine whether all of the elements match a truth test. Delegate to
|
||||
# JavaScript 1.6's every(), if it is present.
|
||||
_.all: (obj, iterator, context) ->
|
||||
_.all: obj, iterator, context =>
|
||||
iterator ||= _.identity
|
||||
return obj.every(iterator, context) if obj and _.isFunction(obj.every)
|
||||
result: true
|
||||
_.each obj, (value, index, list) ->
|
||||
_.each(obj) value, index, list =>
|
||||
_.breakLoop() unless (result: result and iterator.call(context, value, index, list))
|
||||
result
|
||||
|
||||
|
||||
# Determine if at least one element in the object matches a truth test. Use
|
||||
# JavaScript 1.6's some(), if it exists.
|
||||
_.any: (obj, iterator, context) ->
|
||||
_.any: obj, iterator, context =>
|
||||
iterator ||= _.identity
|
||||
return obj.some(iterator, context) if obj and _.isFunction(obj.some)
|
||||
result: false
|
||||
_.each obj, (value, index, list) ->
|
||||
_.each(obj) value, index, list =>
|
||||
_.breakLoop() if (result: iterator.call(context, value, index, list))
|
||||
result
|
||||
|
||||
|
||||
# Determine if a given value is included in the array or object,
|
||||
# based on '==='.
|
||||
_.include: (obj, target) ->
|
||||
return _.indexOf(obj, target) isnt -1 if obj and _.isFunction(obj.indexOf)
|
||||
for key, val of obj
|
||||
_.include: obj, target =>
|
||||
return _.indexOf(obj, target) isnt -1 if _.isArray(obj)
|
||||
for val in obj
|
||||
return true if val is target
|
||||
false
|
||||
|
||||
|
||||
# Invoke a method with arguments on every item in a collection.
|
||||
_.invoke: (obj, method) ->
|
||||
_.invoke: obj, method =>
|
||||
args: _.rest(arguments, 2)
|
||||
(if method then val[method] else val).apply(val, args) for val in obj
|
||||
|
||||
|
||||
# Convenience version of a common use case of map: fetching a property.
|
||||
_.pluck: (obj, key) ->
|
||||
_.map(obj, ((val) -> val[key]))
|
||||
_.pluck: obj, key =>
|
||||
_.map(obj, (val => val[key]))
|
||||
|
||||
|
||||
# Return the maximum item or (item-based computation).
|
||||
_.max: (obj, iterator, context) ->
|
||||
_.max: obj, iterator, context =>
|
||||
return Math.max.apply(Math, obj) if not iterator and _.isArray(obj)
|
||||
result: {computed: -Infinity}
|
||||
_.each obj, (value, index, list) ->
|
||||
_.each(obj) value, index, list =>
|
||||
computed: if iterator then iterator.call(context, value, index, list) else value
|
||||
computed >= result.computed and (result: {value: value, computed: computed})
|
||||
result.value
|
||||
|
||||
|
||||
# Return the minimum element (or element-based computation).
|
||||
_.min: (obj, iterator, context) ->
|
||||
_.min: obj, iterator, context =>
|
||||
return Math.min.apply(Math, obj) if not iterator and _.isArray(obj)
|
||||
result: {computed: Infinity}
|
||||
_.each obj, (value, index, list) ->
|
||||
_.each(obj) value, index, list =>
|
||||
computed: if iterator then iterator.call(context, value, index, list) else value
|
||||
computed < result.computed and (result: {value: value, computed: computed})
|
||||
result.value
|
||||
|
||||
|
||||
# Sort the object's values by a criteria produced by an iterator.
|
||||
_.sortBy: (obj, iterator, context) ->
|
||||
_.pluck(((_.map obj, (value, index, list) ->
|
||||
_.sortBy: obj, iterator, context =>
|
||||
_.pluck(((_.map(obj) value, index, list =>
|
||||
{value: value, criteria: iterator.call(context, value, index, list)}
|
||||
).sort((left, right) ->
|
||||
).sort() left, right =>
|
||||
a: left.criteria; b: right.criteria
|
||||
if a < b then -1 else if a > b then 1 else 0
|
||||
)), 'value')
|
||||
), 'value')
|
||||
|
||||
|
||||
# Use a comparator function to figure out at what index an object should
|
||||
# be inserted so as to maintain order. Uses binary search.
|
||||
_.sortedIndex: (array, obj, iterator) ->
|
||||
_.sortedIndex: array, obj, iterator =>
|
||||
iterator ||= _.identity
|
||||
low: 0; high: array.length
|
||||
while low < high
|
||||
@@ -206,7 +206,7 @@
|
||||
|
||||
|
||||
# Convert anything iterable into a real, live array.
|
||||
_.toArray: (iterable) ->
|
||||
_.toArray: iterable =>
|
||||
return [] if (!iterable)
|
||||
return iterable.toArray() if (iterable.toArray)
|
||||
return iterable if (_.isArray(iterable))
|
||||
@@ -215,7 +215,7 @@
|
||||
|
||||
|
||||
# Return the number of elements in an object.
|
||||
_.size: (obj) -> _.toArray(obj).length
|
||||
_.size: obj => _.toArray(obj).length
|
||||
|
||||
|
||||
# -------------------------- Array Functions: ------------------------------
|
||||
@@ -223,7 +223,7 @@
|
||||
# Get the first element of an array. Passing "n" will return the first N
|
||||
# values in the array. Aliased as "head". The "guard" check allows it to work
|
||||
# with _.map.
|
||||
_.first: (array, n, guard) ->
|
||||
_.first: array, n, guard =>
|
||||
if n and not guard then slice.call(array, 0, n) else array[0]
|
||||
|
||||
|
||||
@@ -231,35 +231,35 @@
|
||||
# Especially useful on the arguments object. Passing an "index" will return
|
||||
# the rest of the values in the array from that index onward. The "guard"
|
||||
# check allows it to work with _.map.
|
||||
_.rest: (array, index, guard) ->
|
||||
_.rest: array, index, guard =>
|
||||
slice.call(array, if _.isUndefined(index) or guard then 1 else index)
|
||||
|
||||
|
||||
# Get the last element of an array.
|
||||
_.last: (array) -> array[array.length - 1]
|
||||
_.last: array => array[array.length - 1]
|
||||
|
||||
|
||||
# Trim out all falsy values from an array.
|
||||
_.compact: (array) -> item for item in array when item
|
||||
_.compact: array => array[i] for i in [0...array.length] when array[i]
|
||||
|
||||
|
||||
# Return a completely flattened version of an array.
|
||||
_.flatten: (array) ->
|
||||
_.reduce array, [], (memo, value) ->
|
||||
_.flatten: array =>
|
||||
_.reduce(array, []) memo, value =>
|
||||
return memo.concat(_.flatten(value)) if _.isArray(value)
|
||||
memo.push(value)
|
||||
memo
|
||||
|
||||
|
||||
# Return a version of the array that does not contain the specified value(s).
|
||||
_.without: (array) ->
|
||||
_.without: array =>
|
||||
values: _.rest(arguments)
|
||||
val for val in _.toArray(array) when not _.include(values, val)
|
||||
|
||||
|
||||
# Produce a duplicate-free version of the array. If the array has already
|
||||
# been sorted, you have the option of using a faster algorithm.
|
||||
_.uniq: (array, isSorted) ->
|
||||
_.uniq: array, isSorted =>
|
||||
memo: []
|
||||
for el, i in _.toArray(array)
|
||||
memo.push(el) if i is 0 || (if isSorted is true then _.last(memo) isnt el else not _.include(memo, el))
|
||||
@@ -268,27 +268,28 @@
|
||||
|
||||
# Produce an array that contains every item shared between all the
|
||||
# passed-in arrays.
|
||||
_.intersect: (array) ->
|
||||
_.intersect: array =>
|
||||
rest: _.rest(arguments)
|
||||
_.select _.uniq(array), (item) ->
|
||||
_.all rest, (other) ->
|
||||
_.select(_.uniq(array)) item =>
|
||||
_.all(rest) other =>
|
||||
_.indexOf(other, item) >= 0
|
||||
|
||||
|
||||
# Zip together multiple lists into a single array -- elements that share
|
||||
# an index go together.
|
||||
_.zip: ->
|
||||
length: _.max(_.pluck(arguments, 'length'))
|
||||
_.zip: =>
|
||||
args: _.toArray(arguments)
|
||||
length: _.max(_.pluck(args, 'length'))
|
||||
results: new Array(length)
|
||||
for i in [0...length]
|
||||
results[i]: _.pluck(arguments, String(i))
|
||||
results[i]: _.pluck(args, String(i))
|
||||
results
|
||||
|
||||
|
||||
# If the browser doesn't supply us with indexOf (I'm looking at you, MSIE),
|
||||
# we need this function. Return the position of the first occurence of an
|
||||
# item in an array, or -1 if the item is not included in the array.
|
||||
_.indexOf: (array, item) ->
|
||||
_.indexOf: array, item =>
|
||||
return array.indexOf(item) if array.indexOf
|
||||
i: 0; l: array.length
|
||||
while l - i
|
||||
@@ -298,7 +299,7 @@
|
||||
|
||||
# Provide JavaScript 1.6's lastIndexOf, delegating to the native function,
|
||||
# if possible.
|
||||
_.lastIndexOf: (array, item) ->
|
||||
_.lastIndexOf: array, item =>
|
||||
return array.lastIndexOf(item) if array.lastIndexOf
|
||||
i: array.length
|
||||
while i
|
||||
@@ -309,11 +310,11 @@
|
||||
# Generate an integer Array containing an arithmetic progression. A port of
|
||||
# the native Python range() function. See:
|
||||
# http://docs.python.org/library/functions.html#range
|
||||
_.range: (start, stop, step) ->
|
||||
a: arguments
|
||||
_.range: start, stop, step =>
|
||||
a: _.toArray(arguments)
|
||||
solo: a.length <= 1
|
||||
i: start: if solo then 0 else a[0]
|
||||
stop: if solo then a[0] else a[1]
|
||||
i: start: if solo then 0 else a[0];
|
||||
stop: if solo then a[0] else a[1];
|
||||
step: a[2] or 1
|
||||
len: Math.ceil((stop - start) / step)
|
||||
return [] if len <= 0
|
||||
@@ -330,45 +331,45 @@
|
||||
|
||||
# Create a function bound to a given object (assigning 'this', and arguments,
|
||||
# optionally). Binding with arguments is also known as 'curry'.
|
||||
_.bind: (func, obj) ->
|
||||
_.bind: func, obj =>
|
||||
args: _.rest(arguments, 2)
|
||||
-> func.apply(obj or root, args.concat(arguments))
|
||||
=> func.apply(obj or root, args.concat(_.toArray(arguments)))
|
||||
|
||||
|
||||
# Bind all of an object's methods to that object. Useful for ensuring that
|
||||
# all callbacks defined on an object belong to it.
|
||||
_.bindAll: (obj) ->
|
||||
_.bindAll: obj =>
|
||||
funcs: if arguments.length > 1 then _.rest(arguments) else _.functions(obj)
|
||||
_.each(funcs, (f) -> obj[f]: _.bind(obj[f], obj))
|
||||
_.each(funcs, (f => obj[f]: _.bind(obj[f], obj)))
|
||||
obj
|
||||
|
||||
|
||||
# Delays a function for the given number of milliseconds, and then calls
|
||||
# it with the arguments supplied.
|
||||
_.delay: (func, wait) ->
|
||||
_.delay: func, wait =>
|
||||
args: _.rest(arguments, 2)
|
||||
setTimeout((-> func.apply(func, args)), wait)
|
||||
setTimeout((=> func.apply(func, args)), wait)
|
||||
|
||||
|
||||
# Defers a function, scheduling it to run after the current call stack has
|
||||
# cleared.
|
||||
_.defer: (func) ->
|
||||
_.defer: func =>
|
||||
_.delay.apply(_, [func, 1].concat(_.rest(arguments)))
|
||||
|
||||
|
||||
# Returns the first function passed as an argument to the second,
|
||||
# allowing you to adjust arguments, run code before and after, and
|
||||
# conditionally execute the original function.
|
||||
_.wrap: (func, wrapper) ->
|
||||
-> wrapper.apply(wrapper, [func].concat(arguments))
|
||||
_.wrap: func, wrapper =>
|
||||
=> wrapper.apply(wrapper, [func].concat(_.toArray(arguments)))
|
||||
|
||||
|
||||
# Returns a function that is the composition of a list of functions, each
|
||||
# consuming the return value of the function that follows.
|
||||
_.compose: ->
|
||||
funcs: arguments
|
||||
->
|
||||
args: arguments
|
||||
_.compose: =>
|
||||
funcs: _.toArray(arguments)
|
||||
=>
|
||||
args: _.toArray(arguments)
|
||||
for i in [(funcs.length - 1)..0]
|
||||
args: [funcs[i].apply(this, args)]
|
||||
args[0]
|
||||
@@ -377,43 +378,43 @@
|
||||
# ------------------------- Object Functions: ----------------------------
|
||||
|
||||
# Retrieve the names of an object's properties.
|
||||
_.keys: (obj) ->
|
||||
_.keys: obj =>
|
||||
return _.range(0, obj.length) if _.isArray(obj)
|
||||
key for key, val of obj
|
||||
key for val, key in obj
|
||||
|
||||
|
||||
# Retrieve the values of an object's properties.
|
||||
_.values: (obj) ->
|
||||
_.values: obj =>
|
||||
_.map(obj, _.identity)
|
||||
|
||||
|
||||
# Return a sorted list of the function names available in Underscore.
|
||||
_.functions: (obj) ->
|
||||
_.select(_.keys(obj), (key) -> _.isFunction(obj[key])).sort()
|
||||
_.functions: obj =>
|
||||
_.select(_.keys(obj), key => _.isFunction(obj[key])).sort()
|
||||
|
||||
|
||||
# Extend a given object with all of the properties in a source object.
|
||||
_.extend: (destination, source) ->
|
||||
for key, val of source
|
||||
_.extend: destination, source =>
|
||||
for val, key in source
|
||||
destination[key]: val
|
||||
destination
|
||||
|
||||
|
||||
# Create a (shallow-cloned) duplicate of an object.
|
||||
_.clone: (obj) ->
|
||||
_.clone: obj =>
|
||||
return obj.slice(0) if _.isArray(obj)
|
||||
_.extend({}, obj)
|
||||
|
||||
|
||||
# Invokes interceptor with the obj, and then returns obj.
|
||||
# The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain.
|
||||
_.tap: (obj, interceptor) ->
|
||||
_.tap: obj, interceptor =>
|
||||
interceptor(obj)
|
||||
obj
|
||||
|
||||
|
||||
# Perform a deep comparison to check if two objects are equal.
|
||||
_.isEqual: (a, b) ->
|
||||
_.isEqual: a, b =>
|
||||
# Check object identity.
|
||||
return true if a is b
|
||||
# Different types?
|
||||
@@ -449,104 +450,93 @@
|
||||
|
||||
|
||||
# Is a given array or object empty?
|
||||
_.isEmpty: (obj) -> _.keys(obj).length is 0
|
||||
_.isEmpty: obj => _.keys(obj).length is 0
|
||||
|
||||
|
||||
# Is a given value a DOM element?
|
||||
_.isElement: (obj) -> obj and obj.nodeType is 1
|
||||
_.isElement: obj => obj and obj.nodeType is 1
|
||||
|
||||
|
||||
# Is a given value an array?
|
||||
_.isArray: (obj) -> !!(obj and obj.concat and obj.unshift)
|
||||
_.isArray: obj => !!(obj and obj.concat and obj.unshift)
|
||||
|
||||
|
||||
# Is a given variable an arguments object?
|
||||
_.isArguments: (obj) -> obj and _.isNumber(obj.length) and not obj.concat and
|
||||
not obj.substr and not obj.apply and not propertyIsEnumerable.call(obj, 'length')
|
||||
_.isArguments: obj => obj and _.isNumber(obj.length) and !_.isArray(obj) and !propertyIsEnumerable.call(obj, 'length')
|
||||
|
||||
|
||||
# Is the given value a function?
|
||||
_.isFunction: (obj) -> !!(obj and obj.constructor and obj.call and obj.apply)
|
||||
_.isFunction: obj => !!(obj and obj.constructor and obj.call and obj.apply)
|
||||
|
||||
|
||||
# Is the given value a string?
|
||||
_.isString: (obj) -> !!(obj is '' or (obj and obj.charCodeAt and obj.substr))
|
||||
_.isString: obj => !!(obj is '' or (obj and obj.charCodeAt and obj.substr))
|
||||
|
||||
|
||||
# Is a given value a number?
|
||||
_.isNumber: (obj) -> (obj is +obj) or toString.call(obj) is '[object Number]'
|
||||
_.isNumber: obj => toString.call(obj) is '[object Number]'
|
||||
|
||||
|
||||
# Is a given value a Date?
|
||||
_.isDate: (obj) -> !!(obj and obj.getTimezoneOffset and obj.setUTCFullYear)
|
||||
_.isDate: obj => !!(obj and obj.getTimezoneOffset and obj.setUTCFullYear)
|
||||
|
||||
|
||||
# Is the given value a regular expression?
|
||||
_.isRegExp: (obj) -> !!(obj and obj.exec and (obj.ignoreCase or obj.ignoreCase is false))
|
||||
_.isRegExp: obj => !!(obj and obj.exec and (obj.ignoreCase or obj.ignoreCase is false))
|
||||
|
||||
|
||||
# Is the given value NaN -- this one is interesting. NaN != NaN, and
|
||||
# isNaN(undefined) == true, so we make sure it's a number first.
|
||||
_.isNaN: (obj) -> _.isNumber(obj) and window.isNaN(obj)
|
||||
_.isNaN: obj => _.isNumber(obj) and window.isNaN(obj)
|
||||
|
||||
|
||||
# Is a given value equal to null?
|
||||
_.isNull: (obj) -> obj is null
|
||||
_.isNull: obj => obj is null
|
||||
|
||||
|
||||
# Is a given variable undefined?
|
||||
_.isUndefined: (obj) -> typeof obj is 'undefined'
|
||||
_.isUndefined: obj => typeof obj is 'undefined'
|
||||
|
||||
|
||||
# -------------------------- Utility Functions: --------------------------
|
||||
|
||||
# Run Underscore.js in noConflict mode, returning the '_' variable to its
|
||||
# previous owner. Returns a reference to the Underscore object.
|
||||
_.noConflict: ->
|
||||
_.noConflict: =>
|
||||
root._: previousUnderscore
|
||||
this
|
||||
|
||||
|
||||
# Keep the identity function around for default iterators.
|
||||
_.identity: (value) -> value
|
||||
_.identity: value => value
|
||||
|
||||
|
||||
# Break out of the middle of an iteration.
|
||||
_.breakLoop: -> throw breaker
|
||||
_.breakLoop: => throw breaker
|
||||
|
||||
|
||||
# Generate a unique integer id (unique within the entire client session).
|
||||
# Useful for temporary DOM ids.
|
||||
idCounter: 0
|
||||
_.uniqueId: (prefix) ->
|
||||
_.uniqueId: prefix =>
|
||||
(prefix or '') + idCounter++
|
||||
|
||||
|
||||
# By default, Underscore uses ERB-style template delimiters, change the
|
||||
# following template settings to use alternative delimiters.
|
||||
_.templateSettings: {
|
||||
start: '<%'
|
||||
end: '%>'
|
||||
interpolate: /<%=(.+?)%>/g
|
||||
}
|
||||
|
||||
|
||||
# JavaScript templating a-la ERB, pilfered from John Resig's
|
||||
# "Secrets of the JavaScript Ninja", page 83.
|
||||
# Single-quote fix from Rick Strahl's version.
|
||||
_.template: (str, data) ->
|
||||
c: _.templateSettings
|
||||
fn: new Function 'obj',
|
||||
_.template: str, data =>
|
||||
`var fn = new Function('obj',
|
||||
'var p=[],print=function(){p.push.apply(p,arguments);};' +
|
||||
'with(obj){p.push(\'' +
|
||||
str.replace(/[\r\t\n]/g, " ")
|
||||
.replace(new RegExp("'(?=[^"+c.end[0]+"]*"+c.end+")","g"),"\t")
|
||||
.split("'").join("\\'")
|
||||
.split("\t").join("'")
|
||||
.replace(c.interpolate, "',$1,'")
|
||||
.split(c.start).join("');")
|
||||
.split(c.end).join("p.push('") +
|
||||
"');}return p.join('');"
|
||||
str.
|
||||
replace(/[\r\t\n]/g, " ").
|
||||
split("<%").join("\t").
|
||||
replace(/((^|%>)[^\t]*)'/g, "$1\r").
|
||||
replace(/\t=(.*?)%>/g, "',$1,'").
|
||||
split("\t").join("');").
|
||||
split("%>").join("p.push('").
|
||||
split("\r").join("\\'") +
|
||||
"');}return p.join('');")`
|
||||
if data then fn(data) else fn
|
||||
|
||||
|
||||
@@ -563,41 +553,41 @@
|
||||
_.methods: _.functions
|
||||
|
||||
|
||||
# ------------------------ Setup the OOP Wrapper: --------------------------
|
||||
# /*------------------------ Setup the OOP Wrapper: --------------------------*/
|
||||
|
||||
# Helper function to continue chaining intermediate results.
|
||||
result: (obj, chain) ->
|
||||
result: obj, chain =>
|
||||
if chain then _(obj).chain() else obj
|
||||
|
||||
|
||||
# Add all of the Underscore functions to the wrapper object.
|
||||
_.each _.functions(_), (name) ->
|
||||
_.each(_.functions(_)) name =>
|
||||
method: _[name]
|
||||
wrapper.prototype[name]: ->
|
||||
wrapper.prototype[name]: =>
|
||||
unshift.call(arguments, this._wrapped)
|
||||
result(method.apply(_, arguments), this._chain)
|
||||
|
||||
|
||||
# Add all mutator Array functions to the wrapper.
|
||||
_.each ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], (name) ->
|
||||
_.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift']) name =>
|
||||
method: Array.prototype[name]
|
||||
wrapper.prototype[name]: ->
|
||||
wrapper.prototype[name]: =>
|
||||
method.apply(this._wrapped, arguments)
|
||||
result(this._wrapped, this._chain)
|
||||
|
||||
|
||||
# Add all accessor Array functions to the wrapper.
|
||||
_.each ['concat', 'join', 'slice'], (name) ->
|
||||
_.each(['concat', 'join', 'slice']) name =>
|
||||
method: Array.prototype[name]
|
||||
wrapper.prototype[name]: ->
|
||||
wrapper.prototype[name]: =>
|
||||
result(method.apply(this._wrapped, arguments), this._chain)
|
||||
|
||||
|
||||
# Start chaining a wrapped Underscore object.
|
||||
wrapper::chain: ->
|
||||
wrapper.prototype.chain: =>
|
||||
this._chain: true
|
||||
this
|
||||
|
||||
|
||||
# Extracts the result from a wrapped and chained object.
|
||||
wrapper::value: -> this._wrapped
|
||||
wrapper.prototype.value: => this._wrapped
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
# Contributed by Jason Huggins
|
||||
|
||||
http: require 'http'
|
||||
|
||||
server: http.createServer (req, res) ->
|
||||
res.sendHeader 200, {'Content-Type': 'text/plain'}
|
||||
res.sendBody 'Hello, World!'
|
||||
res.finish()
|
||||
|
||||
server.listen 3000
|
||||
|
||||
puts "Server running at http://localhost:3000/"
|
||||
@@ -1,20 +0,0 @@
|
||||
This folder includes rough cuts of CoffeeScript syntax highlighters for
|
||||
TextMate and Vim. Improvements to their lexing ability are always welcome.
|
||||
|
||||
To install the TextMate bundle, drop it into:
|
||||
~/Library/Application Support/TextMate/Bundles
|
||||
|
||||
To install the Vim highlighter, copy "coffee.vim" into the "syntax" directory of
|
||||
your vim72, and enable it in either of the following two ways:
|
||||
|
||||
* Manually, by running `:set syntax=coffee`
|
||||
|
||||
* Or automatically, by creating a "filetype.vim" file within "~/.vim", which
|
||||
contains something along these lines:
|
||||
|
||||
if exists("did_load_filetypes")
|
||||
finish
|
||||
end
|
||||
augroup filetypedetect
|
||||
au! BufRead,BufNewFile *.coffee setfiletype coffee
|
||||
augroup END
|
||||
@@ -1,117 +0,0 @@
|
||||
" Vim syntax file
|
||||
" Language: CoffeeScript
|
||||
" Maintainer: Jeff Olson <olson.jeffery@gmail.com>
|
||||
" URL: http://github.com/olsonjeffery
|
||||
" Changes: (jro) initial port from javascript
|
||||
" Last Change: 2006 Jun 19
|
||||
" Adaptation of javascript.vim syntax file (distro'd w/ vim72),
|
||||
" maintained by Claudio Fleiner <claudio@fleiner.com>
|
||||
" with updates from Scott Shattuck (ss) <ss@technicalpursuit.com>
|
||||
|
||||
if !exists("main_syntax")
|
||||
if version < 600
|
||||
syntax clear
|
||||
elseif exists("b:current_syntax")
|
||||
finish
|
||||
endif
|
||||
let main_syntax = 'coffee'
|
||||
endif
|
||||
|
||||
syn case ignore
|
||||
|
||||
syn match coffeeLineComment "#.*" contains=@Spell,CoffeeCommentTodo
|
||||
syn match coffeeSpecial "\\\d\d\d\|\\."
|
||||
syn region coffeeStringD start=+"+ skip=+\\\\\|\\"+ end=+"\|$+ contains=coffeeSpecial,@htmlPreproc
|
||||
syn region coffeeStringS start=+'+ skip=+\\\\\|\\'+ end=+'\|$+ contains=coffeeSpecial,@htmlPreproc
|
||||
|
||||
syn match coffeeSpecialCharacter "'\\.'"
|
||||
syn match coffeeNumber "-\=\<\d\+L\=\>\|0[xX][0-9a-fA-F]\+\>"
|
||||
syn region coffeeRegexpString start=+/[^/*]+me=e-1 skip=+\\\\\|\\/+ end=+/[gi]\{0,2\}\s*$+ end=+/[gi]\{0,2\}\s*[;.,)\]}]+me=e-1 contains=@htmlPreproc oneline
|
||||
|
||||
syn match coffeeFunctionParams "([^)]*)\s*->"
|
||||
syn match coffeeBindFunctionParams "([^)]*)\s*=>"
|
||||
syn match coffeePrototypeAccess "::"
|
||||
syn match coffeeBindFunction "=[1]>[1]"
|
||||
syn match coffeeFunction "->"
|
||||
|
||||
syn keyword coffeeExtends extends
|
||||
syn keyword coffeeConditional if else switch then not
|
||||
syn keyword coffeeRepeat while for in of
|
||||
syn keyword coffeeBranch break continue
|
||||
syn keyword coffeeOperator delete instanceof typeof
|
||||
syn keyword coffeeType Array Boolean Date Function Number Object String RegExp
|
||||
syn keyword coffeeStatement return with
|
||||
syn keyword coffeeBoolean true false
|
||||
syn keyword coffeeNull null undefined
|
||||
syn keyword coffeeIdentifier arguments this var
|
||||
syn keyword coffeeLabel case default
|
||||
syn keyword coffeeException try catch finally throw
|
||||
syn keyword coffeeMessage alert confirm prompt status
|
||||
syn keyword coffeeGlobal self window top parent
|
||||
syn keyword coffeeMember document event location
|
||||
syn keyword coffeeDeprecated escape unescape
|
||||
syn keyword coffeeReserved abstract boolean byte char class const debugger double enum export final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile
|
||||
|
||||
syn sync fromstart
|
||||
syn sync maxlines=100
|
||||
|
||||
if main_syntax == "coffee"
|
||||
syn sync ccomment coffeeComment
|
||||
endif
|
||||
|
||||
" Define the default highlighting.
|
||||
" For version 5.7 and earlier: only when not done already
|
||||
" For version 5.8 and later: only when an item doesn't have highlighting yet
|
||||
if version >= 508 || !exists("did_coffee_syn_inits")
|
||||
if version < 508
|
||||
let did_coffee_syn_inits = 1
|
||||
command -nargs=+ HiLink hi link <args>
|
||||
else
|
||||
command -nargs=+ HiLink hi def link <args>
|
||||
endif
|
||||
HiLink coffeePrototypeAccess Keyword
|
||||
HiLink coffeeExtends Keyword
|
||||
HiLink coffeeLineComment Comment
|
||||
HiLink coffeeSpecial Special
|
||||
HiLink coffeeStringS String
|
||||
HiLink coffeeStringD String
|
||||
HiLink coffeeCharacter Character
|
||||
HiLink coffeeSpecialCharacter coffeeSpecial
|
||||
HiLink coffeeNumber coffeeValue
|
||||
HiLink coffeeConditional Conditional
|
||||
HiLink coffeeRepeat Repeat
|
||||
HiLink coffeeBranch Conditional
|
||||
HiLink coffeeOperator Operator
|
||||
HiLink coffeeType Type
|
||||
HiLink coffeeStatement Statement
|
||||
HiLink coffeeBindFunctionParams Function
|
||||
HiLink coffeeFunctionParams Function
|
||||
HiLink coffeeFunction Function
|
||||
HiLink coffeeBindFunction Function
|
||||
HiLink coffeeBraces Function
|
||||
HiLink coffeeError Error
|
||||
HiLink coffeeScrParenError coffeeError
|
||||
HiLink coffeeNull Keyword
|
||||
HiLink coffeeBoolean Boolean
|
||||
HiLink coffeeRegexpString String
|
||||
|
||||
HiLink coffeeIdentifier Identifier
|
||||
HiLink coffeeLabel Label
|
||||
HiLink coffeeException Exception
|
||||
HiLink coffeeMessage Keyword
|
||||
HiLink coffeeGlobal Keyword
|
||||
HiLink coffeeMember Keyword
|
||||
HiLink coffeeDeprecated Exception
|
||||
HiLink coffeeReserved Keyword
|
||||
HiLink coffeeDebug Debug
|
||||
HiLink coffeeConstant Label
|
||||
|
||||
delcommand HiLink
|
||||
endif
|
||||
|
||||
let b:current_syntax = "coffee"
|
||||
if main_syntax == 'coffee'
|
||||
unlet main_syntax
|
||||
endif
|
||||
|
||||
" vim: ts=8
|
||||
1338
index.html
1338
index.html
File diff suppressed because it is too large
Load Diff
@@ -1,7 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
process.mixin(require('sys'));
|
||||
|
||||
require.paths.unshift('/usr/local/lib/coffee-script/lib');
|
||||
|
||||
require('cake').run();
|
||||
@@ -1,7 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
process.mixin(require('sys'));
|
||||
|
||||
require.paths.unshift('/usr/local/lib/coffee-script/lib');
|
||||
|
||||
require('command_line').run();
|
||||
80
lib/cake.js
80
lib/cake.js
@@ -1,80 +0,0 @@
|
||||
(function(){
|
||||
var coffee, fs, no_such_task, path, print_tasks, tasks;
|
||||
var __hasProp = Object.prototype.hasOwnProperty;
|
||||
// `cake` is a simplified version of Make (Rake, Jake) for CoffeeScript.
|
||||
fs = require('fs');
|
||||
path = require('path');
|
||||
coffee = require('coffee-script');
|
||||
tasks = {};
|
||||
no_such_task = function no_such_task(task) {
|
||||
process.stdio.writeError('No such task: "' + task + '"\n');
|
||||
return process.exit(1);
|
||||
};
|
||||
// Mixin the Cake functionality.
|
||||
process.mixin({
|
||||
// Define a task with a name, a description, and the action itself.
|
||||
task: function task(name, description, action) {
|
||||
return tasks[name] = {
|
||||
name: name,
|
||||
description: description,
|
||||
action: action
|
||||
};
|
||||
},
|
||||
// Invoke another task in the Cakefile.
|
||||
invoke: function invoke(name) {
|
||||
if (!(tasks[name])) {
|
||||
no_such_task(name);
|
||||
}
|
||||
return tasks[name].action();
|
||||
}
|
||||
});
|
||||
// Display the list of Cake tasks.
|
||||
print_tasks = function print_tasks() {
|
||||
var _a, _b, _c, _d, _e, _f, _g, i, name, spaces, task;
|
||||
_a = []; _b = tasks;
|
||||
for (name in _b) { if (__hasProp.call(_b, name)) {
|
||||
task = _b[name];
|
||||
_a.push((function() {
|
||||
spaces = 20 - name.length;
|
||||
spaces = spaces > 0 ? (function() {
|
||||
_c = []; _f = 0; _g = spaces;
|
||||
for (_e=0, i=_f; (_f <= _g ? i <= _g : i >= _g); (_f <= _g ? i += 1 : i -= 1), _e++) {
|
||||
_c.push(' ');
|
||||
}
|
||||
return _c;
|
||||
}).call(this).join('') : '';
|
||||
return puts("cake " + name + spaces + ' # ' + task.description);
|
||||
}).call(this));
|
||||
}}
|
||||
return _a;
|
||||
};
|
||||
// Running `cake` runs the tasks you pass asynchronously (node-style), or
|
||||
// prints them out, with no arguments.
|
||||
exports.run = function run() {
|
||||
return path.exists('Cakefile', function(exists) {
|
||||
var args;
|
||||
if (!(exists)) {
|
||||
throw new Error('Cakefile not found in ' + process.cwd());
|
||||
}
|
||||
args = process.ARGV.slice(2, process.ARGV.length);
|
||||
return fs.readFile('Cakefile', function(err, source) {
|
||||
var _a, _b, _c, arg;
|
||||
eval(coffee.compile(source));
|
||||
if (!(args.length)) {
|
||||
return print_tasks();
|
||||
}
|
||||
_a = []; _b = args;
|
||||
for (_c = 0; _c < _b.length; _c++) {
|
||||
arg = _b[_c];
|
||||
_a.push((function() {
|
||||
if (!(tasks[arg])) {
|
||||
no_such_task(arg);
|
||||
}
|
||||
return tasks[arg].action();
|
||||
}).call(this));
|
||||
}
|
||||
return _a;
|
||||
});
|
||||
});
|
||||
};
|
||||
})();
|
||||
@@ -1,61 +0,0 @@
|
||||
(function(){
|
||||
var lexer, parser, path;
|
||||
// Set up for both the browser and the server.
|
||||
if ((typeof process !== "undefined" && process !== null)) {
|
||||
process.mixin(require('nodes'));
|
||||
path = require('path');
|
||||
lexer = new (require('lexer').Lexer)();
|
||||
parser = require('parser').parser;
|
||||
} else {
|
||||
lexer = new Lexer();
|
||||
parser = exports.parser;
|
||||
this.exports = (this.CoffeeScript = {});
|
||||
}
|
||||
// Thin wrapper for Jison compatibility around the real lexer.
|
||||
parser.lexer = {
|
||||
lex: function lex() {
|
||||
var token;
|
||||
token = this.tokens[this.pos] || [""];
|
||||
this.pos += 1;
|
||||
this.yylineno = token[2];
|
||||
this.yytext = token[1];
|
||||
return token[0];
|
||||
},
|
||||
setInput: function setInput(tokens) {
|
||||
this.tokens = tokens;
|
||||
return this.pos = 0;
|
||||
},
|
||||
upcomingInput: function upcomingInput() {
|
||||
return "";
|
||||
},
|
||||
showPosition: function showPosition() {
|
||||
return this.pos;
|
||||
}
|
||||
};
|
||||
exports.VERSION = '0.5.0';
|
||||
// Compile CoffeeScript to JavaScript, using the Coffee/Jison compiler.
|
||||
exports.compile = function compile(code, options) {
|
||||
return (parser.parse(lexer.tokenize(code))).compile(options);
|
||||
};
|
||||
// Just the tokens.
|
||||
exports.tokenize = function tokenize(code) {
|
||||
return lexer.tokenize(code);
|
||||
};
|
||||
// Just the nodes.
|
||||
exports.tree = function tree(code) {
|
||||
return parser.parse(lexer.tokenize(code));
|
||||
};
|
||||
// Pretty-print a token stream.
|
||||
exports.print_tokens = function print_tokens(tokens) {
|
||||
var _a, _b, _c, strings, token;
|
||||
strings = (function() {
|
||||
_a = []; _b = tokens;
|
||||
for (_c = 0; _c < _b.length; _c++) {
|
||||
token = _b[_c];
|
||||
_a.push('[' + token[0] + ' ' + token[1].toString().replace(/\n/, '\\n') + ']');
|
||||
}
|
||||
return _a;
|
||||
}).call(this);
|
||||
return puts(strings.join(' '));
|
||||
};
|
||||
})();
|
||||
21
lib/coffee-script.rb
Normal file
21
lib/coffee-script.rb
Normal file
@@ -0,0 +1,21 @@
|
||||
$LOAD_PATH.unshift(File.dirname(__FILE__))
|
||||
require "coffee_script/lexer"
|
||||
require "coffee_script/parser"
|
||||
require "coffee_script/nodes"
|
||||
require "coffee_script/value"
|
||||
require "coffee_script/scope"
|
||||
require "coffee_script/rewriter"
|
||||
require "coffee_script/parse_error"
|
||||
|
||||
# Namespace for all CoffeeScript internal classes.
|
||||
module CoffeeScript
|
||||
|
||||
VERSION = '0.2.1' # Keep in sync with the gemspec.
|
||||
|
||||
# Compile a script (String or IO) to JavaScript.
|
||||
def self.compile(script, options={})
|
||||
script = script.read if script.respond_to?(:read)
|
||||
Parser.new.parse(script).compile(options)
|
||||
end
|
||||
|
||||
end
|
||||
@@ -10,40 +10,57 @@
|
||||
</array>
|
||||
<key>name</key>
|
||||
<string>CoffeeScript</string>
|
||||
<key>foldingStartMarker</key>
|
||||
<string>^.*[:=] \{[^\}]*$</string>
|
||||
<key>foldingStopMarker</key>
|
||||
<string>\s*\}</string>
|
||||
<key>patterns</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>captures</key>
|
||||
<dict>
|
||||
<key>1</key>
|
||||
<key>1</key>
|
||||
<dict>
|
||||
<key>name</key>
|
||||
<string>variable.parameter.function.coffee</string>
|
||||
<string>entity.name.function.coffee</string>
|
||||
</dict>
|
||||
<key>2</key>
|
||||
<dict>
|
||||
<key>name</key>
|
||||
<string>keyword.operator.coffee</string>
|
||||
</dict>
|
||||
<key>3</key>
|
||||
<dict>
|
||||
<key>name</key>
|
||||
<string>variable.parameter.function.coffee</string>
|
||||
</dict>
|
||||
<key>4</key>
|
||||
<dict>
|
||||
<key>name</key>
|
||||
<string>storage.type.function.coffee</string>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>comment</key>
|
||||
<string>match stuff like: funcName: => … </string>
|
||||
<key>match</key>
|
||||
<string>([a-zA-Z0-9_?.$*]*)\s*(=|:)\s*([\w,\s]*?)\s*(=>)</string>
|
||||
<key>name</key>
|
||||
<string>meta.function.coffee</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>captures</key>
|
||||
<dict>
|
||||
<key>1</key>
|
||||
<dict>
|
||||
<key>name</key>
|
||||
<string>variable.parameter.function.coffee</string>
|
||||
</dict>
|
||||
<key>5</key>
|
||||
<key>2</key>
|
||||
<dict>
|
||||
<key>name</key>
|
||||
<string>storage.type.function.coffee</string>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>comment</key>
|
||||
<string>match stuff like: a -> … </string>
|
||||
<string>match stuff like: a => … </string>
|
||||
<key>match</key>
|
||||
<string>(\()([a-zA-Z0-9_?.$]*(,\s*[a-zA-Z0-9_?.$]+)*)(\))\s*((=|-)>)</string>
|
||||
<string>([a-zA-Z0-9_?., $*]*)\s*(=>)</string>
|
||||
<key>name</key>
|
||||
<string>meta.inline.function.coffee</string>
|
||||
</dict>
|
||||
@@ -72,36 +89,6 @@
|
||||
<key>name</key>
|
||||
<string>constant.numeric.coffee</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>match</key>
|
||||
<string>(@)([a-zA-Z_$]\w*)?</string>
|
||||
<key>name</key>
|
||||
<string>variable.other.readwrite.instance.coffee</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>name</key>
|
||||
<string>string.quoted.heredoc.coffee</string>
|
||||
<key>begin</key>
|
||||
<string>("""|''')</string>
|
||||
<key>end</key>
|
||||
<string>("""|''')</string>
|
||||
<key>beginCaptures</key>
|
||||
<dict>
|
||||
<key>0</key>
|
||||
<dict>
|
||||
<key>name</key>
|
||||
<string>punctuation.definition.string.begin.coffee</string>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>endCaptures</key>
|
||||
<dict>
|
||||
<key>0</key>
|
||||
<dict>
|
||||
<key>name</key>
|
||||
<string>punctuation.definition.string.end.coffee</string>
|
||||
</dict>
|
||||
</dict>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>begin</key>
|
||||
<string>'</string>
|
||||
@@ -215,48 +202,15 @@
|
||||
<key>name</key>
|
||||
<string>comment.line.coffee</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>begin</key>
|
||||
<string>(?<=[=(:]|^|return)\s*(/)(?![/*+{}?])</string>
|
||||
<key>beginCaptures</key>
|
||||
<dict>
|
||||
<key>1</key>
|
||||
<dict>
|
||||
<key>name</key>
|
||||
<string>punctuation.definition.string.begin.coffee</string>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>end</key>
|
||||
<string>(/)[igm]*</string>
|
||||
<key>endCaptures</key>
|
||||
<dict>
|
||||
<key>1</key>
|
||||
<dict>
|
||||
<key>name</key>
|
||||
<string>punctuation.definition.string.end.coffee</string>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>name</key>
|
||||
<string>string.regexp.coffee</string>
|
||||
<key>patterns</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>match</key>
|
||||
<string>\\.</string>
|
||||
<key>name</key>
|
||||
<string>constant.character.escape.coffee</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>match</key>
|
||||
<string>\b(break|by|catch|continue|else|finally|for|in|of|if|return|switch|then|throw|try|unless|when|while)\b</string>
|
||||
<string>\b(break|by|catch|continue|else|finally|for|if|return|switch|then|throw|try|unless|when|while)\b</string>
|
||||
<key>name</key>
|
||||
<string>keyword.control.coffee</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>match</key>
|
||||
<string>\b([a-zA-Z$_](\w|\$|:|\.)*\s*(?=\:))</string>
|
||||
<string>\b([a-zA-Z$_]\w*)(\:)\s</string>
|
||||
<key>name</key>
|
||||
<string>variable.assignment.coffee</string>
|
||||
<key>captures</key>
|
||||
@@ -266,6 +220,11 @@
|
||||
<key>name</key>
|
||||
<string>entity.name.function.coffee</string>
|
||||
</dict>
|
||||
<key>2</key>
|
||||
<dict>
|
||||
<key>name</key>
|
||||
<string>keyword.operator.coffee</string>
|
||||
</dict>
|
||||
</dict>
|
||||
</dict>
|
||||
<dict>
|
||||
@@ -300,13 +259,7 @@
|
||||
</dict>
|
||||
<dict>
|
||||
<key>match</key>
|
||||
<string>(=|-)></string>
|
||||
<key>name</key>
|
||||
<string>storage.type.function.coffee</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>match</key>
|
||||
<string>!|%|&|\*|\/|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\?|\|\||\:|\*=|(?<!\()/=|%=|\+=|\-=|&=|\^=|\b(instanceof|new|delete|typeof|and|or|is|isnt|not)\b</string>
|
||||
<string>!|\$|%|&|\*|\/|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\?|\|\||\:|\*=|(?<!\()/=|%=|\+=|\-=|&=|\^=|\b(in|instanceof|new|delete|typeof|and|or|is|isnt|not)\b</string>
|
||||
<key>name</key>
|
||||
<string>keyword.operator.coffee</string>
|
||||
</dict>
|
||||
@@ -316,6 +269,39 @@
|
||||
<key>name</key>
|
||||
<string>constant.language.coffee</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>begin</key>
|
||||
<string>(?<=[=(:]|^|return)\s*(/)(?![/*+{}?])</string>
|
||||
<key>beginCaptures</key>
|
||||
<dict>
|
||||
<key>1</key>
|
||||
<dict>
|
||||
<key>name</key>
|
||||
<string>punctuation.definition.string.begin.coffee</string>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>end</key>
|
||||
<string>(/)[igm]*</string>
|
||||
<key>endCaptures</key>
|
||||
<dict>
|
||||
<key>1</key>
|
||||
<dict>
|
||||
<key>name</key>
|
||||
<string>punctuation.definition.string.end.coffee</string>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>name</key>
|
||||
<string>string.regexp.coffee</string>
|
||||
<key>patterns</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>match</key>
|
||||
<string>\\.</string>
|
||||
<key>name</key>
|
||||
<string>constant.character.escape.coffee</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>match</key>
|
||||
<string>\;</string>
|
||||
217
lib/coffee_script/command_line.rb
Normal file
217
lib/coffee_script/command_line.rb
Normal file
@@ -0,0 +1,217 @@
|
||||
require 'optparse'
|
||||
require 'fileutils'
|
||||
require 'open3'
|
||||
require File.expand_path(File.dirname(__FILE__) + '/../coffee-script')
|
||||
|
||||
module CoffeeScript
|
||||
|
||||
# The CommandLine handles all of the functionality of the `coffee`
|
||||
# utility.
|
||||
class CommandLine
|
||||
|
||||
BANNER = <<-EOS
|
||||
coffee compiles CoffeeScript source files into JavaScript.
|
||||
|
||||
Usage:
|
||||
coffee path/to/script.coffee
|
||||
EOS
|
||||
|
||||
# Seconds to pause between checks for changed source files.
|
||||
WATCH_INTERVAL = 0.5
|
||||
|
||||
# Command to execute in Narwhal
|
||||
PACKAGE = File.expand_path(File.dirname(__FILE__) + '/../..')
|
||||
LAUNCHER = "narwhal -p #{PACKAGE} -e 'require(\"coffee-script\").run(system.args);'"
|
||||
|
||||
# Run the CommandLine off the contents of ARGV.
|
||||
def initialize
|
||||
@mtimes = {}
|
||||
parse_options
|
||||
return launch_repl if @options[:interactive]
|
||||
return eval_scriptlet if @options[:eval]
|
||||
check_sources
|
||||
return run_scripts if @options[:run]
|
||||
@sources.each {|source| compile_javascript(source) }
|
||||
watch_coffee_scripts if @options[:watch]
|
||||
end
|
||||
|
||||
# The "--help" usage message.
|
||||
def usage
|
||||
puts "\n#{@option_parser}\n"
|
||||
exit
|
||||
end
|
||||
|
||||
|
||||
private
|
||||
|
||||
# Compiles (or partially compiles) the source CoffeeScript file, returning
|
||||
# the desired JS, tokens, or lint results.
|
||||
def compile_javascript(source)
|
||||
script = File.read(source)
|
||||
return tokens(script) if @options[:tokens]
|
||||
js = compile(script, source)
|
||||
return unless js
|
||||
return puts(js) if @options[:print]
|
||||
return lint(js) if @options[:lint]
|
||||
File.open(path_for(source), 'w+') {|f| f.write(js) }
|
||||
end
|
||||
|
||||
# Spins up a watcher thread to keep track of the modification times of the
|
||||
# source files, recompiling them whenever they're saved.
|
||||
def watch_coffee_scripts
|
||||
watch_thread = Thread.start do
|
||||
loop do
|
||||
@sources.each do |source|
|
||||
mtime = File.stat(source).mtime
|
||||
@mtimes[source] ||= mtime
|
||||
if mtime > @mtimes[source]
|
||||
@mtimes[source] = mtime
|
||||
compile_javascript(source)
|
||||
end
|
||||
end
|
||||
sleep WATCH_INTERVAL
|
||||
end
|
||||
end
|
||||
Signal.trap("INT") { watch_thread.kill }
|
||||
watch_thread.join
|
||||
end
|
||||
|
||||
# Ensure that all of the source files exist.
|
||||
def check_sources
|
||||
usage if @sources.empty?
|
||||
missing = @sources.detect {|s| !File.exists?(s) }
|
||||
if missing
|
||||
STDERR.puts("File not found: '#{missing}'")
|
||||
exit(1)
|
||||
end
|
||||
end
|
||||
|
||||
# Pipe compiled JS through JSLint (requires a working 'jsl' command).
|
||||
def lint(js)
|
||||
stdin, stdout, stderr = Open3.popen3('jsl -nologo -stdin')
|
||||
stdin.write(js)
|
||||
stdin.close
|
||||
puts stdout.read.tr("\n", '')
|
||||
errs = stderr.read.chomp
|
||||
puts errs unless errs.empty?
|
||||
stdout.close and stderr.close
|
||||
end
|
||||
|
||||
# Eval a little piece of CoffeeScript directly from the command line.
|
||||
def eval_scriptlet
|
||||
script = STDIN.tty? ? @sources.join(' ') : STDIN.read
|
||||
return tokens(script) if @options[:tokens]
|
||||
js = compile(script)
|
||||
return lint(js) if @options[:lint]
|
||||
puts js
|
||||
end
|
||||
|
||||
# Use Narwhal to run an interactive CoffeeScript session.
|
||||
def launch_repl
|
||||
exec "#{LAUNCHER}"
|
||||
rescue Errno::ENOENT
|
||||
puts "Error: Narwhal must be installed to use the interactive REPL."
|
||||
exit(1)
|
||||
end
|
||||
|
||||
# Use Narwhal to compile and execute CoffeeScripts.
|
||||
def run_scripts
|
||||
sources = @sources.join(' ')
|
||||
exec "#{LAUNCHER} #{sources}"
|
||||
rescue Errno::ENOENT
|
||||
puts "Error: Narwhal must be installed in order to execute CoffeeScripts."
|
||||
exit(1)
|
||||
end
|
||||
|
||||
# Print the tokens that the lexer generates from a source script.
|
||||
def tokens(script)
|
||||
puts Lexer.new.tokenize(script).inspect
|
||||
end
|
||||
|
||||
# Compile a single source file to JavaScript.
|
||||
def compile(script, source='error')
|
||||
begin
|
||||
options = {}
|
||||
options[:no_wrap] = true if @options[:no_wrap]
|
||||
CoffeeScript.compile(script, options)
|
||||
rescue CoffeeScript::ParseError, SyntaxError => e
|
||||
STDERR.puts "#{source}: #{e.message}"
|
||||
exit(1) unless @options[:watch]
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
# Write out JavaScript alongside CoffeeScript unless an output directory
|
||||
# is specified.
|
||||
def path_for(source)
|
||||
filename = File.basename(source, File.extname(source)) + '.js'
|
||||
dir = @options[:output] || File.dirname(source)
|
||||
File.join(dir, filename)
|
||||
end
|
||||
|
||||
# Install the CoffeeScript TextMate bundle to ~/Library.
|
||||
def install_bundle
|
||||
bundle_dir = File.expand_path('~/Library/Application Support/TextMate/Bundles/')
|
||||
FileUtils.cp_r(File.dirname(__FILE__) + '/CoffeeScript.tmbundle', bundle_dir)
|
||||
end
|
||||
|
||||
# Use OptionParser for all the options.
|
||||
def parse_options
|
||||
@options = {}
|
||||
@option_parser = OptionParser.new do |opts|
|
||||
opts.on('-i', '--interactive', 'run a CoffeeScript REPL (requires Narwhal)') do |i|
|
||||
@options[:interactive] = true
|
||||
end
|
||||
opts.on('-r', '--run', 'compile and run a script (requires Narwhal)') do |r|
|
||||
@options[:run] = true
|
||||
end
|
||||
opts.on('-o', '--output [DIR]', 'set the directory for compiled JavaScript') do |d|
|
||||
@options[:output] = d
|
||||
FileUtils.mkdir_p(d) unless File.exists?(d)
|
||||
end
|
||||
opts.on('-w', '--watch', 'watch scripts for changes, and recompile') do |w|
|
||||
@options[:watch] = true
|
||||
end
|
||||
opts.on('-p', '--print', 'print the compiled JavaScript to stdout') do |d|
|
||||
@options[:print] = true
|
||||
end
|
||||
opts.on('-l', '--lint', 'pipe the compiled JavaScript through JSLint') do |l|
|
||||
@options[:lint] = true
|
||||
end
|
||||
opts.on('-e', '--eval', 'compile a cli scriptlet or read from stdin') do |e|
|
||||
@options[:eval] = true
|
||||
end
|
||||
opts.on('-t', '--tokens', 'print the tokens that the lexer produces') do |t|
|
||||
@options[:tokens] = true
|
||||
end
|
||||
opts.on('-v', '--verbose', 'print at every step of code generation') do |v|
|
||||
ENV['VERBOSE'] = 'true'
|
||||
end
|
||||
opts.on('-n', '--no-wrap', 'raw output, no safety wrapper or vars') do |n|
|
||||
@options[:no_wrap] = true
|
||||
end
|
||||
opts.on_tail('--install-bundle', 'install the CoffeeScript TextMate bundle') do |i|
|
||||
install_bundle
|
||||
exit
|
||||
end
|
||||
opts.on_tail('--version', 'display CoffeeScript version') do
|
||||
puts "CoffeeScript version #{CoffeeScript::VERSION}"
|
||||
exit
|
||||
end
|
||||
opts.on_tail('-h', '--help', 'display this help message') do
|
||||
usage
|
||||
end
|
||||
end
|
||||
@option_parser.banner = BANNER
|
||||
begin
|
||||
@option_parser.parse!(ARGV)
|
||||
rescue OptionParser::InvalidOption => e
|
||||
puts e.message
|
||||
exit(1)
|
||||
end
|
||||
@sources = ARGV
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
443
lib/coffee_script/grammar.y
Normal file
443
lib/coffee_script/grammar.y
Normal file
@@ -0,0 +1,443 @@
|
||||
class Parser
|
||||
|
||||
# Declare tokens produced by the lexer
|
||||
token IF ELSE UNLESS
|
||||
token NUMBER STRING REGEX
|
||||
token TRUE FALSE YES NO ON OFF
|
||||
token IDENTIFIER PROPERTY_ACCESS
|
||||
token CODE PARAM PARAM_SPLAT NEW RETURN
|
||||
token TRY CATCH FINALLY THROW
|
||||
token BREAK CONTINUE
|
||||
token FOR IN BY WHEN WHILE
|
||||
token SWITCH LEADING_WHEN
|
||||
token DELETE INSTANCEOF TYPEOF
|
||||
token SUPER EXTENDS
|
||||
token ARGUMENTS
|
||||
token NEWLINE
|
||||
token COMMENT
|
||||
token JS
|
||||
token INDENT OUTDENT
|
||||
|
||||
# Declare order of operations.
|
||||
prechigh
|
||||
left '?'
|
||||
nonassoc UMINUS PARAM_SPLAT SPLAT NOT '!' '!!' '~' '++' '--'
|
||||
left '*' '/' '%'
|
||||
left '+' '-'
|
||||
left '<<' '>>' '>>>'
|
||||
left '&' '|' '^'
|
||||
left '<=' '<' '>' '>='
|
||||
right '==' '!=' IS ISNT
|
||||
left '&&' '||' AND OR
|
||||
right '-=' '+=' '/=' '*=' '%='
|
||||
right DELETE INSTANCEOF TYPEOF
|
||||
left '.'
|
||||
right INDENT
|
||||
left OUTDENT
|
||||
right WHEN LEADING_WHEN IN BY
|
||||
right THROW FOR NEW SUPER
|
||||
left EXTENDS
|
||||
left ASSIGN '||=' '&&='
|
||||
right RETURN '=>' UNLESS IF ELSE WHILE
|
||||
preclow
|
||||
|
||||
rule
|
||||
|
||||
# All parsing will end in this rule, being the trunk of the AST.
|
||||
Root:
|
||||
/* nothing */ { result = Expressions.new }
|
||||
| Terminator { result = Expressions.new }
|
||||
| Expressions { result = val[0] }
|
||||
| Block Terminator { result = val[0] }
|
||||
;
|
||||
|
||||
# Any list of expressions or method body, seperated by line breaks or semis.
|
||||
Expressions:
|
||||
Expression { result = Expressions.wrap(val) }
|
||||
| Expressions Terminator Expression { result = val[0] << val[2] }
|
||||
| Expressions Terminator { result = val[0] }
|
||||
;
|
||||
|
||||
# All types of expressions in our language.
|
||||
Expression:
|
||||
Value
|
||||
| Call
|
||||
| Code
|
||||
| Operation
|
||||
| Range
|
||||
| Assign
|
||||
| If
|
||||
| Try
|
||||
| Throw
|
||||
| Return
|
||||
| While
|
||||
| For
|
||||
| Switch
|
||||
| Extends
|
||||
| Splat
|
||||
| Existence
|
||||
| Comment
|
||||
;
|
||||
|
||||
Block:
|
||||
INDENT Expressions OUTDENT { result = val[1] }
|
||||
| INDENT OUTDENT { result = Expressions.new }
|
||||
;
|
||||
|
||||
# All tokens that can terminate an expression.
|
||||
Terminator:
|
||||
"\n"
|
||||
| ";"
|
||||
;
|
||||
|
||||
# All hard-coded values.
|
||||
Literal:
|
||||
NUMBER { result = LiteralNode.new(val[0]) }
|
||||
| STRING { result = LiteralNode.new(val[0]) }
|
||||
| JS { result = LiteralNode.new(val[0]) }
|
||||
| REGEX { result = LiteralNode.new(val[0]) }
|
||||
| BREAK { result = LiteralNode.new(val[0]) }
|
||||
| CONTINUE { result = LiteralNode.new(val[0]) }
|
||||
| ARGUMENTS { result = LiteralNode.new(val[0]) }
|
||||
| TRUE { result = LiteralNode.new(true) }
|
||||
| FALSE { result = LiteralNode.new(false) }
|
||||
| YES { result = LiteralNode.new(true) }
|
||||
| NO { result = LiteralNode.new(false) }
|
||||
| ON { result = LiteralNode.new(true) }
|
||||
| OFF { result = LiteralNode.new(false) }
|
||||
;
|
||||
|
||||
# Assignment to a variable.
|
||||
Assign:
|
||||
Value ASSIGN Expression { result = AssignNode.new(val[0], val[2]) }
|
||||
;
|
||||
|
||||
# Assignment within an object literal.
|
||||
AssignObj:
|
||||
IDENTIFIER ASSIGN Expression { result = AssignNode.new(ValueNode.new(val[0]), val[2], :object) }
|
||||
| STRING ASSIGN Expression { result = AssignNode.new(ValueNode.new(LiteralNode.new(val[0])), val[2], :object) }
|
||||
| Comment { result = val[0] }
|
||||
;
|
||||
|
||||
# A return statement.
|
||||
Return:
|
||||
RETURN Expression { result = ReturnNode.new(val[1]) }
|
||||
;
|
||||
|
||||
# A comment.
|
||||
Comment:
|
||||
COMMENT { result = CommentNode.new(val[0]) }
|
||||
;
|
||||
|
||||
# Arithmetic and logical operators
|
||||
# For Ruby's Operator precedence, see:
|
||||
# https://www.cs.auckland.ac.nz/references/ruby/ProgrammingRuby/language.html
|
||||
Operation:
|
||||
'!' Expression { result = OpNode.new(val[0], val[1]) }
|
||||
| '!!' Expression { result = OpNode.new(val[0], val[1]) }
|
||||
| '-' Expression = UMINUS { result = OpNode.new(val[0], val[1]) }
|
||||
| NOT Expression { result = OpNode.new(val[0], val[1]) }
|
||||
| '~' Expression { result = OpNode.new(val[0], val[1]) }
|
||||
| '--' Expression { result = OpNode.new(val[0], val[1]) }
|
||||
| '++' Expression { result = OpNode.new(val[0], val[1]) }
|
||||
| DELETE Expression { result = OpNode.new(val[0], val[1]) }
|
||||
| TYPEOF Expression { result = OpNode.new(val[0], val[1]) }
|
||||
| Expression '--' { result = OpNode.new(val[1], val[0], nil, true) }
|
||||
| Expression '++' { result = OpNode.new(val[1], val[0], nil, true) }
|
||||
|
||||
| Expression '*' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '/' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '%' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
|
||||
| Expression '+' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '-' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
|
||||
| Expression '<<' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '>>' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '>>>' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
|
||||
| Expression '&' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '|' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '^' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
|
||||
| Expression '<=' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '<' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '>' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '>=' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
|
||||
| Expression '==' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '!=' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression IS Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression ISNT Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
|
||||
| Expression '&&' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '||' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression AND Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression OR Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
|
||||
| Expression '-=' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '+=' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '/=' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '*=' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '%=' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '||=' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '&&=' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
|
||||
| Expression INSTANCEOF Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
;
|
||||
|
||||
Existence:
|
||||
Expression '?' { result = ExistenceNode.new(val[0]) }
|
||||
;
|
||||
|
||||
# Function definition.
|
||||
Code:
|
||||
ParamList "=>" Block { result = CodeNode.new(val[0], val[2]) }
|
||||
| "=>" Block { result = CodeNode.new([], val[1]) }
|
||||
;
|
||||
|
||||
# The parameters to a function definition.
|
||||
ParamList:
|
||||
Param { result = val }
|
||||
| ParamList "," Param { result = val[0] << val[2] }
|
||||
;
|
||||
|
||||
Param:
|
||||
PARAM
|
||||
| PARAM_SPLAT PARAM { result = ParamSplatNode.new(val[1]) }
|
||||
;
|
||||
|
||||
Splat:
|
||||
'*' Value = SPLAT { result = ArgSplatNode.new(val[1]) }
|
||||
;
|
||||
|
||||
# Expressions that can be treated as values.
|
||||
Value:
|
||||
IDENTIFIER { result = ValueNode.new(val[0]) }
|
||||
| Literal { result = ValueNode.new(val[0]) }
|
||||
| Array { result = ValueNode.new(val[0]) }
|
||||
| Object { result = ValueNode.new(val[0]) }
|
||||
| Parenthetical { result = ValueNode.new(val[0]) }
|
||||
| Value Accessor { result = val[0] << val[1] }
|
||||
| Invocation Accessor { result = ValueNode.new(val[0], [val[1]]) }
|
||||
;
|
||||
|
||||
# Accessing into an object or array, through dot or index notation.
|
||||
Accessor:
|
||||
PROPERTY_ACCESS IDENTIFIER { result = AccessorNode.new(val[1]) }
|
||||
| Index { result = val[0] }
|
||||
| Range { result = SliceNode.new(val[0]) }
|
||||
;
|
||||
|
||||
# Indexing into an object or array.
|
||||
Index:
|
||||
"[" Expression "]" { result = IndexNode.new(val[1]) }
|
||||
;
|
||||
|
||||
# An object literal.
|
||||
Object:
|
||||
"{" AssignList "}" { result = ObjectNode.new(val[1]) }
|
||||
;
|
||||
|
||||
# Assignment within an object literal (comma or newline separated).
|
||||
AssignList:
|
||||
/* nothing */ { result = [] }
|
||||
| AssignObj { result = val }
|
||||
| AssignList "," AssignObj { result = val[0] << val[2] }
|
||||
| AssignList Terminator AssignObj { result = val[0] << val[2] }
|
||||
| AssignList ","
|
||||
Terminator AssignObj { result = val[0] << val[3] }
|
||||
| INDENT AssignList OUTDENT { result = val[1] }
|
||||
;
|
||||
|
||||
# All flavors of function call (instantiation, super, and regular).
|
||||
Call:
|
||||
Invocation { result = val[0] }
|
||||
| NEW Invocation { result = val[1].new_instance }
|
||||
| Super { result = val[0] }
|
||||
;
|
||||
|
||||
# Extending an object's prototype.
|
||||
Extends:
|
||||
Value EXTENDS Value { result = ExtendsNode.new(val[0], val[2]) }
|
||||
;
|
||||
|
||||
# A generic function invocation.
|
||||
Invocation:
|
||||
Value Arguments { result = CallNode.new(val[0], val[1]) }
|
||||
| Invocation Arguments { result = CallNode.new(val[0], val[1]) }
|
||||
# | Invocation Code { result = val[0] << val[1] }
|
||||
;
|
||||
|
||||
Arguments:
|
||||
"(" ArgList ")" { result = val[1] }
|
||||
| "(" ArgList ")" Code { result = val[1] << val[3] }
|
||||
;
|
||||
|
||||
# Calling super.
|
||||
Super:
|
||||
SUPER "(" ArgList ")" { result = CallNode.new(:super, val[2]) }
|
||||
;
|
||||
|
||||
# The range literal.
|
||||
Range:
|
||||
"[" Expression
|
||||
"." "." Expression "]" { result = RangeNode.new(val[1], val[4]) }
|
||||
| "[" Expression
|
||||
"." "." "." Expression "]" { result = RangeNode.new(val[1], val[5], true) }
|
||||
;
|
||||
|
||||
# The array literal.
|
||||
Array:
|
||||
"[" ArgList "]" { result = ArrayNode.new(val[1]) }
|
||||
;
|
||||
|
||||
# A list of arguments to a method call, or as the contents of an array.
|
||||
ArgList:
|
||||
/* nothing */ { result = [] }
|
||||
| Expression { result = val }
|
||||
| INDENT Expression { result = [val[1]] }
|
||||
| ArgList "," Expression { result = val[0] << val[2] }
|
||||
| ArgList Terminator Expression { result = val[0] << val[2] }
|
||||
| ArgList "," Terminator Expression { result = val[0] << val[3] }
|
||||
| ArgList "," INDENT Expression { result = val[0] << val[3] }
|
||||
| ArgList OUTDENT { result = val[0] }
|
||||
;
|
||||
|
||||
# Try/catch/finally exception handling blocks.
|
||||
Try:
|
||||
TRY Block Catch { result = TryNode.new(val[1], val[2][0], val[2][1]) }
|
||||
| TRY Block FINALLY Block { result = TryNode.new(val[1], nil, nil, val[3]) }
|
||||
| TRY Block Catch
|
||||
FINALLY Block { result = TryNode.new(val[1], val[2][0], val[2][1], val[4]) }
|
||||
;
|
||||
|
||||
# A catch clause.
|
||||
Catch:
|
||||
CATCH IDENTIFIER Block { result = [val[1], val[2]] }
|
||||
;
|
||||
|
||||
# Throw an exception.
|
||||
Throw:
|
||||
THROW Expression { result = ThrowNode.new(val[1]) }
|
||||
;
|
||||
|
||||
# Parenthetical expressions.
|
||||
Parenthetical:
|
||||
"(" Expression ")" { result = ParentheticalNode.new(val[1], val[0].line) }
|
||||
;
|
||||
|
||||
# The while loop. (there is no do..while).
|
||||
While:
|
||||
WHILE Expression Block { result = WhileNode.new(val[1], val[2]) }
|
||||
;
|
||||
|
||||
# Array comprehensions, including guard and current index.
|
||||
# Looks a little confusing, check nodes.rb for the arguments to ForNode.
|
||||
For:
|
||||
Expression FOR
|
||||
ForVariables ForSource { result = ForNode.new(val[0], val[3], val[2][0], val[2][1]) }
|
||||
| FOR ForVariables ForSource Block { result = ForNode.new(val[3], val[2], val[1][0], val[1][1]) }
|
||||
;
|
||||
|
||||
# An array comprehension has variables for the current element and index.
|
||||
ForVariables:
|
||||
IDENTIFIER { result = val }
|
||||
| IDENTIFIER "," IDENTIFIER { result = [val[0], val[2]] }
|
||||
;
|
||||
|
||||
# The source of the array comprehension can optionally be filtered.
|
||||
ForSource:
|
||||
IN Expression { result = {:source => val[1]} }
|
||||
| ForSource
|
||||
WHEN Expression { result = val[0].merge(:filter => val[2]) }
|
||||
| ForSource
|
||||
BY Expression { result = val[0].merge(:step => val[2]) }
|
||||
;
|
||||
|
||||
# Switch/When blocks.
|
||||
Switch:
|
||||
SWITCH Expression INDENT
|
||||
Whens OUTDENT { result = val[3].rewrite_condition(val[1]) }
|
||||
| SWITCH Expression INDENT
|
||||
Whens ELSE Block OUTDENT { result = val[3].rewrite_condition(val[1]).add_else(val[5]) }
|
||||
;
|
||||
|
||||
# The inner list of whens.
|
||||
Whens:
|
||||
When { result = val[0] }
|
||||
| Whens When { result = val[0] << val[1] }
|
||||
;
|
||||
|
||||
# An individual when.
|
||||
When:
|
||||
LEADING_WHEN Expression Block { result = IfNode.new(val[1], val[2], nil, {:statement => true}) }
|
||||
| LEADING_WHEN Expression Block
|
||||
Terminator { result = IfNode.new(val[1], val[2], nil, {:statement => true}) }
|
||||
| Comment
|
||||
;
|
||||
|
||||
# All of the following nutso if-else destructuring is to make the
|
||||
# grammar expand unambiguously.
|
||||
|
||||
IfBlock:
|
||||
IF Expression Block { result = IfNode.new(val[1], val[2]) }
|
||||
;
|
||||
|
||||
# An elsif portion of an if-else block.
|
||||
ElsIf:
|
||||
ELSE IfBlock { result = val[1].force_statement }
|
||||
;
|
||||
|
||||
# Multiple elsifs can be chained together.
|
||||
ElsIfs:
|
||||
ElsIf { result = val[0] }
|
||||
| ElsIfs ElsIf { result = val[0].add_else(val[1]) }
|
||||
;
|
||||
|
||||
# Terminating else bodies are strictly optional.
|
||||
ElseBody
|
||||
/* nothing */ { result = nil }
|
||||
| ELSE Block { result = val[1] }
|
||||
;
|
||||
|
||||
# All the alternatives for ending an if-else block.
|
||||
IfEnd:
|
||||
ElseBody { result = val[0] }
|
||||
| ElsIfs ElseBody { result = val[0].add_else(val[1]) }
|
||||
;
|
||||
|
||||
# The full complement of if blocks, including postfix one-liner ifs and unlesses.
|
||||
If:
|
||||
IfBlock IfEnd { result = val[0].add_else(val[1]) }
|
||||
| Expression IF Expression { result = IfNode.new(val[2], Expressions.wrap(val[0]), nil, {:statement => true}) }
|
||||
| Expression UNLESS Expression { result = IfNode.new(val[2], Expressions.wrap(val[0]), nil, {:statement => true, :invert => true}) }
|
||||
;
|
||||
|
||||
end
|
||||
|
||||
---- header
|
||||
module CoffeeScript
|
||||
|
||||
---- inner
|
||||
# Lex and parse a CoffeeScript.
|
||||
def parse(code)
|
||||
# Uncomment the following line to enable grammar debugging, in combination
|
||||
# with the -g flag in the Rake build task.
|
||||
# @yydebug = true
|
||||
@tokens = Lexer.new.tokenize(code)
|
||||
do_parse
|
||||
end
|
||||
|
||||
# Retrieve the next token from the list.
|
||||
def next_token
|
||||
@tokens.shift
|
||||
end
|
||||
|
||||
# Raise a custom error class that knows about line numbers.
|
||||
def on_error(error_token_id, error_value, value_stack)
|
||||
raise ParseError.new(token_to_str(error_token_id), error_value, value_stack)
|
||||
end
|
||||
|
||||
---- footer
|
||||
end
|
||||
238
lib/coffee_script/lexer.rb
Normal file
238
lib/coffee_script/lexer.rb
Normal file
@@ -0,0 +1,238 @@
|
||||
module CoffeeScript
|
||||
|
||||
# The lexer reads a stream of CoffeeScript and divvys it up into tagged
|
||||
# tokens. A minor bit of the ambiguity in the grammar has been avoided by
|
||||
# pushing some extra smarts into the Lexer.
|
||||
class Lexer
|
||||
|
||||
# The list of keywords passed verbatim to the parser.
|
||||
KEYWORDS = ["if", "else", "then", "unless",
|
||||
"true", "false", "yes", "no", "on", "off",
|
||||
"and", "or", "is", "isnt", "not",
|
||||
"new", "return",
|
||||
"try", "catch", "finally", "throw",
|
||||
"break", "continue",
|
||||
"for", "in", "by", "where", "while",
|
||||
"switch", "when",
|
||||
"super", "extends",
|
||||
"arguments",
|
||||
"delete", "instanceof", "typeof"]
|
||||
|
||||
# Token matching regexes.
|
||||
IDENTIFIER = /\A([a-zA-Z$_]\w*)/
|
||||
NUMBER = /\A(\b((0(x|X)[0-9a-fA-F]+)|([0-9]+(\.[0-9]+)?(e[+\-]?[0-9]+)?)))\b/i
|
||||
STRING = /\A(""|''|"(.*?)[^\\]"|'(.*?)[^\\]')/m
|
||||
JS = /\A(``|`(.*?)[^\\]`)/m
|
||||
OPERATOR = /\A([+\*&|\/\-%=<>:!]+)/
|
||||
WHITESPACE = /\A([ \t]+)/
|
||||
COMMENT = /\A(((\n?[ \t]*)?#.*$)+)/
|
||||
CODE = /\A(=>)/
|
||||
REGEX = /\A(\/(.*?)[^\\]\/[imgy]{0,4})/
|
||||
MULTI_DENT = /\A((\n([ \t]*)?)+)/
|
||||
LAST_DENT = /\n([ \t]*)/
|
||||
ASSIGNMENT = /\A(:|=)\Z/
|
||||
|
||||
# Token cleaning regexes.
|
||||
JS_CLEANER = /(\A`|`\Z)/
|
||||
MULTILINER = /\n/
|
||||
COMMENT_CLEANER = /(^\s*#|\n\s*$)/
|
||||
NO_NEWLINE = /\A([+\*&|\/\-%=<>:!.\\][<>=&|]*|and|or|is|isnt|not|delete|typeof|instanceof)\Z/
|
||||
|
||||
# Tokens which a regular expression will never immediately follow, but which
|
||||
# a division operator might.
|
||||
# See: http://www.mozilla.org/js/language/js20-2002-04/rationale/syntax.html#regular-expressions
|
||||
NOT_REGEX = [
|
||||
:IDENTIFIER, :NUMBER, :REGEX, :STRING,
|
||||
')', '++', '--', ']', '}',
|
||||
:FALSE, :NULL, :THIS, :TRUE
|
||||
]
|
||||
|
||||
# Scan by attempting to match tokens one character at a time. Slow and steady.
|
||||
def tokenize(code)
|
||||
@code = code.chomp # Cleanup code by remove extra line breaks
|
||||
@i = 0 # Current character position we're parsing
|
||||
@line = 1 # The current line.
|
||||
@indent = 0 # The current indent level.
|
||||
@indents = [] # The stack of all indent levels we are currently within.
|
||||
@tokens = [] # Collection of all parsed tokens in the form [:TOKEN_TYPE, value]
|
||||
while @i < @code.length
|
||||
@chunk = @code[@i..-1]
|
||||
extract_next_token
|
||||
end
|
||||
puts "original stream: #{@tokens.inspect}" if ENV['VERBOSE']
|
||||
close_indentation
|
||||
Rewriter.new.rewrite(@tokens)
|
||||
end
|
||||
|
||||
# At every position, run through this list of attempted matches,
|
||||
# short-circuiting if any of them succeed.
|
||||
def extract_next_token
|
||||
return if identifier_token
|
||||
return if number_token
|
||||
return if string_token
|
||||
return if js_token
|
||||
return if regex_token
|
||||
return if indent_token
|
||||
return if comment_token
|
||||
return if whitespace_token
|
||||
return literal_token
|
||||
end
|
||||
|
||||
# Tokenizers ==========================================================
|
||||
|
||||
# Matches identifying literals: variables, keywords, method names, etc.
|
||||
def identifier_token
|
||||
return false unless identifier = @chunk[IDENTIFIER, 1]
|
||||
# Keywords are special identifiers tagged with their own name,
|
||||
# 'if' will result in an [:IF, "if"] token.
|
||||
tag = KEYWORDS.include?(identifier) ? identifier.upcase.to_sym : :IDENTIFIER
|
||||
tag = :LEADING_WHEN if tag == :WHEN && [:OUTDENT, :INDENT, "\n"].include?(last_tag)
|
||||
@tokens[-1][0] = :PROPERTY_ACCESS if tag == :IDENTIFIER && last_value == '.' && !(@tokens[-2][1] == '.')
|
||||
token(tag, identifier)
|
||||
@i += identifier.length
|
||||
end
|
||||
|
||||
# Matches numbers, including decimals, hex, and exponential notation.
|
||||
def number_token
|
||||
return false unless number = @chunk[NUMBER, 1]
|
||||
token(:NUMBER, number)
|
||||
@i += number.length
|
||||
end
|
||||
|
||||
# Matches strings, including multi-line strings.
|
||||
def string_token
|
||||
return false unless string = @chunk[STRING, 1]
|
||||
escaped = string.gsub(MULTILINER) do |match|
|
||||
@line += 1
|
||||
" \\\n"
|
||||
end
|
||||
token(:STRING, escaped)
|
||||
@i += string.length
|
||||
end
|
||||
|
||||
# Matches interpolated JavaScript.
|
||||
def js_token
|
||||
return false unless script = @chunk[JS, 1]
|
||||
token(:JS, script.gsub(JS_CLEANER, ''))
|
||||
@i += script.length
|
||||
end
|
||||
|
||||
# Matches regular expression literals.
|
||||
def regex_token
|
||||
return false unless regex = @chunk[REGEX, 1]
|
||||
return false if NOT_REGEX.include?(last_tag)
|
||||
token(:REGEX, regex)
|
||||
@i += regex.length
|
||||
end
|
||||
|
||||
# Matches and consumes comments.
|
||||
def comment_token
|
||||
return false unless comment = @chunk[COMMENT, 1]
|
||||
@line += comment.scan(MULTILINER).length
|
||||
token(:COMMENT, comment.gsub(COMMENT_CLEANER, '').split(MULTILINER))
|
||||
token("\n", "\n")
|
||||
@i += comment.length
|
||||
end
|
||||
|
||||
# Record tokens for indentation differing from the previous line.
|
||||
def indent_token
|
||||
return false unless indent = @chunk[MULTI_DENT, 1]
|
||||
@line += indent.scan(MULTILINER).size
|
||||
@i += indent.size
|
||||
return suppress_newlines(indent) if last_value.to_s.match(NO_NEWLINE) && last_value != "=>"
|
||||
size = indent.scan(LAST_DENT).last.last.length
|
||||
return newline_token(indent) if size == @indent
|
||||
if size > @indent
|
||||
token(:INDENT, size - @indent)
|
||||
@indents << (size - @indent)
|
||||
else
|
||||
outdent_token(@indent - size)
|
||||
end
|
||||
@indent = size
|
||||
end
|
||||
|
||||
# Record an oudent token or tokens, if we're moving back inwards past
|
||||
# multiple recorded indents.
|
||||
def outdent_token(move_out)
|
||||
while move_out > 0 && !@indents.empty?
|
||||
last_indent = @indents.pop
|
||||
token(:OUTDENT, last_indent)
|
||||
move_out -= last_indent
|
||||
end
|
||||
token("\n", "\n")
|
||||
end
|
||||
|
||||
# Matches and consumes non-meaningful whitespace.
|
||||
def whitespace_token
|
||||
return false unless whitespace = @chunk[WHITESPACE, 1]
|
||||
@i += whitespace.length
|
||||
end
|
||||
|
||||
# Multiple newlines get merged together.
|
||||
# Use a trailing \ to escape newlines.
|
||||
def newline_token(newlines)
|
||||
token("\n", "\n") unless last_value == "\n"
|
||||
true
|
||||
end
|
||||
|
||||
# Tokens to explicitly escape newlines are removed once their job is done.
|
||||
def suppress_newlines(newlines)
|
||||
@tokens.pop if last_value == "\\"
|
||||
true
|
||||
end
|
||||
|
||||
# We treat all other single characters as a token. Eg.: ( ) , . !
|
||||
# Multi-character operators are also literal tokens, so that Racc can assign
|
||||
# the proper order of operations.
|
||||
def literal_token
|
||||
value = @chunk[OPERATOR, 1]
|
||||
tag_parameters if value && value.match(CODE)
|
||||
value ||= @chunk[0,1]
|
||||
tag = value.match(ASSIGNMENT) ? :ASSIGN : value
|
||||
token(tag, value)
|
||||
@i += value.length
|
||||
end
|
||||
|
||||
# Helpers ==========================================================
|
||||
|
||||
# Add a token to the results, taking note of the line number, and
|
||||
# immediately-preceding comment.
|
||||
def token(tag, value)
|
||||
@tokens << [tag, Value.new(value, @line)]
|
||||
end
|
||||
|
||||
# Peek at the previous token's value.
|
||||
def last_value
|
||||
@tokens.last && @tokens.last[1]
|
||||
end
|
||||
|
||||
# Peek at the previous token's tag.
|
||||
def last_tag
|
||||
@tokens.last && @tokens.last[0]
|
||||
end
|
||||
|
||||
# A source of ambiguity in our grammar was parameter lists in function
|
||||
# definitions (as opposed to argument lists in function calls). Tag
|
||||
# parameter identifiers in order to avoid this. Also, parameter lists can
|
||||
# make use of splats.
|
||||
def tag_parameters
|
||||
i = 0
|
||||
loop do
|
||||
i -= 1
|
||||
tok = @tokens[i]
|
||||
return if !tok
|
||||
next if tok[0] == ','
|
||||
next tok[0] = :PARAM_SPLAT if tok[0] == '*'
|
||||
return if tok[0] != :IDENTIFIER
|
||||
tok[0] = :PARAM
|
||||
end
|
||||
end
|
||||
|
||||
# Close up all remaining open blocks. IF the first token is an indent,
|
||||
# axe it.
|
||||
def close_indentation
|
||||
outdent_token(@indent)
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
62
lib/coffee_script/narwhal/coffee-script.coffee
Normal file
62
lib/coffee_script/narwhal/coffee-script.coffee
Normal file
@@ -0,0 +1,62 @@
|
||||
# This (javascript) file is generated from lib/coffee_script/narwhal/coffee-script.coffee
|
||||
|
||||
# Executes the `coffee` Ruby program to convert from CoffeeScript
|
||||
# to Javascript. Eventually this will hopefully happen entirely within JS.
|
||||
|
||||
# Require external dependencies.
|
||||
OS: require('os')
|
||||
File: require('file')
|
||||
Readline: require('readline')
|
||||
|
||||
# The path to the CoffeeScript Compiler.
|
||||
coffeePath: File.path(module.path).dirname().dirname().dirname().dirname().dirname().join('bin', 'coffee')
|
||||
|
||||
# Our general-purpose error handler.
|
||||
checkForErrors: coffeeProcess =>
|
||||
return true if coffeeProcess.wait() is 0
|
||||
system.stderr.print(coffeeProcess.stderr.read())
|
||||
throw new Error("CoffeeScript compile error")
|
||||
|
||||
# Run a simple REPL, round-tripping to the CoffeeScript compiler for every
|
||||
# command.
|
||||
exports.run: args =>
|
||||
if args.length
|
||||
for path, i in args
|
||||
exports.evalCS(File.read(path))
|
||||
delete args[i]
|
||||
return true
|
||||
|
||||
while true
|
||||
try
|
||||
system.stdout.write('coffee> ').flush()
|
||||
result: exports.evalCS(Readline.readline())
|
||||
print(result) if result isnt undefined
|
||||
catch e
|
||||
print(e)
|
||||
|
||||
# Compile a given CoffeeScript file into JavaScript.
|
||||
exports.compileFile: path =>
|
||||
coffee: OS.popen([coffeePath, "--print", "--no-wrap", path])
|
||||
checkForErrors(coffee)
|
||||
coffee.stdout.read()
|
||||
|
||||
# Compile a string of CoffeeScript into JavaScript.
|
||||
exports.compile: source =>
|
||||
coffee: OS.popen([coffeePath, "--eval", "--no-wrap"])
|
||||
coffee.stdin.write(source).flush().close()
|
||||
checkForErrors(coffee)
|
||||
coffee.stdout.read()
|
||||
|
||||
# Evaluating a string of CoffeeScript first compiles it externally.
|
||||
exports.evalCS: source =>
|
||||
eval(exports.compile(source))
|
||||
|
||||
# Make a factory for the CoffeeScript environment.
|
||||
exports.makeNarwhalFactory: path =>
|
||||
code: exports.compileFile(path)
|
||||
factoryText: "function(require,exports,module,system,print){" + code + "/**/\n}"
|
||||
if system.engine is "rhino"
|
||||
Packages.org.mozilla.javascript.Context.getCurrentContext().compileFunction(global, factoryText, path, 0, null)
|
||||
else
|
||||
# eval requires parentheses, but parentheses break compileFunction.
|
||||
eval("(" + factoryText + ")")
|
||||
81
lib/coffee_script/narwhal/lib/coffee-script.js
Normal file
81
lib/coffee_script/narwhal/lib/coffee-script.js
Normal file
@@ -0,0 +1,81 @@
|
||||
(function(){
|
||||
var File, OS, Readline, checkForErrors, coffeePath;
|
||||
// This (javascript) file is generated from lib/coffee_script/narwhal/coffee-script.coffee
|
||||
// Executes the `coffee` Ruby program to convert from CoffeeScript
|
||||
// to Javascript. Eventually this will hopefully happen entirely within JS.
|
||||
// Require external dependencies.
|
||||
OS = require('os');
|
||||
File = require('file');
|
||||
Readline = require('readline');
|
||||
// The path to the CoffeeScript Compiler.
|
||||
coffeePath = File.path(module.path).dirname().dirname().dirname().dirname().dirname().join('bin', 'coffee');
|
||||
// Our general-purpose error handler.
|
||||
checkForErrors = function checkForErrors(coffeeProcess) {
|
||||
if (coffeeProcess.wait() === 0) {
|
||||
return true;
|
||||
}
|
||||
system.stderr.print(coffeeProcess.stderr.read());
|
||||
throw new Error("CoffeeScript compile error");
|
||||
};
|
||||
// Run a simple REPL, round-tripping to the CoffeeScript compiler for every
|
||||
// command.
|
||||
exports.run = function run(args) {
|
||||
var __a, __b, __c, i, path, result;
|
||||
if (args.length) {
|
||||
__a = args;
|
||||
__b = [];
|
||||
for (i in __a) {
|
||||
if (__a.hasOwnProperty(i)) {
|
||||
path = __a[i];
|
||||
exports.evalCS(File.read(path));
|
||||
__c = delete args[i];
|
||||
__b.push(__c);
|
||||
}
|
||||
}
|
||||
__b;
|
||||
return true;
|
||||
}
|
||||
while (true) {
|
||||
try {
|
||||
system.stdout.write('coffee> ').flush();
|
||||
result = exports.evalCS(Readline.readline());
|
||||
if (result !== undefined) {
|
||||
print(result);
|
||||
}
|
||||
} catch (e) {
|
||||
print(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
// Compile a given CoffeeScript file into JavaScript.
|
||||
exports.compileFile = function compileFile(path) {
|
||||
var coffee;
|
||||
coffee = OS.popen([coffeePath, "--print", "--no-wrap", path]);
|
||||
checkForErrors(coffee);
|
||||
return coffee.stdout.read();
|
||||
};
|
||||
// Compile a string of CoffeeScript into JavaScript.
|
||||
exports.compile = function compile(source) {
|
||||
var coffee;
|
||||
coffee = OS.popen([coffeePath, "--eval", "--no-wrap"]);
|
||||
coffee.stdin.write(source).flush().close();
|
||||
checkForErrors(coffee);
|
||||
return coffee.stdout.read();
|
||||
};
|
||||
// Evaluating a string of CoffeeScript first compiles it externally.
|
||||
exports.evalCS = function evalCS(source) {
|
||||
return eval(exports.compile(source));
|
||||
};
|
||||
// Make a factory for the CoffeeScript environment.
|
||||
exports.makeNarwhalFactory = function makeNarwhalFactory(path) {
|
||||
var code, factoryText;
|
||||
code = exports.compileFile(path);
|
||||
factoryText = "function(require,exports,module,system,print){" + code + "/**/\n}";
|
||||
if (system.engine === "rhino") {
|
||||
return Packages.org.mozilla.javascript.Context.getCurrentContext().compileFunction(global, factoryText, path, 0, null);
|
||||
} else {
|
||||
// eval requires parentheses, but parentheses break compileFunction.
|
||||
return eval("(" + factoryText + ")");
|
||||
}
|
||||
};
|
||||
})();
|
||||
21
lib/coffee_script/narwhal/lib/coffee-script/loader.js
Normal file
21
lib/coffee_script/narwhal/lib/coffee-script/loader.js
Normal file
@@ -0,0 +1,21 @@
|
||||
(function(){
|
||||
var coffeescript, factories, loader;
|
||||
// This (javascript) file is generated from lib/coffee_script/narwhal/loader.coffee
|
||||
coffeescript = null;
|
||||
factories = {
|
||||
};
|
||||
loader = {
|
||||
// Reload the coffee-script environment from source.
|
||||
reload: function reload(topId, path) {
|
||||
coffeescript = coffeescript || require('coffee-script');
|
||||
return (factories[topId] = function() {
|
||||
return coffeescript.makeNarwhalFactory(path);
|
||||
});
|
||||
},
|
||||
// Ensure that the coffee-script environment is loaded.
|
||||
load: function load(topId, path) {
|
||||
return factories[topId] = factories[topId] || this.reload(topId, path);
|
||||
}
|
||||
};
|
||||
require.loader.loaders.unshift([".coffee", loader]);
|
||||
})();
|
||||
19
lib/coffee_script/narwhal/loader.coffee
Normal file
19
lib/coffee_script/narwhal/loader.coffee
Normal file
@@ -0,0 +1,19 @@
|
||||
# This (javascript) file is generated from lib/coffee_script/narwhal/loader.coffee
|
||||
|
||||
coffeescript: null
|
||||
factories: {}
|
||||
|
||||
loader: {
|
||||
|
||||
# Reload the coffee-script environment from source.
|
||||
reload: topId, path =>
|
||||
coffeescript ||= require('coffee-script')
|
||||
factories[topId]: => coffeescript.makeNarwhalFactory(path)
|
||||
|
||||
# Ensure that the coffee-script environment is loaded.
|
||||
load: topId, path =>
|
||||
factories[topId] ||= this.reload(topId, path)
|
||||
|
||||
}
|
||||
|
||||
require.loader.loaders.unshift([".coffee", loader])
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user