Compare commits

..

391 Commits

Author SHA1 Message Date
Geoffrey Booth
e5aa758dda 2.2.4 (#5025)
* Update changelog for 2.2.4

* Bump version to 2.2.4; update output
2018-03-29 20:00:45 -07:00
zdenko
001f97ac39 Fix #5013: return statement as an expression (#5014)
* fix #5013

* disallow statement in the expression
2018-03-17 23:08:43 -07:00
Robert de Forest
ce66a499de Make node --harmony bin/cake test pass on Node 9 (#5012)
* Make `node --harmony bin/cake test` pass on Node 9

Make classMaker() explicitly return an object

* Update Travis and AppVeyor to use --harmony and v9
2018-03-17 23:02:40 -07:00
zdenko
0268505119 Optimize 'for-range-by' loop when 'by' is literal number (#5016)
* optimize 'for-range-by' loop when 'by' is literal number

* small fix
2018-03-15 08:02:13 -07:00
Robert de Forest
5a43b2d7c5 simplified test file skipping (#4996) (#5003)
simplified test file skipping (#4996)
2018-03-12 19:03:44 -07:00
Geoffrey Booth
820942c3d0 2.2.3 (#5010)
* Bump version to 2.2.3; update packages

* Update output

* Update changelog
2018-03-11 13:48:14 -07:00
zdenko
1869f3121d Fix: destructuring assignment with an empty array in object (#5000)
* destructuring assignment with empty array in object

* improvements
2018-03-10 07:39:35 -08:00
zdenko
4c0363fb7c Fix #5004: incorrect compiled code when a destructuring array contains accessors (#5005) 2018-03-07 15:57:31 -08:00
Geoffrey Booth
746b0c7cc6 Code of Conduct (#4992)
* Code of Conduct

* Email address
2018-02-26 22:18:13 -08:00
Geoffrey Booth
b2fe7772c5 Pull request template (#4994) 2018-02-26 17:50:25 -08:00
Geoffrey Booth
23479eb486 Create issue template (#4993) 2018-02-26 17:50:14 -08:00
Geoffrey Booth
63b8543d73 Update output 2018-02-25 01:09:52 -08:00
zdenko
7542a75ff8 get/set example (#4990) 2018-02-25 00:18:57 -08:00
Joseph Lin
0875039d52 [update] copyright year to 2018 (#4988) 2018-02-24 23:40:11 -08:00
Geoffrey Booth
e0833c29ce 2.2.2 (#4986)
* Changelog for 2.2.2

* Bump version to 2.2.2

* Bump dependencies

* Update output
2018-02-22 00:31:14 -08:00
zdenko
72ab6feb2f Fix #4889: for...range loop condition (#4891)
* fix #4889

* test

* move test from 'control_flow' to 'ranges'

* More range tests
2018-02-20 00:46:20 -08:00
zdenko
eb7009268d fix #4898 (#4899) 2018-02-17 16:57:49 -08:00
zdenko
571e9df335 fix #4874 (#4888) 2018-02-08 21:11:11 -08:00
Geoffrey Booth
a73f66bc11 2.2.1 (#4885)
* 2.2.1 changelog

* Bump version to 2.2.1 and update output
2018-02-06 22:28:15 -08:00
zdenko
ba094126e2 Fix #4882: Range not declaring var for the "i" (#4883)
* fix #4882

* test
2018-02-04 13:33:08 -08:00
zdenko
794f65fbd7 Fix #4878: Compile error when using destructuring with a splat or expansion in an array (#4879)
* fix #4878

* improvements

* test

* refactor
2018-02-03 13:35:41 -08:00
Geoffrey Booth
0490eb9a3a 2.2.0 (#4873)
* Changelog for 2.2.0

* Bump version

* Bump package versions

* Fix `cake doc:source` for Docco 0.8.0

* Update output; some text tweaks
2018-02-01 20:14:26 -08:00
zdenko
9e80f6fa67 Fix #2047: Infinite loop possible when for loop with range uses variables (#4853)
* fix #2047

* Additional check for 'step'; tests

* Fix #4105 (#4855)

* Update output

* Throw warning for unsupported runtimes, e.g. Node < 6 (#4839)

* fix #1403 (#4854)

* Update output

* [Change]: Destructuring with non-final spread should still use rest syntax (#4517) (#4825)

* destructuring optimization

* refactor

* minor improvement, fix errors

* minor refactoring

* improvements

* Update output

* Update output

* Fix #4843: bad output when assigning to @prop in destructuring assignment with defaults (#4848)

* fix #4843

* improvements

* typo

* small fix

* Fix #3441: parentheses wrapping expression throw invalid error  (#4849)

* fix #3441

* improvements

* refactor

* Fix #1726: expression in property access causes unexpected results (#4851)

* fix #1726

* Explain what's happening, rather than just linking to an issue

* Updated output

* Optimization

* Update output

* remove casting to number

* cleanup tests
2018-01-31 19:51:43 -08:00
Geoffrey Booth
fc5ab1afa3 Update output 2018-01-31 06:33:17 -08:00
zdenko
0aa77f157a fix #4871 (#4872) 2018-01-31 06:31:52 -08:00
Geoffrey Booth
1849f0db76 Fix #4852, @get @set implicit object (#4867)
* Test cases for #4852, get/set oddities

* Fix soak before accessor call to `get` or `set`

* Fixes #4852: More get/set cases; cleanup style

* Check for tokens' existence before referencing them
2018-01-30 21:17:55 -08:00
zdenko
d86597dbad Fix #3306: trailing comma in a function call in the last line throws a syntax error (#4860)
* fix #3306

* added test
2018-01-30 21:09:50 -08:00
zdenko
bf91781888 Fix #4868: Incorrect ‘Can’t call super with @params’ error (#4869)
* fix #4868

* improvements

* tests
2018-01-30 21:06:54 -08:00
Geoffrey Booth
dcd6de9a77 Update output 2018-01-30 20:51:15 -08:00
zdenko
70b510bcb7 Fix #3933: Missing then doesn’t trigger nearby error (#4862)
* fix #3933

* tests
2018-01-30 15:04:29 -08:00
zdenko
84d596d534 Fix #4437: variable scope in chained calls (#4863)
* fix #4437

* tests
2018-01-29 23:01:25 -08:00
zdenko
c804087ec9 Fix #3921 & #2342: inline function without parentheses used in condition, inline 'else' (#4838)
* fix #3921: inline function without parentheses used in condition

* add grammar rules

* fix issue #2343

* typos

* multiple 'else' in line

* close 'else if'
2018-01-28 17:51:57 -08:00
zdenko
74bd537d6c fix #3909 (#4861) 2018-01-28 02:38:39 -08:00
zdenko
0217ed5505 Fix #1726: expression in property access causes unexpected results (#4851)
* fix #1726

* Explain what's happening, rather than just linking to an issue

* Updated output

* Optimization
2018-01-15 20:03:01 -08:00
zdenko
e53307b46b Fix #3441: parentheses wrapping expression throw invalid error (#4849)
* fix #3441

* improvements

* refactor
2018-01-15 19:32:27 -08:00
zdenko
c8c8c167d1 Fix #4843: bad output when assigning to @prop in destructuring assignment with defaults (#4848)
* fix #4843

* improvements

* typo

* small fix
2018-01-15 19:29:48 -08:00
zdenko
c1283ead45 [Change]: Destructuring with non-final spread should still use rest syntax (#4517) (#4825)
* destructuring optimization

* refactor

* minor improvement, fix errors

* minor refactoring

* improvements

* Update output

* Update output
2018-01-15 19:24:21 -08:00
Geoffrey Booth
3ade25a32c Update output 2018-01-15 19:06:57 -08:00
zdenko
7ea3ea92f3 fix #1403 (#4854) 2018-01-15 16:54:55 -08:00
Geoffrey Booth
a70f1a082e Throw warning for unsupported runtimes, e.g. Node < 6 (#4839) 2018-01-14 23:40:36 -08:00
Geoffrey Booth
2ccbb6b91a Update output 2018-01-14 20:56:26 -08:00
zdenko
e348026073 Fix #4105 (#4855) 2018-01-14 20:16:29 -08:00
Geoffrey Booth
7c6f3788ca Fix #4836: functions named get or set can be used without parentheses when attached to @ (#4837) 2018-01-06 13:58:43 -08:00
Geoffrey Booth
12fcbfc654 2.1.1 (#4835)
* Bump version to 2.1.1

* 2.1.1 changelog

* 2.1.1 updated output
2017-12-29 16:54:57 -08:00
Chris Connelly
38f5963b85 Use free variables for anonymous classes (#4826)
Fixes #4822.
2017-12-28 14:50:12 -08:00
Chris Connelly
ffbe51e374 Set the context of executable class body wrappers (#4828)
Fixes #4827.
2017-12-18 10:51:08 -08:00
Geoffrey Booth
926cb8463c 2.1.0 (#4823)
* Changelog for 2.1.0; remove text from objects section that is no longer valid for CS2/ES2015.

* Update packages

* 2.1.0 build

* Update output

* Correct reference to `//` division, per https://github.com/coffeescript6/discuss/issues/39#issuecomment-347144647
2017-12-10 23:12:33 -08:00
zdenko
b1286752b9 improve elision output (#4824) 2017-12-10 15:22:34 -08:00
zdenko
5eb9dded52 [Enhancement] Computed property keys (#4622) (#4803)
* Computed property keys

* refactor

* improvements

* refactor tests

* fix comments
2017-12-08 22:42:47 -08:00
zdenko
7f5ab7eb0d [Enhancement] CSX fragments syntax (#4802) (#4804)
* CSX fragments

* regex improvement; tests

* regex improvement

* regex improvement

* bug fix; regex

* Fix style

* Split fragment tests
2017-12-08 22:41:02 -08:00
zdenko
5bc85b8f6d Fix #4798: Incorrect output for object rest destructuring inside array destructuring (#4799)
* fix #4798

* additional tests
2017-12-04 08:00:45 -08:00
zdenko
81d1b511f0 Fix #4811: Heregex comments cannot contain three slashes in a row (#4814)
* fix comment with /// in heregex

* cleanup

* improved pattern for comments in heregex; fixed unescaped hashes in lexer.coffee

* improvements

* refactor RegExp

* cleanup

* Improved RegEx
2017-12-03 11:55:26 -08:00
Geoffrey Booth
2dc3f6c87a Cache node_modules for AppVeyor builds (#4817) 2017-12-02 20:49:22 -08:00
Geoffrey Booth
04959162c6 AppVeyor (#4812)
* First attempt at using AppVeyor

* Maybe it doesn't like the leading dot?

* Versions are an array

* Fix tests on Windows: for some reason, Windows requires `coffee` to be executed as `node coffee` (in the context of `spawnSync`, at least)

* Use npm@latest, see if that's less noisy

* Nevermind, only an issue on Node 6

* Better to see the NPM version before npm install
2017-12-01 13:19:48 -08:00
zdenko
f14c7ffa3f Fixes #4684: Elision (#4796)
* Elision

* test

* improvements

* grammar optimization

* cleanup
2017-11-28 21:24:18 -08:00
Geoffrey Booth
64b8dd486a 2.0.3 (#4795)
* Fix #4775: Remove no-longer-correct mention of the docs using text/coffeescript

* 2.0.3 changelog

* Update output for 2.0.3

* Bump date
2017-11-26 19:29:08 -08:00
Geoffrey Booth
7864acabc3 Fix #4790: Double-check that we're not creating a bound generator function, even if the yield got stuffed inside a compiler-generated IIFE (#4792) 2017-11-21 17:14:32 -08:00
zdenko
9812d28748 Fix #4787: Destructuring of objects within arrays can generate invalid JavaScript (#4791)
* Fix #4787

* simplify condition
2017-11-20 20:00:27 -08:00
zdenko
555c22af58 fix #4580 (#4793) 2017-11-20 09:15:19 -08:00
Geoffrey Booth
3f4b03bcff Fix #4763: Comments at beginning or end of REPL input shouldn't throw errors (#4764) 2017-11-19 11:37:08 -08:00
Geoffrey Booth
a706a64a6d Fix #4765: .map file should always have the same output base filename as the generated .js file (#4784) 2017-11-16 13:30:40 -08:00
Geoffrey Booth
637fe305a6 Fix #4774: export default followed by an object should always work, even if the object contains braces. default shouldn't suppress a newline, we should handle it in the grammar the same way returning an implicit object is handled (#4783) 2017-11-15 21:38:05 -08:00
Geoffrey Booth
bd824c73dd Fix #4780: Don't mutate the options object when compiling and transpiling, so that options are correct on subsequent iterations (#4785) 2017-11-14 08:13:22 -08:00
Geoffrey Booth
cbc695b831 2.0.2 (#4758)
* Give the notes about `super` and `this` their own section in the docs

* 2.0.2 changelog

* 2.0.2 release output

* Rewrite
2017-10-26 18:29:45 -07:00
Geoffrey Booth
f3375e798c Fix #4756: When moving comments from the children of an Existence, we need to search all its descendants, not just the immediate children (#4757) 2017-10-25 22:15:40 -07:00
Geoffrey Booth
e2308093e4 Fix #4752: Error on calling super with @params in a derived class constructor (#4754)
* Fix #4752: Error on calling super with @params in a derived class constructor

* Catch calls to super with not-top-level @params
2017-10-25 22:15:05 -07:00
Geoffrey Booth
0dc4755920 Fix #4747: Flow local variables (#4753)
* Fix #4706: Comments before a PARAM_START token stay before that token

* Simplify nodes

* Add function-in-function test

* Fix #4706: Comments after class name should go after the identifier that's after `class`, not the variable assigned to

* Fix #4706: Top-level identifiers with trailing comments get wrapped in parentheses (around the comment too) so that Flow doesn't interpret it as a JavaScript label

* Cleanup

* If the source has parentheses wrapping an identifier followed by a block comment, output those parentheses rather than optimizing them away; this is a requirement of Flow, to distinguish from JavaScript labels

* More tests for Flow comments

* For local variables with trailing inline herecomments, output the comments up in the variable declarations line for Flow compatibility
2017-10-19 06:56:59 -07:00
Geoffrey Booth
6faa7f2b35 Fix #4706: Flow generics (#4736)
* Fix #4706: Comments before a PARAM_START token stay before that token

* Simplify nodes

* Add function-in-function test

* Fix #4706: Comments after class name should go after the identifier that's after `class`, not the variable assigned to

* Fix #4706: Top-level identifiers with trailing comments get wrapped in parentheses (around the comment too) so that Flow doesn't interpret it as a JavaScript label

* Cleanup

* If the source has parentheses wrapping an identifier followed by a block comment, output those parentheses rather than optimizing them away; this is a requirement of Flow, to distinguish from JavaScript labels

* More tests for Flow comments
2017-10-18 17:22:02 -07:00
geebo
063c2d1f56 Fix import/export list bug with aliased keywords (#4744) 2017-10-12 11:47:12 -07:00
Chris Connelly
4d4e47bfb2 Fix #4724 (#4737)
The handling of hoisted nodes in class bodies was incorrect, as the node
was being unwrapped *before* checking if it was hoisted, meaning nodes
that should have been hoisted would be output normally.

This affected `PassthroughLiteral`s as they were wrapped in a `Value`.
2017-10-07 11:32:43 -07:00
Geoffrey Booth
22fb31e317 Transpile REPL (#4729)
* Fix #4725: apply transpile option to require’d .coffee files

* Use the current module’s options if it has any, before going searching up the tree

* Don’t mutate passed-in options object

* If the REPL is run with `--transpile`, turn transpilation on for both the current REPL input and any files imported by that input

* Use the command.coffee machinery for parsing arguments

* Fix test for Windows
2017-10-04 17:50:25 -07:00
Geoffrey Booth
a2037e799f Fix #4725: apply transpile option to require’d .coffee files (#4728)
* Fix #4725: apply transpile option to require’d .coffee files

* Use the current module’s options if it has any, before going searching up the tree

* Don’t mutate passed-in options object
2017-10-04 17:49:59 -07:00
Geoffrey Booth
694e69d872 Fix #4727: Tests failing in Windows (#4731)
* ?

* ??

* Revert the coffee.EXE approach

* Explicitly define the PATH to include only the folders we need

* Get spawnSync working in Windows

* Simplify test to be cross-platform
2017-10-02 22:19:32 -07:00
Matthew Ryan
bb2871fdde Allow applying 'get'/'set' property to a bracketless object (#4730) 2017-10-02 11:10:43 -07:00
Geoffrey Booth
08e00331dd Fix #3440: --stdio and --map don’t make sense to use together (#4721) 2017-09-27 00:02:30 -07:00
Geoffrey Booth
0b0a9ef2c4 2.0.1 (#4719)
* 2.0.1 changelog

* Version bump to 2.0.1
2017-09-26 20:16:16 -07:00
Geoffrey Booth
9df1457c55 Fix #4703, 4713: Transpile fixes (#4717)
* Show an appropriate error if the user tries to use --transpile via the CLI and babel-core isn’t installed

* Update documentation around global/local

* Fix #4713: Use Babel’s built-in `filename` option to let Babel search for its options, rather than us doing so

* Improve transpilation docs

* Colons are good

* Docs cleanup

* Rewrite transpilation docs

* Better identifier for compiled scripts that didn’t come from files; better resolving of paths
2017-09-26 09:20:13 -07:00
James Kyle
22f92f23ae Add example of comment include type annotation (#4705)
* Add example of comment include type annotation

* build website
2017-09-25 18:25:55 -07:00
Easy Bills
cd516b954f Update ASCII logo (#4718)
Attempt to reproduce the official logo in ASCII :)
2017-09-25 12:13:30 -07:00
Chris Connelly
27eff5ca77 Fix #4464: backticked expressions in class body (#4712)
* Fix #4464: backticked expressions in class body should be left in the body, not hoisted

* Fix #4464: backticked expressions in class body should be left in the body, not hoisted

* Simplify fix for #4464

This uses more of the existing machinery for moving class body
expressions into the initializer.

* Clarify the purpose of Class::addInitializerExpression

* Further clarify the purpose of Class::addInitializerExpression

* Add reference to class fields; format
 comment wrapping

* Reapply 1d3af8c432, that got lost because of rebase/force-push shenanigans

* Updated output
2017-09-20 19:11:05 -07:00
Geoffrey Booth
5cbd25f5d4 Docs fixes (#4707)
* Mobile Safari needs the code to be >= 16px

* Buttons that just run the code shouldn’t have a label, since in all the other examples the label signifies the command to be run

* Use Bootstrap’s breakpoints

* Use Bootstrap’s styling for the <code> element, to avoid misaligned baseline

* Updated output

* Fix #4704: use replaceState, so that back/forward only happen for user clicks on links; opening and closing Try CoffeeScript doesn’t count as a new history entry, and closing it retrieves the previous URL

* Fix #4702: Some changelog entries are more equal than others

* Updated output

* Eliminate the 1px jitter when initializing code editors

* On first time opening Try CoffeeScript, use just #try as the hash

* Update output

* Increase general body line spacing

* Code styling per Jeremy

* Don’t let the main text column grow unreasonably wide

* Give list items some modest bottom margin (and use ems whenever possible)

* Updated output
2017-09-20 13:10:48 -07:00
Jeremy Ashkenas
eb127923a7 Merge pull request #4708 from jz5/master
Fix link to logo
2017-09-19 11:37:06 -04:00
jz5
42da56deb1 Fix link to logo 2017-09-19 16:47:32 +09:00
Jeremy Ashkenas
81260bff7d boom 2017-09-18 18:23:27 -04:00
Jeremy Ashkenas
35f784bcdf Fixes #4703 — Don't depend on Babel in package.json 2017-09-18 17:14:01 -04:00
Jeremy Ashkenas
c17b6b8863 fix the code popping 2017-09-18 16:06:11 -04:00
Jeremy Ashkenas
1965996933 slightly less cramped code 2017-09-18 14:06:45 -04:00
Jeremy Ashkenas
a67dfae985 Tweaking font sizes. 2017-09-18 14:04:04 -04:00
Jeremy Ashkenas
1cb733989c Removing slightly defensive and slightly incorrect 'why coffeescript' section 2017-09-18 13:56:02 -04:00
Geoffrey Booth
a2a2e769c3 Update docs output for 2.0.0 2017-09-18 08:31:07 -07:00
Geoffrey Booth
19231dbcad 2.0.0 (#4701)
* Bump version to 2.0.0; bump dependencies versions

* Make v2 docs the primary docs; jettison the v1 docs’ source: whenever the v1 docs need to be rebuild in the future, that can be done on the `1` branch and copied over; simplify folder tree

* Updated v1 docs that reflect that v2 is out and have updated paths to reflect that the v2 docs are now the primary docs, and the v1 docs only live under /v1/

* Add Google Analytics; track navigation, editing code and running code

* 2.0.0 changelog

* Fix link to root docs

* No more @next; installing local copy should be --save-dev

* Analytics on the browser-based tests page should prove fascinating . . .

* Update annotated source

* Add note to changelog clarifying scope
2017-09-18 08:19:19 -07:00
Geoffrey Booth
aecc115c79 Fix #4686: if a CSX interpolation contains comments, not just inner CSX (JSX) tags, it needs to be wrapped in braces (#4689) 2017-09-16 12:03:33 -07:00
Geoffrey Booth
4c41831474 CoffeeScript 2 announcement (#4695)
* CoffeeScript 2 announcement, first draft

* Lydell's notes

* Jeremy’s notes; Rollup is not a transpiler

* Revise “unsupported features” section

* Fix links, invalid HTML

* Announcing CoffeeScript 2 HTML page

* Link to the announcement

* Add some references

* Fix anchors

* Better example
2017-09-16 11:57:18 -07:00
Geoffrey Booth
659f1b3c4c Update transpilation docs (#4700) 2017-09-16 09:32:48 -07:00
Geoffrey Booth
f51c1a150b Option to transpile with Babel (#4697)
* Upgrade Babeli (now babel-minify) which fixes the bug that was forcing us to run Babel twice for transpilation

* Add --transpile option (WIP)

* Node API always compiles a string, so it doesn’t need the option to pass a path to an options file, it can always just pass an object to `transpile`; get `transpile` working with `eval`

* Not allowing argument to `--transpile` so don’t need to cover so many cases

* Don’t need to worry about `sourceMaps` option to pass to Babel, `inputSourceMap` overrides it

* Rewrite Webpack test to use Node API

* Make the compiler safe again for browsers and Webpack/Browserify

* Node version of CoffeeScript.compile passes reference to Babel if transpile is requested

* Test Node API for transpile option

* Test for merged source maps

* Test for Node API error message

* Only stop searching for Babel options if a package.json has a truthy "babel" key

* Update docs
2017-09-15 06:58:18 -07:00
Geoffrey Booth
970f31c292 Fix #4342: Always output sourcesContent property as part of source map, whether inline map or written-to-disk map (#4698) 2017-09-11 22:38:48 -07:00
Geoffrey Booth
d172405244 First pass at using Travis CI (#4690) 2017-09-08 22:01:11 -07:00
Geoffrey Booth
44ebfdb764 Merge branch '2'
# Conflicts:
#	lib/coffee-script/nodes.js
#	src/nodes.coffee
#	test/arrays.coffee
2017-09-07 21:08:04 -07:00
Julian Rosse
1b8f1af287 [CS2] Fix destructuring bugs #4673 and #4657 (#4683)
* destructuring fixes [Fixes #4673] [Fixes #4657]

* test for destructured @prop

* Add another test to cover #4657 cases

* don't declare actual params
2017-09-07 10:06:35 -07:00
Geoffrey Booth
e7073bc5d9 Update CS2 docs per #4688 2017-09-07 08:05:04 -07:00
Geoffrey Booth
63d3b699d7 [CS2] Fix CS2 docs mobile issues, improve performance (#4688)
* Get rid of offcanvas slide-in; fix sidebar

* We need to transpile docs.coffee, since Safari 9 throws an error on it and that’s too new a browser not to support; but this should also speed things up

* Fix some tabs

* Fix scrollbar

* Use Highlight.js to format placeholder code (during compilation, not rendering) before CodeMirror loads; match Highlight.js styles to CodeMirror styles as best we can

* Improve hash management

* Initialize CodeMirror on demand, on mouseover a particular code example, rather than all examples on startup

* Replace highlight.js with Prism for placeholder syntax highlighting

* Scratch Prism, use CodeMirror itself to do Node-based syntax highlighting, so that on CodeMirror initialization there’s no flash from mismatched highlighting

* Update packages; there’s a new version of Jison! (doesn’t change much)

* Fix mobile issues: use SVG play button icon, to avoid iOS blue square play button; make the code editor text 16px size explicit, to avoid unwanted mobile zoom; make the ‘code play’ buttons work even if the code examples are in placeholder (non-editable) mode, in case a user hasn’t moused over/tapped them

* Update docs output

* Whoops, CodeMirror is only a devDependency
2017-09-07 08:01:12 -07:00
Geoffrey Booth
458440e57b 2.0.0-beta5 docs 2017-09-02 12:55:56 -07:00
Geoffrey Booth
df9d4a2343 [CS2] 2.0.0-beta5 (#4682)
* Upgrade docs to Bootstrap 4 beta, including refactoring styles; upgrade docs jQuery and CodeMirror

* Better style the docs for mobile, including Try CoffeeScript

* Fix #4642, erroneous statement about named functions

* Update packages

* 2.0.0-beta5
2017-09-02 12:48:38 -07:00
Geoffrey Booth
9e043bbae7 [CS2] Fix async tests (#4680)
* Get `coffee` command working again in Node 6, by converting the ‘await’ wrapper in the REPL to use a Promise instead of the ‘await’ keyword; add tests for REPL ‘await’ wrapper, including test to skip async tests if the runtime doesn’t support them

* Fix async tests: now if a test function is a Promise (which an `await` function is), we add it to an array of async test functions and wait for them all to resolve before finishing the test run, so that if any async tests fail we see those failures in the output

* Code review

* Unnecessary

* Let's support Node 6+ if we can

* Simplify the returned promise

* Simplify async check
2017-09-01 12:26:47 -07:00
Geoffrey Booth
671486989f [CS2] Don’t require async/await support to run coffee (#4679)
* Get `coffee` command working again in Node 6, by converting the ‘await’ wrapper in the REPL to use a Promise instead of the ‘await’ keyword; add tests for REPL ‘await’ wrapper, including test to skip async tests if the runtime doesn’t support them

* Code review

* Let's support Node 6+ if we can
2017-09-01 12:19:15 -07:00
Geoffrey Booth
4a4f752204 Fix #3098: Suppressed newline should be unsuppressed by semicolon (#4669) 2017-09-01 07:09:36 -07:00
Julian Rosse
b20e52da99 [CS2] use _extends utility instead of Object.assign() for object spreads (#4675)
* _extends utility instead of Object.assign()

* eqJS test for _extends

* Test that a user-defined function named `_extends` doesn’t conflict with our utility function

* IE8 polyfill note in docs
2017-09-01 07:09:16 -07:00
Chris Connelly
5525b2ba01 Merge pull request #4652 from GeoffreyBooth/bug-fix-4651
[CS2] Fix #4651: object spread destructuring bug
2017-09-01 13:10:49 +01:00
Geoffrey Booth
fe5ff39ca2 [CS2] Fix v3 source map (#4671)
* Per discussion in #3075: if `sourceFiles` is unspecified, but `filename` is, use `filename`; output null instead of an empty string for `sources` or `sourceRoot`

* Update source map tests to reflect that now we return null instead of empty strings; check generated sources array

* Update source map documentation; still leave more obscure options undocumented

* Follow the TypeScript compiler’s example regarding v3SourceMap, but output empty strings instead of made-up filenames

* Have `sources` default to ‘<anonymous>’
2017-09-01 01:06:45 -07:00
Geoffrey Booth
906bedf93a Fix #1768: Ignore space after :: (#4670) 2017-08-30 22:43:17 -07:00
Julian Rosse
6f961a20dd [CS2] Refine #4666: add parens to chained do IIFE with params (#4672)
* add parens to chained do iife [Fixes #3736]

* remove debug code

* fixes from code review

* handle iife with params

* add test w/ destructured param from code review
2017-08-30 22:42:50 -07:00
Julian Rosse
e54b8a1009 [CS2] add parens to chained do IIFE (#4666)
* add parens to chained do iife [Fixes #3736]

* remove debug code

* fixes from code review
2017-08-29 14:17:56 -07:00
Geoffrey Booth
d7d69a4a18 Fix #4576: Allow accessing a property of a function literal (like .call) via chaining syntax (#4665) 2017-08-28 13:16:22 -07:00
Geoffrey Booth
eb38dba5d6 Only unescape newlines for CSX; updated compiled output 2017-08-27 21:37:21 -07:00
zdenko
6cea181ff1 [CS1] fix #4260 and #1349: splat error with soak properties or expressions (#4643)
* fix splat error with soak properties or expressions

* Add test based on #4260

* Add test based on #1349

* remove 'void 0' replacement; add Splat::compileNode
2017-08-27 16:25:13 -07:00
Geoffrey Booth
9ff82fe17b Fix #4589: Unquote all interpolated strings, not just CSX ones, so that quotation marks are not unnecessarily escaped in backtick-delimited strings/template literals (#4660) 2017-08-27 15:16:31 -07:00
zdenko
5713b7eb6c [CS2] Fix #4260 and #1349: Splat error with soak properties or expressions (#4644)
* fix splat error with soak properties or expressions

* Add test based on #4260

* Add test based on #1349

* tests for the leading splat variant

* test for spaced prefix ...

* fixed 'if' statement in parens

* fixed replacing 'void 0' with '[]'

* remove 'void 0' replacement; add Splat::compileNode

* Use LEVEL_OP; follow style better
2017-08-27 15:11:14 -07:00
Geoffrey Booth
7c627f9dfd [CS2] Fix #3709, #3789: ‘throw’ an ‘if’, ‘for’, ‘switch’, ‘while’ (#4664)
* Fix #3709: throwing an if, for, switch or while should throw the returned value of the statement/loop

* Fix #3789: don’t throw a throw (unless it’s in a closure)

* LEVEL_LIST works better than a list of node types
2017-08-25 11:11:10 -07:00
Geoffrey Booth
c81e2d4767 Fix #4575: Check for the previous token’s existence before comparing against it (#4663) 2017-08-24 00:05:26 -07:00
Geoffrey Booth
3dd458267b [CS2] Fix #2870: Allow specifying output filename (#4661)
* Fix #2870: If --output ends with a filename, and the input is a file and not a path, save as the desired filename

* If an output path ends in a slash, force saving into an output folder even if that folder name would contain a period (e.g. /scripts.js/); if output filename is only periods, treat it as a path

* Restrict exceptions
2017-08-24 00:03:57 -07:00
Geoffrey Booth
892c4699dd Fix #4578: Never look back past the start of the token stream (#4662) 2017-08-24 00:02:57 -07:00
Geoffrey Booth
40c351135a [CS2] Fix #4629: interpolations (whether in strings or CSX tags) with only comments (#4659)
* Fix #4629: interpolations (whether in strings or CSX tags) that contain nothing but comments should not be optimized out

* Template literals need an expression inside their interpolations, so if we only have a comment to put in there, toss in an empty string as well
2017-08-23 23:34:59 -07:00
Geoffrey Booth
a3b08e1bef [CS2] Fix #4209: --require for filenames that are invalid identifiers (#4658)
* When using --require, check that the variable we’re creating from the required file/module is a valid identifier name before assigning to it; fixes #4209

* We don’t need no stinkin’ regex
2017-08-23 06:51:14 -07:00
Geoffrey Booth
44a27c6204 Fix #4558: Stack trace line numbers for scripts that compile CoffeeScript (#4645)
* Don't throw an error in the console when loading a try: URL

* Handle the possibility of compiling multiple scripts with the same filename, or multiple anonymous scripts

* Fix #4558: Much more robust caching of sources and source maps, more careful lookup of source maps especially for CoffeeScript code compiled within a Coffee script (. . . within a Coffee script, etc.)

* Reimplement `cake release` to just use the shell to avoid the issues plaguing that command (something to do with module caching perhaps)
2017-08-23 06:50:46 -07:00
Zdenko Vujasinovic
c212e6e9ab refactor 2017-08-22 21:19:56 +02:00
Zdenko Vujasinovic
5a709ed4a8 improve variable declaration 2017-08-22 10:48:12 +02:00
Zdenko Vujasinovic
2491d3286d fix assign in nested properties
fix assign in nested properties
2017-08-21 21:16:28 +02:00
Julian Rosse
1a6477adec resolve merge conflicts 2017-08-21 10:39:46 -04:00
Julian Rosse
2149c3561b ensure Value; breaking test for {a={b...}} = c 2017-08-21 10:34:33 -04:00
Zdenko Vujasinovic
232041db2a fixed issue with nested properties 2017-08-21 16:22:17 +02:00
Ben Drechsel
4623bf5bba Docs: Define functions used in loop examples (#4653)
* Cherrypick changes from messy branch

* Reorder function defs
2017-08-18 17:15:52 -07:00
Zdenko Vujasinovic
2664c2c108 small fix 2017-08-18 08:51:11 +02:00
Zdenko Vujasinovic
f9367bacf1 fix object spread destructuring bug: #4651 2017-08-18 04:06:37 +02:00
zdenko
aef54aeaf7 [CS2] Fix #4631: Expansion that becomes rest parameter causes runtime error (#4634)
* expansion-rest bug fix

* tests; improved implicit call recognition with dots on the left in the `rewriter`

* whitespace cleanup

* more tests
2017-08-17 13:13:52 -07:00
Chris Connelly
eff160eeb7 Merge pull request #4640 from GeoffreyBooth/generated-variables-in-function-parameters
[CS2] Fix #4413: Generated variables in function parameters
2017-08-15 14:19:21 +01:00
Geoffrey Booth
911c21f7be Update test to prove that there's no collision in generated variables 2017-08-14 03:06:38 +00:00
Geoffrey Booth
52795587ec If compiling a function parameter creates any generated variables (e.g. ref), shift the declarations for those variables into the parent scope; fixes #4413 2017-08-14 03:00:01 +00:00
Geoffrey Booth
3a6ffa6a85 Clean up function parameter compilation to get name for scope 2017-08-14 02:42:01 +00:00
Geoffrey Booth
e3c2c0397a 2.0.0-beta4 docs 2017-08-03 18:18:31 -07:00
Geoffrey Booth
ae7f97b639 2.0.0-beta4 (#4628)
* 2.0.0-beta4 changelog

* Recompile parser, update browser compiler

* Updated annotated source and browser tests

* Bump version to 2.0.0-beta4
2017-08-03 18:11:19 -07:00
Julian Rosse
2653b3bbf9 Refine sameLine implicit object tagging [Fixes #4568] (#4598) 2017-08-02 22:31:51 -07:00
Michal Brašna
64c790f299 [CS2] CLI: Propagate SIGINT and SIGTERM signals when node is forked (#4625)
* Propagate SIGINT and SIGTERM signals when node is forked

* Use for loop for consistency
2017-08-02 22:20:23 -07:00
zdenko
cbf035fca9 [CS2] CSX spread attributes: <div {props…} /> (#4607)
* CSX spread attributes: <div {props...} />

* whitespace cleanup

* Style

* valid CSX attributes

* added comments; cleanup

* Fixed allowed CSX properties.

* Cleanup

* Typo

* Improved RegEx

* Reworked CSX attributes

* small fix for CSX attribute validation

* cleanup

* tests

* fix nested assignement; remove unused variable

* cleanup; improve tests

* fix esoteric case; improve tracking nested splats in CSX tag
2017-08-02 21:00:39 -07:00
zdenko
a118ec7cc9 [CS2] fix for “do super in constructor” bug (#4627)
* bug fix 'do super' in constructor

* improve regex
2017-08-02 19:41:01 -07:00
Geoffrey Booth
6d21dc5495 [CS2] Comments (#4572)
* Make `addLocationDataFn` more DRY

* Style fixes

* Provide access to full parser inside our custom function running in parser.js; rename the function to lay the groundwork for adding data aside from location data

* Fix style.

* Fix style.

* Label test comments

* Update grammar to remove comment tokens; update DSL to call new helper function that preserves comments through parsing

* New implementation of compiling block comments: the lexer pulls them out of the token stream, attaching them as a property to a token; the rewriter moves the attachment around so it lives on a token that is destined to make it through to compilation (and in a good placement); and the nodes render the block comment. All tests but one pass (commented out).

* If a comment follows a class declaration, move the comment inside the class body

* Style

* Improve indentation of multiline comments

* Fix indentation for block comments, at least in the cases covered by the one failing test

* Don’t reverse the order of unshifted comments

* Simplify rewriter’s handling of comments, generalizing the special case

* Expand the list of tokens we need to avoid for passing comments through the parser; get some literal tokens to have nodes created for them so that the comments pass through

* Improve comments; fix multiline flag

* Prepare HereComments for processing line comments

* Line comments, first draft: the tests pass, but the line comments aren’t indented and sometimes trail previous lines when they shouldn’t; updated compiler output in following commit

* Updated compiler, now with line comments

* `process` doesn’t exist in the browser, so we should check for its existence first

* Update parser output

* Test that proves #4290 is fixed

* Indent line comments, first pass

* Compiled output with indented line comments

* Comments that start a new line shouldn’t trail; don’t skip comments attached to generated tokens; stop looking for indentation once we hit a newline

* Revised output

* Cleanup

* Split “multiline” line comment tokens, shifting them forward or back as appropriate

* Fix comments in module specifiers

* Abstract attaching comments to a node

* Line comments in interpolated strings

* Line comments can’t be multiline anymore

* Improve handling of blank lines and indentation of following comments that start a new line (i.e. don’t trail)

* Make comments compilation more object-oriented

* Remove lots of dead code that we don’t need anymore because a comment is never a node, only a fragment

* Improve eqJS helper

* Fix #4290 definitively, with improved output for arrays with interspersed block comments

* Add support for line comments output interspersed within arrays

* Fix mistake, don’t lose the variable we’re working on

* Remove redundant replacements

* Check for indentation only from the start of the string

* Indentations in generated JS are always multiples of two spaces (never tabs) so just look for 2+ spaces

* Update package versions; run Babel twice, once for each preset, temporarily until a Babili bug is fixed that prevents it from running with the env preset

* Don’t rely on `fragment.type`, which can break when the compiler is minified

* Updated generated docs and browser compiler

* Output block comments after function arguments

* Comments appear above scope `var` declarations; better tracking of generated `JS` tokens created only to shepherd comments through to the output

* Create new FuncGlyph node, to hold comments we want to output near the function parameters

* Block comments between `)` and `->`/`=>` get output between `)` and `{`.

* Fix indentation of comments that are the first line inside a bare mode block

* Updated output

* Full Flow example

* Updated browser compiler

* Abstract and organize comment fragment generation code; store more properties on the comment fragment objects; make `throw` behave like `return`

* Abstract token insertion code

* Add missing locationData to STRING_START token, giving it the locationData of the overall StringWithInterpolations token so that comments attached to STRING_START end up on the StringWithInterpolations node

* Allow `SUPER` tokens to carry comments

* Rescue comments from `Existence` nodes and `If` nodes’ conditions

* Rescue comments after `\` line continuation tokens

* Updated compiled output

* Updated browser compiler

* Output block comments in the same `compileFragments` method as line comments, except for inline block comments

* Comments before splice

* Updated browser compiler

* Track compiledComments as a property of Base, to ensure that it’s not a global variable

* Docs: split up the Usage section

* Docs for type annotations via Flow; updated docs output

* Update regular comments documentation

* Updated browser compiler

* Comments before soak

* Comments before static methods, and probably before `@variable =` (this) assignments generally

* Comments before ‘if exists?’, refactor comment before ‘if this.var’ to be more precise, improve helper methods

* Comments before a method that contains ‘super()’ should output above the method property, not above the ‘super.method()’ call

* Fix missing comments before `if not` (i.e. before a UNARY token)

* Fix comments before ‘for’; add test for comment before assignment if (fixed in earlier commit)

* Comments within heregexes

* Updated browser compiler

* Update description to reflect what’s now happening in compileCommentFragments

* Preserve blank lines between line comments; output “whitespace-only” line comments as blank lines, rather than `//` following by whitespace

* Better future-proof comments tests

* Comments before object destructuring; abstract method for setting comments aside before compilation

* Handle more cases of comments before or after `for` loop declaration lines

* Fix indentation of comments preceding `for` loops

* Fix comment before splat function parameter

* Catch another RegexWithInterpolations comment edge case

* Updated browser compiler

* Change heregex example to one that’s more readable; update output

* Remove a few last references to the defunct HERECOMMENT token

* Abstract location hash creation into a function

* Improved clarity per code review notes

* Updated browser compiler
2017-08-02 19:34:34 -07:00
Chris Connelly
6c9cf37811 [CS2] Support await in REPL without wrapper function (#4604)
* Support `await` in REPL without wrapper function

Rather than compiling top-level await expressions directly, which will
always throw a syntax error, the REPL wrapper will now wrap them in a
closure and handle the returned promise before calling back to the REPL.

Fixes #4603.

* Cancel REPL callback after a SIGINT during an awaited evaluation

This change allows users to 'cancel' awaited expressions that they don't
want to see the result of. Ultimately, this *does not* prevent the
expression from completing (e.g. for `await fetch(url)`, `url` will
still be downloaded, but the user won't have to wait for it to finish
and the result won't be printed).
2017-07-24 12:47:14 -07:00
zdenko
557351156e [CS2] Fix object spread nested properties (#4611)
* fix for object spread nested properties: obj2 = {obj.c..., obj["b"]["c"]..., d: 55}

* tests
2017-07-22 17:44:35 -07:00
Danny McClanahan
4e57ca6833 [CS2] Add #! support for executable scripts on Linux. (#3946)
* Add #! support for executable scripts on Linux.

Pass arguments to executable script unchanged if using "#!/usr/bin/env
coffee". (Previously, "./test.coffee -abck" would be turned into "-a -b -c -k",
for example.)

Fixes #1752.

* refactor option parsing

clean up parsing code and in the process fix oustanding bug where coffeescript
modified arguments meant for an executable script

* address comments

* intermediate save

* add note saying where OptionParser is used in coffee command

* add some more work

* fix flatten functions

* refactor tests

* make argument processing less confusing

* add basic test

* remove unused file

* compilation now hangs

* remove unnecessary changes

* add tests!!!

* add/fix some tests

* clarify a test

* fix helpers

* fix opt parsing

* fix infinite loop

* make rule building easier to read

* add tests for flag overlap

* revamp argument parsing again and add more thorough testing

* add tests, comment, clean unused method

* address review comments

* add test for direct invocation of shebang scripts

* move shebang parsing test to separate file and check for browser

* remove TODO

* example backwards compatible warnings

* add correct tests for warning 1

* add tests for warnings

* commit output js libs and update docs

* respond to review comments

also add tests for help text

* respond to review comments

* fix example output

* Rewrite argument parsing documentation to be more concise; add it to sidebar and body; add new output

* Don’t mention deprecated syntax; clean up variable names
2017-07-19 16:25:06 -07:00
Geoffrey Booth
d287a798cc 1.12.7 docs 2017-07-17 00:25:02 -07:00
Julian Rosse
852c5786ee [CS2]: Fix #4591: multiple accesses after super (#4592)
* support multiple accesses after super [Fixes #4591]

* addtl tests from code review
2017-07-13 13:15:18 -07:00
Julian Rosse
50674cb351 [CS2] Fix #3199: throw multiline implicit object (#4599)
* throw multiline implicit object [Fixes #3199]

* restrict to Object

* test error on non-object

* test error on call indented non-object
2017-07-09 10:28:50 -07:00
zdenko
3be9038028 Spread syntax triple dots on either right or left (#4606)
* Spread dots on both sides: {a:1, ...obj1, obj2...},  [a..., ...b], f ...a, b...

* Optimization
2017-07-08 22:32:02 -07:00
zdenko
35eb58fae8 fix #4577; renamed destructured parameters with same default value (#4596) 2017-07-05 19:04:52 -07:00
Julian Rosse
ab52fd75c2 [CS2] Fix #4467: tagged template literal call (#4601)
* working on making Invocation a grammar Value

* cleanup

* update location when adding value properties

* test for #4467

* more location data tests
2017-07-05 13:58:36 -07:00
Wesley Moore
56725ad275 [CS2] Fix a couple of typos (#4602) 2017-07-03 22:10:03 -07:00
Julian Rosse
8ea7edf02a merge master (#4597) 2017-07-03 20:52:49 -07:00
Geoffrey Booth
704924c3cd 2.0.0-beta3 (#4594)
* Don’t confuse the syntax highlighter

* Comment Assign::compilePatternMatch a bit

* Assignment expressions in conditionals are a bad practice

* Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[`

* Correct comment

* object destructuring

* Allow custom position of the rest element.

* Output simple array destructuring assignments to ES2015

* Output simple object destructured assignments to ES2015

* Compile shorthand object properties to ES2015 shorthand properties

This dramatically improves the appearance of destructured imports.

* Don’t confuse the syntax highlighter

* Comment Assign::compilePatternMatch a bit

* Assignment expressions in conditionals are a bad practice

* Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[`

* object destructuring

* Allow custom position of the rest element.

* rest element in object destructuring

* rest element in object destructuring

* fix string interpolation

* merging

* fixing splats in object literal

* Rest element in parameter destructuring

* merging with CS2

* merged with CS2

* Add support for the object spread initializer. https://github.com/tc39/proposal-object-rest-spread/blob/master/Spread.md

* Fix misspellings, trailing whitespace, other minor details

* merging with beta2

* refactor object spread properties

* small fix

* - Fixed object spread function parameters.
- Clean up "Assign" and moved all logic for object rest properties in single method (compileObjectDestruct).
- Add helper function "objectWithoutKeys" to the "UTILITIES" for use with object rest properties,
  e.g. {a, b, r...} = obj => {a, b} = obj, r = objectWithoutKeys(...)
- Clean up "Obj" and moved all logic for object spread properties in single method (compileSpread).
- Clean up "Code".
- Add method "hasSplat" to "Obj" and "Value" for checking if Obj contains the splat.
- Enable placing spread syntax triple dots on either right or left, per #85 (https://github.com/coffeescript6/discuss/issues/85)

* Fixed typos

* Remove unused code

* Removed dots (e.g. splat) on the left side from the grammar

* Initial release for deep spread properties, e.g. obj2 = {obj.b..., a: 1} or {obj[b][c]..., d: 7}
Tests need to be prepared!

* 1. Object literal spread properties

Object literals:
- obj = { {b:{c:{d:1}}}..., a:1 }

Parenthetical:
- obj = { ( body ), a:1 }
- obj = { ( body )..., a:1 }

Invocation:
- obj = { ( (args) -> ... )(params), a:1 }
- obj = { ( (args) -> ... )(params)..., a:1 }
- obj = { foo(), a:1 }
- obj = { foo()..., a:1 }

2. Refactor, cleanup & other optimizations.

* Merged with 2.0

* Cleanup

* Some more cleanup.

* Fixed error with freeVariable and object destructuring.

* Fixed errors with object spread properties.

* Improvements, fixed errors.

* Minor improvement.

* Minor improvements.

* Typo.

* Remove unnecessary whitespace.

* Remove unnecessary whitespace.

* Changed few "assertErrorFormat" tests since parentheses are now allowed in the Obj.

* Whitespace cleanup

* Comments cleanup

* fix destructured obj param declarations

* refine fix; add test

* Refactor function args ({a, b...})

* Additional tests for object destructuring in function argument.

* Minor improvement for object destructuring variable declaration.

* refactor function args ({a, b...}) and ({a, b...} = {}); Obj And Param cleanup

* fix comment

* Fix object destructuring variable declaration.

* more tests with default values

* fix typo

* Fixed default values in object destructuring.

* small fix

* Babel’s tests for object rest spread

* Style: spaces after colons in object declarations

* Cleanup comments

* Simplify Babel tests

* Fix comments

* Fix destructuring with splats in multiple objects

* Add test for default values in detsructuring assignment with splats

* Handle default values when assigning to object splats

* Rewrite traverseRest to fix handling of dynamic keys

* Fix double parens around destructuring with splats

* Update compileObjectDestruct comments

* Improve formatting of top-level destructures with splats and tidy parens

* Added a bigger destructuring-with-defaults test and fixed a bug

* Refactor destructuring grammar to allow additional forms

* Add a missing case to ObjSpreadExpr

* These tests shouldn’t run in the browser

* Fix test.html

* Fix docs scroll position getting screwed up by CodeMirror initialization

* Breaking change documentation about => (fixes #4593)

* Spread/rest syntax documentation

* Documentation about bound class methods

* 2.0.0-beta3 changelog

* Add note about ‘lib’

* Fix accidentally converting this to tabs

* Bump version to 2.0.0-beta3

* Update annotated source and test.html
2017-06-30 09:58:05 -07:00
Geoffrey Booth
a7a6006533 [CS2] Destructuring object spreads (#4493)
* Don’t confuse the syntax highlighter

* Comment Assign::compilePatternMatch a bit

* Assignment expressions in conditionals are a bad practice

* Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[`

* Correct comment

* object destructuring

* Allow custom position of the rest element.

* Output simple array destructuring assignments to ES2015

* Output simple object destructured assignments to ES2015

* Compile shorthand object properties to ES2015 shorthand properties

This dramatically improves the appearance of destructured imports.

* Don’t confuse the syntax highlighter

* Comment Assign::compilePatternMatch a bit

* Assignment expressions in conditionals are a bad practice

* Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[`

* object destructuring

* Allow custom position of the rest element.

* rest element in object destructuring

* rest element in object destructuring

* fix string interpolation

* merging

* fixing splats in object literal

* Rest element in parameter destructuring

* merging with CS2

* merged with CS2

* Add support for the object spread initializer. https://github.com/tc39/proposal-object-rest-spread/blob/master/Spread.md

* Fix misspellings, trailing whitespace, other minor details

* merging with beta2

* refactor object spread properties

* small fix

* - Fixed object spread function parameters.
- Clean up "Assign" and moved all logic for object rest properties in single method (compileObjectDestruct).
- Add helper function "objectWithoutKeys" to the "UTILITIES" for use with object rest properties,
  e.g. {a, b, r...} = obj => {a, b} = obj, r = objectWithoutKeys(...)
- Clean up "Obj" and moved all logic for object spread properties in single method (compileSpread).
- Clean up "Code".
- Add method "hasSplat" to "Obj" and "Value" for checking if Obj contains the splat.
- Enable placing spread syntax triple dots on either right or left, per #85 (https://github.com/coffeescript6/discuss/issues/85)

* Fixed typos

* Remove unused code

* Removed dots (e.g. splat) on the left side from the grammar

* Initial release for deep spread properties, e.g. obj2 = {obj.b..., a: 1} or {obj[b][c]..., d: 7}
Tests need to be prepared!

* 1. Object literal spread properties

Object literals:
- obj = { {b:{c:{d:1}}}..., a:1 }

Parenthetical:
- obj = { ( body ), a:1 }
- obj = { ( body )..., a:1 }

Invocation:
- obj = { ( (args) -> ... )(params), a:1 }
- obj = { ( (args) -> ... )(params)..., a:1 }
- obj = { foo(), a:1 }
- obj = { foo()..., a:1 }

2. Refactor, cleanup & other optimizations.

* Merged with 2.0

* Cleanup

* Some more cleanup.

* Fixed error with freeVariable and object destructuring.

* Fixed errors with object spread properties.

* Improvements, fixed errors.

* Minor improvement.

* Minor improvements.

* Typo.

* Remove unnecessary whitespace.

* Remove unnecessary whitespace.

* Changed few "assertErrorFormat" tests since parentheses are now allowed in the Obj.

* Whitespace cleanup

* Comments cleanup

* fix destructured obj param declarations

* refine fix; add test

* Refactor function args ({a, b...})

* Additional tests for object destructuring in function argument.

* Minor improvement for object destructuring variable declaration.

* refactor function args ({a, b...}) and ({a, b...} = {}); Obj And Param cleanup

* fix comment

* Fix object destructuring variable declaration.

* more tests with default values

* fix typo

* Fixed default values in object destructuring.

* small fix

* Babel’s tests for object rest spread

* Style: spaces after colons in object declarations

* Cleanup comments

* Simplify Babel tests

* Fix comments

* Fix destructuring with splats in multiple objects

* Add test for default values in detsructuring assignment with splats

* Handle default values when assigning to object splats

* Rewrite traverseRest to fix handling of dynamic keys

* Fix double parens around destructuring with splats

* Update compileObjectDestruct comments

* Improve formatting of top-level destructures with splats and tidy parens

* Added a bigger destructuring-with-defaults test and fixed a bug

* Refactor destructuring grammar to allow additional forms

* Add a missing case to ObjSpreadExpr

* These tests shouldn’t run in the browser

* Fix test.html
2017-06-29 22:57:42 -07:00
Julian Rosse
58c608620e disallow inline chained call after func glyph (#4590) 2017-06-29 19:00:01 -07:00
Julian Rosse
b1d2061cbc [CS2] Fix #3906: handle indentation inside indented chain (#4587)
* safe missing end token error [Fixes #3906]

* handle indentation inside indented chain [Fixes #3906]
2017-06-29 18:39:05 -07:00
Geoffrey Booth
1f31073201 [CS2] JSX documentation, Try CoffeeScript improvements (#4583)
* Update browser compiler

* Argument parsing tests require CommonJS environment

* JSX section in the docs

* Breaking change note for < and > operators

* Fix JSX example

* Try CoffeeScript improvements: set the hash automatically, remove ‘link’ button, automatically save code in localStorage

* Fix the code editors’ handling of tab-indented code

* Fix JSX example to work with React

* Compiled, not rendered
2017-06-25 23:53:35 -07:00
Julian Rosse
a3a1fb0dd7 [CS2] Fix for comma after function glyph [#1043] (#4588)
* comma after function glyph [#1043]

* test fat arrow

* chain after function glyph [#3446] [#3845]
2017-06-25 23:46:54 -07:00
Julian Rosse
26f6fa6570 [CS2] destructured nested defaults [fixes #4566] (#4574)
* destructured nested defaults [fixes #4566]

* don't parenthesize nested assigns
2017-06-20 21:53:37 -07:00
Julian Rosse
0619a7a76c Fix #4579: postfix for in object literals (#4581)
* postfix for on first line of implicit object

* issue numbers

* handle until and while similarly
2017-06-20 21:50:50 -07:00
Danny McClanahan
31cd782ba7 [CS2] CLI: Test option parsing for current CLI (#4565)
* intermediate save

* add note saying where OptionParser is used in coffee command

* add some more work

* fix flatten functions

* refactor tests

* add basic test

* remove unused file

* compilation now hangs

* remove unnecessary changes

* add tests!!!

* clarify a test
2017-06-15 09:09:02 -07:00
Julian Rosse
5e90b224c2 Fix #4564: indent closes implicit object (#4570)
* indent closes implicit object [Fixes #4564]

* add test for just implicit object

* remove stray lib file
2017-06-15 09:07:36 -07:00
Julian Rosse
9a48566b24 [CS2] Restore bound class methods via runtime check to avoid premature calling of bound method before binding (#4561)
* bound method runtime check

* restore bound method tests

* bound method tests

* test bound method in prop-named class

* run check against parent class

* dummy commit

* remove comment

* rename to boundMethodCheck

* fixes from code review

* use ref to own class for check

* fixes from code review

* remove unneeded param
2017-06-14 15:11:53 -07:00
Chris Connelly
76e70a6c81 Fix immediately invoked named classes (#4569)
Fixes #4436.
2017-06-12 23:11:39 -07:00
Geoffrey
5b7a7779fb Merge branch 'master' of github.com:jashkenas/coffeescript into 2 2017-06-08 21:57:01 -07:00
Michal Srb
dc0fb85fd3 [CS2] Support for CSX - equivalent of JSX (#4551)
* CSX implementation

* fixed comment, used toJS, added error tests, fixed error in identifier regex, fixed interpolation inside attributes value and added test

* added missing test for bare attributes, split attribute and indentifier regex, fixed checking for closing tags closing angle bracket

* Refactor tests that compare expected generated JavaScript with actual generated JavaScript to use common helper; add colors to error message to make differences easier to read

* Better match the style of the rest of the codebase

* Remove unused function

* More style fixes

* Allow unspaced less-than operator when not using CSX

* Replace includesCSX with a counter and simplify the unspaced operator logic

* Fixed indexing and realized that I completely enabled the tight spacing, added a test for it too

* Style fixes
2017-06-06 23:33:46 -07:00
Julian Rosse
63b109a4f5 Fix #4544: postfix conditional on first line of implicit object (#4554)
* support postfix conditional on first line of implicit object

* cleanup cleanup

* also fixes #2051, added test
2017-05-29 17:29:45 -07:00
Geoffrey Booth
d756bd6851 [CS2] 2.0.0-beta2 (#4550)
* Breaking changes note about bound class methods

* Changelog for 2.0.0-beta2, including renaming “Change Log” to “Changelog” (the preferred spelling per Wikipedia)

* Update version to 2.0.0-beta2

* 2.0.0-beta2 generated output
2017-05-16 11:53:22 -07:00
Geoffrey Booth
8c9e24841e Merge branch 'master' into 2
# Conflicts:
#	bin/cake
#	bin/coffee
#	documentation/sections/changelog.md
#	documentation/sections/installation.md
#	documentation/sections/introduction.md
#	lib/coffee-script/index.js
#	lib/coffee-script/nodes.js
#	lib/coffee-script/rewriter.js
#	lib/coffee-script/sourcemap.js
#	lib/coffeescript/browser.js
#	lib/coffeescript/cake.js
#	lib/coffeescript/coffeescript.js
#	lib/coffeescript/command.js
#	lib/coffeescript/grammar.js
#	lib/coffeescript/helpers.js
#	lib/coffeescript/lexer.js
#	lib/coffeescript/optparse.js
#	lib/coffeescript/register.js
#	lib/coffeescript/repl.js
#	lib/coffeescript/scope.js
#	package.json
2017-05-14 22:05:37 -07:00
Geoffrey Booth
b449e1be60 Comments and style fixes 2017-05-14 12:30:49 -07:00
Geoffrey Booth
7134856df2 Merge branch 'master' of github.com:jashkenas/coffeescript into 2
# Conflicts:
#	lib/coffee-script/rewriter.js
2017-05-13 21:23:05 -07:00
AKFish
8407dd885a [CS2] Module should be require-able in non-Node environments like Webpack and Browserify (#4546)
* Add webpack support

* Move Node.js-only code from src/coffee-script.coffee to src/index.coffee
* Use lib/coffee-script/index.js as npm package's "main" script
* Export CoffeeScript from src/browser.coffee
* Set package.json's "browser" field to lib/coffee-script/browser.js (used by webpack as entry point)
* Use lib/coffee-script/browser.js as bower package's "main" script

* Use NOP moduleMain when generating parser with Jison

* Remove legacy debug code from browser.coffee

* Improve comments, style

* Fix path

* Remove stub that was only to avoid breaking browser tests; compensate for the lack of stub when running the browser tests in Node

* Update output

* Add test:webpack task to Cakefile

* Update output files

* Run browser tests against webpack build

* Fix newline at end of file

* Export webpack test bundle as CommonJS module

* Remove build:webpack task

* Save webpack build to tmpdir; suppress build output unless it fails
2017-05-13 21:20:36 -07:00
Geoffrey Booth
993347bb8a [CS2] Un-prefer global (#4543)
* Don’t prefer global installation; the `coffee` or `cake` commands should try to run the locally-installed module if it exists, or the global version otherwise

* Style
2017-05-08 23:35:11 -07:00
Geoffrey Booth
e381e48a79 Fix typo; closes #4187 (#4539) 2017-05-06 06:11:21 -07:00
Geoffrey Booth
22d0cc1012 Fix #4020: No need for break; after a switch case that throws (#4538) 2017-05-06 01:38:20 -07:00
Geoffrey Booth
b28e398396 [CS2] Docs updates (#4536)
* Docs: named functions and function declarations

* No more prototypal `extends`; update docs and example

* More comprehensive documentation of the existential operator; closes #1631

* Better document operators, including `from`

* No fat arrow class methods anymore

* Destructuring shouldn’t say that default values are applied in case of undefined or null

* Spinoff generator and async functions into their own sections; reorder things so that the sections on functions come just before classes, and destructuring goes next to the operators (which discuss assignment)

* Rewrite “CoffeeScript 2” section, making it less practical and more explanatory; move practical info into “Usage”

* Update “Variable Scoping and Lexical Safety” section to remove incorrect reference to Ruby (fixes #2360), add missing details about the safety wrapper, add note about `let`/`const`.

* Updated browser compiler

* Updated docs

* Rewrite Literate CoffeeScript breaking changes

* Split apart the “Breaking Changes” and “Unsupported Features” sections into separate sidebar items and files

* Add example of `not in`, closes #3281

* Fix words in bold that should be in backticks

* Consolidate some breaking changes sections

* Add Node API documentation; closes #3551

* Move the chaining documentation out of the changelog into its own section
2017-05-05 19:44:11 -07:00
Geoffrey Booth
eba271db5b Merge branch 'master' of github.com:jashkenas/coffeescript into 2
# Conflicts:
#	lib/coffee-script/rewriter.js
#	lib/coffeescript/lexer.js
2017-05-02 23:03:37 -07:00
Geoffrey Booth
2f9ab1d328 [CS2] return and export default can now accept implicit objects (#4532)
* Start with the test I want to pass: return an implicit (braces-less) object

* Update Rewriter class to follow pattern of nodes.coffee; move debugging snippet to where it’ll work in CS2

* Allow export default implicit object

* `return` assumes a continuation onto the next line *if* the next line is indented

* Fix comment; improve test
2017-05-01 19:26:24 -07:00
Chris Connelly
3e70d31e5d Remove support for bound instance methods (#4530)
Bound methods are implemented as assignments to `this` in the
constructor. In derived classes, where `this` is unavailable until
after `super` has been called, the binding is applied and assigned after
the `super` call. This means that any references to 'bound' methods
reachable from the parent constructor will actually point to the unbound
prototype methods.

This can lead to very subtle bugs where a method that is thought to be
bound is handed off and later called with an incorrect context, and the
only defence is for users to be vigilant about referencing bound methods
in constructors.
2017-04-27 23:03:01 -07:00
Geoffrey Booth
277975e33a [CS2] Replace Closure Compiler with Babili, transform browser compiler into ES5-ish (#4523)
* Swap Google Closure Compiler for Babili

* Browser compiler, minified by Babili

* Use Babel to transform, not just to minify; add process.env.TRANSFORM to disable transforming if we only want to minify. Unfortunately several browser tests fail when transformed . . .

* Move `super()` calls so that the Babel-transformed browser compiler passes all the browser tests (in Node, at least)

* Updated browser build

* Update browser tests
2017-04-26 16:21:29 -07:00
Julian Rosse
7ef5cb4a1f Keep unicode code point escapes as is when possible (#4520) 2017-04-25 19:15:08 +02:00
Geoffrey Booth
07ae1edb44 [CS2] Remove unnecessary utility helper functions (#4526)
* Uncomment module test that was waiting for classes to be supported

* Rely on native indexOf

* Replace `bind` helper with native `bind` (no shortcut necessary)

* Update output

* Update modules class tests

* Remove helper for prototype extends

* Update docs to reflect removed extends operator

* Add shortcut for splice, like we have for slice
2017-04-25 07:10:42 -07:00
Geoffrey Booth
7e35c2c3da We no longer need to wrap in quotes JavaScript reserved words used as properties (#4527) 2017-04-24 09:23:42 -07:00
Geoffrey Booth
5651b8b14b [CS2] Fix non-bare get set when called with @ argument (#4525)
* Fixes #4524: `get` and `set` should be usable without parentheses when accessed via a period

* More get/set tests
2017-04-23 11:23:36 -07:00
Geoffrey Booth
3058eedf47 Merge pull request #4521 from helixbass/2_merged_master
merge `master` into `2`
2017-04-20 14:54:07 -07:00
Julian Rosse
89db842c3d merge master 2017-04-20 14:41:28 -05:00
jessaustin
e215a2d280 Write .coffee_history in $XDG_CACHE_HOME (#4472)
* Write .coffee_history in $XDG_CACHE_HOME

Previously, if the $HOME environmental variable was set, the
.coffee_history file was written there. This is still the case, but
first we check if $XDG_CACHE_HOME is set, and if so we write it
there instead. This allows users who want to follow the XDG Base
Directory Specification [0] to do so. Actually, this helps out *all*
users who want to keep their home directory a bit cleaner. It seems
that using this standardized environmental variable is the cleanest
way to do this, rather than involving configuration files or command
line flags or anything else.

Fixes #3705.

[0] https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html

* Stylistic corrections

Corrected some style deficiencies, thanks to helpful advice from
@GeoffreyBooth.
2017-04-18 10:52:02 -07:00
Geoffrey Booth
0e8feb7ee9 [CS2] Literate CoffeeScript without dependencies (#4509)
* Reimplement `invertLiterate` without any dependency, tracking indentation levels (including inside lists); update literate test files to also check that no tests are skipped

* Drop Literate CoffeeScript’s support for executable code blocks inside list items (and also for second paragraphs or blockquotes in list items)

* Update Literate CoffeeScript docs to reflect current supported syntax
2017-04-17 23:30:40 -07:00
Geoffrey Booth
ae096a331a Merge branch 'master' into 2
# Conflicts:
#	Cakefile
#	documentation/sections/changelog.md
#	documentation/sections/classes.md
#	documentation/sections/fat_arrow.md
#	documentation/sections/installation.md
#	documentation/sections/introduction.md
#	documentation/sections/resources.md
#	documentation/sections/scripts.md
#	lib/coffeescript/repl.js
#	src/lexer.coffee
2017-04-17 19:52:34 -07:00
Geoffrey Booth
d7e096aeee [CS2] Fix links in v2 docs (#4506)
* Update 2.0.0-beta1 docs

* Fix broken links, update redirected links

* Rebuild v2 docs with updated links

* A few more fixed links
2017-04-17 19:43:22 -07:00
Geoffrey Booth
db216ec384 [CS2] 2.0.0-beta1 (#4499)
* Fix browser build to incorporate Markdown-It, not Marked

* Update Google Closure Compiler; recompile browser build but with MINIFY=false, because Closure Compiler throws an error on our current code; see https://github.com/google/closure-compiler-js/issues/59

* Bump version to 2.0.0-beta1; do release build, with updated docs and annotated source
2017-04-13 10:42:32 -07:00
Geoffrey Booth
9b77371ea8 Merge commit '72cf485dceb6a88abb3b83493032734409c3591a' into 2
# Conflicts:
#	Cakefile
#	docs/v1/index.html
#	documentation/sections/changelog.md
#	documentation/sections/installation.md
#	documentation/sections/introduction.md
#	lib/coffee-script/nodes.js
#	lib/coffee-script/rewriter.js
#	lib/coffee-script/sourcemap.js
#	lib/coffeescript/browser.js
#	lib/coffeescript/cake.js
#	lib/coffeescript/coffeescript.js
#	lib/coffeescript/command.js
#	lib/coffeescript/grammar.js
#	lib/coffeescript/helpers.js
#	lib/coffeescript/index.js
#	lib/coffeescript/lexer.js
#	lib/coffeescript/optparse.js
#	lib/coffeescript/register.js
#	lib/coffeescript/repl.js
#	lib/coffeescript/scope.js
#	package.json
2017-04-12 20:27:57 -07:00
Geoffrey Booth
d20f54967e [CS2] 2.0.0-beta1 docs (#4494)
* Update package versions; remove marked

* Revise docs to use Markdown-It: tables are now GitHub-Flavored Markdown tables, avoid hack of blockquoted code blocks

* Add anchors for sub-sections

* Add syntax highlighting to uneducable code blocks; fix missing italics variant for comments font

* Update docs about breaking changes in Literate CoffeeScript, move Breaking Changes section below Literate CoffeeScript section

* Update docs regarding destructuring default values breaking change

* Update changelog, with spitball release date for beta1

* Fix highlight function return statement
2017-04-09 23:07:58 -07:00
Geoffrey Booth
be7c1be75f Merge branch 'get-set-warning' into 2 2017-04-08 21:59:53 -07:00
Geoffrey Booth
8292d25d29 [CS2] Throw an error for ambiguous get or set keywords or function calls (#4484)
* Throw an error for ambiguous `get` or `set` function calls or ES5 getter/setter keywords, to warn the user to use parentheses if they intend a function call (or to inform them that `get` or `set` cannot be used as a keyword)

* Code golf

* Catch get or set keyword before static method

* DRY up getting the previous token

* Throw an error if get or set are used as keywords before what looks like a function or method with an interpolated/dynamic name

* Allow `get` or `set` parentheses-less function calls when first argument is a string without a colon (so a plain string, not a property accessor)

* Revert "Allow `get` or `set` parentheses-less function calls when first argument is a string without a colon (so a plain string, not a property accessor)"

This reverts commit 2d1addf5a4.

* Optimization

* No longer throw an error on `get` or `set` function calls to objects with dynamic property names (introduces a way to circumvent our check for trying to avoid the `get` or `set` keywords, but not worth the complications for this tiny edge case)
2017-04-08 21:59:09 -07:00
Julian Rosse
76945ab458 Fix #4487: Outdentation bug (#4488) 2017-04-08 13:12:55 -07:00
Geoffrey Booth
0576eb3a10 No longer throw an error on get or set function calls to objects with dynamic property names (introduces a way to circumvent our check for trying to avoid the get or set keywords, but not worth the complications for this tiny edge case) 2017-04-06 15:23:14 -07:00
Geoffrey Booth
7129f8347e Merge branch '2' into get-set-warning
# Conflicts:
#	lib/coffeescript/lexer.js
2017-04-06 10:12:46 -07:00
Geoffrey Booth
4d25907155 Optimization 2017-04-06 10:11:29 -07:00
Geoffrey Booth
b192e215a5 [CS2] Destructuring (#4478)
* Output simple array destructuring assignments to ES2015

* Output simple object destructured assignments to ES2015

* Compile shorthand object properties to ES2015 shorthand properties

This dramatically improves the appearance of destructured imports.

* Compile default values in destructured assignment to ES2015

* Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.)

* Don’t confuse the syntax highlighter

* Comment Assign::compilePatternMatch a bit

* Assignment expressions in conditionals are a bad practice

* Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy

* Add comments; remove unnecessary array splats in function tests

* The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec

* Support destructuring in function parameters (first pass); catch destructured reserved words

* Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005

* Remove redundancy in undefined-only check for existence; fix passing option to check

* Fix undefined redundancy

* Simplify getting the variable name

* Reimplement “check for existence if not undefined” without creating a new operator

* `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring

* Revert changes to tests

* Restore revised test for empty destructuring assignment
2017-04-06 10:06:45 -07:00
Geoffrey Booth
5e1d978946 [CS2] Fix handling of tabbed code blocks in .litcoffee files (#4485)
* Add tabbed literate test; modernize Markdown title heading

* Better parsing of Literate CoffeeScript files, including now correct parsing of tabbed .litcoffee files; and more accurate stack traces (assuming you don’t do your own word wrapping within list items)

* Swap Marked for MarkdownIt for parsing the Markdown of Literate CoffeeScript files; use MarkdownIt’s `map` property to preserve correct line numbers

* Literate CoffeeScript tests: remove trailing whitespace, fix spelling

* Literate CoffeeScript tests: add block quote test

* Literate CoffeeScript (tabbed, at least) seems to need a consistent starting indentation

* Restore test

* Reference links work now in MarkdownIt

* Breaking change in Literate CoffeeScript: code blocks within HTML tags must be unindented

* Breaking change in Literate CoffeeScript: code blocks within lists need a blank line separating them from the list item text
2017-04-06 09:59:11 -07:00
Geoffrey Booth
a7447d5bba Revert "Allow get or set parentheses-less function calls when first argument is a string without a colon (so a plain string, not a property accessor)"
This reverts commit 2d1addf5a4.
2017-04-06 09:28:23 -07:00
Geoffrey Booth
2d1addf5a4 Allow get or set parentheses-less function calls when first argument is a string without a colon (so a plain string, not a property accessor) 2017-04-06 00:47:06 -07:00
Geoffrey Booth
962374aec1 Throw an error if get or set are used as keywords before what looks like a function or method with an interpolated/dynamic name 2017-04-04 17:03:11 -07:00
Geoffrey Booth
ed4c8286a2 DRY up getting the previous token 2017-04-04 17:00:43 -07:00
Geoffrey Booth
fcf7ddaf45 Catch get or set keyword before static method 2017-04-04 16:31:52 -07:00
Geoffrey Booth
725fe8e018 Code golf 2017-04-04 00:05:14 -07:00
Geoffrey Booth
5596dac5e1 Throw an error for ambiguous get or set function calls or ES5 getter/setter keywords, to warn the user to use parentheses if they intend a function call (or to inform them that get or set cannot be used as a keyword) 2017-04-03 22:43:50 -07:00
Geoffrey Booth
57c0b16eeb Merge pull request #4469 from mrmowgli/2-docs
[CS2] An explanation of why we don’t currently support certain features
2017-04-03 22:40:56 -07:00
Geoffrey Booth
0c06fb2b9f Merge branch '2' into 2-docs 2017-04-02 23:13:00 -07:00
Geoffrey Booth
cfdec64958 Merge branch 'master' of github.com:jashkenas/coffeescript into 2
# Conflicts:
#	lib/coffee-script/parser.js
#	lib/coffeescript/lexer.js
2017-04-02 23:10:31 -07:00
Geoffrey Booth
d0c6e53b83 Merge branch '2' into 2-docs
# Conflicts:
#	documentation/sections/coffeescript_2.md
2017-04-02 22:55:31 -07:00
Geoffrey Booth
27caf62322 Merge discussion of CoffeeScript’s benefits into expanded CoffeeScript 2 section and revised Contributing section 2017-04-02 22:53:18 -07:00
Geoffrey Booth
b8df321058 Merge unsupported let/const and get/set sections, shorten 2017-04-02 22:52:37 -07:00
Geoffrey Booth
06f6efa6d5 Bump minimum Node version to 7.6, which has non-harmony support for async/await; make async tests always enabled, not just for harmony mode 2017-04-02 22:05:09 -07:00
7anshuai
c035d53fb0 Fix broken links in 2 docs (#4480)
Thanks!
2017-04-02 20:09:13 -07:00
mrmowgli
5888ac56d8 Added example, simplified text via suggestion from GeoffreyBooth 2017-03-22 05:16:55 -04:00
mrmowgli
a6bf72a791 Remove language and add link to Wiki article- In the Wild. 2017-03-22 01:51:07 -04:00
mrmowgli
3aa177c88f Reduced overall size per section, cleaned up some style issues and fixed some spelling issues. 2017-03-21 04:59:25 -04:00
mrmowgli
608799f5d0 Looking for comments, Documentation of unsupported features, and suggested menu locations. Separated Why Coffeescript out. Yes I know I need to trim let/const down. 2017-03-19 06:33:15 -04:00
mrmowgli
97aef9b30d An explanation of why we don't currently support certain features within CS2. First draft. 2017-03-16 07:05:30 -04:00
Geoffrey
ccbf3152af Update NPM installation instructions 2017-02-21 21:12:40 -08:00
Geoffrey Booth
f8c150f201 Merge pull request #4439 from GeoffreyBooth/2.0.0-alpha1
[CS2] 2.0.0-alpha1
2017-02-21 07:04:18 -08:00
Geoffrey Booth
a5cb8cd7c3 Rebuild release 2017-02-20 16:07:44 -08:00
Geoffrey Booth
32799ad732 Make test compatible with Firefox (though it still fails there while it passes in Node and Chrome) 2017-02-20 15:59:59 -08:00
Geoffrey Booth
d47f90599e Bump date 2017-02-20 15:59:59 -08:00
Geoffrey Booth
5817aeb837 Fix browser test.html to work with async tests 2017-02-20 15:59:58 -08:00
Geoffrey Booth
7de06c3dcb Ensure unique source maps’ sourceURL; closes #4126 2017-02-20 15:46:48 -08:00
Geoffrey Booth
6f0f173795 Update changelog for 1.12.4 2017-02-20 15:31:28 -08:00
Geoffrey Booth
221a8720fe Merge branch '2' into 2.0.0-alpha1
# Conflicts:
#	Cakefile
#	README.md
#	documentation/sections/changelog.md
2017-02-18 18:36:15 -05:00
Alan Pierce
ff56533e0b Fix CS2 build after merge pulled in a bare super call (#4447)
[CS2] Fix CS2 build after merge pulled in a bare super call
2017-02-18 18:14:47 -05:00
Geoffrey Booth
e88619a3bb Merge branch 'master' into 2
# Conflicts:
#	documentation/sections/resources.md
#	lib/coffee-script/browser.js
#	lib/coffee-script/cake.js
#	lib/coffee-script/coffee-script.js
#	lib/coffee-script/command.js
#	lib/coffee-script/grammar.js
#	lib/coffee-script/helpers.js
#	lib/coffee-script/index.js
#	lib/coffee-script/lexer.js
#	lib/coffee-script/nodes.js
#	lib/coffee-script/optparse.js
#	lib/coffee-script/register.js
#	lib/coffee-script/repl.js
#	lib/coffee-script/rewriter.js
#	lib/coffee-script/scope.js
#	lib/coffee-script/sourcemap.js
#	package.json
2017-02-18 10:52:55 -05:00
Geoffrey
4cc701a9da Remove hyphen in coffee-script 2017-02-12 17:00:05 -08:00
Geoffrey
d2e94c6ebd Fix Try CoffeeScript for mobile 2017-02-12 16:36:52 -08:00
Geoffrey Booth
d7d32cf0b6 Prepare for new module name on NPM 2017-02-10 11:38:43 -08:00
Geoffrey Booth
ebe32d35e2 Add breaking changes link to changelog; bump date 2017-02-10 11:36:35 -08:00
Geoffrey Booth
ecafe7ce0f Update changelog for 2.0.0-alpha1 2017-02-09 13:33:35 -08:00
Geoffrey Booth
41a229e22e Update browser-based tests output 2017-02-09 13:29:23 -08:00
Geoffrey Booth
d9194b2670 Update annotated source for 2.0.0-alpha1 2017-02-09 13:29:12 -08:00
Geoffrey Booth
365d1968e9 Bump CoffeeScript version to 2.0.0-alpha1 2017-02-09 13:28:22 -08:00
Geoffrey Booth
eebc432efb Fix link to browser-based tests 2017-02-09 13:27:24 -08:00
Geoffrey Booth
dd5aa2b7a4 Bump version of Closure Compiler, update browser compiler 2017-02-09 13:26:46 -08:00
Geoffrey Booth
d1d2c16fdd Update docs for classes, breaking changes (#4438)
* Update classes docs for CS2

* Port breaking changes from https://github.com/jashkenas/coffeescript/wiki/%5BWIP%5D-Breaking-changes-in-CoffeeScript-2 into new docs section

* Update browser compiler

* Update re @connec’s notes; split classes section into two sections for classes and working with prototypes; make breaking changes examples editable whenever possible
2017-02-09 08:50:11 -08:00
Geoffrey
ef1898ba42 Merge commit '3d0d04efe286fdbd9b1b1841112a6b9c991e9698' into 2 2017-02-07 20:20:51 -08:00
Geoffrey Booth
81cbca5bb8 Update async test to use new super syntax 2017-02-04 17:05:18 -08:00
Geoffrey
da3db1be39 Merge branch 'master' of github.com:jashkenas/coffeescript into 2
# Conflicts:
#	lib/coffee-script/nodes.js
#	lib/coffee-script/scope.js
2017-02-04 12:36:49 -08:00
Chris Connelly
396bd4f2f2 [CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super

This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.

* Use bound functions for IIFEs containing `super`

`super` can only be called directly in a method, or in an arrow
function.

* Fix handling of `class @A extends A`

This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.

* Fix tests broken by compiling ES2015 `super`

* Disallow bare super

This removes syntax support for 'bare' super calls, e.g.:

    class B extends A
      constructor: -> super

`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:

    class B extends A
      constructor: -> super arguments...

* Support super with accessors

`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).

`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.

    speak: -> super()

...is equivalent to

    speak: -> super.speak()

A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.

* Prevent calling `super` methods with `new`

This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.

* Clean up some old super handling code

This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.

* Add TODO to improve bare super parse error

* Add some TODOs to improve some of the class tests
2017-02-04 12:03:17 -08:00
Geoffrey Booth
cbea7b5d1c [CS2] Fix handling of parameters that are complex (#4430)
* Add failing test per #4406

* If a parameter is a function call, define it in an expression within the function body

* Remove the space between `function` and `*` for generator functions, to follow usual ES idiom

* We can collapse `isCall` into `isComplex`

* Don’t need existence check here

* Correct destructured parameter default evaluation order with an incrementing variable (or more generally any complicated parameter that isComplex)

* Try to pull complex parameters out of the parameter list if their order of execution matters; but don’t pull _all_ complex parameters out of the parameter list, so that we don’t lose parameter default values

* Add lots of comments about node special properties

* Err on the side of caution in deciding whether a complex parameter is allowable in a function parameter list rather than the function body (there are lots more detections we could add to find additional “safe” parameters)

* Follow the ES and CS2 convention of assigning parameter default values only when undefined, not when null or undefined

* Along with arrays and empty objects, also let values whose bases are not complex be allowed in the function parameter list (like `obj.prop`)

* Better way to check for undefined parameters when declaring them in a function body

* Once we’ve put a complex parameter in the function body, all following complex parameters go into the function body; no need to create lots of exceptions of when to choose whether to put a complex param in the body

* Rename `isComplex` to `shouldCache` for clarity
2017-02-01 06:54:42 -08:00
Geoffrey Booth
3e7973e08d Merge branch 'master' into 2
# Conflicts:
#	lib/coffee-script/browser.js
#	lib/coffee-script/cake.js
#	lib/coffee-script/coffee-script.js
#	lib/coffee-script/command.js
#	lib/coffee-script/grammar.js
#	lib/coffee-script/helpers.js
#	lib/coffee-script/index.js
#	lib/coffee-script/lexer.js
#	lib/coffee-script/nodes.js
#	lib/coffee-script/optparse.js
#	lib/coffee-script/register.js
#	lib/coffee-script/repl.js
#	lib/coffee-script/rewriter.js
#	lib/coffee-script/scope.js
#	lib/coffee-script/sourcemap.js
#	package.json
2017-01-24 18:54:55 -08:00
Geoffrey Booth
ec5adf53a7 Fix CodeMirror cursor in CoffeeScript input columns; update generated documentation 2017-01-22 20:05:12 -08:00
Geoffrey Booth
48eb173bcd Merge branch 'master' of github.com:jashkenas/coffeescript into 2
# Conflicts:
#	lib/coffee-script/nodes.js
#	test/error_messages.coffee
2017-01-22 16:32:38 -08:00
Geoffrey Booth
69a07dfa6d [CS2] Fix handling of parameters that are function calls (#4427)
* Add failing test per #4406

* If a parameter is a function call, define it in an expression within the function body

* Remove the space between `function` and `*` for generator functions, to follow usual ES idiom

* We can collapse `isCall` into `isComplex`

* Don’t need existence check here
2017-01-22 04:40:33 -08:00
Simon Lydell
800116d859 Merge pull request #4426 from connec/class-dynamic-key-scope
[CS2] Fix scope of assignments in dynamic class keys
2017-01-21 09:55:33 +01:00
Chris Connelly
4f6073f283 Fix scope of assignments in dynamic class keys
Dynamic class keys were using the method scope for compilation,
resulting in missing declarations and runtime errors.
2017-01-19 21:47:25 +00:00
Geoffrey Booth
9e13100f58 Allow copying JavaScript from examples 2017-01-12 22:08:11 -08:00
Geoffrey Booth
52bc1dab0b Update docs per #4354 2017-01-12 21:59:54 -08:00
Geoffrey Booth
ff9f078a89 Merge branch '2' into 2-docs 2017-01-12 21:57:16 -08:00
Chris Connelly
8d81804fee [CS2] Compile class constructors to ES2015 classes (#4354)
* Compile classes to ES2015 classes

Rather than compiling classes to named functions with prototype and
class assignments, they are now compiled to ES2015 class declarations.

Backwards compatibility has been maintained by compiling ES2015-
incompatible properties as prototype or class assignments. `super`
continues to be compiled as before.

Where possible, classes will be compiled "bare", without an enclosing
IIFE. This is possible when the class contains only ES2015 compatible
expressions (methods and static methods), and has no parent (this last
constraint is a result of the legacy `super` compilation, and could be
removed once ES2015 `super` is being used). Classes are still assigned
to variables to maintain compatibility for assigned class expressions.

There are a few changes to existing functionality that could break
backwards compatibility:

- Derived constructors that deliberately don't call `super` are no
  longer possible. ES2015 derived classes can't use `this` unless the
  parent constructor has been called, so it's now called implicitly when
  not present.

- As a consequence of the above, derived constructors with @ parameters
  or bound methods and explicit `super` calls are not allowed. The
  implicit `super` must be used in these cases.

* Add tests to verify class interoperability with ES

* Refactor class nodes to separate executable body logic

Logic has been redistributed amongst the class nodes so that:

- `Class` contains the logic necessary to compile an ES class
  declaration.
- `ExecutableClassBody` contains the logic necessary to compile CS'
  class extensions that require an executable class body.

`Class` still necessarily contains logic to determine whether an
expression is valid in an ES class initializer or not. If any invalid
expressions are found then `Class` will wrap itself in an
`ExecutableClassBody` when compiling.

* Rename `Code#static` to `Code#isStatic`

This naming is more consistent with other `Code` flags.

* Output anonymous classes when possible

Anonymous classes can be output when:

- The class has no parent. The current super compilation needs a class
  variable to reference. This condition will go away when ES2015 super
  is in use.
- The class contains no bound static methods. Bound static methods have
  their context set to the class name.

* Throw errors at compile time for async or generator constructors

* Improve handling of anonymous classes

Anonymous classes are now always anonymous. If a name is required (e.g.
for bound static methods or derived classes) then the class is compiled
in an `ExecutableClassBody` which will give the anonymous class a stable
reference.

* Add a `replaceInContext` method to `Node`

`replaceInContext` will traverse children looking for a node for which
`match` returns true. Once found, the matching node will be replaced by
the result of calling `replacement`.

* Separate `this` assignments from function parameters

This change has been made to simplify two future changes:

1. Outputting `@`-param assignments after a `super` call.
   In this case it is necessary that non-`@` parameters are available
   before `super` is called, so destructuring has to happen before
   `this` assignment.
2. Compiling destructured assignment to ES6
   In this case also destructuring has to happen before `this`,
   as destructuring can happen in the arguments list, but `this`
   assignment can not.

A bonus side-effect is that default values for `@` params are now output
as ES6 default parameters, e.g.

    (@a = 1) ->

becomes

    function a (a = 1) {
      this.a = a;
    }

* Change `super` handling in class constructors

Inside an ES derived constructor (a constructor for a class that extends
another class), it is impossible to access `this` until `super` has been
called. This conflicts with CoffeeScript's `@`-param and bound method
features, which compile to `this` references at the top of a function
body. For example:

    class B extends A
      constructor: (@param) -> super
      method: =>

This would compile to something like:

    class B extends A {
      constructor (param) {
        this.param = param;
        this.method = bind(this.method, this);
        super(...arguments);
      }
    }

This would break in an ES-compliant runtime as there are `this`
references before the call to `super`. Before this commit we were
dealing with this by injecting an implicit `super` call into derived
constructors that do not already have an explicit `super` call.
Furthermore, we would disallow explicit `super` calls in derived
constructors that used bound methods or `@`-params, meaning the above
example would need to be rewritten as:

    class B extends A
      constructor: (@param) ->
      method: =>

This would result in a call to `super(...arguments)` being generated as
the first expression in `B#constructor`.

Whilst this approach seems to work pretty well, and is arguably more
convenient than having to manually call `super` when you don't
particularly care about the arguments, it does introduce some 'magic'
and separation from ES, and would likely be a pain point in a project
that made use of significant constructor overriding.

This commit introduces a mechanism through which `super` in constructors
is 'expanded' to include any generated `this` assignments, whilst
retaining the same semantics of a super call. The first example above
now compiles to something like:

    class B extends A {
      constructor (param) {
        var ref
        ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref;
      }
   }

* Improve `super` handling in constructors

Rather than functions expanding their `super` calls, the `SuperCall`
node can now be given a list of `thisAssignments` to apply when it is
compiled.

This allows us to use the normal compiler machinery to determine whether
the `super` result needs to be cached, whether it appears inline or not,
etc.

* Fix anonymous classes at the top level

Anonymous classes in ES are only valid within expressions. If an
anonymous class is at the top level it will now be wrapped in
parenthses to force it into an expression.

* Re-add Parens wrapper around executable class bodies

This was lost in the refactoring, but it necessary to ensure
`new class ...` works as expected when there's an executable body.

* Throw compiler errors for badly configured derived constructors

Rather than letting them become runtime errors, the following checks are
now performed when compiling a derived constructor:

- The constructor **must** include a call to `super`.
- The constructor **must not** reference `this` in the function body
  before `super` has been called.

* Add some tests exercising new class behaviour

- async methods in classes
- `this` access after `super` in extended classes
- constructor super in arrow functions
- constructor functions can't be async
- constructor functions can't be generators
- derived constructors must call super
- derived constructors can't reference `this` before calling super
- generator methods in classes
- 'new' target

* Improve constructor `super` errors

Add a check for `super` in non-extended class constructors, and
explicitly mention derived constructors in the "can't reference this
before super" error.

* Fix compilation of multiple `super` paths in derived constructors

`super` can only be called once, but it can be called conditionally from
multiple locations. The chosen fix is to add the `this` assignments to
every super call.

* Additional class tests, added as a separate file to simplify testing and merging.
Some methods are commented out because they currently throw and I'm not sure how
to test for compilation errors like those.

There is also one test which I deliberately left without passing, `super` in an external prototype override.
This test should 'pass' but is really a variation on the failing `super only allowed in an instance method`
tests above it.

* Changes to the tests. Found bug in super in prototype method. fixed.

* Added failing test back in, dealing with bound functions in external prototype overrides.

* Located a bug in the compiler relating to assertions and escaped ES6 classes.

* Move tests from classes-additional.coffee into classes.coffee; comment out console.log

* Cleaned up tests and made changes based on feedback.  Test at the end still has issues, but it's commented out for now.

* Make HoistTarget.expand recursive

It's possible that a hoisted node may itself contain hoisted nodes (e.g.
a class method inside a class method). For this to work the hoisted
fragments need to be expanded recursively.

* Uncomment final test in classes.coffee

The test case now compiles, however another issue is affecting the test
due to the error for `this` before `super` triggering based on source
order rather than execution order. These have been commented out for
now.

* Fixed last test TODOs in test/classes.coffee

Turns out an expression like `this.foo = super()` won't run in JS as it
attempts to lookup `this` before evaluating `super` (i.e. throws "this
is not defined").

* Added more tests for compatability checks, statics, prototypes and ES6 expectations.  Cleaned test "nested classes with super".

* Changes to reflect feedback and to comment out issues that will be addressed seperately.

* Clean up test/classes.coffee

- Trim trailing whitespace.
- Rephrase a condition to be more idiomatic.

* Remove check for `super` in derived constructors

In order to be usable at runtime, an extended ES class must call `super`
OR return an alternative object. This check prevented the latter case,
and checking for an alternative return can't be completed statically
without control flow analysis.

* Disallow 'super' in constructor parameter defaults

There are many edge cases when combining 'super' in parameter defaults
with @-parameters and bound functions (and potentially property
initializers in the future).

Rather than attempting to resolve these edge cases, 'super' is now
explicitly disallowed in constructor parameter defaults.

* Disallow @-params in derived constructors without 'super'

@-parameters can't be assigned unless 'super' is called.
2017-01-12 21:55:30 -08:00
Geoffrey Booth
0fc625d7e9 Try CoffeeScript add play and link buttons 2016-12-27 22:53:52 -05:00
Geoffrey Booth
ef1005b920 Try CoffeeScript first draft 2016-12-27 21:35:43 -05:00
Geoffrey Booth
5cf8256d2e Merge branch 'master' of github.com:jashkenas/coffeescript into 2 2016-12-26 21:17:20 -05:00
Geoffrey Booth
f0e884dc4e Update output 2016-12-19 22:32:51 -08:00
Geoffrey Booth
24bef3a1f5 Merge branch '2' into 2-docs
# Conflicts:
#	docs/v1/index.html
#	docs/v1/test.html
#	documentation/sections/changelog.md
#	documentation/sections/chat.md
#	documentation/sections/fat_arrow.md
#	documentation/sections/functions.md
#	documentation/sections/installation.md
#	documentation/sections/introduction.md
#	documentation/sections/language.md
#	documentation/sections/literate.md
#	documentation/sections/operators.md
#	documentation/sections/overview.md
#	documentation/sections/resources.md
#	documentation/sections/scripts.md
#	documentation/sections/source_maps.md
#	documentation/sections/strings.md
#	documentation/sections/tagged_template_literals.md
#	documentation/sections/usage.md
2016-12-19 22:32:07 -08:00
Geoffrey Booth
5d557a54e1 Updated v2 docs generated output 2016-12-19 22:27:42 -08:00
Geoffrey Booth
3379f233e8 Modernize various sections as relevant to v2; improve presentation of tables 2016-12-19 22:27:32 -08:00
Geoffrey Booth
26b1584fd8 Trim the installation and usage sections; can backport to v1 2016-12-19 22:10:32 -08:00
Geoffrey Booth
5fa91e7b95 Fix scrollspy for Resources 2016-12-19 21:59:19 -08:00
Geoffrey Booth
d8bd2b7fd0 Embedded JavaScript should really be the last item in the language reference 2016-12-19 21:55:44 -08:00
Geoffrey Booth
d02376c4c6 Convert async docs text to markdown, add to sidebar 2016-12-19 21:50:30 -08:00
Geoffrey Booth
69fbb361f2 Merge branch '2-docs' into async-docs
# Conflicts:
#	documentation/index.html.js
2016-12-19 21:41:22 -08:00
Geoffrey Booth
4468ca69c0 Add some v1-style ribbing 2016-12-19 21:29:03 -08:00
Geoffrey Booth
a4b3a3ba39 Updated output v2 docs 2016-12-18 23:40:30 -08:00
Geoffrey Booth
ad90f4ad99 Update introduction for CoffeeScript 2 2016-12-18 23:25:01 -08:00
Geoffrey Booth
cc8dd150f5 Fix filename style 2016-12-18 23:24:43 -08:00
Geoffrey Booth
7ced071934 Add some links to header navbar; fix sidebar to work at various breakpoints, including navigating to anchors 2016-12-18 23:03:17 -08:00
Geoffrey Booth
28d077c08a Style blockquotes 2016-12-18 18:29:36 -08:00
Geoffrey Booth
31ff5e4194 Merge branch 'master' of github.com:jashkenas/coffeescript into 2
# Conflicts:
#	lib/coffee-script/browser.js
#	lib/coffee-script/cake.js
#	lib/coffee-script/coffee-script.js
#	lib/coffee-script/command.js
#	lib/coffee-script/grammar.js
#	lib/coffee-script/helpers.js
#	lib/coffee-script/index.js
#	lib/coffee-script/lexer.js
#	lib/coffee-script/nodes.js
#	lib/coffee-script/optparse.js
#	lib/coffee-script/register.js
#	lib/coffee-script/repl.js
#	lib/coffee-script/rewriter.js
#	lib/coffee-script/scope.js
#	lib/coffee-script/sourcemap.js
#	package.json
2016-12-18 18:16:18 -08:00
Geoffrey Booth
ea269104bd Refactor docs resources section; reorganize outline; other minor corrections 2016-12-18 18:13:59 -08:00
Geoffrey Booth
78b21c2483 Fix releaseHeader for the initial release; should backport to v1 2016-12-18 15:57:04 -08:00
Geoffrey Booth
fc42b3ed24 Remove out-of-date info and dead link from Literate CoffeeScript section of the docs 2016-12-18 15:21:41 -08:00
Geoffrey Booth
c8a3c1a6fd Improvements to strings and comments docs; could be back-ported to v1 docs 2016-12-18 15:13:54 -08:00
Geoffrey Booth
58f9428c58 Colors 2016-12-18 03:54:57 -08:00
Geoffrey Booth
3c6e235b32 Show header bar on all breakpoints 2016-12-18 02:43:41 -08:00
Geoffrey Booth
35cfba06b4 Add fonts 2016-12-18 02:20:10 -08:00
Geoffrey Booth
f01dcd3894 Line spacing notes 2016-12-18 00:07:10 -08:00
Geoffrey Booth
e48fea1892 Fix sidebar scrolling on mobile 2016-12-16 00:17:11 -08:00
Geoffrey Booth
47bd5aca58 Fix menu button on regular browsers sized narrowly 2016-12-16 00:05:24 -08:00
Geoffrey Booth
0aa3166709 Updated compiled output 2016-12-15 23:59:11 -08:00
Geoffrey Booth
51aaef3d76 Add logo to top of content pane 2016-12-15 23:58:59 -08:00
Geoffrey Booth
d62f7adc9b Animated sidebar menu toggle button 2016-12-15 23:58:40 -08:00
Geoffrey Booth
853dd456a8 On mobile, the code examples are stacked 2016-12-15 23:19:50 -08:00
Geoffrey Booth
462a60da7b Mobile off canvas sidebar nav that slides in 2016-12-15 23:19:34 -08:00
Geoffrey Booth
4abd0fa06d Mobile header nav with menu button 2016-12-15 23:18:40 -08:00
Geoffrey Booth
b1313962a7 Merge branch 'master' of github.com:jashkenas/coffeescript into 2
# Conflicts:
#	Cakefile
#	lib/coffee-script/coffee-script.js
#	src/coffee-script.coffee
2016-12-15 21:13:52 -08:00
Geoffrey Booth
2a862d533f Merge branch 'master' of github.com:jashkenas/coffeescript into 2-docs
# Conflicts:
#	Cakefile
#	lib/coffee-script/coffee-script.js
#	src/coffee-script.coffee
2016-12-15 21:01:52 -08:00
Geoffrey Booth
a825336ba9 Merge branch 'master' of github.com:jashkenas/coffeescript into 2 2016-12-15 20:36:53 -08:00
Geoffrey Booth
a55dbc0c37 Merge branch 'improve-docs' into 2-docs 2016-12-14 00:06:39 -08:00
Geoffrey Booth
818d262843 Update packages, including new highlight.js which supports our newer keywords and triple backticks (docs output is unchanged) 2016-12-14 00:06:20 -08:00
Geoffrey Booth
e05a4e9000 Merge branch 'improve-docs' into 2-docs
# Conflicts:
#	documentation/v1/code.coffee
2016-12-13 23:50:41 -08:00
Geoffrey Booth
c3b3af8746 Fix margin 2016-12-13 23:49:26 -08:00
Geoffrey Booth
4889109b8d 2 docs output, first draft 2016-12-13 23:15:33 -08:00
Geoffrey Booth
93f1f3777c Wire up the buttons that run the code examples 2016-12-13 23:14:21 -08:00
Geoffrey Booth
14382abc2d Move code example HTML into a template where it belongs 2016-12-13 23:13:38 -08:00
Geoffrey Booth
85b3be9ce3 Move the codeFor function into versioned folders, so that v1 and v2 docs can have different example code blocks/editors 2016-12-12 23:42:33 -08:00
Geoffrey Booth
512b580820 Add CodeMirror for editable code examples; recompile CoffeeScript into JavaScript on change (WIP) 2016-12-12 22:56:31 -08:00
Geoffrey Booth
e90cf16965 Merge branch 'improve-docs' into 2-docs 2016-12-12 22:52:14 -08:00
Geoffrey Booth
59001f2fe3 Move the codeFor function into versioned folders, so that v1 and v2 docs can have different example code blocks/editors 2016-12-12 22:50:30 -08:00
Geoffrey Booth
db055bb916 V2 docs starting point: jQuery, Bootstrap, basic layout, nav with scrollspy 2016-12-11 20:33:54 -08:00
Geoffrey Booth
80fdc6ecc3 Merge branch 'improve-docs' into 2-docs 2016-12-11 20:29:35 -08:00
Geoffrey Booth
ff1725b367 Handle ids within the template, not in the Cakefile; remove marked’s auto-generated and conflicting ids 2016-12-11 20:29:08 -08:00
Geoffrey Booth
d278c730ea Merge branch 'improve-docs' into 2-docs 2016-12-11 17:12:53 -08:00
Geoffrey Booth
4aa0130a92 Use idiomatic markdown output for code blocks (<pre><code>) 2016-12-11 17:12:29 -08:00
Geoffrey Booth
c7ad70731a Merge branch 'improve-docs' into 2-docs 2016-12-11 16:55:12 -08:00
Geoffrey Booth
16dda9c496 Use idiomatic markdown output for code blocks (<pre><code>) 2016-12-11 15:46:38 -08:00
Geoffrey Booth
b2e10e597f Merge branch 'improve-docs' into 2-docs 2016-12-11 01:12:47 -08:00
Geoffrey Booth
b2bf505e4c Update gitignore 2016-12-11 01:06:21 -08:00
Geoffrey Booth
9c9058ebb4 Add marked 2016-12-11 01:06:11 -08:00
Geoffrey Booth
ece610d682 Revert "Split body into nav and body"
This reverts commit ec9e559ec0.
2016-12-11 00:18:46 -08:00
Geoffrey Booth
d61d4272ce Watch subtemplates 2016-12-11 00:13:53 -08:00
Geoffrey Booth
618e851cd6 Watch subtemplates 2016-12-11 00:13:44 -08:00
Geoffrey Booth
2167a7ab2e Merge branch 'improve-docs' into 2-docs 2016-12-11 00:03:24 -08:00
Geoffrey Booth
ec9e559ec0 Split body into nav and body 2016-12-11 00:02:38 -08:00
Geoffrey Booth
07e4047b7f Merge branch 'improve-docs' into 2-docs 2016-12-10 23:42:57 -08:00
Geoffrey Booth
7bb5ccfd80 Update output index.html 2016-12-10 23:35:18 -08:00
Geoffrey Booth
eb36d6e7a2 Get error messages tests to work in the browser 2016-12-10 23:25:20 -08:00
Geoffrey Booth
000dc03360 Move include logic into templates 2016-12-10 22:21:12 -08:00
Geoffrey Booth
0dd727e6eb Split building index.html and building test.html into two tasks; collapse the parts of releaseHeader into one compact function 2016-12-10 19:13:37 -08:00
Geoffrey Booth
6a845aa4f6 Split apart index.html into components that Cakefile assembles, so that we can add in logic to include different files for v1 versus v2 2016-12-10 18:53:58 -08:00
Geoffrey
9eb7c63158 Render the examples when we’re rendering index.html; they compile so quickly that there’s no need to pre-render them and save the intermediate .js files 2016-12-10 11:52:42 -08:00
Geoffrey
0f10082a21 Merge branch 'master' of github.com:jashkenas/coffeescript into improve-docs
# Conflicts:
#	documentation/index.html
2016-12-10 11:40:25 -08:00
Geoffrey
6bd087ebb2 Merge branch 'master' of github.com:jashkenas/coffeescript into 2
# Conflicts:
#	lib/coffee-script/browser.js
#	lib/coffee-script/cake.js
#	lib/coffee-script/coffee-script.js
#	lib/coffee-script/command.js
#	lib/coffee-script/grammar.js
#	lib/coffee-script/helpers.js
#	lib/coffee-script/index.js
#	lib/coffee-script/lexer.js
#	lib/coffee-script/nodes.js
#	lib/coffee-script/optparse.js
#	lib/coffee-script/register.js
#	lib/coffee-script/repl.js
#	lib/coffee-script/rewriter.js
#	lib/coffee-script/scope.js
#	lib/coffee-script/sourcemap.js
#	package.json
#	src/coffee-script.coffee
2016-12-10 11:06:14 -08:00
Geoffrey Booth
c7539e3310 Documentation is now markdown, converted to HTML on compilation 2016-12-08 00:20:52 -08:00
Geoffrey Booth
e139d59896 Merge branch 'master' of github.com:jashkenas/coffeescript into improve-docs 2016-12-08 00:20:41 -08:00
Geoffrey Booth
b481bd1f73 Merge branch 'master' into 2 2016-12-07 20:35:30 -08:00
Geoffrey Booth
2392a91033 Embed CSS; a bit unorthodox, but we’re a single page so there’s no point in separate .css files and their separate HTTP requests 2016-12-06 22:27:08 -08:00
Geoffrey Booth
0145bf397a Modernize favicon 2016-12-06 22:21:58 -08:00
Geoffrey Booth
d524dc8ad0 Optimize SVGs; replace logo PNG with SVG 2016-12-06 22:13:47 -08:00
Geoffrey Booth
d2fb1b5ce8 Replace tiny bitmaps with base64-encoded URIs 2016-12-06 21:54:30 -08:00
Geoffrey Booth
286eec74f9 Merge branch 'master' into 2
# Conflicts:
#	lib/coffee-script/lexer.js
#	lib/coffee-script/parser.js
2016-12-06 20:59:21 -08:00
Geoffrey Booth
fb3e1a8e65 Merge branch 'master' of github.com:jashkenas/coffeescript into 2
# Conflicts:
#	docs/v1/browser-compiler/coffee-script.js
#	lib/coffee-script/browser.js
#	lib/coffee-script/cake.js
#	lib/coffee-script/coffee-script.js
#	lib/coffee-script/command.js
#	lib/coffee-script/grammar.js
#	lib/coffee-script/helpers.js
#	lib/coffee-script/index.js
#	lib/coffee-script/lexer.js
#	lib/coffee-script/nodes.js
#	lib/coffee-script/optparse.js
#	lib/coffee-script/register.js
#	lib/coffee-script/repl.js
#	lib/coffee-script/rewriter.js
#	lib/coffee-script/scope.js
#	lib/coffee-script/sourcemap.js
#	package.json
#	src/coffee-script.coffee
#	src/nodes.coffee
2016-12-04 12:52:23 -08:00
Geoffrey Booth
ba3411a1ac Merge branch 'master' of github.com:jashkenas/coffeescript into 2 2016-11-30 19:51:55 -08:00
Geoffrey Booth
6685771255 Merge branch 'master' of github.com:jashkenas/coffeescript into 2
# Conflicts:
#	package.json
2016-11-29 08:26:49 -08:00
Geoffrey Booth
e38866b2bf Merge branch '2' of github.com:jashkenas/coffeescript into 2 2016-11-28 20:18:54 -08:00
Geoffrey Booth
6f6df0e48d Merge branch 'master' into 2 2016-11-28 20:18:43 -08:00
Gregory Huczynski
33e6242f6f [CS2] Output interpolated strings as template literals (#4365)
* Output interpolated strings as template literals.

* Update comments to use Markdown, so the annotated source reads well; remove TODOs per @lydell’s explanations
2016-11-28 06:05:51 -08:00
Geoffrey Booth
aff191fc53 Merge branch 'master' into 2 2016-11-27 20:49:22 -08:00
Geoffrey Booth
dd0a4f33ee Async example should follow its introduction 2016-11-27 19:38:41 -08:00
Geoffrey Booth
4d4839011b Merge branch '2' into async-docs 2016-11-27 19:06:24 -08:00
Geoffrey
0ef9eef87d Merge branch 'master' of github.com:jashkenas/coffeescript into 2 2016-11-27 10:50:31 -08:00
Geoffrey Booth
14a63149f4 Merge branch 'master' of github.com:jashkenas/coffeescript into 2
# Conflicts:
#	bower.json
2016-11-22 22:13:13 -08:00
Geoffrey Booth
ceca091816 Relocate example per new folder structure; update per final notes 2016-11-22 21:53:03 -08:00
Geoffrey Booth
bc471da960 Merge branch '2' into async-docs 2016-11-20 17:20:42 -08:00
Geoffrey Booth
6f595f8fd3 Merge branch 'master' into 2 2016-11-20 17:19:59 -08:00
Geoffrey Booth
42a10ba39e Merge branch '2' into async-docs
# Conflicts:
#	Cakefile
2016-11-19 18:52:00 -08:00
Geoffrey Booth
a21ce38fdf Merge branch 'ma'ter' into 2
# Conflicts:
#	lib/coffee-script/lexer.js
2016-11-19 11:19:50 -08:00
Geoffrey Booth
f8fa52a5d7 Merge branch 'master' of github.com:GeoffreyBooth/coffeescript into 2
# Conflicts:
#	lib/coffee-script/nodes.js
#	lib/coffee-script/parser.js
2016-11-18 10:34:13 -08:00
Geoffrey Booth
57ffe14fab Merge branch 'master' into 2
# Conflicts:
#	Cakefile
#	package.json
2016-11-17 22:00:36 -08:00
Geoffrey Booth
9524159e68 Merge branch 'master' into 2
# Conflicts:
#	lib/coffee-script/lexer.js
#	lib/coffee-script/nodes.js
#	lib/coffee-script/optparse.js
#	lib/coffee-script/rewriter.js
#	lib/coffee-script/scope.js
#	lib/coffee-script/sourcemap.js
#	src/nodes.coffee
#	test/classes.coffee
#	test/comments.coffee
#	test/error_messages.coffee
2016-11-10 22:51:39 -08:00
Gabe
dc25f462a9 keeping it simple 2016-11-06 11:26:34 -08:00
Chris Connelly
663595ba94 Compile splats in arrays and function calls to ES2015 splats (#4353)
Rather than compiling splats to arrays built using `Array#concat`, splats
are now compiled directly to ES2015 splats, e.g.

    f foo, arguments..., bar

    [ foo, arguments..., bar ]

Which used to be compiled to:

    f.apply(null, [foo].concat(slice.call(arguments), [bar]));

    [foo].concat(slice.call(arguments), [bar]);

Is now compiled to:

    f(foo, ...arguments, bar);

    [ foo, ...arguments, bar ];
2016-11-06 08:30:04 -08:00
Gabe
8b1c109b9c eliminate utterance queuing 2016-11-06 02:40:24 -08:00
Gabe
ea3f044816 refine sound example 2016-11-06 02:30:01 -08:00
Gabe
993f459880 switch to interactive sound example 2016-11-05 13:57:22 -07:00
Gabe
43e580321a change async code snippet 2016-11-05 02:54:48 -07:00
Gabe
327395d793 change async code snippet 2016-11-05 02:54:18 -07:00
Gabe
acb3c8d79c changed wording 2016-11-04 16:23:18 -07:00
Gabe
ad4a6c4877 doc fixes and updates 2016-11-04 14:20:27 -07:00
geebo
496fd5d3d3 Add Implicit Async Functions (#3757)
* changed jison acceptable versions

* added await support

* wrong function bug fix

* added tests for async/await

* invalid to have await, yield(from) in same function

* changed error handling and tests

* bug fix

* made error handling test more rigorous

* consolidated harmony test files

* added async constructor support and tests

* removed .orig files

* Fixed browser testing issue

* Minor cleanup

* Async test-suite and Cake support, simplified/removed funky tests

* Skip async/await tests when not supported in runtime

* cleanup

* Replaced polyfill with native JS async/await

* Oops

* Make 'async' reserved word

* Remove all async polyfills

* fix merge conflict

* make async testing opt-in

* restore test, remove confusing polyfill language

* Revert changes to test runners

* Only run async tests where async/await is supported (Node 7+ with --harmony, for now)

* remove 'async' from JS reserved words

* The async tests should use their own special async-capable version of `global.test`, which is only loaded for the async tests and only loaded by async-capable environments

* Reverting rename of `async`, it’s not a reserved word so there’s no longer a need for this change

* async test refactoring and additions

* oops

* sync

* better error reporting for `await`

* more stuff geoffrey wants

* fixed litcoffee tests

* change test title
2016-11-02 08:51:26 -07:00
Geoffrey Booth
a1bcf7f1d9 Merge branch 'master' into 2 2016-10-26 09:06:58 -07:00
Geoffrey Booth
9e0a4f844a Merge branch 'master' into 2
# Conflicts:
#	test/error_messages.coffee
2016-10-26 08:59:43 -07:00
Geoffrey Booth
fb2be8e1e3 [CS2] Output ES2015 arrow functions, default parameters, rest parameters (#4311)
* Eliminate wrapper around “bound” (arrow) functions; output `=>` for such functions

* Remove irrelevant (and breaking) tests

* Minor cleanup

* When a function parameter is a splat (i.e., it uses the ES2015 rest parameter syntax) output that parameter as ES2015

* Rearrange function parameters when one of the parameters is a splat and isn’t the last parameter (very WIP)

* Handle params like `@param`, adding assignment expressions for them when they appear; ensure splat parameter is last

* Add parameter names (not a text like `'\nValue IdentifierLiteral: a'`) to the scope, so that parameters can’t be deleted; move body-related lines together; more explanation of what’s going on

* For parameters with a default value, correctly add the parameter name to the function scope

* Handle expansions in function parameters: when an expansion is found, set the parameters to only be the original parameters left of the expansion, then an `...args` parameter; and in the function body define variables for the parameters to the right of the expansion, including setting default values

* Handle splat parameters the same way we handle expansions: if a splat parameter is found, it becomes the last parameter in the function definition, and all following parameters get declared in the function body. Fix the splat/rest parameter values after the post-splat parameters have been extracted from it. Clean up `Code.compileNode` so that we loop through the parameters only once, and we create all expressions using calls like `new IdentifierLiteral` rather than `@makeCode`.

* Fix parameter name when a parameter is a splat attached to `this` (e.g. `@param...`)

* Rather than assigning post-splat parameters based on index, use slice; passes test “Functions with splats being called with too few arguments”

* Dial back our w00t indentation

* Better parsing of parameter names (WIP)

* Refactor processing of splat/expansion parameters

* Fix assignment of default parameters for parameters that come after a splat

* Better check for whether a param is attached to `this`

* More understandable variable names

* For parameters after a splat or expansion, assign them similar to the 1.x destructuring method of using `arguments`, except only concern ourselves with the post-splat parameters instead of all parameters; and use the splat/expansion parameter name, since `arguments` in ES fat arrow functions refers to the parent function’s `arguments` rather than the fat arrow function’s arguments/parameters

* Don’t add unnamed parameters (like `[]` as a parameter) to the function scope

* Disallow multiple splat/expansion parameters in function definitions; disallow lone expansion parameters

* Fix `this` params not getting assigned if the parameter is after a splat parameter

* Allow names of function parameters attached to `this` to be reserved words

* Always add a statement to the function body defining a variable with its default value, if it has one, if the variable `== null`; this covers the case when ES doesn’t apply the default value when `null` is passed in as a value, but CoffeeScript expects `null` and `undefined` to act interchangeably

* Aftermath of having both `undefined` and `null` trigger the use of default values for parameters with default values

* More careful parsing of destructured parameters

* Fall back to processing destructured parameters in the function body, to account for `this` or default values within destructured objects

* Clean up comments

* Restore new bare function test, minus the arrow function part of it

* Test that bound/arrow functions aren’t overwriting the `arguments` object, which should refer to the parent scope’s `arguments` (like `this`)

* Follow ES2015 spec for parameter default values: `null` gets assigned as as `null`, not the default value

* Mimic ES default parameters behavior for parameters after a splat or expansion parameter

* Bound functions cannot be generators: remove no-longer-relevant test, add check to throw error if `yield` appears inside a bound (arrow) function

* Error for bound generator functions should underline the `yield`
2016-10-25 22:26:13 -07:00
Geoffrey Booth
c04c3850ec Merge branch 'master' into 2 2016-10-23 17:08:48 -07:00
Chris Connelly
f14e8b279c [CS2] Compile computed properties to ES2015 equivalent (#4338)
* Add missing compiled files

* Compile computed properties to ES2015 equivalent

This is a fairly small change that simplifies the code generation for computed
properties as they're now generated in the object initializer like regular
properties.
2016-10-23 17:00:51 -07:00
Geoffrey Booth
70a7265f35 Fix tabbed Literate CoffeeScript (#4345)
* failing test case

* add markdown parser for literate coffeescript

this should help to handle ligitimate markdown with indentation correctly

* Update generated code

* Update package.json

* Add `marked` dependency to browser version of CoffeeScript

* Update invertLiterate to use a randomly-generated token that we check for uniqueness, rather than a magic number that we hope might not occur in the code

* Fix typos
2016-10-23 08:37:51 -07:00
Geoffrey Booth
b35bb20a18 Upgrade dependencies 2016-10-22 11:54:05 -07:00
Geoffrey Booth
def685a4e1 Commit generated files that should've been committed as part of #4313 merge 2016-10-22 11:51:41 -07:00
Geoffrey Booth
8647e50941 Bump version in other files (but not documentation) 2016-10-22 11:50:44 -07:00
Geoffrey Booth
8b50fd0461 [CS2] Require Node 6.9.1+ (#4341)
* Node 6 deprecated `new Buffer` in favor of `Buffer.from` and `Buffer.alloc`; update our calls, and set the required version of Node to be >= 6.9.0, and set this to be 2.0.0-alpha for now

* Bump to Node version 6.9.1
2016-10-21 09:56:25 -07:00
Geoffrey Booth
01890cd415 Merge branch 'master' into 2 2016-10-18 23:10:00 -07:00
Geoffrey Booth
a1809277a0 Merge branch 'master' into 2 2016-10-17 21:22:28 -07:00
Geoffrey Booth
8138c663a8 Merge branch 'master' into 2 2016-10-01 11:21:07 -07:00
Jeremy Ashkenas
c5c4d7c8f8 Merge pull request #4313 from eelco/no-whitespace-mixing-strict
Don’t allow mixing spaces and tabs for indentation
2016-09-27 10:24:20 -04:00
Jeremy Ashkenas
f8b0c8049c Merge pull request #4318 from GeoffreyBooth/octal-and-binaries-as-is
Pass through octal and binary literals as-is
2016-09-27 10:22:23 -04:00
Geoffrey Booth
1d230fe055 Minor cleanup 2016-09-26 20:52:23 -07:00
Alexander Pánek
329b2d1cb2 Pass through octal and binary literals as-is
See https://github.com/coffeescript6/discuss/issues/45
2016-09-26 18:04:12 +02:00
Eelco Lempsink
bb40b1188c Don’t allow mixing different types of whitespace for indentation, per line. 2016-09-20 23:33:19 +02:00
Eelco Lempsink
98068611b1 Make sure the indentation is consistent with the previous level.
This prevents mixing spaces and tabs in the same ‘block’ of code.

Mixing is still allowed if each line uses the same mix and if the indentation level returns to 0.

This breaks the literate coffeescript test that mixes spaces and tabs.
2016-09-20 23:06:44 +02:00
234 changed files with 45349 additions and 15311 deletions

3
.babelrc Normal file
View File

@@ -0,0 +1,3 @@
{
"presets": ["env"]
}

1
.gitignore vendored
View File

@@ -8,3 +8,4 @@ test/*.js
parser.output
/node_modules
npm-debug.log*
yarn.lock

20
.travis.yml Normal file
View File

@@ -0,0 +1,20 @@
language: node_js
node_js:
- 6
- 8
- 9
cache:
directories:
- node_modules
script:
- node ./bin/cake build:except-parser
- node ./bin/cake build:parser
- node ./bin/cake build:full
- node ./bin/cake build:browser
- node ./bin/cake test
- node --harmony ./bin/cake test
- node ./bin/cake test:browser
- node ./bin/cake test:integrations

46
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at maintainers@coffeescript.org. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View File

@@ -4,6 +4,6 @@
* Before sending a pull request for a feature, be sure to have [tests](https://github.com/jashkenas/coffeescript/tree/master/test).
* Use the same coding style as the rest of the [codebase](https://github.com/jashkenas/coffeescript/tree/master/src). If you're just getting started with CoffeeScript, there's a nice [style guide](https://github.com/polarmobile/coffeescript-style-guide).
* Use the same coding style as the rest of the [codebase](https://github.com/jashkenas/coffeescript/tree/master/src). If youre just getting started with CoffeeScript, theres a nice [style guide](https://github.com/polarmobile/coffeescript-style-guide).
* In your pull request, do not add documentation to `index.html` or re-build the minified `coffee-script.js` file. We'll do those things before cutting a new release.
* In your pull request, do not add documentation to `index.html` or re-build the minified `coffeescript.js` file. Well do those things before cutting a new release. You _should,_ however, commit the updated compiled JavaScript files in `lib`.

227
Cakefile
View File

@@ -1,17 +1,19 @@
fs = require 'fs'
os = require 'os'
path = require 'path'
_ = require 'underscore'
{ spawn, exec, execSync } = require 'child_process'
CoffeeScript = require './lib/coffee-script'
helpers = require './lib/coffee-script/helpers'
CoffeeScript = require './lib/coffeescript'
helpers = require './lib/coffeescript/helpers'
# ANSI Terminal Colors.
bold = red = green = reset = ''
bold = red = green = yellow = reset = ''
unless process.env.NODE_DISABLE_COLORS
bold = '\x1B[0;1m'
red = '\x1B[0;31m'
green = '\x1B[0;32m'
reset = '\x1B[0m'
bold = '\x1B[0;1m'
red = '\x1B[0;31m'
green = '\x1B[0;32m'
yellow = '\x1B[0;33m'
reset = '\x1B[0m'
# Built file header.
header = """
@@ -51,27 +53,35 @@ run = (args, callback) ->
buildParser = ->
helpers.extend global, require 'util'
require 'jison'
parser = require('./lib/coffee-script/grammar').parser.generate()
# Patch Jisons output, until https://github.com/zaach/jison/pull/339 is accepted,
# to ensure that require('fs') is only called where it exists.
parser = parser.replace "var source = require('fs')", """
var source = '';
var fs = require('fs');
if (typeof fs !== 'undefined' && fs !== null)
source = fs"""
fs.writeFileSync 'lib/coffee-script/parser.js', parser
# We don't need `moduleMain`, since the parser is unlikely to be run standalone.
parser = require('./lib/coffeescript/grammar').parser.generate(moduleMain: ->)
fs.writeFileSync 'lib/coffeescript/parser.js', parser
buildExceptParser = (callback) ->
files = fs.readdirSync 'src'
files = ('src/' + file for file in files when file.match(/\.(lit)?coffee$/))
run ['-c', '-o', 'lib/coffee-script'].concat(files), callback
run ['-c', '-o', 'lib/coffeescript'].concat(files), callback
build = (callback) ->
buildParser()
buildExceptParser callback
transpile = (code) ->
babel = require 'babel-core'
presets = []
# Exclude the `modules` plugin in order to not break the `}(this));`
# at the end of the `build:browser` code block.
presets.push ['env', {modules: no}] unless process.env.TRANSFORM is 'false'
presets.push 'minify' unless process.env.MINIFY is 'false'
babelOptions =
compact: process.env.MINIFY isnt 'false'
presets: presets
sourceType: 'script'
{ code } = babel.transform code, babelOptions unless presets.length is 0
code
testBuiltCode = (watch = no) ->
csPath = './lib/coffee-script'
csPath = './lib/coffeescript'
csDir = path.dirname require.resolve csPath
for mod of require.cache when csDir is mod[0 ... csDir.length]
@@ -83,7 +93,7 @@ testBuiltCode = (watch = no) ->
buildAndTest = (includingParser = yes, harmony = no) ->
process.stdout.write '\x1Bc' # Clear terminal screen.
execSync 'git checkout lib/*', stdio: [0,1,2] # Reset the generated compiler.
execSync 'git checkout lib/*', stdio: 'inherit' # Reset the generated compiler.
buildArgs = ['bin/cake']
buildArgs.push if includingParser then 'build' else 'build:except-parser'
@@ -122,11 +132,11 @@ task 'build:browser', 'merge the built scripts into a single file for use in a b
return #{fs.readFileSync "./package.json"};
})();
"""
for name in ['helpers', 'rewriter', 'lexer', 'parser', 'scope', 'nodes', 'sourcemap', 'coffee-script', 'browser']
for name in ['helpers', 'rewriter', 'lexer', 'parser', 'scope', 'nodes', 'sourcemap', 'coffeescript', 'browser']
code += """
require['./#{name}'] = (function() {
var exports = {}, module = {exports: exports};
#{fs.readFileSync "lib/coffee-script/#{name}.js"}
#{fs.readFileSync "lib/coffeescript/#{name}.js"}
return module.exports;
})();
"""
@@ -135,7 +145,7 @@ task 'build:browser', 'merge the built scripts into a single file for use in a b
var CoffeeScript = function() {
function require(path){ return require[path]; }
#{code}
return require['./coffee-script'];
return require['./browser'];
}();
if (typeof define === 'function' && define.amd) {
@@ -145,15 +155,10 @@ task 'build:browser', 'merge the built scripts into a single file for use in a b
}
}(this));
"""
unless process.env.MINIFY is 'false'
{compiledCode: code} = require('google-closure-compiler-js').compile
jsCode: [
src: code
languageOut: if majorVersion is 1 then 'ES5' else 'ES6'
]
code = transpile code
outputFolder = "docs/v#{majorVersion}/browser-compiler"
fs.mkdirSync outputFolder unless fs.existsSync outputFolder
fs.writeFileSync "#{outputFolder}/coffee-script.js", header + '\n' + code
fs.writeFileSync "#{outputFolder}/coffeescript.js", header + '\n' + code
task 'build:browser:full', 'merge the built scripts into a single file for use in a browser, and test it', ->
invoke 'build:browser'
@@ -169,11 +174,11 @@ task 'build:watch:harmony', 'watch and continually rebuild the CoffeeScript comp
buildDocs = (watch = no) ->
# Constants
indexFile = 'documentation/index.html'
versionedSourceFolder = "documentation/v#{majorVersion}"
indexFile = 'documentation/site/index.html'
siteSourceFolder = "documentation/site"
sectionsSourceFolder = 'documentation/sections'
examplesSourceFolder = 'documentation/examples'
outputFolder = "docs/v#{majorVersion}"
outputFolder = "docs/v#{majorVersion}"
# Helpers
releaseHeader = (date, version, prevVersion) ->
@@ -191,12 +196,22 @@ buildDocs = (watch = no) ->
</h2>
"""
codeFor = require "./documentation/v#{majorVersion}/code.coffee"
codeFor = require "./documentation/site/code.coffee"
htmlFor = ->
hljs = require 'highlight.js'
hljs.configure classPrefix: ''
markdownRenderer = require('markdown-it')
html: yes
typographer: yes
highlight: (str, lang) ->
# From https://github.com/markdown-it/markdown-it#syntax-highlighting
if lang and hljs.getLanguage(lang)
try
return hljs.highlight(lang, str).value
catch ex
return '' # No syntax highlighting
# Add some custom overrides to Markdown-Its rendering, per
# https://github.com/markdown-it/markdown-it/blob/master/docs/architecture.md#renderer
@@ -218,9 +233,17 @@ buildDocs = (watch = no) ->
codeFor: codeFor()
releaseHeader: releaseHeader
includeScript = ->
(file) ->
file = "#{siteSourceFolder}/#{file}" unless '/' in file
code = fs.readFileSync file, 'utf-8'
code = CoffeeScript.compile code
code = transpile code
code
include = ->
(file) ->
file = "#{versionedSourceFolder}/#{file}" if file.indexOf('/') is -1
file = "#{siteSourceFolder}/#{file}" unless '/' in file
output = fs.readFileSync file, 'utf-8'
if /\.html$/.test(file)
render = _.template output
@@ -231,6 +254,7 @@ buildDocs = (watch = no) ->
htmlFor: htmlFor()
codeFor: codeFor()
include: include()
includeScript: includeScript()
output
# Task
@@ -245,7 +269,7 @@ buildDocs = (watch = no) ->
catch exception
if watch
for target in [indexFile, versionedSourceFolder, examplesSourceFolder, sectionsSourceFolder]
for target in [indexFile, siteSourceFolder, examplesSourceFolder, sectionsSourceFolder]
fs.watch target, interval: 200, renderIndex
log 'watching...', green
@@ -258,9 +282,9 @@ task 'doc:site:watch', 'watch and continually rebuild the documentation for the
buildDocTests = (watch = no) ->
# Constants
testFile = 'documentation/test.html'
testFile = 'documentation/site/test.html'
testsSourceFolder = 'test'
outputFolder = "docs/v#{majorVersion}"
outputFolder = "docs/v#{majorVersion}"
# Included in test.html
testHelpers = fs.readFileSync('test/support/helpers.coffee', 'utf-8').replace /exports\./g, '@'
@@ -308,7 +332,7 @@ task 'doc:test:watch', 'watch and continually rebuild the browser-based tests',
buildAnnotatedSource = (watch = no) ->
do generateAnnotatedSource = ->
exec "node_modules/docco/bin/docco src/*.*coffee --output docs/v#{majorVersion}/annotated-source", (err) -> throw err if err
exec "cd src && ../node_modules/docco/bin/docco *.*coffee --output ../docs/v#{majorVersion}/annotated-source", (err) -> throw err if err
log 'generated', green, "annotated source in docs/v#{majorVersion}/annotated-source/"
if watch
@@ -323,15 +347,19 @@ task 'doc:source:watch', 'watch and continually rebuild the annotated source doc
task 'release', 'build and test the CoffeeScript source, and build the documentation', ->
invoke 'build:full'
invoke 'build:browser:full'
invoke 'doc:site'
invoke 'doc:test'
invoke 'doc:source'
execSync '''
cake build:full
cake build:browser
cake test:browser
cake test:integrations
cake doc:site
cake doc:test
cake doc:source''', stdio: 'inherit'
task 'bench', 'quick benchmark of compilation time', ->
{Rewriter} = require './lib/coffee-script/rewriter'
sources = ['coffee-script', 'grammar', 'helpers', 'lexer', 'nodes', 'rewriter']
{Rewriter} = require './lib/coffeescript/rewriter'
sources = ['coffeescript', 'grammar', 'helpers', 'lexer', 'nodes', 'rewriter']
coffee = sources.map((name) -> fs.readFileSync "src/#{name}.coffee").join '\n'
litcoffee = fs.readFileSync("src/scope.litcoffee").toString()
fmt = (ms) -> " #{bold}#{ " #{ms}".slice -4 }#{reset} ms"
@@ -353,30 +381,49 @@ task 'bench', 'quick benchmark of compilation time', ->
# Run the CoffeeScript test suite.
runTests = (CoffeeScript) ->
CoffeeScript.register()
startTime = Date.now()
currentFile = null
passedTests = 0
failures = []
CoffeeScript.register() unless global.testingBrowser
# These are attached to `global` so that theyre accessible from within
# `test/async.coffee`, which has an async-capable version of
# `global.test`.
global.currentFile = null
global.passedTests = 0
global.failures = []
global[name] = func for name, func of require 'assert'
# Convenience aliases.
global.CoffeeScript = CoffeeScript
global.Repl = require './lib/coffee-script/repl'
global.Repl = require './lib/coffeescript/repl'
global.bold = bold
global.red = red
global.green = green
global.yellow = yellow
global.reset = reset
asyncTests = []
onFail = (description, fn, err) ->
failures.push
filename: global.currentFile
error: err
description: description
source: fn.toString() if fn.toString?
# Our test helper function for delimiting different test cases.
global.test = (description, fn) ->
try
fn.test = {description, currentFile}
fn.call(fn)
++passedTests
catch e
failures.push
filename: currentFile
error: e
description: description if description?
source: fn.toString() if fn.toString?
result = fn.call(fn)
if result instanceof Promise # An async test.
asyncTests.push result
result.then ->
passedTests++
.catch (err) ->
onFail description, fn, err
else
passedTests++
catch err
onFail description, fn, err
helpers.extend global, require './test/support/helpers'
@@ -395,9 +442,20 @@ runTests = (CoffeeScript) ->
console.log " #{source}" if source
return
# Run every test in the `test` folder, recording failures.
files = fs.readdirSync 'test'
# Run every test in the `test` folder, recording failures, except for files
# were skipping because the features to be tested are unsupported in the
# current Node runtime.
testFilesToSkip = []
skipUnless = (featureDetect, filenames) ->
unless (try new Function featureDetect)
testFilesToSkip = testFilesToSkip.concat filenames
skipUnless 'async () => {}', ['async.coffee', 'async_iterators.coffee']
skipUnless 'async function* generator() { yield 42; }', ['async_iterators.coffee']
skipUnless 'var a = 2 ** 2; a **= 3', ['exponentiation.coffee']
files = fs.readdirSync('test').filter (filename) ->
filename not in testFilesToSkip
startTime = Date.now()
for file in files when helpers.isCoffee file
literate = helpers.isLiterate file
currentFile = filename = path.join 'test', file
@@ -406,18 +464,53 @@ runTests = (CoffeeScript) ->
CoffeeScript.run code.toString(), {filename, literate}
catch error
failures.push {filename, error}
return !failures.length
Promise.all(asyncTests).then ->
Promise.reject() if failures.length isnt 0
task 'test', 'run the CoffeeScript language test suite', ->
testResults = runTests CoffeeScript
process.exit 1 unless testResults
runTests(CoffeeScript).catch -> process.exit 1
task 'test:browser', 'run the test suite against the merged browser script', ->
source = fs.readFileSync "docs/v#{majorVersion}/browser-compiler/coffee-script.js", 'utf-8'
source = fs.readFileSync "docs/v#{majorVersion}/browser-compiler/coffeescript.js", 'utf-8'
result = {}
global.testingBrowser = yes
(-> eval source).call result
testResults = runTests result.CoffeeScript
process.exit 1 unless testResults
runTests(CoffeeScript).catch -> process.exit 1
task 'test:integrations', 'test the module integrated with other libraries and environments', ->
# Tools like Webpack and Browserify generate builds intended for a browser
# environment where Node modules are not available. We want to ensure that
# the CoffeeScript module as presented by the `browser` key in `package.json`
# can be built by such tools; if such a build succeeds, it verifies that no
# Node modules are required as part of the compiler (as opposed to the tests)
# and that therefore the compiler will run in a browser environment.
tmpdir = os.tmpdir()
webpack = require 'webpack'
webpack {
entry: './'
output:
path: tmpdir
filename: 'coffeescript.js'
library: 'CoffeeScript'
libraryTarget: 'commonjs2'
}, (err, stats) ->
if err or stats.hasErrors()
if err
console.error err.stack or err
console.error err.details if err.details
if stats.hasErrors()
console.error error for error in stats.compilation.errors
if stats.hasWarnings()
console.warn warning for warning in stats.compilation.warnings
process.exit 1
builtCompiler = path.join tmpdir, 'coffeescript.js'
CoffeeScript = require builtCompiler
global.testingBrowser = yes
testResults = runTests CoffeeScript
fs.unlinkSync builtCompiler
process.exit 1 unless testResults

62
ISSUE_TEMPLATE.md Normal file
View File

@@ -0,0 +1,62 @@
<!---
Thanks for filing an issue 😄! Before you submit, please read the following:
Search open/closed issues before submitting since someone might have asked the same thing before!
Our issues history stretches back to 2009, so the odds are good that your topic has come up.
If you have a support request or question please use Stack Overflow:
https://stackoverflow.com/questions/tagged/coffeescript
Issues on GitHub are only related to problems of the CoffeeScript compiler itself and we cannot answer
support questions here.
-->
Choose one: is this a bug report or feature request?
<!---
Provide a general summary of the issue in the title above.
For bugs, please also preface your title with “Bug:”. For feature requests, please preface your title
with “Proposal:”. Once your issue is reviewed, a maintainer will edit the title to refer to the part
of the codebase most relevant to the issue (if applicable).
If your request is that CoffeeScript support a new feature recently arrived to JavaScript, please note
that we generally only add features that have reached Stage 4 in the specification (in other words,
the syntax is finalized and the feature is approved to be part of the next ES release). You can still
open an issue, but it will likely be tagged with “[Awaiting Stage 4]” until the relevant ES feature is
approved for release. See http://coffeescript.org/#contributing
There are also a handful of JavaScript features that CoffeeScript intentionally does not support.
Please do not open issues regarding these. Theyre listed in http://coffeescript.org/#unsupported
-->
### Input Code
<!--- If you're describing a bug, please let us know which sample code reproduces your problem. -->
<!--- If you have link from http://coffeescript.org/#try or a standalone repo please include that! -->
```coffee
your (code) => here
```
### Expected Behavior
<!--- If youre describing a bug, tell us what should happen. -->
<!--- If youre suggesting a change/improvement, tell us how it should work. -->
### Current Behavior
<!--- If describing a bug, tell us what happens instead of the expected behavior. -->
<!--- If suggesting a change/improvement, explain the difference from current behavior. -->
### Possible Solution
<!--- Not obligatory, but suggest a fix/reason for the bug, -->
<!--- or ideas how to implement the addition or change. -->
### Context
<!--- How has this issue affected you? What are you trying to accomplish? -->
<!--- Providing context helps us come up with a solution that is most useful in the real world. -->
### Environment
<!--- For bugs, please let us know what version of CoffeeScript youre running: `coffee -v`. -->
<!--- If you think it might be relevant, please also let us know your version of Node. -->
* CoffeeScript version:
* Node.js version:

View File

@@ -1,4 +1,4 @@
Copyright (c) 2009-2017 Jeremy Ashkenas
Copyright (c) 2009-2018 Jeremy Ashkenas
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation

22
PULL_REQUEST_TEMPLATE.md Normal file
View File

@@ -0,0 +1,22 @@
<!--
Before making a PR please make sure to read our contributing guidelines:
http://coffeescript.org/#contributing
For issue references: Add a comma-separated list of a
[closing word](https://help.github.com/articles/closing-issues-via-commit-messages/) followed by
the ticket number fixed by the PR. It should be underlined in the preview if done correctly.
All new features require tests. All but the most trivial bug fixes should also have new or updated tests.
Ensure that all new code you add to the compiler can be run in the minimum version of Node listed in
`package.json`. New tests can require newer Node runtimes, but you may need to ensure that such tests
only run in supported runtimes; see `Cakefile` for examples of how to filter out certain tests in
runtimes that dont support them.
Please follow the code style of the rest of the CoffeeScript codebase. Write comments in complete
sentences using Markdown, as the comments become the [annotated source](http://coffeescript.org/#annotated-source).
For tests proving a bug is fixed, please mention the issue number in the test description (see examples
in the codebase).
Describe your changes below in as much detail as possible.
-->

View File

@@ -1,22 +1,27 @@
{
} } {
{ { } }
} }{ {
{ }{ } } _____ __ __
{ }{ }{ { } / ____| / _|/ _|
.- { { } { }} -. | | ___ | |_| |_ ___ ___
( { } { } { } } ) | | / _ \| _| _/ _ \/ _ \
|`-..________ ..-'| | |___| (_) | | | || __/ __/
| | \_____\___/|_| |_| \___|\___|
| ;--.
| (__ \ _____ _ _
| | ) ) / ____| (_) | |
| |/ / | (___ ___ _ __ _ _ __ | |_
| ( / \___ \ / __| '__| | '_ \| __|
| |/ ____) | (__| | | | |_) | |_
| | |_____/ \___|_| |_| .__/ \__|
`-.._________..-' | |
|_|
@@@@@@@ @@@@ @@@@@
{ @@@@@@@@@@ @@@ @@@
} } { @@@@ @@ @@@ @@@
{ { } } @@@@ @@@@@@@ @@@ @@@ @@@@@@ @@@@@@
} }{ { @@@@ @@@ @@ @@@@@ @@@@@@ @@@ @@ @@@@ @@
{ }{ } } @@@@ @@@@ @@ @@@ @@@ @@@ @@@ @@@ @@@
{ }{ }{ { } @@@@ @@@@ @@ @@@ @@@ @@@@@@@@ @@@@@@@@
{ { } { } { } } @@@@@ @@@@ @@ @@@ @@@ @@@ @@@
{ } { } { } @@@@@@@@@@ @@@@@@@@ @@@ @@@ @@@@@@@@ @@@@@@@@
@@@@@@ { } { } @@@@@@@ @@@@@ @@@ @@@ @@@@@ @@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@ @@@
@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@ @@@ @@@
@@ @@@@@@@@@@@@@@@@@@@@@@@@ @@@@ @@ @@@ @@@@
@@@ @@@@@@@@@@@@@@@@@@@@@ @@@@ @@@ @@ @@@@
@@@ @@@@@@@@@@@@@@@@@@ @@@@@ @@@@@ @@ @@ @@@ @@@@@@@ @@@@@
@@@ @@@@@@@@@@@@@@@@ @@@@@ @@@ @@@ @@@@@@@@ @@@@ @@@@ @@@@@@@
@@@@@@@@@@@@@@ @@@@@ @@@ @@@@ @@@@ @@@ @@@ @@@
@@@@@ @@@@ @@@@ @@@@ @@@@ @@@@ @@@@ @@@@
@@@ @@@@ @@@ @@@@ @@@@ @@@ @@@@ @@@@
@@@ @@@@ @@@@ @@@@ @@@@ @@@@ @@@@ @@@@
@@@@@@@@@ @@@@@@ @@@@ @@@@ @@@@@@@@@ @@@@
@@@ @@@@
@@@
@@@
CoffeeScript is a little language that compiles into JavaScript.

29
appveyor.yml Normal file
View File

@@ -0,0 +1,29 @@
environment:
matrix:
- nodejs_version: '6'
- nodejs_version: '8'
- nodejs_version: '9'
- nodejs_version: '' # Installs latest.
install:
- ps: Install-Product node $env:nodejs_version
- node --version
- npm --version
- npm install
cache:
- node_modules
test_script:
- node ./bin/cake build:except-parser
- node ./bin/cake build:parser
- node ./bin/cake build:full
- node ./bin/cake build:browser
- node ./bin/cake test
- node --harmony ./bin/cake test
- node ./bin/cake test:browser
- node ./bin/cake test:integrations
build: off
version: "{build}"

View File

@@ -1,5 +1,12 @@
#!/usr/bin/env node
try {
new Function('var {a} = {a: 1}')();
} catch (error) {
console.error('Your JavaScript runtime does not support some features used by the cake command. Please use Node 6 or later.');
process.exit(1);
}
var path = require('path');
var fs = require('fs');
@@ -7,7 +14,7 @@ var potentialPaths = [
path.join(process.cwd(), 'node_modules/coffeescript/lib/coffeescript'),
path.join(process.cwd(), 'node_modules/coffeescript/lib/coffee-script'),
path.join(process.cwd(), 'node_modules/coffee-script/lib/coffee-script'),
path.join(__dirname, '../lib/coffee-script')
path.join(__dirname, '../lib/coffeescript')
];
for (var i = 0, len = potentialPaths.length; i < len; i++) {

View File

@@ -1,5 +1,12 @@
#!/usr/bin/env node
try {
new Function('var {a} = {a: 1}')();
} catch (error) {
console.error('Your JavaScript runtime does not support some features used by the coffee command. Please use Node 6 or later.');
process.exit(1);
}
var path = require('path');
var fs = require('fs');
@@ -7,7 +14,7 @@ var potentialPaths = [
path.join(process.cwd(), 'node_modules/coffeescript/lib/coffeescript'),
path.join(process.cwd(), 'node_modules/coffeescript/lib/coffee-script'),
path.join(process.cwd(), 'node_modules/coffee-script/lib/coffee-script'),
path.join(__dirname, '../lib/coffee-script')
path.join(__dirname, '../lib/coffeescript')
];
for (var i = 0, len = potentialPaths.length; i < len; i++) {

View File

@@ -1,7 +1,7 @@
{
"name": "coffee-script",
"name": "coffeescript",
"main": [
"lib/coffee-script/coffee-script.js"
"lib/coffeescript/browser.js"
],
"description": "Unfancy JavaScript",
"keywords": [

1
docs/annotated-source Symbolic link
View File

@@ -0,0 +1 @@
v2/annotated-source

View File

@@ -0,0 +1 @@
v2/announcing-coffeescript-2

1
docs/browser-compiler Symbolic link
View File

@@ -0,0 +1 @@
v2/browser-compiler

View File

@@ -1 +1 @@
v1/index.html
v2/index.html

View File

@@ -1,5 +1,6 @@
{
"name": "",
"name": "CoffeeScript",
"description": "Unfancy JavaScript",
"icons": [
{
"src": "\/android-chrome-192x192.png",

1
docs/test.html Symbolic link
View File

@@ -0,0 +1 @@
v2/test.html

View File

@@ -594,18 +594,18 @@ pre .xml .cdata {
Annotated Source
</div>
<div class="contents menu">
<a href="/v1/annotated-source/grammar.html">Grammar Rules — src/grammar</a>
<a href="/v1/annotated-source/lexer.html">Lexing Tokens — src/lexer</a>
<a href="/v1/annotated-source/rewriter.html">The Rewriter — src/rewriter</a>
<a href="/v1/annotated-source/nodes.html">The Syntax Tree — src/nodes</a>
<a href="/v1/annotated-source/scope.html">Lexical Scope — src/scope</a>
<a href="/v1/annotated-source/helpers.html">Helpers &amp; Utility Functions — src/helpers</a>
<a href="/v1/annotated-source/coffee-script.html">The CoffeeScript Module — src/coffee-script</a>
<a href="/v1/annotated-source/cake.html">Cake &amp; Cakefiles — src/cake</a>
<a href="/v1/annotated-source/command.html">“coffee” Command-Line Utility — src/command</a>
<a href="/v1/annotated-source/optparse.html">Option Parsing — src/optparse</a>
<a href="/v1/annotated-source/repl.html">Interactive REPL — src/repl</a>
<a href="/v1/annotated-source/sourcemap.html">Source Maps — src/sourcemap</a>
<a href="annotated-source/grammar.html">Grammar Rules — src/grammar</a>
<a href="annotated-source/lexer.html">Lexing Tokens — src/lexer</a>
<a href="annotated-source/rewriter.html">The Rewriter — src/rewriter</a>
<a href="annotated-source/nodes.html">The Syntax Tree — src/nodes</a>
<a href="annotated-source/scope.html">Lexical Scope — src/scope</a>
<a href="annotated-source/helpers.html">Helpers &amp; Utility Functions — src/helpers</a>
<a href="annotated-source/coffee-script.html">The CoffeeScript Module — src/coffee-script</a>
<a href="annotated-source/cake.html">Cake &amp; Cakefiles — src/cake</a>
<a href="annotated-source/command.html">“coffee” Command-Line Utility — src/command</a>
<a href="annotated-source/optparse.html">Option Parsing — src/optparse</a>
<a href="annotated-source/repl.html">Interactive REPL — src/repl</a>
<a href="annotated-source/sourcemap.html">Source Maps — src/sourcemap</a>
</div>
</div>
</div>
@@ -615,10 +615,10 @@ pre .xml .cdata {
<p><strong>CoffeeScript is a little language that compiles into JavaScript.</strong> Underneath that awkward Java-esque patina, JavaScript has always had a gorgeous heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.</p>
<p>The golden rule of CoffeeScript is: <em>“Its just JavaScript”</em>. The code compiles one-to-one into the equivalent JS, and there is no interpretation at runtime. You can use any existing JavaScript library seamlessly from CoffeeScript (and vice-versa). The compiled output is readable, pretty-printed, and tends to run as fast or faster than the equivalent handwritten JavaScript.</p>
<p>The CoffeeScript compiler goes to great lengths to generate output JavaScript that runs in every JavaScript runtime, but there are exceptions. Use <a href="#generator-functions">generator functions</a>, <a href="#generator-iteration"><code>for…from</code></a>, or <a href="#tagged-template-literals">tagged template literals</a> only if you know that your <a href="http://kangax.github.io/compat-table/es6/">target runtimes can support them</a>. If you use <a href="#modules">modules</a>, you will need to <a href="#modules-note">use an additional tool to resolve them</a>.</p>
<p><strong>Latest Version:</strong> <a href="https://github.com/jashkenas/coffeescript/tarball/1.12.7">1.12.7</a></p>
<p><strong>Latest 1.x Version:</strong> <a href="https://github.com/jashkenas/coffeescript/tarball/1.12.7">1.12.7</a></p>
<blockquote class="uneditable-code-block"><pre><code class="language-bash">npm install -g coffeescript
</code></pre>
</blockquote><p><strong>CoffeeScript 2 is coming!</strong> It adds support for <a href="/v2/#classes">ES2015 classes</a>, <a href="/v2/#fat-arrow"><code>async</code>/<code>await</code></a>, <a href="/v2/#jsx">JSX</a>, <span class="nowrap"><a href="/v2/#splats">object rest/spread syntax</a></span>, and JavaScript generated using ES2015+ syntax. <a href="/v2/">Learn more</a>.</p>
</blockquote><p><strong>Upgrade to CoffeeScript 2!</strong> It adds support for <a href="/#classes">ES2015 classes</a>, <a href="/#async-functions"><code>async</code>/<code>await</code></a>, <a href="/#jsx">JSX</a>, <span class="nowrap"><a href="/#splats">object rest/spread syntax</a></span>, and <a href="/#coffeescript-2">JavaScript generated using modern syntax</a>. <a href="/announcing-coffeescript-2/">Learn more</a>.</p>
<h2>Overview</h2>
<p><em>CoffeeScript on the left, compiled JavaScript output on the right.</em></p>
@@ -741,7 +741,7 @@ cubes = (function() {
;alert(cubes);">run: cubes</div><br class='clear' /></div>
<span class="bookmark" id="installation"></span>
<h2>Installation</h2>
<p>The command-line version of <code>coffee</code> is available as a <a href="https://nodejs.org/">Node.js</a> utility. The <a href="/v1/browser-compiler/coffee-script.js">core compiler</a> however, does not depend on Node, and can be run in any JavaScript environment, or in the browser (see <a href="#try">Try CoffeeScript</a>).</p>
<p>The command-line version of <code>coffee</code> is available as a <a href="https://nodejs.org/">Node.js</a> utility. The <a href="browser-compiler/coffee-script.js">core compiler</a> however, does not depend on Node, and can be run in any JavaScript environment, or in the browser (see <a href="#try">Try CoffeeScript</a>).</p>
<p>To install, first make sure you have a working copy of the latest stable version of <a href="https://nodejs.org/">Node.js</a>. You can then install CoffeeScript globally with <a href="https://www.npmjs.com/">npm</a>:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-bash">npm install --global coffeescript
</code></pre>
@@ -2441,7 +2441,7 @@ task(<span class="string">'build:parser'</span>, <span class="string">'rebuild t
dir = options.output || <span class="string">'lib'</span>;
<span class="keyword">return</span> fs.writeFile(dir + <span class="string">"/parser.js"</span>, code);
});
</code></pre><script>window.example1 = "fs = require 'fs'\n\noption '-o', '--output [DIR]', 'directory for compiled code'\n\ntask 'build:parser', 'rebuild the Jison parser', (options) ->\n require 'jison'\n code = require('./lib/grammar').parser.generate()\n dir = options.output or 'lib'\n fs.writeFile \"#{dir}/parser.js\", code\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example1);'>load</div><br class='clear' /></div><p>If you need to invoke one task before another — for example, running <code>build</code> before <code>test</code>, you can use the <code>invoke</code> function: <code>invoke 'build'</code>. Cake tasks are a minimal way to expose your CoffeeScript functions to the command line, so <a href="/v1/annotated-source/cake.html">dont expect any fanciness built-in</a>. If you need dependencies, or async callbacks, its best to put them in your code itself — not the cake task.</p>
</code></pre><script>window.example1 = "fs = require 'fs'\n\noption '-o', '--output [DIR]', 'directory for compiled code'\n\ntask 'build:parser', 'rebuild the Jison parser', (options) ->\n require 'jison'\n code = require('./lib/grammar').parser.generate()\n dir = options.output or 'lib'\n fs.writeFile \"#{dir}/parser.js\", code\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example1);'>load</div><br class='clear' /></div><p>If you need to invoke one task before another — for example, running <code>build</code> before <code>test</code>, you can use the <code>invoke</code> function: <code>invoke 'build'</code>. Cake tasks are a minimal way to expose your CoffeeScript functions to the command line, so <a href="annotated-source/cake.html">dont expect any fanciness built-in</a>. If you need dependencies, or async callbacks, its best to put them in your code itself — not the cake task.</p>
<span class="bookmark" id="source-maps"></span>
<h2>Source Maps</h2>
@@ -2450,7 +2450,7 @@ task(<span class="string">'build:parser'</span>, <span class="string">'rebuild t
<span class="bookmark" id="scripts"></span>
<h2>“text/coffeescript” Script Tags</h2>
<p>While its not recommended for serious use, CoffeeScripts may be included directly within the browser using <code>&lt;script type=&quot;text/coffeescript&quot;&gt;</code> tags. The source includes a compressed and minified version of the compiler (<a href="/v1/browser-compiler/coffee-script.js">Download current version here, 51k when gzipped</a>) as <code>v1/browser-compiler/coffee-script.js</code>. Include this file on a page with inline CoffeeScript tags, and it will compile and evaluate them in order.</p>
<p>While its not recommended for serious use, CoffeeScripts may be included directly within the browser using <code>&lt;script type=&quot;text/coffeescript&quot;&gt;</code> tags. The source includes a compressed and minified version of the compiler (<a href="browser-compiler/coffee-script.js">Download current version here, 51k when gzipped</a>) as <code>docs/v1/browser-compiler/coffee-script.js</code>. Include this file on a page with inline CoffeeScript tags, and it will compile and evaluate them in order.</p>
<p>In fact, the little bit of glue script that runs “Try CoffeeScript” above, as well as the jQuery for the menu, is implemented in just this way. View source and look at the bottom of the page to see the example. Including the script also gives you access to <code>CoffeeScript.compile()</code> so you can pop open Firebug and try compiling some strings.</p>
<p>The usual caveats about CoffeeScript apply — your inline scripts will run within a closure wrapper, so if you want to expose global variables or functions, attach them to the <code>window</code> object.</p>
@@ -2501,7 +2501,7 @@ Use <code>bin/coffee</code> to test your changes,<br>
<p><code>git checkout lib &amp;&amp; bin/cake build:full</code> is a good command to run when youre working on the core language. Itll refresh the <code>lib</code> folder (in case you broke something), build your altered compiler, use that to rebuild itself (a good sanity test) and then run all of the tests. If they pass, theres a good chance youve made a successful change.</p>
</li>
<li>
<p><a href="/v1/test.html">Browser Tests</a><br>
<p><a href="test.html">Browser Tests</a><br>
Run CoffeeScripts test suite in your current browser.</p>
</li>
<li>
@@ -2592,7 +2592,7 @@ The CoffeeScript logo is available in SVG for use in presentations.</p>
<li>The browser compiler can once again be built unminified via <code>MINIFY=false cake build:browser</code>.</li>
<li>The error-prone patched version of <code>Error.prepareStackTrace</code> has been removed.</li>
<li>Command completion in the REPL (pressing tab to get suggestions) has been fixed for Node 6.9.1+.</li>
<li>The <a href="/v1/test.html">browser-based tests</a> now include all the tests as the Node-based version.</li>
<li>The <a href="test.html">browser-based tests</a> now include all the tests as the Node-based version.</li>
</ul>
<div class="anchor" id="1.12.1"></div>
<h2 class="header">
@@ -2611,7 +2611,7 @@ The CoffeeScript logo is available in SVG for use in presentations.</p>
<li>CoffeeScript now provides a <a href="#generator-iteration"><code>for…from</code></a> syntax for outputting ES2015 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of"><code>for…of</code></a>. (Sorry they couldnt match, but we came up with <code>for…of</code> first for something else.) This allows iterating over generators or any other iterable object. Note that using <code>for…from</code> in your code makes you responsible for ensuring that either your runtime supports <code>for…of</code> or that you transpile the output JavaScript further to a version your target runtime(s) support.</li>
<li>Triple backticks (<code>```</code>) allow the creation of embedded JavaScript blocks where escaping single backticks is not required, which should improve interoperability with ES2015 template literals and with Markdown.</li>
<li>Within single-backtick embedded JavaScript, backticks can now be escaped via <code>\`</code>.</li>
<li>The browser tests now run in the browser again, and are accessible <a href="/v1/test.html">here</a> if you would like to test your browser.</li>
<li>The browser tests now run in the browser again, and are accessible <a href="test.html">here</a> if you would like to test your browser.</li>
<li>CoffeeScript-only keywords in ES2015 <code>import</code>s and <code>export</code>s are now ignored.</li>
<li>The compiler now throws an error on trying to export an anonymous class.</li>
<li>Bugfixes related to tokens and location data, for better source maps and improved compatibility with downstream tools.</li>
@@ -3016,7 +3016,7 @@ used to parse as <code>result = (i for i in list)</code> by default … it now p
<a href="https://github.com/jashkenas/coffeescript/compare/0.5.1...0.5.2">0.5.2</a>
<span class="timestamp"> &mdash; <time datetime="2010-02-25">February 25, 2010</time></span>
</h2><p>Added a compressed version of the compiler for inclusion in web pages as
<code>/v1/browser-compiler/coffee-script.js</code>. Itll automatically run any script tags with type <code>text/coffeescript</code> for you. Added a <code>--stdio</code> option to the <code>coffee</code> command, for piped-in compiles.</p>
<code>browser-compiler/coffee-script.js</code>. Itll automatically run any script tags with type <code>text/coffeescript</code> for you. Added a <code>--stdio</code> option to the <code>coffee</code> command, for piped-in compiles.</p>
<div class="anchor" id="0.5.1"></div>
<h2 class="header">
<a href="https://github.com/jashkenas/coffeescript/compare/0.5.0...0.5.1">0.5.1</a>
@@ -3222,7 +3222,7 @@ compileSource()
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="v1/browser-compiler/coffee-script.js"></script>
<script src="browser-compiler/coffee-script.js"></script>
</body>
</html>

View File

@@ -159,7 +159,7 @@ evaluated from <code>lib/coffeescript</code>.</p>
<div class="content"><div class='highlight'><pre>exports.VERSION = packageJson.version
exports.FILE_EXTENSIONS = [<span class="hljs-string">'.coffee'</span>, <span class="hljs-string">'.litcoffee'</span>, <span class="hljs-string">'.coffee.md'</span>]</pre></div></div>
exports.FILE_EXTENSIONS = FILE_EXTENSIONS = [<span class="hljs-string">'.coffee'</span>, <span class="hljs-string">'.litcoffee'</span>, <span class="hljs-string">'.coffee.md'</span>]</pre></div></div>
</li>
@@ -252,7 +252,7 @@ didnt create a source map (faster) but something went wrong and we need
a stack trace. Assuming that most of the time, code isnt throwing
exceptions, its probably more efficient to compile twice only when we
need a stack trace, rather than always generating a source map even when
its not likely to be used. Save in form of <code>filename</code>: <code>(source)</code></p>
its not likely to be used. Save in form of <code>filename</code>: [<code>(source)</code>]</p>
</div>
@@ -267,7 +267,7 @@ its not likely to be used. Save in form of <code>filename</code>: <code>(sour
<div class="pilwrap ">
<a class="pilcrow" href="#section-9">&#182;</a>
</div>
<p>Also save source maps if generated, in form of <code>filename</code>: <code>(source map)</code>.</p>
<p>Also save source maps if generated, in form of <code>(source)</code>: [<code>(source map)</code>].</p>
</div>
@@ -293,9 +293,7 @@ doing programmatic lookups.</p>
</div>
<div class="content"><div class='highlight'><pre>exports.compile = compile = withPrettyErrors (code, options) -&gt;
{merge, extend} = helpers
options = extend {}, options</pre></div></div>
<div class="content"><div class='highlight'><pre>exports.compile = compile = withPrettyErrors (code, options = {}) -&gt;</pre></div></div>
</li>
@@ -306,19 +304,11 @@ doing programmatic lookups.</p>
<div class="pilwrap ">
<a class="pilcrow" href="#section-11">&#182;</a>
</div>
<p>Always generate a source map if no filename is passed in, since without a
a filename we have no way to retrieve this source later in the event that
we need to recompile it to get a source map for <code>prepareStackTrace</code>.</p>
<p>Clone <code>options</code>, to avoid mutating the <code>options</code> object passed in.</p>
</div>
<div class="content"><div class='highlight'><pre> generateSourceMap = options.sourceMap <span class="hljs-keyword">or</span> options.inlineMap <span class="hljs-keyword">or</span> <span class="hljs-keyword">not</span> options.filename?
filename = options.filename <span class="hljs-keyword">or</span> <span class="hljs-string">'&lt;anonymous&gt;'</span>
sources[filename] = code
map = <span class="hljs-keyword">new</span> SourceMap <span class="hljs-keyword">if</span> generateSourceMap
tokens = lexer.tokenize code, options</pre></div></div>
<div class="content"><div class='highlight'><pre> options = Object.assign {}, options</pre></div></div>
</li>
@@ -329,6 +319,32 @@ we need to recompile it to get a source map for <code>prepareStackTrace</code>.<
<div class="pilwrap ">
<a class="pilcrow" href="#section-12">&#182;</a>
</div>
<p>Always generate a source map if no filename is passed in, since without a
a filename we have no way to retrieve this source later in the event that
we need to recompile it to get a source map for <code>prepareStackTrace</code>.</p>
</div>
<div class="content"><div class='highlight'><pre> generateSourceMap = options.sourceMap <span class="hljs-keyword">or</span> options.inlineMap <span class="hljs-keyword">or</span> <span class="hljs-keyword">not</span> options.filename?
filename = options.filename <span class="hljs-keyword">or</span> <span class="hljs-string">'&lt;anonymous&gt;'</span>
checkShebangLine filename, code
sources[filename] ?= []
sources[filename].push code
map = <span class="hljs-keyword">new</span> SourceMap <span class="hljs-keyword">if</span> generateSourceMap
tokens = lexer.tokenize code, options</pre></div></div>
</li>
<li id="section-13">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-13">&#182;</a>
</div>
<p>Pass a list of referenced variables, so that generated variables wont get
the same name.</p>
@@ -341,11 +357,11 @@ the same name.</p>
</li>
<li id="section-13">
<li id="section-14">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-13">&#182;</a>
<a class="pilcrow" href="#section-14">&#182;</a>
</div>
<p>Check for import or export; if found, force bare mode.</p>
@@ -369,11 +385,11 @@ the same name.</p>
</li>
<li id="section-14">
<li id="section-15">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-14">&#182;</a>
<a class="pilcrow" href="#section-15">&#182;</a>
</div>
<p>Update the sourcemap with data from each fragment.</p>
@@ -384,11 +400,11 @@ the same name.</p>
</li>
<li id="section-15">
<li id="section-16">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-15">&#182;</a>
<a class="pilcrow" href="#section-16">&#182;</a>
</div>
<p>Do not include empty, whitespace, or semicolon-only fragments.</p>
@@ -409,11 +425,11 @@ the same name.</p>
</li>
<li id="section-16">
<li id="section-17">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-16">&#182;</a>
<a class="pilcrow" href="#section-17">&#182;</a>
</div>
<p>Copy the code from each fragment into the final JavaScript.</p>
@@ -426,8 +442,69 @@ the same name.</p>
js = <span class="hljs-string">"// <span class="hljs-subst">#{header}</span>\n<span class="hljs-subst">#{js}</span>"</span>
<span class="hljs-keyword">if</span> generateSourceMap
v3SourceMap = map.generate(options, code)
sourceMaps[filename] = map
v3SourceMap = map.generate options, code
sourceMaps[filename] ?= []
sourceMaps[filename].push map
<span class="hljs-keyword">if</span> options.transpile
<span class="hljs-keyword">if</span> <span class="hljs-keyword">typeof</span> options.transpile <span class="hljs-keyword">isnt</span> <span class="hljs-string">'object'</span></pre></div></div>
</li>
<li id="section-18">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-18">&#182;</a>
</div>
<p>This only happens if run via the Node API and <code>transpile</code> is set to
something other than an object.</p>
</div>
<div class="content"><div class='highlight'><pre> <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Error <span class="hljs-string">'The transpile option must be given an object with options to pass to Babel'</span></pre></div></div>
</li>
<li id="section-19">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-19">&#182;</a>
</div>
<p>Get the reference to Babel that we have been passed if this compiler
is run via the CLI or Node API.</p>
</div>
<div class="content"><div class='highlight'><pre> transpiler = options.transpile.transpile
<span class="hljs-keyword">delete</span> options.transpile.transpile
transpilerOptions = Object.assign {}, options.transpile</pre></div></div>
</li>
<li id="section-20">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-20">&#182;</a>
</div>
<p>See <a href="https://github.com/babel/babel/issues/827#issuecomment-77573107">https://github.com/babel/babel/issues/827#issuecomment-77573107</a>:
Babel can take a v3 source map object as input in <code>inputSourceMap</code>
and it will return an <em>updated</em> v3 source map object in its output.</p>
</div>
<div class="content"><div class='highlight'><pre> <span class="hljs-keyword">if</span> v3SourceMap <span class="hljs-keyword">and</span> <span class="hljs-keyword">not</span> transpilerOptions.inputSourceMap?
transpilerOptions.inputSourceMap = v3SourceMap
transpilerOutput = transpiler js, transpilerOptions
js = transpilerOutput.code
<span class="hljs-keyword">if</span> v3SourceMap <span class="hljs-keyword">and</span> transpilerOutput.map
v3SourceMap = transpilerOutput.map
<span class="hljs-keyword">if</span> options.inlineMap
encoded = base64encode JSON.stringify v3SourceMap
@@ -447,11 +524,11 @@ the same name.</p>
</li>
<li id="section-17">
<li id="section-21">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-17">&#182;</a>
<a class="pilcrow" href="#section-21">&#182;</a>
</div>
<p>Tokenize a string of CoffeeScript code, and return the array of tokens.</p>
@@ -463,11 +540,11 @@ the same name.</p>
</li>
<li id="section-18">
<li id="section-22">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-18">&#182;</a>
<a class="pilcrow" href="#section-22">&#182;</a>
</div>
<p>Parse a string of CoffeeScript code or an array of lexed tokens, and
return the AST. You can then compile it by calling <code>.compile()</code> on the root,
@@ -484,11 +561,11 @@ or traverse it by using <code>.traverseChildren()</code> with a callback.</p>
</li>
<li id="section-19">
<li id="section-23">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-19">&#182;</a>
<a class="pilcrow" href="#section-23">&#182;</a>
</div>
<p>This file used to export these methods; leave stubs that throw warnings
instead. These methods have been moved into <code>index.coffee</code> to provide
@@ -504,11 +581,11 @@ environment.</p>
</li>
<li id="section-20">
<li id="section-24">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-20">&#182;</a>
<a class="pilcrow" href="#section-24">&#182;</a>
</div>
<p>Instantiate a Lexer for our use here.</p>
@@ -519,11 +596,11 @@ environment.</p>
</li>
<li id="section-21">
<li id="section-25">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-21">&#182;</a>
<a class="pilcrow" href="#section-25">&#182;</a>
</div>
<p>The real Lexer produces a generic stream of tokens. This object provides a
thin wrapper around it, compatible with the Jison API. We can then pass it
@@ -540,22 +617,20 @@ directly as a “Jison lexer”.</p>
@yylineno = @yylloc.first_line
<span class="hljs-keyword">else</span>
tag = <span class="hljs-string">''</span>
tag
setInput: <span class="hljs-function"><span class="hljs-params">(tokens)</span> -&gt;</span>
parser.tokens = tokens
@pos = <span class="hljs-number">0</span>
upcomingInput: <span class="hljs-function">-&gt;</span>
<span class="hljs-string">""</span></pre></div></div>
upcomingInput: <span class="hljs-function">-&gt;</span> <span class="hljs-string">''</span></pre></div></div>
</li>
<li id="section-22">
<li id="section-26">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-22">&#182;</a>
<a class="pilcrow" href="#section-26">&#182;</a>
</div>
<p>Make all the AST nodes visible to the parser.</p>
@@ -566,11 +641,11 @@ directly as a “Jison lexer”.</p>
</li>
<li id="section-23">
<li id="section-27">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-23">&#182;</a>
<a class="pilcrow" href="#section-27">&#182;</a>
</div>
<p>Override Jisons default error handling function.</p>
@@ -581,11 +656,11 @@ directly as a “Jison lexer”.</p>
</li>
<li id="section-24">
<li id="section-28">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-24">&#182;</a>
<a class="pilcrow" href="#section-28">&#182;</a>
</div>
<p>Disregard Jisons message, it contains redundant line number information.
Disregard the token, we take its value directly from the lexer in case
@@ -609,11 +684,11 @@ the error is caused by a generated token which might refer to its origin.</p>
</li>
<li id="section-25">
<li id="section-29">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-25">&#182;</a>
<a class="pilcrow" href="#section-29">&#182;</a>
</div>
<p>The second argument has a <code>loc</code> property, which should have the location
data for this token. Unfortunately, Jison seems to send an outdated <code>loc</code>
@@ -627,11 +702,11 @@ from the lexer.</p>
</li>
<li id="section-26">
<li id="section-30">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-26">&#182;</a>
<a class="pilcrow" href="#section-30">&#182;</a>
</div>
<p>Based on <a href="http://v8.googlecode.com/svn/branches/bleeding_edge/src/messages.js">http://v8.googlecode.com/svn/branches/bleeding_edge/src/messages.js</a>
Modified to handle sourceMap</p>
@@ -659,11 +734,11 @@ Modified to handle sourceMap</p>
</li>
<li id="section-27">
<li id="section-31">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-27">&#182;</a>
<a class="pilcrow" href="#section-31">&#182;</a>
</div>
<p>Check for a sourceMap position</p>
@@ -701,29 +776,87 @@ Modified to handle sourceMap</p>
<span class="hljs-keyword">else</span>
fileLocation
<span class="hljs-function">
<span class="hljs-title">getSourceMap</span> = <span class="hljs-params">(filename)</span> -&gt;</span>
<span class="hljs-keyword">if</span> sourceMaps[filename]?
sourceMaps[filename]</pre></div></div>
<span class="hljs-title">getSourceMap</span> = <span class="hljs-params">(filename, line, column)</span> -&gt;</span></pre></div></div>
</li>
<li id="section-28">
<li id="section-32">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-28">&#182;</a>
<a class="pilcrow" href="#section-32">&#182;</a>
</div>
<p>CoffeeScript compiled in a browser may get compiled with <code>options.filename</code>
of <code>&lt;anonymous&gt;</code>, but the browser may request the stack trace with the
filename of the script file.</p>
<p>Skip files that we didnt compile, like Node system files that appear in
the stack trace, as they never have source maps.</p>
</div>
<div class="content"><div class='highlight'><pre> <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> sourceMaps[<span class="hljs-string">'&lt;anonymous&gt;'</span>]?
sourceMaps[<span class="hljs-string">'&lt;anonymous&gt;'</span>]
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> sources[filename]?
answer = compile sources[filename],
<div class="content"><div class='highlight'><pre> <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span> <span class="hljs-keyword">unless</span> filename <span class="hljs-keyword">is</span> <span class="hljs-string">'&lt;anonymous&gt;'</span> <span class="hljs-keyword">or</span> filename.slice(filename.lastIndexOf(<span class="hljs-string">'.'</span>)) <span class="hljs-keyword">in</span> FILE_EXTENSIONS
<span class="hljs-keyword">if</span> filename <span class="hljs-keyword">isnt</span> <span class="hljs-string">'&lt;anonymous&gt;'</span> <span class="hljs-keyword">and</span> sourceMaps[filename]?
<span class="hljs-keyword">return</span> sourceMaps[filename][sourceMaps[filename].length - <span class="hljs-number">1</span>]</pre></div></div>
</li>
<li id="section-33">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-33">&#182;</a>
</div>
<p>CoffeeScript compiled in a browser or via <code>CoffeeScript.compile</code> or <code>.run</code>
may get compiled with <code>options.filename</code> thats missing, which becomes
<code>&lt;anonymous&gt;</code>; but the runtime might request the stack trace with the
filename of the script file. See if we have a source map cached under
<code>&lt;anonymous&gt;</code> that matches the error.</p>
</div>
<div class="content"><div class='highlight'><pre> <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> sourceMaps[<span class="hljs-string">'&lt;anonymous&gt;'</span>]?</pre></div></div>
</li>
<li id="section-34">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-34">&#182;</a>
</div>
<p>Work backwards from the most recent anonymous source maps, until we find
one that works. This isnt foolproof; there is a chance that multiple
source maps will have line/column pairs that match. But we have no other
way to match them. <code>frame.getFunction().toString()</code> doesnt always work,
and its not foolproof either.</p>
</div>
<div class="content"><div class='highlight'><pre> <span class="hljs-keyword">for</span> map <span class="hljs-keyword">in</span> sourceMaps[<span class="hljs-string">'&lt;anonymous&gt;'</span>] <span class="hljs-keyword">by</span> <span class="hljs-number">-1</span>
sourceLocation = map.sourceLocation [line - <span class="hljs-number">1</span>, column - <span class="hljs-number">1</span>]
<span class="hljs-keyword">return</span> map <span class="hljs-keyword">if</span> sourceLocation?[<span class="hljs-number">0</span>]? <span class="hljs-keyword">and</span> sourceLocation[<span class="hljs-number">1</span>]?</pre></div></div>
</li>
<li id="section-35">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-35">&#182;</a>
</div>
<p>If all else fails, recompile this source to get a source map. We need the
previous section (for <code>&lt;anonymous&gt;</code>) despite this option, because after it
gets compiled we will still need to look it up from
<code>sourceMaps[&#39;&lt;anonymous&gt;&#39;]</code> in order to find and return it. Thats why we
start searching from the end in the previous block, because most of the
time the source map we want is the last one.</p>
</div>
<div class="content"><div class='highlight'><pre> <span class="hljs-keyword">if</span> sources[filename]?
answer = compile sources[filename][sources[filename].length - <span class="hljs-number">1</span>],
filename: filename
sourceMap: <span class="hljs-literal">yes</span>
literate: helpers.isLiterate filename
@@ -734,11 +867,11 @@ filename of the script file.</p>
</li>
<li id="section-29">
<li id="section-36">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-29">&#182;</a>
<a class="pilcrow" href="#section-36">&#182;</a>
</div>
<p>Based on <a href="http://goo.gl/ZTx1p">michaelficarra/CoffeeScriptRedux</a>
NodeJS / V8 have no support for transforming positions in stack traces using
@@ -749,7 +882,7 @@ positions.</p>
<div class="content"><div class='highlight'><pre>Error.prepareStackTrace = <span class="hljs-function"><span class="hljs-params">(err, stack)</span> -&gt;</span>
<span class="hljs-function"> <span class="hljs-title">getSourceMapping</span> = <span class="hljs-params">(filename, line, column)</span> -&gt;</span>
sourceMap = getSourceMap filename
sourceMap = getSourceMap filename, line, column
answer = sourceMap.sourceLocation [line - <span class="hljs-number">1</span>, column - <span class="hljs-number">1</span>] <span class="hljs-keyword">if</span> sourceMap?
<span class="hljs-keyword">if</span> answer? <span class="hljs-keyword">then</span> [answer[<span class="hljs-number">0</span>] + <span class="hljs-number">1</span>, answer[<span class="hljs-number">1</span>] + <span class="hljs-number">1</span>] <span class="hljs-keyword">else</span> <span class="hljs-literal">null</span>
@@ -757,7 +890,20 @@ positions.</p>
<span class="hljs-keyword">break</span> <span class="hljs-keyword">if</span> frame.getFunction() <span class="hljs-keyword">is</span> exports.run
<span class="hljs-string">" at <span class="hljs-subst">#{formatSourcePosition frame, getSourceMapping}</span>"</span>
<span class="hljs-string">"<span class="hljs-subst">#{err.toString()}</span>\n<span class="hljs-subst">#{frames.join <span class="hljs-string">'\n'</span>}</span>\n"</span></pre></div></div>
<span class="hljs-string">"<span class="hljs-subst">#{err.toString()}</span>\n<span class="hljs-subst">#{frames.join <span class="hljs-string">'\n'</span>}</span>\n"</span>
<span class="hljs-function">
<span class="hljs-title">checkShebangLine</span> = <span class="hljs-params">(file, input)</span> -&gt;</span>
firstLine = input.split(<span class="hljs-regexp">/$/m</span>)[<span class="hljs-number">0</span>]
rest = firstLine?.match(<span class="hljs-regexp">/^#!\s*([^\s]+\s*)(.*)/</span>)
args = rest?[<span class="hljs-number">2</span>]?.split(<span class="hljs-regexp">/\s/</span>).filter (s) -&gt; s <span class="hljs-keyword">isnt</span> <span class="hljs-string">''</span>
<span class="hljs-keyword">if</span> args?.length &gt; <span class="hljs-number">1</span>
<span class="hljs-built_in">console</span>.error <span class="hljs-string">'''
The script to be run begins with a shebang line with more than one
argument. This script will fail on platforms such as Linux which only
allow a single argument.
'''</span>
<span class="hljs-built_in">console</span>.error <span class="hljs-string">"The shebang line was: '<span class="hljs-subst">#{firstLine}</span>' in file '<span class="hljs-subst">#{file}</span>'"</span>
<span class="hljs-built_in">console</span>.error <span class="hljs-string">"The arguments were: <span class="hljs-subst">#{JSON.stringify args}</span>"</span></pre></div></div>
</li>

View File

@@ -180,7 +180,7 @@ useWinPathSep = path.sep <span class="hljs-keyword">is</span> <span class="hljs
</div>
<div class="content"><div class='highlight'><pre>BANNER = <span class="hljs-string">'''
Usage: coffee [options] path/to/script.coffee -- [args]
Usage: coffee [options] path/to/script.coffee [args]
If called without options, `coffee` will run your script.
'''</span></pre></div></div>
@@ -199,25 +199,26 @@ useWinPathSep = path.sep <span class="hljs-keyword">is</span> <span class="hljs
</div>
<div class="content"><div class='highlight'><pre>SWITCHES = [
[<span class="hljs-string">'-b'</span>, <span class="hljs-string">'--bare'</span>, <span class="hljs-string">'compile without a top-level function wrapper'</span>]
[<span class="hljs-string">'-c'</span>, <span class="hljs-string">'--compile'</span>, <span class="hljs-string">'compile to JavaScript and save as .js files'</span>]
[<span class="hljs-string">'-e'</span>, <span class="hljs-string">'--eval'</span>, <span class="hljs-string">'pass a string from the command line as input'</span>]
[<span class="hljs-string">'-h'</span>, <span class="hljs-string">'--help'</span>, <span class="hljs-string">'display this help message'</span>]
[<span class="hljs-string">'-i'</span>, <span class="hljs-string">'--interactive'</span>, <span class="hljs-string">'run an interactive CoffeeScript REPL'</span>]
[<span class="hljs-string">'-j'</span>, <span class="hljs-string">'--join [FILE]'</span>, <span class="hljs-string">'concatenate the source CoffeeScript before compiling'</span>]
[<span class="hljs-string">'-m'</span>, <span class="hljs-string">'--map'</span>, <span class="hljs-string">'generate source map and save as .js.map files'</span>]
[<span class="hljs-string">'-M'</span>, <span class="hljs-string">'--inline-map'</span>, <span class="hljs-string">'generate source map and include it directly in output'</span>]
[<span class="hljs-string">'-n'</span>, <span class="hljs-string">'--nodes'</span>, <span class="hljs-string">'print out the parse tree that the parser produces'</span>]
[ <span class="hljs-string">'--nodejs [ARGS]'</span>, <span class="hljs-string">'pass options directly to the "node" binary'</span>]
[ <span class="hljs-string">'--no-header'</span>, <span class="hljs-string">'suppress the "Generated by" header'</span>]
[<span class="hljs-string">'-o'</span>, <span class="hljs-string">'--output [DIR]'</span>, <span class="hljs-string">'set the output directory for compiled JavaScript'</span>]
[<span class="hljs-string">'-p'</span>, <span class="hljs-string">'--print'</span>, <span class="hljs-string">'print out the compiled JavaScript'</span>]
[<span class="hljs-string">'-b'</span>, <span class="hljs-string">'--bare'</span>, <span class="hljs-string">'compile without a top-level function wrapper'</span>]
[<span class="hljs-string">'-c'</span>, <span class="hljs-string">'--compile'</span>, <span class="hljs-string">'compile to JavaScript and save as .js files'</span>]
[<span class="hljs-string">'-e'</span>, <span class="hljs-string">'--eval'</span>, <span class="hljs-string">'pass a string from the command line as input'</span>]
[<span class="hljs-string">'-h'</span>, <span class="hljs-string">'--help'</span>, <span class="hljs-string">'display this help message'</span>]
[<span class="hljs-string">'-i'</span>, <span class="hljs-string">'--interactive'</span>, <span class="hljs-string">'run an interactive CoffeeScript REPL'</span>]
[<span class="hljs-string">'-j'</span>, <span class="hljs-string">'--join [FILE]'</span>, <span class="hljs-string">'concatenate the source CoffeeScript before compiling'</span>]
[<span class="hljs-string">'-m'</span>, <span class="hljs-string">'--map'</span>, <span class="hljs-string">'generate source map and save as .js.map files'</span>]
[<span class="hljs-string">'-M'</span>, <span class="hljs-string">'--inline-map'</span>, <span class="hljs-string">'generate source map and include it directly in output'</span>]
[<span class="hljs-string">'-n'</span>, <span class="hljs-string">'--nodes'</span>, <span class="hljs-string">'print out the parse tree that the parser produces'</span>]
[ <span class="hljs-string">'--nodejs [ARGS]'</span>, <span class="hljs-string">'pass options directly to the "node" binary'</span>]
[ <span class="hljs-string">'--no-header'</span>, <span class="hljs-string">'suppress the "Generated by" header'</span>]
[<span class="hljs-string">'-o'</span>, <span class="hljs-string">'--output [PATH]'</span>, <span class="hljs-string">'set the output path or path/filename for compiled JavaScript'</span>]
[<span class="hljs-string">'-p'</span>, <span class="hljs-string">'--print'</span>, <span class="hljs-string">'print out the compiled JavaScript'</span>]
[<span class="hljs-string">'-r'</span>, <span class="hljs-string">'--require [MODULE*]'</span>, <span class="hljs-string">'require the given module before eval or REPL'</span>]
[<span class="hljs-string">'-s'</span>, <span class="hljs-string">'--stdio'</span>, <span class="hljs-string">'listen for and compile scripts over stdio'</span>]
[<span class="hljs-string">'-l'</span>, <span class="hljs-string">'--literate'</span>, <span class="hljs-string">'treat stdio as literate style coffeescript'</span>]
[<span class="hljs-string">'-t'</span>, <span class="hljs-string">'--tokens'</span>, <span class="hljs-string">'print out the tokens that the lexer/rewriter produce'</span>]
[<span class="hljs-string">'-v'</span>, <span class="hljs-string">'--version'</span>, <span class="hljs-string">'display the version number'</span>]
[<span class="hljs-string">'-w'</span>, <span class="hljs-string">'--watch'</span>, <span class="hljs-string">'watch scripts for changes and rerun commands'</span>]
[<span class="hljs-string">'-s'</span>, <span class="hljs-string">'--stdio'</span>, <span class="hljs-string">'listen for and compile scripts over stdio'</span>]
[<span class="hljs-string">'-l'</span>, <span class="hljs-string">'--literate'</span>, <span class="hljs-string">'treat stdio as literate style coffeescript'</span>]
[<span class="hljs-string">'-t'</span>, <span class="hljs-string">'--transpile'</span>, <span class="hljs-string">'pipe generated JavaScript through Babel'</span>]
[ <span class="hljs-string">'--tokens'</span>, <span class="hljs-string">'print out the tokens that the lexer/rewriter produce'</span>]
[<span class="hljs-string">'-v'</span>, <span class="hljs-string">'--version'</span>, <span class="hljs-string">'display the version number'</span>]
[<span class="hljs-string">'-w'</span>, <span class="hljs-string">'--watch'</span>, <span class="hljs-string">'watch scripts for changes and rerun commands'</span>]
]</pre></div></div>
</li>
@@ -260,7 +261,21 @@ Many flags cause us to divert before compiling anything. Flags passed after
<div class="content"><div class='highlight'><pre>exports.run = <span class="hljs-function">-&gt;</span>
optionParser = buildCSOptionParser()
parseOptions()</pre></div></div>
<span class="hljs-keyword">try</span> parseOptions()
<span class="hljs-keyword">catch</span> err
<span class="hljs-built_in">console</span>.error <span class="hljs-string">"option parsing error: <span class="hljs-subst">#{err.message}</span>"</span>
process.exit <span class="hljs-number">1</span>
<span class="hljs-keyword">if</span> (<span class="hljs-keyword">not</span> opts.doubleDashed) <span class="hljs-keyword">and</span> (opts.arguments[<span class="hljs-number">1</span>] <span class="hljs-keyword">is</span> <span class="hljs-string">'--'</span>)
printWarn <span class="hljs-string">'''
coffee was invoked with '--' as the second positional argument, which is
now deprecated. To pass '--' as an argument to a script to run, put an
additional '--' before the path to your script.
'--' will be removed from the argument list.
'''</span>
printWarn <span class="hljs-string">"The positional arguments were: <span class="hljs-subst">#{JSON.stringify opts.arguments}</span>"</span>
opts.arguments = [opts.arguments[<span class="hljs-number">0</span>]].concat opts.arguments[<span class="hljs-number">2.</span>.]</pre></div></div>
</li>
@@ -280,6 +295,7 @@ Many flags cause us to divert before compiling anything. Flags passed after
<div class="content"><div class='highlight'><pre> replCliOpts = useGlobal: <span class="hljs-literal">yes</span>
opts.prelude = makePrelude opts.<span class="hljs-built_in">require</span> <span class="hljs-keyword">if</span> opts.<span class="hljs-built_in">require</span>
replCliOpts.prelude = opts.prelude
replCliOpts.transpile = opts.transpile
<span class="hljs-keyword">return</span> forkNode() <span class="hljs-keyword">if</span> opts.nodejs
<span class="hljs-keyword">return</span> usage() <span class="hljs-keyword">if</span> opts.help
<span class="hljs-keyword">return</span> version() <span class="hljs-keyword">if</span> opts.version
@@ -291,7 +307,45 @@ Many flags cause us to divert before compiling anything. Flags passed after
process.argv = process.argv[<span class="hljs-number">0.</span><span class="hljs-number">.1</span>].concat literals
process.argv[<span class="hljs-number">0</span>] = <span class="hljs-string">'coffee'</span>
opts.output = path.resolve opts.output <span class="hljs-keyword">if</span> opts.output
<span class="hljs-keyword">if</span> opts.output
outputBasename = path.basename opts.output
<span class="hljs-keyword">if</span> <span class="hljs-string">'.'</span> <span class="hljs-keyword">in</span> outputBasename <span class="hljs-keyword">and</span>
outputBasename <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> [<span class="hljs-string">'.'</span>, <span class="hljs-string">'..'</span>] <span class="hljs-keyword">and</span>
<span class="hljs-keyword">not</span> helpers.ends(opts.output, path.sep)</pre></div></div>
</li>
<li id="section-9">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-9">&#182;</a>
</div>
<p>An output filename was specified, e.g. <code>/dist/scripts.js</code>.</p>
</div>
<div class="content"><div class='highlight'><pre> opts.outputFilename = outputBasename
opts.outputPath = path.resolve path.dirname opts.output
<span class="hljs-keyword">else</span></pre></div></div>
</li>
<li id="section-10">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-10">&#182;</a>
</div>
<p>An output path was specified, e.g. <code>/dist</code>.</p>
</div>
<div class="content"><div class='highlight'><pre> opts.outputFilename = <span class="hljs-literal">null</span>
opts.outputPath = path.resolve opts.output
<span class="hljs-keyword">if</span> opts.join
opts.join = path.resolve opts.join
<span class="hljs-built_in">console</span>.error <span class="hljs-string">'''
@@ -314,19 +368,19 @@ Many flags cause us to divert before compiling anything. Flags passed after
<span class="hljs-function">
<span class="hljs-title">makePrelude</span> = <span class="hljs-params">(requires)</span> -&gt;</span>
requires.map (<span class="hljs-built_in">module</span>) -&gt;
[_, name, <span class="hljs-built_in">module</span>] = match <span class="hljs-keyword">if</span> match = <span class="hljs-built_in">module</span>.match(<span class="hljs-regexp">/^(.*)=(.*)$/</span>)
name ||= helpers.baseFileName <span class="hljs-built_in">module</span>, <span class="hljs-literal">yes</span>, useWinPathSep
<span class="hljs-string">"<span class="hljs-subst">#{name}</span> = require('<span class="hljs-subst">#{<span class="hljs-built_in">module</span>}</span>')"</span>
[full, name, <span class="hljs-built_in">module</span>] = match <span class="hljs-keyword">if</span> match = <span class="hljs-built_in">module</span>.match(<span class="hljs-regexp">/^(.*)=(.*)$/</span>)
name <span class="hljs-keyword">or</span>= helpers.baseFileName <span class="hljs-built_in">module</span>, <span class="hljs-literal">yes</span>, useWinPathSep
<span class="hljs-string">"global['<span class="hljs-subst">#{name}</span>'] = require('<span class="hljs-subst">#{<span class="hljs-built_in">module</span>}</span>')"</span>
.join <span class="hljs-string">';'</span></pre></div></div>
</li>
<li id="section-9">
<li id="section-11">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-9">&#182;</a>
<a class="pilcrow" href="#section-11">&#182;</a>
</div>
<p>Compile a path, which could be a script or a directory. If a directory
is passed, recursively compile all .coffee, .litcoffee, and .coffee.md
@@ -368,7 +422,7 @@ extension source files in it and all subdirectories.</p>
code = fs.readFileSync source
<span class="hljs-keyword">catch</span> err
<span class="hljs-keyword">if</span> err.code <span class="hljs-keyword">is</span> <span class="hljs-string">'ENOENT'</span> <span class="hljs-keyword">then</span> <span class="hljs-keyword">return</span> <span class="hljs-keyword">else</span> <span class="hljs-keyword">throw</span> err
compileScript(source, code.toString(), base)
compileScript source, code.toString(), base
<span class="hljs-keyword">else</span>
notSources[source] = <span class="hljs-literal">yes</span>
<span class="hljs-function">
@@ -385,53 +439,56 @@ extension source files in it and all subdirectories.</p>
</li>
<li id="section-10">
<li id="section-12">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-10">&#182;</a>
<a class="pilcrow" href="#section-12">&#182;</a>
</div>
<p>Compile a single source script, containing the given code, according to the
requested options. If evaluating the script directly sets <code>__filename</code>,
requested options. If evaluating the script directly, set <code>__filename</code>,
<code>__dirname</code> and <code>module.filename</code> to be correct relative to the scripts path.</p>
</div>
<div class="content"><div class='highlight'><pre><span class="hljs-function"><span class="hljs-title">compileScript</span> = <span class="hljs-params">(file, input, base = <span class="hljs-literal">null</span>)</span> -&gt;</span>
o = opts
options = compileOptions file, base
<span class="hljs-keyword">try</span>
t = task = {file, input, options}
task = {file, input, options}
CoffeeScript.emit <span class="hljs-string">'compile'</span>, task
<span class="hljs-keyword">if</span> o.tokens
printTokens CoffeeScript.tokens t.input, t.options
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> o.nodes
printLine CoffeeScript.nodes(t.input, t.options).toString().trim()
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> o.run
<span class="hljs-keyword">if</span> opts.tokens
printTokens CoffeeScript.tokens task.input, task.options
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> opts.nodes
printLine CoffeeScript.nodes(task.input, task.options).toString().trim()
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> opts.run
CoffeeScript.register()
CoffeeScript.eval opts.prelude, t.options <span class="hljs-keyword">if</span> opts.prelude
CoffeeScript.run t.input, t.options
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> o.join <span class="hljs-keyword">and</span> t.file <span class="hljs-keyword">isnt</span> o.join
t.input = helpers.invertLiterate t.input <span class="hljs-keyword">if</span> helpers.isLiterate file
sourceCode[sources.indexOf(t.file)] = t.input
CoffeeScript.eval opts.prelude, task.options <span class="hljs-keyword">if</span> opts.prelude
CoffeeScript.run task.input, task.options
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> opts.join <span class="hljs-keyword">and</span> task.file <span class="hljs-keyword">isnt</span> opts.join
task.input = helpers.invertLiterate task.input <span class="hljs-keyword">if</span> helpers.isLiterate file
sourceCode[sources.indexOf(task.file)] = task.input
compileJoin()
<span class="hljs-keyword">else</span>
compiled = CoffeeScript.compile t.input, t.options
t.output = compiled
<span class="hljs-keyword">if</span> o.map
t.output = compiled.js
t.sourceMap = compiled.v3SourceMap
compiled = CoffeeScript.compile task.input, task.options
task.output = compiled
<span class="hljs-keyword">if</span> opts.map
task.output = compiled.js
task.sourceMap = compiled.v3SourceMap
CoffeeScript.emit <span class="hljs-string">'success'</span>, task
<span class="hljs-keyword">if</span> o.<span class="hljs-built_in">print</span>
printLine t.output.trim()
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> o.compile <span class="hljs-keyword">or</span> o.map
writeJs base, t.file, t.output, options.jsPath, t.sourceMap
<span class="hljs-keyword">if</span> opts.<span class="hljs-built_in">print</span>
printLine task.output.trim()
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> opts.compile <span class="hljs-keyword">or</span> opts.map
saveTo = <span class="hljs-keyword">if</span> opts.outputFilename <span class="hljs-keyword">and</span> sources.length <span class="hljs-keyword">is</span> <span class="hljs-number">1</span>
path.join opts.outputPath, opts.outputFilename
<span class="hljs-keyword">else</span>
options.jsPath
writeJs base, task.file, task.output, saveTo, task.sourceMap
<span class="hljs-keyword">catch</span> err
CoffeeScript.emit <span class="hljs-string">'failure'</span>, err, task
<span class="hljs-keyword">return</span> <span class="hljs-keyword">if</span> CoffeeScript.listeners(<span class="hljs-string">'failure'</span>).length
message = err?.stack <span class="hljs-keyword">or</span> <span class="hljs-string">"<span class="hljs-subst">#{err}</span>"</span>
<span class="hljs-keyword">if</span> o.watch
<span class="hljs-keyword">if</span> opts.watch
printLine message + <span class="hljs-string">'\x07'</span>
<span class="hljs-keyword">else</span>
printWarn message
@@ -440,11 +497,11 @@ requested options. If evaluating the script directly sets <code>__filename</code
</li>
<li id="section-11">
<li id="section-13">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-11">&#182;</a>
<a class="pilcrow" href="#section-13">&#182;</a>
</div>
<p>Attach the appropriate listeners to compile scripts incoming over <strong>stdin</strong>,
and write them back to <strong>stdout</strong>.</p>
@@ -452,6 +509,9 @@ and write them back to <strong>stdout</strong>.</p>
</div>
<div class="content"><div class='highlight'><pre><span class="hljs-function"><span class="hljs-title">compileStdio</span> = -&gt;</span>
<span class="hljs-keyword">if</span> opts.map
<span class="hljs-built_in">console</span>.error <span class="hljs-string">'--stdio and --map cannot be used together'</span>
process.exit <span class="hljs-number">1</span>
buffers = []
stdin = process.openStdin()
stdin.<span class="hljs-literal">on</span> <span class="hljs-string">'data'</span>, <span class="hljs-function"><span class="hljs-params">(buffer)</span> -&gt;</span>
@@ -462,11 +522,11 @@ and write them back to <strong>stdout</strong>.</p>
</li>
<li id="section-12">
<li id="section-14">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-12">&#182;</a>
<a class="pilcrow" href="#section-14">&#182;</a>
</div>
<p>If all of the source files are done being read, concatenate and compile
them together.</p>
@@ -484,11 +544,11 @@ them together.</p>
</li>
<li id="section-13">
<li id="section-15">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-13">&#182;</a>
<a class="pilcrow" href="#section-15">&#182;</a>
</div>
<p>Watch a source CoffeeScript file using <code>fs.watch</code>, recompiling it every
time the file is updated. May be used in combination with other options,
@@ -544,11 +604,11 @@ such as <code>--print</code>.</p>
</li>
<li id="section-14">
<li id="section-16">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-14">&#182;</a>
<a class="pilcrow" href="#section-16">&#182;</a>
</div>
<p>Watch a directory of files for new additions.</p>
@@ -595,11 +655,11 @@ such as <code>--print</code>.</p>
</li>
<li id="section-15">
<li id="section-17">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-15">&#182;</a>
<a class="pilcrow" href="#section-17">&#182;</a>
</div>
<p>Remove a file from our source list, and source code cache. Optionally remove
the compiled JS version as well.</p>
@@ -624,11 +684,11 @@ the compiled JS version as well.</p>
</li>
<li id="section-16">
<li id="section-18">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-16">&#182;</a>
<a class="pilcrow" href="#section-18">&#182;</a>
</div>
<p>Get the corresponding output JavaScript path for a source file.</p>
@@ -637,22 +697,22 @@ the compiled JS version as well.</p>
<div class="content"><div class='highlight'><pre><span class="hljs-function"><span class="hljs-title">outputPath</span> = <span class="hljs-params">(source, base, extension=<span class="hljs-string">".js"</span>)</span> -&gt;</span>
basename = helpers.baseFileName source, <span class="hljs-literal">yes</span>, useWinPathSep
srcDir = path.dirname source
<span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> opts.output
dir = srcDir
dir = <span class="hljs-keyword">unless</span> opts.outputPath
srcDir
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> source <span class="hljs-keyword">is</span> base
dir = opts.output
opts.outputPath
<span class="hljs-keyword">else</span>
dir = path.join opts.output, path.relative base, srcDir
path.join opts.outputPath, path.relative base, srcDir
path.join dir, basename + extension</pre></div></div>
</li>
<li id="section-17">
<li id="section-19">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-17">&#182;</a>
<a class="pilcrow" href="#section-19">&#182;</a>
</div>
<p>Recursively mkdir, like <code>mkdir -p</code>.</p>
@@ -674,11 +734,11 @@ the compiled JS version as well.</p>
</li>
<li id="section-18">
<li id="section-20">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-18">&#182;</a>
<a class="pilcrow" href="#section-20">&#182;</a>
</div>
<p>Write out a JavaScript source file with the compiled code. By default, files
are written out in <code>cwd</code> as <code>.js</code> files with the same name, but the output
@@ -689,7 +749,7 @@ same directory as the <code>.js</code> file.</p>
</div>
<div class="content"><div class='highlight'><pre><span class="hljs-function"><span class="hljs-title">writeJs</span> = <span class="hljs-params">(base, sourcePath, js, jsPath, generatedSourceMap = <span class="hljs-literal">null</span>)</span> -&gt;</span>
sourceMapPath = outputPath sourcePath, base, <span class="hljs-string">".js.map"</span>
sourceMapPath = <span class="hljs-string">"<span class="hljs-subst">#{jsPath}</span>.map"</span>
jsDir = path.dirname jsPath
<span class="hljs-function"> <span class="hljs-title">compile</span> = -&gt;</span>
<span class="hljs-keyword">if</span> opts.compile
@@ -712,11 +772,11 @@ same directory as the <code>.js</code> file.</p>
</li>
<li id="section-19">
<li id="section-21">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-19">&#182;</a>
<a class="pilcrow" href="#section-21">&#182;</a>
</div>
<p>Convenience for cleaner setTimeouts.</p>
@@ -727,11 +787,11 @@ same directory as the <code>.js</code> file.</p>
</li>
<li id="section-20">
<li id="section-22">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-20">&#182;</a>
<a class="pilcrow" href="#section-22">&#182;</a>
</div>
<p>When watching scripts, its useful to log changes with the timestamp.</p>
@@ -743,11 +803,11 @@ same directory as the <code>.js</code> file.</p>
</li>
<li id="section-21">
<li id="section-23">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-21">&#182;</a>
<a class="pilcrow" href="#section-23">&#182;</a>
</div>
<p>Pretty-print a stream of tokens, sans location data.</p>
@@ -763,11 +823,11 @@ same directory as the <code>.js</code> file.</p>
</li>
<li id="section-22">
<li id="section-24">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-22">&#182;</a>
<a class="pilcrow" href="#section-24">&#182;</a>
</div>
<p>Use the <a href="optparse.html">OptionParser module</a> to extract all options from
<code>process.argv</code> that are specified in <code>SWITCHES</code>.</p>
@@ -783,25 +843,121 @@ same directory as the <code>.js</code> file.</p>
</li>
<li id="section-23">
<li id="section-25">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-23">&#182;</a>
<a class="pilcrow" href="#section-25">&#182;</a>
</div>
<p>The compile-time options to pass to the CoffeeScript compiler.</p>
</div>
<div class="content"><div class='highlight'><pre><span class="hljs-function"><span class="hljs-title">compileOptions</span> = <span class="hljs-params">(filename, base)</span> -&gt;</span>
answer = {
filename
<span class="hljs-keyword">if</span> opts.transpile</pre></div></div>
</li>
<li id="section-26">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-26">&#182;</a>
</div>
<p>The user has requested that the CoffeeScript compiler also transpile
via Babel. We dont include Babel as a dependency because we want to
avoid dependencies in general, and most users probably wont be relying
on us to transpile for them; we assume most users will probably either
run CoffeeScripts output without transpilation (modern Node or evergreen
browsers) or use a proper build chain like Gulp or Webpack.</p>
</div>
<div class="content"><div class='highlight'><pre> <span class="hljs-keyword">try</span>
<span class="hljs-built_in">require</span> <span class="hljs-string">'babel-core'</span>
<span class="hljs-keyword">catch</span></pre></div></div>
</li>
<li id="section-27">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-27">&#182;</a>
</div>
<p>Give appropriate instructions depending on whether <code>coffee</code> was run
locally or globally.</p>
</div>
<div class="content"><div class='highlight'><pre> <span class="hljs-keyword">if</span> <span class="hljs-built_in">require</span>.resolve(<span class="hljs-string">'.'</span>).indexOf(process.cwd()) <span class="hljs-keyword">is</span> <span class="hljs-number">0</span>
<span class="hljs-built_in">console</span>.error <span class="hljs-string">'''
To use --transpile, you must have babel-core installed:
npm install --save-dev babel-core
And you must save options to configure Babel in one of the places it looks to find its options.
See http://coffeescript.org/#transpilation
'''</span>
<span class="hljs-keyword">else</span>
<span class="hljs-built_in">console</span>.error <span class="hljs-string">'''
To use --transpile with globally-installed CoffeeScript, you must have babel-core installed globally:
npm install --global babel-core
And you must save options to configure Babel in one of the places it looks to find its options, relative to the file being compiled or to the current folder.
See http://coffeescript.org/#transpilation
'''</span>
process.exit <span class="hljs-number">1</span>
opts.transpile = {} <span class="hljs-keyword">unless</span> <span class="hljs-keyword">typeof</span> opts.transpile <span class="hljs-keyword">is</span> <span class="hljs-string">'object'</span></pre></div></div>
</li>
<li id="section-28">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-28">&#182;</a>
</div>
<p>Pass a reference to Babel into the compiler, so that the transpile option
is available for the CLI. We need to do this so that tools like Webpack
can <code>require(&#39;coffeescript&#39;)</code> and build correctly, without trying to
require Babel.</p>
</div>
<div class="content"><div class='highlight'><pre> opts.transpile.transpile = CoffeeScript.transpile</pre></div></div>
</li>
<li id="section-29">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-29">&#182;</a>
</div>
<p>Babel searches for its options (a <code>.babelrc</code> file, a <code>.babelrc.js</code> file,
a <code>package.json</code> file with a <code>babel</code> key, etc.) relative to the path
given to it in its <code>filename</code> option. Make sure we have a path to pass
along.</p>
</div>
<div class="content"><div class='highlight'><pre> <span class="hljs-keyword">unless</span> opts.transpile.filename
opts.transpile.filename = filename <span class="hljs-keyword">or</span> path.resolve(base <span class="hljs-keyword">or</span> process.cwd(), <span class="hljs-string">'&lt;anonymous&gt;'</span>)
<span class="hljs-keyword">else</span>
opts.transpile = <span class="hljs-literal">no</span>
answer =
filename: filename
literate: opts.literate <span class="hljs-keyword">or</span> helpers.isLiterate(filename)
bare: opts.bare
header: opts.compile <span class="hljs-keyword">and</span> <span class="hljs-keyword">not</span> opts[<span class="hljs-string">'no-header'</span>]
transpile: opts.transpile
sourceMap: opts.map
inlineMap: opts[<span class="hljs-string">'inline-map'</span>]
}
<span class="hljs-keyword">if</span> filename
<span class="hljs-keyword">if</span> base
cwd = process.cwd()
@@ -823,11 +979,11 @@ same directory as the <code>.js</code> file.</p>
</li>
<li id="section-24">
<li id="section-30">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-24">&#182;</a>
<a class="pilcrow" href="#section-30">&#182;</a>
</div>
<p>Start up a new Node.js instance with the arguments in <code>--nodejs</code> passed to
the <code>node</code> binary, preserving the other options.</p>
@@ -842,16 +998,19 @@ the <code>node</code> binary, preserving the other options.</p>
cwd: process.cwd()
env: process.env
stdio: [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
<span class="hljs-keyword">for</span> signal <span class="hljs-keyword">in</span> [<span class="hljs-string">'SIGINT'</span>, <span class="hljs-string">'SIGTERM'</span>]
process.<span class="hljs-literal">on</span> signal, <span class="hljs-keyword">do</span> (signal) -&gt;
-&gt; p.kill signal
p.<span class="hljs-literal">on</span> <span class="hljs-string">'exit'</span>, <span class="hljs-function"><span class="hljs-params">(code)</span> -&gt;</span> process.exit code</pre></div></div>
</li>
<li id="section-25">
<li id="section-31">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-25">&#182;</a>
<a class="pilcrow" href="#section-31">&#182;</a>
</div>
<p>Print the <code>--help</code> usage message and exit. Deprecated switches are not
shown.</p>
@@ -864,11 +1023,11 @@ shown.</p>
</li>
<li id="section-26">
<li id="section-32">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-26">&#182;</a>
<a class="pilcrow" href="#section-32">&#182;</a>
</div>
<p>Print the <code>--version</code> message and exit.</p>

File diff suppressed because it is too large Load Diff

View File

@@ -382,7 +382,10 @@ If <code>last</code> is not provided, this will simply return <code>first</code>
first_line: first.first_line
first_column: first.first_column
last_line: last.last_line
last_column: last.last_column</pre></div></div>
last_column: last.last_column
<span class="hljs-function">
<span class="hljs-title">buildLocationHash</span> = <span class="hljs-params">(loc)</span> -&gt;</span>
<span class="hljs-string">"<span class="hljs-subst">#{loc.first_line}</span>x<span class="hljs-subst">#{loc.first_column}</span>-<span class="hljs-subst">#{loc.last_line}</span>x<span class="hljs-subst">#{loc.last_column}</span>"</span></pre></div></div>
</li>
@@ -399,12 +402,8 @@ The object is returned either way.</p>
</div>
<div class="content"><div class='highlight'><pre>exports.addLocationDataFn = <span class="hljs-function"><span class="hljs-params">(first, last)</span> -&gt;</span>
(obj) -&gt;
<span class="hljs-keyword">if</span> ((<span class="hljs-keyword">typeof</span> obj) <span class="hljs-keyword">is</span> <span class="hljs-string">'object'</span>) <span class="hljs-keyword">and</span> (!!obj[<span class="hljs-string">'updateLocationDataIfMissing'</span>])
obj.updateLocationDataIfMissing buildLocationData(first, last)
<span class="hljs-keyword">return</span> obj</pre></div></div>
<div class="content"><div class='highlight'><pre>exports.addDataToNode = <span class="hljs-function"><span class="hljs-params">(parserState, first, last)</span> -&gt;</span>
(obj) -&gt;</pre></div></div>
</li>
@@ -415,6 +414,56 @@ The object is returned either way.</p>
<div class="pilwrap ">
<a class="pilcrow" href="#section-16">&#182;</a>
</div>
<p>Add location data</p>
</div>
<div class="content"><div class='highlight'><pre> <span class="hljs-keyword">if</span> obj?.updateLocationDataIfMissing? <span class="hljs-keyword">and</span> first?
obj.updateLocationDataIfMissing buildLocationData(first, last)</pre></div></div>
</li>
<li id="section-17">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-17">&#182;</a>
</div>
<p>Add comments data</p>
</div>
<div class="content"><div class='highlight'><pre> <span class="hljs-keyword">unless</span> parserState.tokenComments
parserState.tokenComments = {}
<span class="hljs-keyword">for</span> token <span class="hljs-keyword">in</span> parserState.parser.tokens <span class="hljs-keyword">when</span> token.comments
tokenHash = buildLocationHash token[<span class="hljs-number">2</span>]
<span class="hljs-keyword">unless</span> parserState.tokenComments[tokenHash]?
parserState.tokenComments[tokenHash] = token.comments
<span class="hljs-keyword">else</span>
parserState.tokenComments[tokenHash].push token.comments...
<span class="hljs-keyword">if</span> obj.locationData?
objHash = buildLocationHash obj.locationData
<span class="hljs-keyword">if</span> parserState.tokenComments[objHash]?
attachCommentsToNode parserState.tokenComments[objHash], obj
obj
exports.attachCommentsToNode = attachCommentsToNode = <span class="hljs-function"><span class="hljs-params">(comments, node)</span> -&gt;</span>
<span class="hljs-keyword">return</span> <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> comments? <span class="hljs-keyword">or</span> comments.length <span class="hljs-keyword">is</span> <span class="hljs-number">0</span>
node.comments ?= []
node.comments.push comments...</pre></div></div>
</li>
<li id="section-18">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-18">&#182;</a>
</div>
<p>Convert jison location data to a string.
<code>obj</code> can be a token, or a locationData.</p>
@@ -433,11 +482,11 @@ The object is returned either way.</p>
</li>
<li id="section-17">
<li id="section-19">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-17">&#182;</a>
<a class="pilcrow" href="#section-19">&#182;</a>
</div>
<p>A <code>.coffee.md</code> compatible version of <code>basename</code>, that returns the file sans-extension.</p>
@@ -456,11 +505,11 @@ The object is returned either way.</p>
</li>
<li id="section-18">
<li id="section-20">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-18">&#182;</a>
<a class="pilcrow" href="#section-20">&#182;</a>
</div>
<p>Determine if a filename represents a CoffeeScript file.</p>
@@ -471,11 +520,11 @@ The object is returned either way.</p>
</li>
<li id="section-19">
<li id="section-21">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-19">&#182;</a>
<a class="pilcrow" href="#section-21">&#182;</a>
</div>
<p>Determine if a filename represents a Literate CoffeeScript file.</p>
@@ -486,11 +535,11 @@ The object is returned either way.</p>
</li>
<li id="section-20">
<li id="section-22">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-20">&#182;</a>
<a class="pilcrow" href="#section-22">&#182;</a>
</div>
<p>Throws a SyntaxError from a given location.
The errors <code>toString</code> will return an error message following the “standard”
@@ -507,11 +556,11 @@ marker showing where the error is.</p>
</li>
<li id="section-21">
<li id="section-23">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-21">&#182;</a>
<a class="pilcrow" href="#section-23">&#182;</a>
</div>
<p>Instead of showing the compilers stacktrace, show our custom error message
(this is useful when the error bubbles up in Node.js applications that
@@ -526,11 +575,11 @@ compile CoffeeScript for example).</p>
</li>
<li id="section-22">
<li id="section-24">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-22">&#182;</a>
<a class="pilcrow" href="#section-24">&#182;</a>
</div>
<p>Update a compiler SyntaxError with source code information if it didnt have
it already.</p>
@@ -542,11 +591,11 @@ it already.</p>
</li>
<li id="section-23">
<li id="section-25">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-23">&#182;</a>
<a class="pilcrow" href="#section-25">&#182;</a>
</div>
<p>Avoid screwing up the <code>stack</code> property of other errors (i.e. possible bugs).</p>
@@ -572,11 +621,11 @@ it already.</p>
</li>
<li id="section-24">
<li id="section-26">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-24">&#182;</a>
<a class="pilcrow" href="#section-26">&#182;</a>
</div>
<p>Show only the first line on multi-line errors.</p>
@@ -588,11 +637,11 @@ it already.</p>
</li>
<li id="section-25">
<li id="section-27">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-25">&#182;</a>
<a class="pilcrow" href="#section-27">&#182;</a>
</div>
<p>Check to see if were running on a color-enabled TTY.</p>

View File

@@ -125,7 +125,11 @@ vm = <span class="hljs-built_in">require</span> <span class="hljs-str
path = <span class="hljs-built_in">require</span> <span class="hljs-string">'path'</span>
helpers = CoffeeScript.helpers
compile = CoffeeScript.compile</pre></div></div>
CoffeeScript.transpile = <span class="hljs-function"><span class="hljs-params">(js, options)</span> -&gt;</span>
<span class="hljs-keyword">try</span>
babel = <span class="hljs-built_in">require</span> <span class="hljs-string">'babel-core'</span>
<span class="hljs-keyword">catch</span></pre></div></div>
</li>
@@ -136,6 +140,73 @@ compile = CoffeeScript.compile</pre></div></div>
<div class="pilwrap ">
<a class="pilcrow" href="#section-2">&#182;</a>
</div>
<p>This error is only for Node, as CLI users will see a different error
earlier if they dont have Babel installed.</p>
</div>
<div class="content"><div class='highlight'><pre> <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Error <span class="hljs-string">'To use the transpile option, you must have the \'babel-core\' module installed'</span>
babel.transform js, options</pre></div></div>
</li>
<li id="section-3">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-3">&#182;</a>
</div>
<p>The <code>compile</code> method shared by the CLI, Node and browser APIs.</p>
</div>
<div class="content"><div class='highlight'><pre>universalCompile = CoffeeScript.compile</pre></div></div>
</li>
<li id="section-4">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-4">&#182;</a>
</div>
<p>The <code>compile</code> method particular to the Node API.</p>
</div>
<div class="content"><div class='highlight'><pre>CoffeeScript.compile = <span class="hljs-function"><span class="hljs-params">(code, options)</span> -&gt;</span></pre></div></div>
</li>
<li id="section-5">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-5">&#182;</a>
</div>
<p>Pass a reference to Babel into the compiler, so that the transpile option
is available in the Node API. We need to do this so that tools like Webpack
can <code>require(&#39;coffeescript&#39;)</code> and build correctly, without trying to
require Babel.</p>
</div>
<div class="content"><div class='highlight'><pre> <span class="hljs-keyword">if</span> options?.transpile
options.transpile.transpile = CoffeeScript.transpile
universalCompile.call CoffeeScript, code, options</pre></div></div>
</li>
<li id="section-6">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-6">&#182;</a>
</div>
<p>Compile and execute a string of CoffeeScript (on the server), correctly
setting <code>__filename</code>, <code>__dirname</code>, and relative <code>require()</code>.</p>
@@ -147,11 +218,11 @@ setting <code>__filename</code>, <code>__dirname</code>, and relative <code>requ
</li>
<li id="section-3">
<li id="section-7">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-3">&#182;</a>
<a class="pilcrow" href="#section-7">&#182;</a>
</div>
<p>Set the filename.</p>
@@ -163,11 +234,11 @@ setting <code>__filename</code>, <code>__dirname</code>, and relative <code>requ
</li>
<li id="section-4">
<li id="section-8">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-4">&#182;</a>
<a class="pilcrow" href="#section-8">&#182;</a>
</div>
<p>Clear the module cache.</p>
@@ -178,11 +249,11 @@ setting <code>__filename</code>, <code>__dirname</code>, and relative <code>requ
</li>
<li id="section-5">
<li id="section-9">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-5">&#182;</a>
<a class="pilcrow" href="#section-9">&#182;</a>
</div>
<p>Assign paths for node_modules loading</p>
@@ -197,18 +268,33 @@ setting <code>__filename</code>, <code>__dirname</code>, and relative <code>requ
</li>
<li id="section-6">
<li id="section-10">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-6">&#182;</a>
<a class="pilcrow" href="#section-10">&#182;</a>
</div>
<p>Save the options for compiling child imports.</p>
</div>
<div class="content"><div class='highlight'><pre> mainModule.options = options</pre></div></div>
</li>
<li id="section-11">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-11">&#182;</a>
</div>
<p>Compile.</p>
</div>
<div class="content"><div class='highlight'><pre> <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> helpers.isCoffee(mainModule.filename) <span class="hljs-keyword">or</span> <span class="hljs-built_in">require</span>.extensions
answer = compile code, options
answer = CoffeeScript.compile code, options
code = answer.js ? answer
mainModule._compile code, mainModule.filename</pre></div></div>
@@ -216,11 +302,11 @@ setting <code>__filename</code>, <code>__dirname</code>, and relative <code>requ
</li>
<li id="section-7">
<li id="section-12">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-7">&#182;</a>
<a class="pilcrow" href="#section-12">&#182;</a>
</div>
<p>Compile and evaluate a string of CoffeeScript (in a Node.js-like environment).
The CoffeeScript REPL uses this to run the input.</p>
@@ -250,11 +336,11 @@ The CoffeeScript REPL uses this to run the input.</p>
</li>
<li id="section-8">
<li id="section-13">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-8">&#182;</a>
<a class="pilcrow" href="#section-13">&#182;</a>
</div>
<p>define module/require only if they chose not to specify their own</p>
@@ -271,11 +357,11 @@ The CoffeeScript REPL uses this to run the input.</p>
</li>
<li id="section-9">
<li id="section-14">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-9">&#182;</a>
<a class="pilcrow" href="#section-14">&#182;</a>
</div>
<p>use the same hack node currently uses for their own REPL</p>
@@ -286,7 +372,7 @@ The CoffeeScript REPL uses this to run the input.</p>
o = {}
o[k] = v <span class="hljs-keyword">for</span> own k, v <span class="hljs-keyword">of</span> options
o.bare = <span class="hljs-literal">on</span> <span class="hljs-comment"># ensure return value</span>
js = compile code, o
js = CoffeeScript.compile code, o
<span class="hljs-keyword">if</span> sandbox <span class="hljs-keyword">is</span> <span class="hljs-built_in">global</span>
vm.runInThisContext js
<span class="hljs-keyword">else</span>
@@ -297,11 +383,11 @@ CoffeeScript.register = <span class="hljs-function">-&gt;</span> <span class="hl
</li>
<li id="section-10">
<li id="section-15">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-10">&#182;</a>
<a class="pilcrow" href="#section-15">&#182;</a>
</div>
<p>Throw error with deprecation warning when depending upon implicit <code>require.extensions</code> registration</p>
@@ -314,17 +400,17 @@ CoffeeScript.register = <span class="hljs-function">-&gt;</span> <span class="hl
Use CoffeeScript.register() or require the coffeescript/register module to require <span class="hljs-subst">#{ext}</span> files.
"""</span>
CoffeeScript._compileFile = <span class="hljs-function"><span class="hljs-params">(filename, sourceMap = <span class="hljs-literal">no</span>, inlineMap = <span class="hljs-literal">no</span>)</span> -&gt;</span>
CoffeeScript._compileFile = <span class="hljs-function"><span class="hljs-params">(filename, options = {})</span> -&gt;</span>
raw = fs.readFileSync filename, <span class="hljs-string">'utf8'</span></pre></div></div>
</li>
<li id="section-11">
<li id="section-16">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-11">&#182;</a>
<a class="pilcrow" href="#section-16">&#182;</a>
</div>
<p>Strip the Unicode byte order mark, if this file begins with one.</p>
@@ -332,22 +418,24 @@ CoffeeScript._compileFile = <span class="hljs-function"><span class="hljs-params
<div class="content"><div class='highlight'><pre> stripped = <span class="hljs-keyword">if</span> raw.charCodeAt(<span class="hljs-number">0</span>) <span class="hljs-keyword">is</span> <span class="hljs-number">0xFEFF</span> <span class="hljs-keyword">then</span> raw.substring <span class="hljs-number">1</span> <span class="hljs-keyword">else</span> raw
options = Object.assign {}, options,
filename: filename
literate: helpers.isLiterate filename
sourceFiles: [filename]
inlineMap: <span class="hljs-literal">yes</span> <span class="hljs-comment"># Always generate a source map, so that stack traces line up.</span>
<span class="hljs-keyword">try</span>
answer = compile stripped, {
filename, sourceMap, inlineMap
sourceFiles: [filename]
literate: helpers.isLiterate filename
}
answer = CoffeeScript.compile stripped, options
<span class="hljs-keyword">catch</span> err</pre></div></div>
</li>
<li id="section-12">
<li id="section-17">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-12">&#182;</a>
<a class="pilcrow" href="#section-17">&#182;</a>
</div>
<p>As the filename and code of a dynamically loaded file will be different
from the original file compiled with CoffeeScript.run, add that

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -157,8 +157,8 @@ command-line arguments in <code>src/command.coffee</code>.</p>
</div>
<div class="content"><div class='highlight'><pre> constructor: <span class="hljs-function"><span class="hljs-params">(rules, @banner)</span> -&gt;</span>
@rules = buildRules rules</pre></div></div>
<div class="content"><div class='highlight'><pre> constructor: <span class="hljs-function"><span class="hljs-params">(ruleDeclarations, @banner)</span> -&gt;</span>
@rules = buildRules ruleDeclarations</pre></div></div>
</li>
@@ -178,20 +178,7 @@ youre responsible for interpreting the options object.</p>
</div>
<div class="content"><div class='highlight'><pre> parse: <span class="hljs-function"><span class="hljs-params">(args)</span> -&gt;</span>
options = arguments: []
skippingArgument = <span class="hljs-literal">no</span>
originalArgs = args
args = normalizeArguments args
<span class="hljs-keyword">for</span> arg, i <span class="hljs-keyword">in</span> args
<span class="hljs-keyword">if</span> skippingArgument
skippingArgument = <span class="hljs-literal">no</span>
<span class="hljs-keyword">continue</span>
<span class="hljs-keyword">if</span> arg <span class="hljs-keyword">is</span> <span class="hljs-string">'--'</span>
pos = originalArgs.indexOf <span class="hljs-string">'--'</span>
options.arguments = options.arguments.concat originalArgs[(pos + <span class="hljs-number">1</span>)..]
<span class="hljs-keyword">break</span>
isOption = !!(arg.match(LONG_FLAG) <span class="hljs-keyword">or</span> arg.match(SHORT_FLAG))</pre></div></div>
<div class="content"><div class='highlight'><pre> parse: <span class="hljs-function"><span class="hljs-params">(args)</span> -&gt;</span></pre></div></div>
</li>
@@ -202,27 +189,18 @@ youre responsible for interpreting the options object.</p>
<div class="pilwrap ">
<a class="pilcrow" href="#section-5">&#182;</a>
</div>
<p>the CS option parser is a little odd; options after the first
non-option argument are treated as non-option arguments themselves</p>
<p>The CoffeeScript option parser is a little odd; options after the first
non-option argument are treated as non-option arguments themselves.
Optional arguments are normalized by expanding merged flags into multiple
flags. This allows you to have <code>-wl</code> be the same as <code>--watch --lint</code>.
Note that executable scripts with a shebang (<code>#!</code>) line should use the
line <code>#!/usr/bin/env coffee</code>, or <code>#!/absolute/path/to/coffee</code>, without a
<code>--</code> argument after, because that will fail on Linux (see #3946).</p>
</div>
<div class="content"><div class='highlight'><pre> seenNonOptionArg = options.arguments.length &gt; <span class="hljs-number">0</span>
<span class="hljs-keyword">unless</span> seenNonOptionArg
matchedRule = <span class="hljs-literal">no</span>
<span class="hljs-keyword">for</span> rule <span class="hljs-keyword">in</span> @rules
<span class="hljs-keyword">if</span> rule.shortFlag <span class="hljs-keyword">is</span> arg <span class="hljs-keyword">or</span> rule.longFlag <span class="hljs-keyword">is</span> arg
value = <span class="hljs-literal">true</span>
<span class="hljs-keyword">if</span> rule.hasArgument
skippingArgument = <span class="hljs-literal">yes</span>
value = args[i + <span class="hljs-number">1</span>]
options[rule.name] = <span class="hljs-keyword">if</span> rule.isList <span class="hljs-keyword">then</span> (options[rule.name] <span class="hljs-keyword">or</span> []).concat value <span class="hljs-keyword">else</span> value
matchedRule = <span class="hljs-literal">yes</span>
<span class="hljs-keyword">break</span>
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Error <span class="hljs-string">"unrecognized option: <span class="hljs-subst">#{arg}</span>"</span> <span class="hljs-keyword">if</span> isOption <span class="hljs-keyword">and</span> <span class="hljs-keyword">not</span> matchedRule
<span class="hljs-keyword">if</span> seenNonOptionArg <span class="hljs-keyword">or</span> <span class="hljs-keyword">not</span> isOption
options.arguments.push arg
options</pre></div></div>
<div class="content"><div class='highlight'><pre> {rules, positional} = normalizeArguments args, @rules.flagDict
options = {}</pre></div></div>
</li>
@@ -233,20 +211,27 @@ non-option argument are treated as non-option arguments themselves</p>
<div class="pilwrap ">
<a class="pilcrow" href="#section-6">&#182;</a>
</div>
<p>Return the help text for this <strong>OptionParser</strong>, listing and describing all
of the valid options, for <code>--help</code> and such.</p>
<p>The <code>argument</code> field is added to the rule instance non-destructively by
<code>normalizeArguments</code>.</p>
</div>
<div class="content"><div class='highlight'><pre> help: <span class="hljs-function">-&gt;</span>
lines = []
lines.unshift <span class="hljs-string">"<span class="hljs-subst">#{@banner}</span>\n"</span> <span class="hljs-keyword">if</span> @banner
<span class="hljs-keyword">for</span> rule <span class="hljs-keyword">in</span> @rules
spaces = <span class="hljs-number">15</span> - rule.longFlag.length
spaces = <span class="hljs-keyword">if</span> spaces &gt; <span class="hljs-number">0</span> <span class="hljs-keyword">then</span> repeat <span class="hljs-string">' '</span>, spaces <span class="hljs-keyword">else</span> <span class="hljs-string">''</span>
letPart = <span class="hljs-keyword">if</span> rule.shortFlag <span class="hljs-keyword">then</span> rule.shortFlag + <span class="hljs-string">', '</span> <span class="hljs-keyword">else</span> <span class="hljs-string">' '</span>
lines.push <span class="hljs-string">' '</span> + letPart + rule.longFlag + spaces + rule.description
<span class="hljs-string">"\n<span class="hljs-subst">#{ lines.join(<span class="hljs-string">'\n'</span>) }</span>\n"</span></pre></div></div>
<div class="content"><div class='highlight'><pre> <span class="hljs-keyword">for</span> {hasArgument, argument, isList, name} <span class="hljs-keyword">in</span> rules
<span class="hljs-keyword">if</span> hasArgument
<span class="hljs-keyword">if</span> isList
options[name] ?= []
options[name].push argument
<span class="hljs-keyword">else</span>
options[name] = argument
<span class="hljs-keyword">else</span>
options[name] = <span class="hljs-literal">true</span>
<span class="hljs-keyword">if</span> positional[<span class="hljs-number">0</span>] <span class="hljs-keyword">is</span> <span class="hljs-string">'--'</span>
options.doubleDashed = <span class="hljs-literal">yes</span>
positional = positional[<span class="hljs-number">1.</span>.]
options.arguments = positional
options</pre></div></div>
</li>
@@ -257,10 +242,21 @@ of the valid options, for <code>--help</code> and such.</p>
<div class="pilwrap ">
<a class="pilcrow" href="#section-7">&#182;</a>
</div>
<h2 id="helpers">Helpers</h2>
<p>Return the help text for this <strong>OptionParser</strong>, listing and describing all
of the valid options, for <code>--help</code> and such.</p>
</div>
<div class="content"><div class='highlight'><pre> help: <span class="hljs-function">-&gt;</span>
lines = []
lines.unshift <span class="hljs-string">"<span class="hljs-subst">#{@banner}</span>\n"</span> <span class="hljs-keyword">if</span> @banner
<span class="hljs-keyword">for</span> rule <span class="hljs-keyword">in</span> @rules.ruleList
spaces = <span class="hljs-number">15</span> - rule.longFlag.length
spaces = <span class="hljs-keyword">if</span> spaces &gt; <span class="hljs-number">0</span> <span class="hljs-keyword">then</span> repeat <span class="hljs-string">' '</span>, spaces <span class="hljs-keyword">else</span> <span class="hljs-string">''</span>
letPart = <span class="hljs-keyword">if</span> rule.shortFlag <span class="hljs-keyword">then</span> rule.shortFlag + <span class="hljs-string">', '</span> <span class="hljs-keyword">else</span> <span class="hljs-string">' '</span>
lines.push <span class="hljs-string">' '</span> + letPart + rule.longFlag + spaces + rule.description
<span class="hljs-string">"\n<span class="hljs-subst">#{ lines.join(<span class="hljs-string">'\n'</span>) }</span>\n"</span></pre></div></div>
</li>
@@ -270,7 +266,8 @@ of the valid options, for <code>--help</code> and such.</p>
<div class="pilwrap ">
<a class="pilcrow" href="#section-8">&#182;</a>
</div>
<h2 id="helpers">Helpers</h2>
</div>
</li>
@@ -282,15 +279,9 @@ of the valid options, for <code>--help</code> and such.</p>
<div class="pilwrap ">
<a class="pilcrow" href="#section-9">&#182;</a>
</div>
<p>Regex matchers for option flags.</p>
</div>
<div class="content"><div class='highlight'><pre>LONG_FLAG = <span class="hljs-regexp">/^(--\w[\w\-]*)/</span>
SHORT_FLAG = <span class="hljs-regexp">/^(-\w)$/</span>
MULTI_FLAG = <span class="hljs-regexp">/^-(\w{2,})/</span>
OPTIONAL = <span class="hljs-regexp">/\[(\w+(\*?))\]/</span></pre></div></div>
</li>
@@ -300,15 +291,13 @@ OPTIONAL = <span class="hljs-regexp">/\[(\w+(\*?))\]/</span></pre></div></div>
<div class="pilwrap ">
<a class="pilcrow" href="#section-10">&#182;</a>
</div>
<p>Build and return the list of option rules. If the optional <em>short-flag</em> is
unspecified, leave it out by padding with <code>null</code>.</p>
<p>Regex matchers for option flags on the command line and their rules.</p>
</div>
<div class="content"><div class='highlight'><pre><span class="hljs-function"><span class="hljs-title">buildRules</span> = <span class="hljs-params">(rules)</span> -&gt;</span>
<span class="hljs-keyword">for</span> tuple <span class="hljs-keyword">in</span> rules
tuple.unshift <span class="hljs-literal">null</span> <span class="hljs-keyword">if</span> tuple.length &lt; <span class="hljs-number">3</span>
buildRule tuple...</pre></div></div>
<div class="content"><div class='highlight'><pre>LONG_FLAG = <span class="hljs-regexp">/^(--\w[\w\-]*)/</span>
SHORT_FLAG = <span class="hljs-regexp">/^(-\w)$/</span>
MULTI_FLAG = <span class="hljs-regexp">/^-(\w{2,})/</span></pre></div></div>
</li>
@@ -319,22 +308,12 @@ unspecified, leave it out by padding with <code>null</code>.</p>
<div class="pilwrap ">
<a class="pilcrow" href="#section-11">&#182;</a>
</div>
<p>Build a rule from a <code>-o</code> short flag, a <code>--output [DIR]</code> long flag, and the
description of what the option does.</p>
<p>Matches the long flag part of a rule for an option with an argument. Not
applied to anything in process.argv.</p>
</div>
<div class="content"><div class='highlight'><pre><span class="hljs-function"><span class="hljs-title">buildRule</span> = <span class="hljs-params">(shortFlag, longFlag, description, options = {})</span> -&gt;</span>
match = longFlag.match(OPTIONAL)
longFlag = longFlag.match(LONG_FLAG)[<span class="hljs-number">1</span>]
{
name: longFlag.substr <span class="hljs-number">2</span>
shortFlag: shortFlag
longFlag: longFlag
description: description
hasArgument: !!(match <span class="hljs-keyword">and</span> match[<span class="hljs-number">1</span>])
isList: !!(match <span class="hljs-keyword">and</span> match[<span class="hljs-number">2</span>])
}</pre></div></div>
<div class="content"><div class='highlight'><pre>OPTIONAL = <span class="hljs-regexp">/\[(\w+(\*?))\]/</span></pre></div></div>
</li>
@@ -345,20 +324,156 @@ description of what the option does.</p>
<div class="pilwrap ">
<a class="pilcrow" href="#section-12">&#182;</a>
</div>
<p>Normalize arguments by expanding merged flags into multiple flags. This allows
you to have <code>-wl</code> be the same as <code>--watch --lint</code>.</p>
<p>Build and return the list of option rules. If the optional <em>short-flag</em> is
unspecified, leave it out by padding with <code>null</code>.</p>
</div>
<div class="content"><div class='highlight'><pre><span class="hljs-function"><span class="hljs-title">normalizeArguments</span> = <span class="hljs-params">(args)</span> -&gt;</span>
args = args[..]
result = []
<span class="hljs-keyword">for</span> arg <span class="hljs-keyword">in</span> args
<span class="hljs-keyword">if</span> match = arg.match MULTI_FLAG
result.push <span class="hljs-string">'-'</span> + l <span class="hljs-keyword">for</span> l <span class="hljs-keyword">in</span> match[<span class="hljs-number">1</span>].split <span class="hljs-string">''</span>
<span class="hljs-keyword">else</span>
result.push arg
result</pre></div></div>
<div class="content"><div class='highlight'><pre><span class="hljs-function"><span class="hljs-title">buildRules</span> = <span class="hljs-params">(ruleDeclarations)</span> -&gt;</span>
ruleList = <span class="hljs-keyword">for</span> tuple <span class="hljs-keyword">in</span> ruleDeclarations
tuple.unshift <span class="hljs-literal">null</span> <span class="hljs-keyword">if</span> tuple.length &lt; <span class="hljs-number">3</span>
buildRule tuple...
flagDict = {}
<span class="hljs-keyword">for</span> rule <span class="hljs-keyword">in</span> ruleList</pre></div></div>
</li>
<li id="section-13">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-13">&#182;</a>
</div>
<p><code>shortFlag</code> is null if not provided in the rule.</p>
</div>
<div class="content"><div class='highlight'><pre> <span class="hljs-keyword">for</span> flag <span class="hljs-keyword">in</span> [rule.shortFlag, rule.longFlag] <span class="hljs-keyword">when</span> flag?
<span class="hljs-keyword">if</span> flagDict[flag]?
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Error <span class="hljs-string">"flag <span class="hljs-subst">#{flag}</span> for switch <span class="hljs-subst">#{rule.name}</span>
was already declared for switch <span class="hljs-subst">#{flagDict[flag].name}</span>"</span>
flagDict[flag] = rule
{ruleList, flagDict}</pre></div></div>
</li>
<li id="section-14">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-14">&#182;</a>
</div>
<p>Build a rule from a <code>-o</code> short flag, a <code>--output [DIR]</code> long flag, and the
description of what the option does.</p>
</div>
<div class="content"><div class='highlight'><pre><span class="hljs-function"><span class="hljs-title">buildRule</span> = <span class="hljs-params">(shortFlag, longFlag, description)</span> -&gt;</span>
match = longFlag.match(OPTIONAL)
shortFlag = shortFlag?.match(SHORT_FLAG)[<span class="hljs-number">1</span>]
longFlag = longFlag.match(LONG_FLAG)[<span class="hljs-number">1</span>]
{
name: longFlag.replace <span class="hljs-regexp">/^--/</span>, <span class="hljs-string">''</span>
shortFlag: shortFlag
longFlag: longFlag
description: description
hasArgument: !!(match <span class="hljs-keyword">and</span> match[<span class="hljs-number">1</span>])
isList: !!(match <span class="hljs-keyword">and</span> match[<span class="hljs-number">2</span>])
}
<span class="hljs-function">
<span class="hljs-title">normalizeArguments</span> = <span class="hljs-params">(args, flagDict)</span> -&gt;</span>
rules = []
positional = []
needsArgOpt = <span class="hljs-literal">null</span>
<span class="hljs-keyword">for</span> arg, argIndex <span class="hljs-keyword">in</span> args</pre></div></div>
</li>
<li id="section-15">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-15">&#182;</a>
</div>
<p>If the previous argument given to the script was an option that uses the
next command-line argument as its argument, create copy of the options
rule with an <code>argument</code> field.</p>
</div>
<div class="content"><div class='highlight'><pre> <span class="hljs-keyword">if</span> needsArgOpt?
withArg = Object.assign {}, needsArgOpt.rule, {argument: arg}
rules.push withArg
needsArgOpt = <span class="hljs-literal">null</span>
<span class="hljs-keyword">continue</span>
multiFlags = arg.match(MULTI_FLAG)?[<span class="hljs-number">1</span>]
.split(<span class="hljs-string">''</span>)
.map (flagName) -&gt; <span class="hljs-string">"-<span class="hljs-subst">#{flagName}</span>"</span>
<span class="hljs-keyword">if</span> multiFlags?
multiOpts = multiFlags.map (flag) -&gt;
rule = flagDict[flag]
<span class="hljs-keyword">unless</span> rule?
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Error <span class="hljs-string">"unrecognized option <span class="hljs-subst">#{flag}</span> in multi-flag <span class="hljs-subst">#{arg}</span>"</span>
{rule, flag}</pre></div></div>
</li>
<li id="section-16">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-16">&#182;</a>
</div>
<p>Only the last flag in a multi-flag may have an argument.</p>
</div>
<div class="content"><div class='highlight'><pre> [innerOpts..., lastOpt] = multiOpts
<span class="hljs-keyword">for</span> {rule, flag} <span class="hljs-keyword">in</span> innerOpts
<span class="hljs-keyword">if</span> rule.hasArgument
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Error <span class="hljs-string">"cannot use option <span class="hljs-subst">#{flag}</span> in multi-flag <span class="hljs-subst">#{arg}</span> except
as the last option, because it needs an argument"</span>
rules.push rule
<span class="hljs-keyword">if</span> lastOpt.rule.hasArgument
needsArgOpt = lastOpt
<span class="hljs-keyword">else</span>
rules.push lastOpt.rule
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> ([LONG_FLAG, SHORT_FLAG].some (pat) -&gt; arg.match(pat)?)
singleRule = flagDict[arg]
<span class="hljs-keyword">unless</span> singleRule?
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Error <span class="hljs-string">"unrecognized option <span class="hljs-subst">#{arg}</span>"</span>
<span class="hljs-keyword">if</span> singleRule.hasArgument
needsArgOpt = {rule: singleRule, flag: arg}
<span class="hljs-keyword">else</span>
rules.push singleRule
<span class="hljs-keyword">else</span></pre></div></div>
</li>
<li id="section-17">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-17">&#182;</a>
</div>
<p>This is a positional argument.</p>
</div>
<div class="content"><div class='highlight'><pre> positional = args[argIndex..]
<span class="hljs-keyword">break</span>
<span class="hljs-keyword">if</span> needsArgOpt?
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Error <span class="hljs-string">"value required for <span class="hljs-subst">#{needsArgOpt.flag}</span>, but it was the last
argument provided"</span>
{rules, positional}</pre></div></div>
</li>

View File

@@ -137,7 +137,8 @@ path = <span class="hljs-built_in">require</span> <span class="hljs-str
</div>
<div class="content"><div class='highlight'><pre><span class="hljs-function"><span class="hljs-title">loadFile</span> = <span class="hljs-params">(<span class="hljs-built_in">module</span>, filename)</span> -&gt;</span>
answer = CoffeeScript._compileFile filename, <span class="hljs-literal">no</span>, <span class="hljs-literal">yes</span>
options = <span class="hljs-built_in">module</span>.options <span class="hljs-keyword">or</span> getRootModule(<span class="hljs-built_in">module</span>).options
answer = CoffeeScript._compileFile filename, options
<span class="hljs-built_in">module</span>._compile answer, filename</pre></div></div>
</li>
@@ -245,6 +246,22 @@ to fork both CoffeeScript files, and JavaScript files, directly.</p>
</li>
<li id="section-8">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-8">&#182;</a>
</div>
<p>Utility function to find the <code>options</code> object attached to the topmost module.</p>
</div>
<div class="content"><div class='highlight'><pre><span class="hljs-function"><span class="hljs-title">getRootModule</span> = <span class="hljs-params">(<span class="hljs-built_in">module</span>)</span> -&gt;</span>
<span class="hljs-keyword">if</span> <span class="hljs-built_in">module</span>.parent <span class="hljs-keyword">then</span> getRootModule <span class="hljs-built_in">module</span>.parent <span class="hljs-keyword">else</span> <span class="hljs-built_in">module</span></pre></div></div>
</li>
</ul>
</div>
</body>

View File

@@ -125,6 +125,9 @@ nodeREPL = <span class="hljs-built_in">require</span> <span class="hljs-string">
CoffeeScript = <span class="hljs-built_in">require</span> <span class="hljs-string">'./'</span>
{merge, updateSyntaxError} = <span class="hljs-built_in">require</span> <span class="hljs-string">'./helpers'</span>
sawSIGINT = <span class="hljs-literal">no</span>
transpile = <span class="hljs-literal">no</span>
replDefaults =
prompt: <span class="hljs-string">'coffee&gt; '</span>,
historyFile: <span class="hljs-keyword">do</span> -&gt;
@@ -193,7 +196,7 @@ Unwrap that too.</p>
</div>
<div class="content"><div class='highlight'><pre> {Block, Assign, Value, Literal} = <span class="hljs-built_in">require</span> <span class="hljs-string">'./nodes'</span>
<div class="content"><div class='highlight'><pre> {Block, Assign, Value, Literal, Call, Code} = <span class="hljs-built_in">require</span> <span class="hljs-string">'./nodes'</span>
<span class="hljs-keyword">try</span></pre></div></div>
@@ -221,13 +224,17 @@ Unwrap that too.</p>
<div class="pilwrap ">
<a class="pilcrow" href="#section-7">&#182;</a>
</div>
<p>Collect referenced variable names just like in <code>CoffeeScript.compile</code>.</p>
<p>Filter out tokens generated just to hold comments.</p>
</div>
<div class="content"><div class='highlight'><pre> referencedVars = (
token[<span class="hljs-number">1</span>] <span class="hljs-keyword">for</span> token <span class="hljs-keyword">in</span> tokens <span class="hljs-keyword">when</span> token[<span class="hljs-number">0</span>] <span class="hljs-keyword">is</span> <span class="hljs-string">'IDENTIFIER'</span>
)</pre></div></div>
<div class="content"><div class='highlight'><pre> <span class="hljs-keyword">if</span> tokens.length &gt;= <span class="hljs-number">2</span> <span class="hljs-keyword">and</span> tokens[<span class="hljs-number">0</span>].generated <span class="hljs-keyword">and</span>
tokens[<span class="hljs-number">0</span>].comments?.length <span class="hljs-keyword">isnt</span> <span class="hljs-number">0</span> <span class="hljs-keyword">and</span> tokens[<span class="hljs-number">0</span>][<span class="hljs-number">1</span>] <span class="hljs-keyword">is</span> <span class="hljs-string">''</span> <span class="hljs-keyword">and</span>
tokens[<span class="hljs-number">1</span>][<span class="hljs-number">0</span>] <span class="hljs-keyword">is</span> <span class="hljs-string">'TERMINATOR'</span>
tokens = tokens[<span class="hljs-number">2.</span>..]
<span class="hljs-keyword">if</span> tokens.length &gt;= <span class="hljs-number">1</span> <span class="hljs-keyword">and</span> tokens[tokens.length - <span class="hljs-number">1</span>].generated <span class="hljs-keyword">and</span>
tokens[tokens.length - <span class="hljs-number">1</span>].comments?.length <span class="hljs-keyword">isnt</span> <span class="hljs-number">0</span> <span class="hljs-keyword">and</span> tokens[tokens.length - <span class="hljs-number">1</span>][<span class="hljs-number">1</span>] <span class="hljs-keyword">is</span> <span class="hljs-string">''</span>
tokens.pop()</pre></div></div>
</li>
@@ -238,11 +245,11 @@ Unwrap that too.</p>
<div class="pilwrap ">
<a class="pilcrow" href="#section-8">&#182;</a>
</div>
<p>Generate the AST of the tokens.</p>
<p>Collect referenced variable names just like in <code>CoffeeScript.compile</code>.</p>
</div>
<div class="content"><div class='highlight'><pre> ast = CoffeeScript.nodes tokens</pre></div></div>
<div class="content"><div class='highlight'><pre> referencedVars = (token[<span class="hljs-number">1</span>] <span class="hljs-keyword">for</span> token <span class="hljs-keyword">in</span> tokens <span class="hljs-keyword">when</span> token[<span class="hljs-number">0</span>] <span class="hljs-keyword">is</span> <span class="hljs-string">'IDENTIFIER'</span>)</pre></div></div>
</li>
@@ -253,16 +260,11 @@ Unwrap that too.</p>
<div class="pilwrap ">
<a class="pilcrow" href="#section-9">&#182;</a>
</div>
<p>Add assignment to <code>_</code> variable to force the input to be an expression.</p>
<p>Generate the AST of the tokens.</p>
</div>
<div class="content"><div class='highlight'><pre> ast = <span class="hljs-keyword">new</span> Block [
<span class="hljs-keyword">new</span> Assign (<span class="hljs-keyword">new</span> Value <span class="hljs-keyword">new</span> Literal <span class="hljs-string">'__'</span>), ast, <span class="hljs-string">'='</span>
]
js = ast.compile {bare: <span class="hljs-literal">yes</span>, locals: Object.keys(context), referencedVars}
cb <span class="hljs-literal">null</span>, runInContext js, context, filename
<span class="hljs-keyword">catch</span> err</pre></div></div>
<div class="content"><div class='highlight'><pre> ast = CoffeeScript.nodes tokens</pre></div></div>
</li>
@@ -273,6 +275,93 @@ Unwrap that too.</p>
<div class="pilwrap ">
<a class="pilcrow" href="#section-10">&#182;</a>
</div>
<p>Add assignment to <code>__</code> variable to force the input to be an expression.</p>
</div>
<div class="content"><div class='highlight'><pre> ast = <span class="hljs-keyword">new</span> Block [<span class="hljs-keyword">new</span> Assign (<span class="hljs-keyword">new</span> Value <span class="hljs-keyword">new</span> Literal <span class="hljs-string">'__'</span>), ast, <span class="hljs-string">'='</span>]</pre></div></div>
</li>
<li id="section-11">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-11">&#182;</a>
</div>
<p>Wrap the expression in a closure to support top-level <code>await</code>.</p>
</div>
<div class="content"><div class='highlight'><pre> ast = <span class="hljs-keyword">new</span> Code [], ast
isAsync = ast.isAsync</pre></div></div>
</li>
<li id="section-12">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-12">&#182;</a>
</div>
<p>Invoke the wrapping closure.</p>
</div>
<div class="content"><div class='highlight'><pre> ast = <span class="hljs-keyword">new</span> Block [<span class="hljs-keyword">new</span> Call ast]
js = ast.compile {bare: <span class="hljs-literal">yes</span>, locals: Object.keys(context), referencedVars, sharedScope: <span class="hljs-literal">yes</span>}
<span class="hljs-keyword">if</span> transpile
js = transpile.transpile(js, transpile.options).code</pre></div></div>
</li>
<li id="section-13">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-13">&#182;</a>
</div>
<p>Strip <code>&quot;use strict&quot;</code>, to avoid an exception on assigning to
undeclared variable <code>__</code>.</p>
</div>
<div class="content"><div class='highlight'><pre> js = js.replace <span class="hljs-regexp">/^"use strict"|^'use strict'/</span>, <span class="hljs-string">''</span>
result = runInContext js, context, filename</pre></div></div>
</li>
<li id="section-14">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-14">&#182;</a>
</div>
<p>Await an async result, if necessary.</p>
</div>
<div class="content"><div class='highlight'><pre> <span class="hljs-keyword">if</span> isAsync
result.<span class="hljs-keyword">then</span> (resolvedResult) -&gt;
cb <span class="hljs-literal">null</span>, resolvedResult <span class="hljs-keyword">unless</span> sawSIGINT
sawSIGINT = <span class="hljs-literal">no</span>
<span class="hljs-keyword">else</span>
cb <span class="hljs-literal">null</span>, result
<span class="hljs-keyword">catch</span> err</pre></div></div>
</li>
<li id="section-15">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-15">&#182;</a>
</div>
<p>ASTs <code>compile</code> does not add source code information to syntax errors.</p>
</div>
@@ -292,11 +381,11 @@ Unwrap that too.</p>
</li>
<li id="section-11">
<li id="section-16">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-11">&#182;</a>
<a class="pilcrow" href="#section-16">&#182;</a>
</div>
<p>Node 0.11.12 changed API, prompt is now _prompt.</p>
@@ -313,11 +402,11 @@ Unwrap that too.</p>
</li>
<li id="section-12">
<li id="section-17">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-12">&#182;</a>
<a class="pilcrow" href="#section-17">&#182;</a>
</div>
<p>Proxy nodes line listener</p>
@@ -338,11 +427,11 @@ Unwrap that too.</p>
</li>
<li id="section-13">
<li id="section-18">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-13">&#182;</a>
<a class="pilcrow" href="#section-18">&#182;</a>
</div>
<p>Handle Ctrl-v</p>
@@ -355,11 +444,11 @@ Unwrap that too.</p>
</li>
<li id="section-14">
<li id="section-19">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-14">&#182;</a>
<a class="pilcrow" href="#section-19">&#182;</a>
</div>
<p>allow arbitrarily switching between modes any time before multiple lines are entered</p>
@@ -374,11 +463,11 @@ Unwrap that too.</p>
</li>
<li id="section-15">
<li id="section-20">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-15">&#182;</a>
<a class="pilcrow" href="#section-20">&#182;</a>
</div>
<p>no-op unless the current line is empty</p>
@@ -389,11 +478,11 @@ Unwrap that too.</p>
</li>
<li id="section-16">
<li id="section-21">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-16">&#182;</a>
<a class="pilcrow" href="#section-21">&#182;</a>
</div>
<p>eval, print, loop</p>
@@ -408,11 +497,11 @@ Unwrap that too.</p>
</li>
<li id="section-17">
<li id="section-22">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-17">&#182;</a>
<a class="pilcrow" href="#section-22">&#182;</a>
</div>
<p>XXX: multiline hack</p>
@@ -430,11 +519,11 @@ Unwrap that too.</p>
</li>
<li id="section-18">
<li id="section-23">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-18">&#182;</a>
<a class="pilcrow" href="#section-23">&#182;</a>
</div>
<p>Store and load command history from a file</p>
@@ -447,11 +536,11 @@ Unwrap that too.</p>
</li>
<li id="section-19">
<li id="section-24">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-19">&#182;</a>
<a class="pilcrow" href="#section-24">&#182;</a>
</div>
<p>Get file info and at most maxSize of command history</p>
@@ -463,11 +552,11 @@ Unwrap that too.</p>
</li>
<li id="section-20">
<li id="section-25">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-20">&#182;</a>
<a class="pilcrow" href="#section-25">&#182;</a>
</div>
<p>Read last <code>size</code> bytes from the file</p>
@@ -481,11 +570,11 @@ Unwrap that too.</p>
</li>
<li id="section-21">
<li id="section-26">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-21">&#182;</a>
<a class="pilcrow" href="#section-26">&#182;</a>
</div>
<p>Set the history on the interpreter</p>
@@ -496,11 +585,11 @@ Unwrap that too.</p>
</li>
<li id="section-22">
<li id="section-27">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-22">&#182;</a>
<a class="pilcrow" href="#section-27">&#182;</a>
</div>
<p>If the history file was truncated we should pop off a potential partial line</p>
@@ -511,11 +600,11 @@ Unwrap that too.</p>
</li>
<li id="section-23">
<li id="section-28">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-23">&#182;</a>
<a class="pilcrow" href="#section-28">&#182;</a>
</div>
<p>Shift off the final blank newline</p>
@@ -533,29 +622,43 @@ Unwrap that too.</p>
</li>
<li id="section-24">
<li id="section-29">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-24">&#182;</a>
<a class="pilcrow" href="#section-29">&#182;</a>
</div>
<p>Save the latest command in the file</p>
</div>
<div class="content"><div class='highlight'><pre> fs.writeSync fd, <span class="hljs-string">"<span class="hljs-subst">#{code}</span>\n"</span>
lastLine = code
lastLine = code</pre></div></div>
</li>
<li id="section-30">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-30">&#182;</a>
</div>
<p>XXX: The SIGINT event from REPLServer is undocumented, so this is a bit fragile</p>
</div>
<div class="content"><div class='highlight'><pre> repl.<span class="hljs-literal">on</span> <span class="hljs-string">'SIGINT'</span>, <span class="hljs-function">-&gt;</span> sawSIGINT = <span class="hljs-literal">yes</span>
repl.<span class="hljs-literal">on</span> <span class="hljs-string">'exit'</span>, <span class="hljs-function">-&gt;</span> fs.closeSync fd</pre></div></div>
</li>
<li id="section-25">
<li id="section-31">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-25">&#182;</a>
<a class="pilcrow" href="#section-31">&#182;</a>
</div>
<p>Add a command to show the history stack</p>
@@ -572,11 +675,11 @@ Unwrap that too.</p>
</li>
<li id="section-26">
<li id="section-32">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-26">&#182;</a>
<a class="pilcrow" href="#section-32">&#182;</a>
</div>
<p>Node 0.11 changed API, a command such as .help is now stored as help</p>
@@ -595,6 +698,44 @@ Unwrap that too.</p>
CoffeeScript.register()
process.argv = [<span class="hljs-string">'coffee'</span>].concat process.argv[<span class="hljs-number">2.</span>.]
<span class="hljs-keyword">if</span> opts.transpile
<span class="hljs-keyword">try</span>
transpile = {}
transpile.transpile = <span class="hljs-built_in">require</span>(<span class="hljs-string">'babel-core'</span>).transform
<span class="hljs-keyword">catch</span>
<span class="hljs-built_in">console</span>.error <span class="hljs-string">'''
To use --transpile with an interactive REPL, babel-core must be installed either in the current folder or globally:
npm install --save-dev babel-core
or
npm install --global babel-core
And you must save options to configure Babel in one of the places it looks to find its options.
See http://coffeescript.org/#transpilation
'''</span>
process.exit <span class="hljs-number">1</span>
transpile.options =
filename: path.resolve process.cwd(), <span class="hljs-string">'&lt;repl&gt;'</span></pre></div></div>
</li>
<li id="section-33">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-33">&#182;</a>
</div>
<p>Since the REPL compilation path is unique (in <code>eval</code> above), we need
another way to get the <code>options</code> object attached to a module so that
it knows later on whether it needs to be transpiled. In the case of
the REPL, the only applicable option is <code>transpile</code>.</p>
</div>
<div class="content"><div class='highlight'><pre> Module = <span class="hljs-built_in">require</span> <span class="hljs-string">'module'</span>
originalModuleLoad = Module::load
Module::load = <span class="hljs-function"><span class="hljs-params">(filename)</span> -&gt;</span>
@options = transpile: transpile.options
originalModuleLoad.call @, filename
opts = merge replDefaults, opts
repl = nodeREPL.start opts
runInContext opts.prelude, repl.context, <span class="hljs-string">'prelude'</span> <span class="hljs-keyword">if</span> opts.prelude
@@ -605,11 +746,11 @@ Unwrap that too.</p>
</li>
<li id="section-27">
<li id="section-34">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-27">&#182;</a>
<a class="pilcrow" href="#section-34">&#182;</a>
</div>
<p>Adapt help inherited from the node REPL</p>

File diff suppressed because it is too large Load Diff

View File

@@ -139,12 +139,14 @@ with external scopes.</p>
as well as a reference to the <strong>Block</strong> node it belongs to, which is
where it should declare its variables, a reference to the function that
it belongs to, and a list of variables referenced in the source code
and therefore should be avoided when generating variables.</p>
and therefore should be avoided when generating variables. Also track comments
that should be output as part of variable declarations.</p>
</div>
<div class="content"><div class='highlight'><pre> constructor: <span class="hljs-function"><span class="hljs-params">(@parent, @expressions, @method, @referencedVars)</span> -&gt;</span>
@variables = [{name: <span class="hljs-string">'arguments'</span>, type: <span class="hljs-string">'arguments'</span>}]
@comments = {}
@positions = {}
@utilities = {} <span class="hljs-keyword">unless</span> @parent</pre></div></div>

View File

@@ -370,15 +370,22 @@ column for the current line:</p>
</div>
<div class="content"><div class='highlight'><pre> v3 =
<div class="content"><div class='highlight'><pre> sources = <span class="hljs-keyword">if</span> options.sourceFiles
options.sourceFiles
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> options.filename
[options.filename]
<span class="hljs-keyword">else</span>
[<span class="hljs-string">'&lt;anonymous&gt;'</span>]
v3 =
version: <span class="hljs-number">3</span>
file: options.generatedFile <span class="hljs-keyword">or</span> <span class="hljs-string">''</span>
sourceRoot: options.sourceRoot <span class="hljs-keyword">or</span> <span class="hljs-string">''</span>
sources: options.sourceFiles <span class="hljs-keyword">or</span> [<span class="hljs-string">''</span>]
sources: sources
names: []
mappings: buffer
v3.sourcesContent = [code] <span class="hljs-keyword">if</span> options.inlineMap
v3.sourcesContent = [code] <span class="hljs-keyword">if</span> options.sourceMap <span class="hljs-keyword">or</span> options.inlineMap
v3</pre></div></div>

View File

@@ -0,0 +1,351 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Announcing CoffeeScript 2</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="canonical" href="http://coffeescript.org" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">
<meta name="theme-color" content="#ffffff">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Alegreya+Sans:400,800|Galada:400|Lato:300,300i,400,700|Roboto+Mono:400,400i" rel="stylesheet" crossorigin="anonymous">
<style>
body {
/* Push below header bar */
margin-top: 3.5rem;
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 3"><path opacity=".02" fill="#000" d="M0 0h1v1H0z"/><path opacity=".005" fill="#000" d="M0 1h1v2H0z"/></svg>');
background-size: 1px 3px;
}
svg {
width: auto;
height: 100%;
}
a {
color: #1b5e20;
transition: 0.1s ease-in-out;
}
a:focus, a:hover, a:active {
color: #388e3c;
cursor: pointer;
text-decoration: none;
}
button:focus, .navbar-dark .navbar-toggler:focus {
outline: none;
border: thin solid rgba(248, 243, 240, 0.3);
}
.bg-dark {
background-color: #3e2723 !important;
}
.bg-ribbed-light {
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 3"><path opacity=".03" fill="#000" d="M0 0h1v1H0z"/><path opacity=".005" fill="#000" d="M0 1h1v2H0z"/></svg>');
background-size: 1px 3px;
}
.bg-ribbed-dark {
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 3"><path opacity=".2" fill="#000" d="M0 0h1v1H0z"/><path opacity=".15" fill="#000" d="M0 1h1v2H0z"/></svg>');
background-size: 1px 3px;
}
/*
* Header
*/
.site-navbar {
height: 3.5rem;
font-family: 'Lato';
font-weight: 400;
font-size: 1.1em;
}
.navbar-brand {
height: 2.2em;
margin-right: 1em;
}
.navbar-dark path {
fill: #fff;
}
.navbar-nav .nav-item {
margin-left: 0.6em;
margin-right: 0.6em;
border-radius: 0.4em;
}
.navbar-nav .nav-item:hover,
.navbar-nav .nav-item:active,
.navbar-nav .nav-item.show {
background-color: #4e342e;
}
.navbar-toggler {
transition: all 0.1s ease-in-out;
}
/*
* Main content
*/
.main {
padding: 1.3em;
}
@media (min-width: 992px) {
.main {
padding-right: 2em;
padding-left: 2em;
}
}
h1 {
font: 2.5em Galada;
color: #2f2625;
text-align: center;
}
@media (min-width: 768px) {
h1 {
font-size: 3em;
}
}
@media (min-width: 992px) {
h1 {
font-size: 4em;
}
}
.title-logo {
display: inline-block;
height: 1em;
transform: translateY(0.2em);
margin-left: 0.3em;
margin-right: 0.25em;
fill: #2f2625;
}
.main p, .main li {
font-family: Lato;
font-weight: 300;
font-size: 1.1em;
line-height: 1.6;
}
.main blockquote {
font-size: 1.1em;
}
@media (min-width: 768px) {
.main p, .main li {
font-size: 1.3em;
}
.main blockquote {
font-size: 1.3em;
}
}
.main strong {
font-weight: 700;
}
.main a {
border-bottom: 2px solid transparent;
font-weight: 400;
}
.main a:focus, .main a:hover, .main a:active {
border-bottom: 2px solid rgba(56, 142, 60, 0.2);
}
.main blockquote pre {
background-color: #f8f3f0;
color: #2f2625;
border-radius: .3em;
padding: 0.4em 0.6em;
}
p, blockquote, li {
margin-bottom: 1.3rem;
}
.credits li {
margin-bottom: 0.3em;
}
h2, h3, h4 {
margin-top: 1.3em;
margin-bottom: 0.6em;
font-family: 'Alegreya Sans';
}
h2 {
font-weight: 800;
}
h3, h4, h2 time {
font-weight: 400;
}
.main h2 {
padding-top: 4rem;
margin-top: -4rem;
}
code {
font-family: 'Roboto Mono';
font-weight: 400;
}
code, a > code {
background-color: #f8f3f0;
padding: 0.2rem 0.4rem;
}
code {
color: #2f2625;
}
.uneditable-code-block .comment {
font-style: italic;
color: #837B85;
}
.uneditable-code-block .class,
.uneditable-code-block .function,
.uneditable-code-block .keyword,
.uneditable-code-block .reserved,
.uneditable-code-block .title {
color: #534328;
}
.uneditable-code-block .string
.uneditable-code-block .value
.uneditable-code-block .inheritance
.uneditable-code-block .header {
color: #3A4029;
}
.uneditable-code-block .variable,
.uneditable-code-block .literal,
.uneditable-code-block .tag,
.uneditable-code-block .regexp,
.uneditable-code-block .subst,
.uneditable-code-block .property {
color: #474429;
}
.uneditable-code-block .number,
.uneditable-code-block .preprocessor,
.uneditable-code-block .built_in,
.uneditable-code-block .params,
.uneditable-code-block .constant {
color: #474429;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg fixed-top navbar-dark bg-dark bg-ribbed-dark site-navbar">
<a class="navbar-brand" href="/" data-close="try"><svg xmlns="http://www.w3.org/2000/svg" viewBox="-22 347 566 100">
<title>
CoffeeScript Logo
</title>
<path d="M21.7 351.1c.1.6-.2 1.1-1.2 1.6-1.3-.7-4.1-1.1-6.4-.9-2.5.2-4.6 1-4.3 2.7.4 1.7 2.8 2.7 7.1 2.3 10.5-.9 10.4-8 25.8-9.4 12-1.1 18.7 2.6 19.6 7.1.7 3.5-2.2 6.9-10.9 7.6-7.7.7-12.2-1.4-12.6-3.5-.2-1.1.4-2.7 4.1-3.1.4 1.7 2.5 3.5 7.5 3 3.6-.3 6.6-1.6 6.2-3.6-.4-2.1-4.2-3.3-10.2-2.8-12.2 1.1-15.2 7.8-25.6 8.7-7.4.7-13.4-2-14.2-6-.3-1.5-.3-5 7.5-5.7 4-.3 7.2.4 7.6 2zm-39 41.8c-3.4 4.3-4.9 9.3-4.6 14.2.3 4.9 2.7 8.9 6.5 12 4 3.1 8.3 4 13.2 3.1 1.9-.3 4-1.3 5.9-1.9-4 0-7.4-1.3-10.8-4-3.7-2.7-6.2-6.5-6.8-11.1-.9-4.3 0-8.3 2.4-11.8 2.7-3.4 6.2-5.3 10.8-5.9 4.6-.3 8.6.9 12.6 3.7-.9-1.3-2.2-2.2-3.4-3.4-4-2.7-8.3-4-13.6-2.7-4.8 1-8.8 3.5-12.2 7.8zm53.6-23.1c-12.9 0-24.4-1.3-32.7-3.1-8.9-2.2-13.6-4.6-13.6-7.7 0-1.3.6-2.4 2.4-3.7-5.6 2.2-8.6 4-8.6 6.8.3 3.1 5.3 6.2 15.5 8.6 9.6 2.4 21.9 3.7 36.7 3.7 15.1 0 27.1-1.3 36.7-3.7 10.2-2.4 15.1-5.6 15.1-8.6 0-2.2-2.2-4.3-6.2-5.9.9.6 1.6 1.6 1.6 2.7 0 3.1-4.6 5.6-13.9 7.7-8.6 1.9-19.6 3.2-33 3.2zm36.8 8.6c-9.6 2.2-21.9 3.7-36.7 3.7-15.1 0-27.4-1.6-37-3.7-8.6-2.2-13.2-4.6-14.8-7.1 1.6 10.8 5.3 21 10.2 30 3.7 5.6 7.4 10.5 11.1 15.8 1.6 3.1 2.7 6.2 3.4 9.3 2.4 3.4 5.9 5.6 10.2 6.8 5.3 1.9 10.8 2.7 16.4 2.4h.6c5.6.3 11.5-.6 16.9-2.4 4-1.3 7.4-3.4 9.9-6.8h.3c.6-3.1 1.6-6.2 3.1-9.3 3.7-5.3 7.4-10.2 11.1-15.8 4.9-8.9 8.3-19.1 10.2-30-2 2.8-6.6 5.2-14.9 7.1zm106.2 30.1c-4.8 12.1-17.6 16.9-25.9 16.9-13.4 0-19.9-6-19.9-22.3 0-16.5 7.9-47.3 31.7-47.3 8.5 0 15.2 3.3 15.2 12.1 0 4.8-1.8 8.3-6.4 8.3-1.5 0-3.4-.4-5.2-2.4 2.2-1.1 4.2-4.9 4.2-8.3 0-2.9-1.5-5.6-5.6-5.6-10 0-18.9 23.9-18.9 42.4 0 8.3 2.2 14.2 10.9 14.2 7.1 0 13.5-3.4 17.7-9.1l2.2 1.1zm32.9-16.3c.4.2.7.2 1 .2 4.2 0 10.1-2.7 14-5.5l.8 2.4c-3.4 3.7-9.5 6.5-16.1 7.5-1.5 16.8-10.6 27.3-21.7 27.3-8.4 0-14.5-4-14.5-14.4 0-10.5 6.2-32.2 24.9-32.2 7.8.3 11.6 5.3 11.6 14.7zm-7.7 5c-1.9-.5-2.4-2-2.4-3.8 0-2.5 1.2-4.2 2.8-4.9-.2-3.8-1.1-5.3-3.4-5.3-6.5 0-12 16.6-12 25.6 0 6 1.2 7.3 4.6 7.3 4.2.1 8.9-8 10.4-18.9zm-6.6 39.7c0-8.3 7.1-11 15.8-13.6l10.9-51.9c2.7-13 10.6-15.5 16.5-15.5 4.1 0 8 2.2 9.7 5.7 3.6-4.6 8.4-5.7 12.4-5.7 5.6 0 10.8 3.9 10.8 9.8 0 1.5-.1 2.6-.3 3.7h-4.3c.1-.9.2-1.7.2-2.4 0-2.1-1.7-3.1-3.4-3.1-2 0-4.8 1.1-6.2 7.1l-1.7 7.4h9.1l-.8 3.6h-9l-10.3 49.1c-2.7 13-10.6 15.5-16.5 15.5-5.2 0-8.3-2.3-9.8-5.7-3.5 4.6-8.3 5.7-12.3 5.7-5.6.1-10.8-3.8-10.8-9.7zm9.1 1.8c1.9 0 4.2-1.8 5.4-7.1l1.1-5.3c-5.7 2-10.1 4.4-10.1 9.4 0 1.2 1.7 3 3.6 3zm21.7 0c1.9 0 4.2-1.8 5.4-7.1l2.2-10.4-9.4 1.8-1.8 8.3c-.5 2.1-1.1 4-1.8 5.6.9 1.3 3 1.8 5.4 1.8zm-1.4-18l9.4-1.7 7.7-36.8h-9l-8.1 38.5zm16.6-56.7c-2 0-4.8 1.1-6.2 7.1l-1.7 7.4h9l2.1-9.5c.2-.7.2-1.3.2-2 .1-2-1.5-3-3.4-3zm37.9 53c7.1 0 11.6-4 16.1-9.2h3.1c-5.2 8.3-12.9 16.8-25 16.8-8.5 0-14.2-4.2-14.2-14.5 0-10.5 5.9-32.3 24.6-32.3 8.1 0 10 4.2 10 8.7 0 10.5-10 18.5-20.9 19.2-.1 1.3-.2 2.5-.2 3.6 0 6.2 2.2 7.7 6.5 7.7zm5.3-34.4c-4.6 0-9.1 9.7-10.9 18.7 7-.5 13.2-7.4 13.2-15 0-2.2-.5-3.7-2.3-3.7zm28.6 33.4c3.4 0 7.8-2.3 10.8-4.8-2 10.4-8.4 13.4-15.8 13.4-8.4 0-14.1-4.2-14.1-14.5 0-10.5 5.9-32.3 24.6-32.3 8.1 0 10 4.2 10 8.7 0 10.6-10 18.5-20.9 19.2-.1.9-.2 2-.2 2.7 0 5.7 2.5 7.6 5.6 7.6zm6.2-33.4c-4.5 0-9.1 10.1-11 18.7 7.1-.4 13.3-7.3 13.3-15 0-2.2-.6-3.7-2.3-3.7zm51.3-6.7c-1.7 0-3-.6-4.2-1.9 2.4-1.5 4.1-4.8 4.1-7.8 0-3.1-1.8-6.1-6.8-6.1s-8.3 2.8-8.3 8.2c0 13.3 20.5 15.2 20.5 34.8 0 15.3-12.3 22.7-25.6 22.7-10.4 0-19.3-4.5-19.3-15.7 0-9.8 7-14.9 13.3-14.9 3.1 0 7.7 1.3 8 6-4.9 0-10.7 2.3-10.7 8.5 0 4.5 2.9 8.7 8.7 8.7 6.1 0 10.6-4.4 10.6-12 0-15.6-18.6-21.1-18.6-34.5 0-9.5 9.3-16.3 21-16.3 4.3 0 14.6.9 14.6 10.9.1 5.5-2.8 9.4-7.3 9.4zm36.2 10.3c0-2.3-.8-3.7-2.5-3.7-5.7 0-11.7 16.6-11.7 26.7 0 6.2 2.2 7.6 6.6 7.6 7.1 0 11.6-4 16.1-9.2h3.1c-5.2 8.3-12.9 16.8-25 16.8-8.5 0-14.2-4.2-14.2-14.5 0-10.6 6-32.3 24.5-32.3 8.1 0 10.1 4.2 10.1 8.3 0 4.4-2.2 6.7-4.8 6.7-1 0-2.1-.4-3.1-1.1.5-1.9.9-3.6.9-5.3zm27.7-7.6l-1.2 5.7c3.1-2.7 6.7-5.7 11-5.7 4.1 0 6.3 3.3 6.3 6.9 0 3.1-2.1 6.7-6.6 6.7-5.1 0-2.5-6-5.3-6-2.7 0-4.4 1.4-6.7 3.4l-7.2 34.6h-13.1l9.6-45.4 13.2-.2zm34.2 0l-6.6 30.9c-.3 1.2-.4 2.1-.4 2.9 0 2.5 1.2 3.3 3.7 3.3 3.5 0 6.9-3.4 8.1-8h3.8c-5.2 14.8-14.2 16.8-19.1 16.8-5.5 0-9.7-3.2-9.7-10.9 0-1.8.3-3.7.7-5.9l6.2-29.2 13.3.1zm-4.1-19.4c4 0 7.2 3.2 7.2 7.2s-3.2 7.1-7.2 7.1-7.1-3.1-7.1-7.1c-.1-4 3.2-7.2 7.1-7.2zm29.1 16l-1.5 6.9c2.6-2.3 6.1-3.9 10.7-3.9 6.2 0 11.1 3.5 11.1 14.4 0 12.2-4.7 32.1-22.3 32.1-4.5 0-6.8-1.6-7.7-3.2l-4.7 22.1-13.7 3.2 15.2-71.5 12.9-.1zm7.8 17c0-7-2.9-7.5-4.5-7.5-2 0-4.5 1.6-6.3 4.4l-5.4 25.5c.4 1 1.4 2.1 3.4 2.1 9.7 0 12.8-15.9 12.8-24.5zm27.8 17.3c-.3 1.1-.5 2.2-.5 3.1 0 1.9.7 3.2 3.1 3.2.7 0 1.7 0 2.4-.3-2.5 7.8-6.6 8.9-9.6 8.9-6.4 0-9.1-4.4-9.1-10.3 0-1.6.2-3.1.6-4.8l5.8-27.2h-3l.7-3.6h3L528 366l13.4-1.9s-1.4 6.2-3.1 14.4h5.5l-.7 3.6h-5.5l-5.7 27.4z"/>
</svg>
</a>
<button class="navbar-toggler" type="button" data-toggle="offcanvas" data-close="try" aria-label="Toggle sidebar">
<span class="navbar-toggler-icon"></span>
</button>
<nav class="collapse navbar-collapse">
<div class="navbar-nav mr-auto d-none d-lg-flex">
<a href="../#try" id="try-link" class="nav-item nav-link" data-toggle="try">Try CoffeeScript</a>
<a href="../#language" class="nav-item nav-link" data-close="try">Language Reference</a>
<a href="../#resources" class="nav-item nav-link" data-close="try">Resources</a>
<a href="https://github.com/jashkenas/coffeescript" class="nav-item nav-link" data-close="try">GitHub
</a>
</div>
</nav>
</nav>
<div class="container" id="top">
<div class="row">
<main class="main">
<header>
<h1>Announcing <span class="text-nowrap"><svg class="title-logo" xmlns="http://www.w3.org/2000/svg" viewBox="-76 212 458 369">
<title>
CoffeeScript Icon
</title>
<path d="M106 228.6c.5 2.3-.9 4.4-5 6.5-5.5-3.1-16.9-4.4-26.7-3.5-10.4.9-19.4 4.2-17.9 11.3 1.5 7.1 11.7 11 29.5 9.5 43.6-3.8 43.4-33.3 107.4-39 49.8-4.4 77.8 11 81.8 29.7 3.1 14.7-9.1 28.6-45.2 31.8-32 2.8-50.7-5.6-52.6-14.6-1-4.5 1.8-11.3 17.2-13.1 1.5 7 10.6 14.4 31.1 12.6 14.8-1.3 27.6-6.6 25.9-14.9-1.8-8.6-17.7-13.7-42.6-11.5-50.7 4.5-63.2 32.5-106.8 36.3-30.8 2.7-55.9-8.5-59.4-25.1-1.3-6.1-1.4-21 31.2-23.9 17.1-1.5 30.7 1.5 32.1 7.9zM-56.4 402.5c-14.3 18-20.4 38.8-19.2 59.2 1.2 20.4 11.4 37.1 26.9 50.2C-32 525-14 528.6 6.4 525c7.8-1.2 16.7-5.3 24.5-7.8-16.7 0-31-5.3-44.9-16.7-15.5-11.4-25.7-26.9-28.2-46.1-3.7-18 0-34.7 10.2-49 11.4-14.3 25.7-22 44.9-24.5 19.2-1.2 35.9 3.7 52.6 15.5-3.7-5.3-9-9-14.3-14.3-16.7-11.4-34.7-16.7-56.7-11.4-19.9 3.6-36.7 13.8-50.9 31.8zm223.6-96.3c-53.9 0-101.6-5.3-136.3-13.1-37.1-9-56.7-19.2-56.7-32.2 0-5.3 2.4-10.2 10.2-15.5-23.3 9-35.9 16.7-35.9 28.2 1.2 13.1 22 25.7 64.5 35.9 40 10.2 91.4 15.5 153 15.5 62.8 0 113-5.3 153-15.5 42.4-10.2 62.8-23.3 62.8-35.9 0-9-9-18-25.7-24.5 3.7 2.4 6.5 6.5 6.5 11.4 0 13.1-19.2 23.3-57.9 32.2-36 8.2-82.1 13.5-137.5 13.5zm153 35.9c-40 9-91.4 15.5-153 15.5-62.8 0-114.2-6.5-154.2-15.5-35.9-9-55.1-19.2-61.6-29.4 6.5 44.9 22 87.3 42.4 124.8 15.5 23.3 31 43.7 46.1 65.7 6.5 13.1 11.4 25.7 14.3 38.8 10.2 14.3 24.5 23.3 42.4 28.2 22 7.8 44.9 11.4 68.1 10.2h2.4c23.3 1.2 47.7-2.4 70.6-10.2 16.7-5.3 31-14.3 41.2-28.2h1.2c2.4-13.1 6.5-25.7 13.1-38.8 15.5-22 31-42.4 46.1-65.7 20.4-37.1 34.7-79.6 42.4-124.8-7.7 11.4-26.9 21.6-61.5 29.4z"/>
</svg> CoffeeScript 2</span></h1>
</header>
<section>
<p>We are pleased to announce CoffeeScript 2! This new release of the CoffeeScript language and compiler aims to bring CoffeeScript into the modern JavaScript era, closing gaps in compatibility with JavaScript while preserving the clean syntax that is CoffeeScripts hallmark. In a nutshell:</p>
<ul>
<li>The CoffeeScript 2 compiler now translates CoffeeScript code into modern JavaScript syntax. So a CoffeeScript <code>=&gt;</code> is now output as <code>=&gt;</code>, a CoffeeScript <code>class</code> is now output using the <code>class</code> keyword, and so on. This means you may need to <a href="../#transpilation">transpile the CoffeeScript compilers output</a>.</li>
<li>CoffeeScript 2 adds support for <a href="../#async-functions">async functions</a> syntax, for the future <a href="../#destructuring">object destructuring</a> syntax, and for <a href="../#jsx">JSX</a>. Some features, such as <a href="../#modules">modules</a> (<code>import</code> and <code>export</code> statements), <a href="../#generator-iteration"><code>for…of</code></a>, and <a href="../#tagged-template-literals">tagged template literals</a> were backported into CoffeeScript versions 1.11 and 1.12.</li>
<li>All of the above was achieved with very few <a href="../#breaking-changes">breaking changes from 1.x</a>. Most current CoffeeScript projects should be able to upgrade with little or no refactoring necessary.</li>
</ul>
<p>CoffeeScript 2 was developed with two primary goals: remove any incompatibilities with modern JavaScript that might prevent CoffeeScript from being used on a project; and preserve as much backward compatibility as possible. <a href="../#installation">Install now</a>: <code>npm install -g coffeescript@2</code></p>
<h2 id="modern-javascript-output">Modern JavaScript Output</h2>
<p>From the beginning, CoffeeScript has been described as being “just JavaScript.” And today, JavaScript is ES2015 (well, ES2017; also commonly known as ES6). CoffeeScript welcomes the changes in the JavaScript world and were happy to stop outputting circa-1999 syntax for modern features.</p>
<p>Many new JavaScript features, such as <code>=&gt;</code>, were informed by CoffeeScript and are one-to-one compatible, or very nearly so. This has made outputting many of CoffeeScripts innovations into new JS syntax straightforward: not only does <code>=&gt;</code> become <code>=&gt;</code>, but <code>{ a } = obj</code> becomes <code>{ a } = obj</code>, <code>&quot;a#{b}c&quot;</code> becomes <code>`a${b}c`</code> and so on.</p>
<p>The following CoffeeScript features were updated in 2.0 to output using modern JavaScript syntax (or added in CoffeeScript 1.11 through 2.0, output using modern syntax):</p>
<ul>
<li>Modules: <code>import</code>/<code>export</code></li>
<li>Classes: <code>class Animal</code></li>
<li>Async functions: <code>await someFunction()</code></li>
<li>Bound/arrow functions: <code>=&gt;</code></li>
<li>Function default parameters: <code>(options = {}) -&gt;</code></li>
<li>Function splat/rest parameters: <code>(items...) -&gt;</code></li>
<li>Destructuring, for both arrays and objects: <code>[first, second] = items</code>, <code>{length} = items</code></li>
<li>Object rest/spread properties: <code>{options..., force: yes}</code>, <code>{force, otherOptions...} = options</code></li>
<li>Interpolated strings/template literals (JS backticked strings): <code>&quot;Hello, #{user}!&quot;</code></li>
<li>Tagged template literals: <code>html&quot;&lt;strong&gt;coffee&lt;/strong&gt;&quot;</code></li>
<li>JavaScripts <code>for…of</code> is now available as CoffeeScripts <code>for…from</code> (we already had a <code>for…of</code>): <code>for n from generatorFunction()</code></li>
</ul>
<p>Not all CoffeeScript features were adopted into JavaScript in 100% the same way; most notably, <a href="../#breaking-changes-default-values">default values</a> in JavaScript (and also in CoffeeScript 2) are only applied when a variable is <code>undefined</code>, not <code>undefined</code> or <code>null</code> as in CoffeeScript 1; and <a href="../#breaking-changes-classes">classes</a> have their own differences. See the <a href="../#breaking-changes">breaking changes</a> for the fine details.</p>
<p>In our experience, most breaking changes are edge cases that should affect very few people, like JavaScripts <a href="../#breaking-change-fat-arrow">lack of an <code>arguments</code> object inside arrow functions</a>. There seem to be two breaking changes that affect a significant number of projects:</p>
<ul>
<li>In CoffeeScript 2, “bare” <code>super</code> (calling <code>super</code> without arguments) is now no longer allowed, and one must use <code>super()</code> or <code>super arguments...</code> instead.</li>
<li>References to <code>this</code>/<code>@</code> cannot occur before a call to <code>super</code>, per the JS spec.</li>
</ul>
<p>See the <a href="../#breaking-changes-super-extends">full details</a>. Either the CoffeeScript compiler or your transpiler will throw errors for either of these cases, so updating your code is a matter of fixing each occurrence as the compiler errors on it, until your code compiles successfully.</p>
<h2 id="other-features">Other Features</h2>
<p>Besides supporting new JavaScript features and outputting older CoffeeScript features in modern JS syntax, CoffeeScript 2 has added support for the following:</p>
<ul>
<li><a href="../#jsx">JSX</a></li>
<li><a href="../#comments">Line comments</a> are now output (in CoffeeScript 1 they were discarded)</li>
<li>Block comments are now allowed anywhere, enabling <a href="../#type-annotations">static type annotations</a> using Flows comment-based syntax</li>
</ul>
<p>There are many smaller improvements as well, such as to the <code>coffee</code> command-line tool. You can read all the details in the <a href="../#changelog">changelog</a> for the 2.0.0 betas.</p>
<h2 id="what-about-…">“What About …?”</h2>
<p>A few JavaScript features have been intentionally omitted from CoffeeScript. These include <code>let</code> and <code>const</code> (and <code>var</code>), named functions and the <code>get</code> and <code>set</code> keywords. These get asked about so often that we added a section to the docs called <a href="../#unsupported">Unsupported ECMAScript Features</a>. CoffeeScripts lack of equivalents for these features does not affect compatibility or interoperability with JavaScript modules or libraries.</p>
<h2 id="future-compatibility">Future Compatibility</h2>
<p>Back when CoffeeScript 1 was created, ES2015 JavaScript and transpilers like <a href="http://babeljs.io/">Babel</a>, <a href="https://buble.surge.sh/">Bublé</a> or <a href="https://github.com/google/traceur-compiler">Traceur Compiler</a> were several years away. The CoffeeScript compiler itself had to do what todays transpilers do, converting modern features like destructuring and arrow functions into equivalent lowest-common-denominator JavaScript.</p>
<p>But transpilers exist now, and they do their job well. With them around, theres no need for the CoffeeScript compiler to duplicate this functionality. All the CoffeeScript compiler needs to worry about now is converting the CoffeeScript version of new syntax into the JS version of that syntax, e.g. <code>&quot;Hello, #{name}!&quot;</code> into <code>`Hello, ${name}!`</code>. This makes adding support for new JavaScript features much easier than before.</p>
<p>Most features added by ECMA in recent years havent required any updates at all in CoffeeScript. New global objects, or new methods on global objects, dont require any updates on CoffeeScripts part to work. Some proposed future JS features <em>do</em> involve new syntax, like <a href="https://github.com/tc39/proposal-class-fields">class fields</a>. We have adopted a policy of supporting new syntax only when it reaches Stage 4 in ECMAs process, which means that the syntax is final and will be in the next ES release. On occasion we might support a <em>feature</em> before it has reached Stage 4, but output it using equivalent non-experimental syntax instead of the newly-proposed syntax; thats whats happening in 2.0.0 for <a href="../#splats">object destructuring</a>, where our output uses the same polyfill that Babel uses. When the new syntax is finalized, we will update our output to use the final syntax.</p>
<h2 id="credits">Credits</h2>
<p>The major features of 2.0.0 would not have been possible without the following people:</p>
<ul class="credits">
<li><a href="https://github.com/GeoffreyBooth">@GeoffreyBooth</a>: Organizer of the CoffeeScript 2 effort, developer for modules; arrow functions, function default parameters and function rest parameters output using ES2015 syntax; line comments output and block comments output anywhere; block embedded JavaScript via triple backticks; improved parsing of Literate CoffeeScript; and the new docs website.</li>
<li><a href="https://github.com/connec">@connec</a>: Classes; destructuring; splats/rest syntax in arrays and function calls; and computed properties all output using ES2015 syntax.</li>
<li><a href="https://github.com/GabrielRatener">@GabrielRatener</a>: Async functions.</li>
<li><a href="https://github.com/xixixao">@xixixao</a>: JSX.</li>
<li><a href="https://github.com/zdenko">@zdenko</a>: Object rest/spread properties (object destructuring).</li>
<li><a href="https://github.com/greghuc">@greghuc</a>: Tagged template literals, interpolated strings output in ES2015 syntax.</li>
<li><a href="https://github.com/atg">@atg</a>: ES2015 <code>for…of</code>, supported as CoffeeScripts <code>for…from</code>.</li>
<li><a href="https://github.com/lydell">@lydell</a> and <a href="https://github.com/jashkenas">@jashkenas</a>: Guidance, code reviews and feedback.</li>
</ul>
<p>See the full <a href="https://github.com/jashkenas/coffeescript/wiki/CoffeeScript-2-Honor-Roll">honor roll</a>.</p>
<p>Thanks and we hope you enjoy CoffeeScript 2!</p>
</section>
</main>
</div>
</div>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-106156830-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments)};
gtag('js', new Date());
gtag('config', 'UA-106156830-1');
</script>
</body>
</html>

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,10 @@
# Eat lunch.
eat = (food) -> "#{food} eaten."
eat food for food in ['toast', 'cheese', 'wine']
# Fine five course dining.
courses = ['greens', 'caviar', 'truffles', 'roast', 'cake']
menu = (i, dish) -> "Menu Item #{i}: #{dish}"
menu i + 1, dish for dish, i in courses
# Health conscious meal.

View File

@@ -0,0 +1,4 @@
popular = ['pepperoni', 'sausage', 'cheese']
unwanted = ['anchovies', 'olives']
all = [popular..., unwanted..., 'mushrooms']

View File

@@ -0,0 +1,18 @@
# Your browser must support async/await and speech synthesis
# to run this example.
sleep = (ms) ->
new Promise (resolve) ->
window.setTimeout resolve, ms
say = (text) ->
window.speechSynthesis.cancel()
window.speechSynthesis.speak new SpeechSynthesisUtterance text
countdown = (seconds) ->
for i in [seconds..1]
say i
await sleep 1000 # wait one second
say "Blastoff!"
countdown 3

View File

@@ -1,4 +0,0 @@
###
SkinnyMochaHalfCaffScript Compiler v1.0
Released under the MIT License
###

View File

@@ -0,0 +1,2 @@
self = this
f = -> yield self

View File

@@ -0,0 +1,3 @@
{a = 1} = {a: null}
a # Equals 1 in CoffeeScript 1.x, null in CoffeeScript 2

View File

@@ -0,0 +1,5 @@
outer = ->
inner = => Array.from arguments
inner()
outer(1, 2) # Returns '' in CoffeeScript 1.x, '1, 2' in CoffeeScript 2

View File

@@ -0,0 +1,3 @@
f = (a = 1) -> a
f(null) # Returns 1 in CoffeeScript 1.x, null in CoffeeScript 2

View File

@@ -0,0 +1,18 @@
# Helper functions
hasProp = {}.hasOwnProperty
extend = (child, parent) ->
ctor = ->
@constructor = child
return
for key of parent
if hasProp.call(parent, key)
child[key] = parent[key]
ctor.prototype = parent.prototype
child.prototype = new ctor
child
A = ->
B = ->
extend B, A
B.prototype.foo = -> A::foo.apply this, arguments

View File

@@ -0,0 +1,3 @@
class A
class B extends A
foo: -> super arguments...

View File

@@ -0,0 +1,4 @@
class B extends A
constructor: (arg) ->
super arg
@arg = arg

View File

@@ -0,0 +1,2 @@
class B extends A
foo: -> super arguments...

View File

@@ -0,0 +1,2 @@
class B extends A
foo: -> super()

View File

@@ -2,5 +2,5 @@ $ 'body'
.click (e) ->
$ '.box'
.fadeIn 'fast'
.addClass '.active'
.addClass 'show'
.css 'background', 'white'

View File

@@ -0,0 +1,7 @@
###
Fortune Cookie Reader v1.0
Released under the MIT License
###
sayFortune = (fortune) ->
console.log fortune # in bed!

View File

@@ -1,4 +1,5 @@
for filename in list
do (filename) ->
fs.readFile filename, (err, contents) ->
compile filename, contents.toString()
if filename not in ['.DS_Store', 'Thumbs.db', 'ehthumbs.db']
fs.readFile filename, (err, contents) ->
compile filename, contents.toString()

View File

@@ -0,0 +1,4 @@
major = 'Computer Science'
unless major?
signUpForClass 'Introduction to Wines'

View File

@@ -0,0 +1,2 @@
if window?
environment = 'browser (probably)'

View File

@@ -0,0 +1,9 @@
screen =
width: 1200
ratio: 16/9
Object.defineProperty screen, 'height',
get: ->
this.width / this.ratio
set: (val) ->
this.width = val * this.ratio

View File

@@ -1,9 +1,6 @@
OPERATOR = /// ^ (
?: [-=]> # function
| [-+*/%<>&|^!?=]= # compound assign / compare
| >>>=? # zero-fill right shift
| ([-+:])\1 # doubles
| ([&|<>])\2=? # logic / shift
| \?\. # soak access
| \.{2,3} # range or splat
) ///
NUMBER = ///
^ 0b[01]+ | # binary
^ 0o[0-7]+ | # octal
^ 0x[\da-f]+ | # hex
^ \d*\.?\d+ (?:e[+-]?\d+)? # decimal
///i

View File

@@ -0,0 +1,9 @@
renderStarRating = ({ rating, maxStars }) ->
<aside title={"Rating: #{rating} of #{maxStars} stars"}>
{for wholeStar in [0...Math.floor(rating)]
<Star className="wholeStar" key={wholeStar} />}
{if rating % 1 isnt 0
<Star className="halfStar" />}
{for emptyStar in [Math.ceil(rating)...maxStars]
<Star className="emptyStar" key={emptyStar} />}
</aside>

View File

@@ -0,0 +1,5 @@
user =
name: 'Werner Heisenberg'
occupation: 'theoretical physicist'
currentUser = { user..., status: 'Uncertain' }

View File

@@ -1,3 +1,3 @@
$('.account').attr class: 'active'
$('.account').prop class: 'active'
log object.class

View File

@@ -20,6 +20,8 @@ contenders = [
awardMedals contenders...
alert "Gold: " + gold
alert "Silver: " + silver
alert "The Field: " + rest
alert """
Gold: #{gold}
Silver: #{silver}
The Field: #{rest.join ', '}
"""

View File

@@ -0,0 +1,9 @@
class Teenager
@say: (speech) ->
words = speech.split ' '
fillers = ['uh', 'um', 'like', 'actually', 'so', 'maybe']
output = []
for word, index in words
output.push word
output.push fillers[Math.floor(Math.random() * fillers.length)] unless index is words.length - 1
output.join ', '

View File

@@ -0,0 +1,10 @@
# @flow
###::
type Obj = {
num: number,
};
###
fn = (str ###: string ###, obj ###: Obj ###) ###: string ### ->
str + obj.num

View File

@@ -1,6 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-22 347 566 100">
<title>
CoffeeScript Logo
</title>
<path d="M21.7 351.1c.1.6-.2 1.1-1.2 1.6-1.3-.7-4.1-1.1-6.4-.9-2.5.2-4.6 1-4.3 2.7.4 1.7 2.8 2.7 7.1 2.3 10.5-.9 10.4-8 25.8-9.4 12-1.1 18.7 2.6 19.6 7.1.7 3.5-2.2 6.9-10.9 7.6-7.7.7-12.2-1.4-12.6-3.5-.2-1.1.4-2.7 4.1-3.1.4 1.7 2.5 3.5 7.5 3 3.6-.3 6.6-1.6 6.2-3.6-.4-2.1-4.2-3.3-10.2-2.8-12.2 1.1-15.2 7.8-25.6 8.7-7.4.7-13.4-2-14.2-6-.3-1.5-.3-5 7.5-5.7 4-.3 7.2.4 7.6 2zm-39 41.8c-3.4 4.3-4.9 9.3-4.6 14.2.3 4.9 2.7 8.9 6.5 12 4 3.1 8.3 4 13.2 3.1 1.9-.3 4-1.3 5.9-1.9-4 0-7.4-1.3-10.8-4-3.7-2.7-6.2-6.5-6.8-11.1-.9-4.3 0-8.3 2.4-11.8 2.7-3.4 6.2-5.3 10.8-5.9 4.6-.3 8.6.9 12.6 3.7-.9-1.3-2.2-2.2-3.4-3.4-4-2.7-8.3-4-13.6-2.7-4.8 1-8.8 3.5-12.2 7.8zm53.6-23.1c-12.9 0-24.4-1.3-32.7-3.1-8.9-2.2-13.6-4.6-13.6-7.7 0-1.3.6-2.4 2.4-3.7-5.6 2.2-8.6 4-8.6 6.8.3 3.1 5.3 6.2 15.5 8.6 9.6 2.4 21.9 3.7 36.7 3.7 15.1 0 27.1-1.3 36.7-3.7 10.2-2.4 15.1-5.6 15.1-8.6 0-2.2-2.2-4.3-6.2-5.9.9.6 1.6 1.6 1.6 2.7 0 3.1-4.6 5.6-13.9 7.7-8.6 1.9-19.6 3.2-33 3.2zm36.8 8.6c-9.6 2.2-21.9 3.7-36.7 3.7-15.1 0-27.4-1.6-37-3.7-8.6-2.2-13.2-4.6-14.8-7.1 1.6 10.8 5.3 21 10.2 30 3.7 5.6 7.4 10.5 11.1 15.8 1.6 3.1 2.7 6.2 3.4 9.3 2.4 3.4 5.9 5.6 10.2 6.8 5.3 1.9 10.8 2.7 16.4 2.4h.6c5.6.3 11.5-.6 16.9-2.4 4-1.3 7.4-3.4 9.9-6.8h.3c.6-3.1 1.6-6.2 3.1-9.3 3.7-5.3 7.4-10.2 11.1-15.8 4.9-8.9 8.3-19.1 10.2-30-2 2.8-6.6 5.2-14.9 7.1zm106.2 30.1c-4.8 12.1-17.6 16.9-25.9 16.9-13.4 0-19.9-6-19.9-22.3 0-16.5 7.9-47.3 31.7-47.3 8.5 0 15.2 3.3 15.2 12.1 0 4.8-1.8 8.3-6.4 8.3-1.5 0-3.4-.4-5.2-2.4 2.2-1.1 4.2-4.9 4.2-8.3 0-2.9-1.5-5.6-5.6-5.6-10 0-18.9 23.9-18.9 42.4 0 8.3 2.2 14.2 10.9 14.2 7.1 0 13.5-3.4 17.7-9.1l2.2 1.1zm32.9-16.3c.4.2.7.2 1 .2 4.2 0 10.1-2.7 14-5.5l.8 2.4c-3.4 3.7-9.5 6.5-16.1 7.5-1.5 16.8-10.6 27.3-21.7 27.3-8.4 0-14.5-4-14.5-14.4 0-10.5 6.2-32.2 24.9-32.2 7.8.3 11.6 5.3 11.6 14.7zm-7.7 5c-1.9-.5-2.4-2-2.4-3.8 0-2.5 1.2-4.2 2.8-4.9-.2-3.8-1.1-5.3-3.4-5.3-6.5 0-12 16.6-12 25.6 0 6 1.2 7.3 4.6 7.3 4.2.1 8.9-8 10.4-18.9zm-6.6 39.7c0-8.3 7.1-11 15.8-13.6l10.9-51.9c2.7-13 10.6-15.5 16.5-15.5 4.1 0 8 2.2 9.7 5.7 3.6-4.6 8.4-5.7 12.4-5.7 5.6 0 10.8 3.9 10.8 9.8 0 1.5-.1 2.6-.3 3.7h-4.3c.1-.9.2-1.7.2-2.4 0-2.1-1.7-3.1-3.4-3.1-2 0-4.8 1.1-6.2 7.1l-1.7 7.4h9.1l-.8 3.6h-9l-10.3 49.1c-2.7 13-10.6 15.5-16.5 15.5-5.2 0-8.3-2.3-9.8-5.7-3.5 4.6-8.3 5.7-12.3 5.7-5.6.1-10.8-3.8-10.8-9.7zm9.1 1.8c1.9 0 4.2-1.8 5.4-7.1l1.1-5.3c-5.7 2-10.1 4.4-10.1 9.4 0 1.2 1.7 3 3.6 3zm21.7 0c1.9 0 4.2-1.8 5.4-7.1l2.2-10.4-9.4 1.8-1.8 8.3c-.5 2.1-1.1 4-1.8 5.6.9 1.3 3 1.8 5.4 1.8zm-1.4-18l9.4-1.7 7.7-36.8h-9l-8.1 38.5zm16.6-56.7c-2 0-4.8 1.1-6.2 7.1l-1.7 7.4h9l2.1-9.5c.2-.7.2-1.3.2-2 .1-2-1.5-3-3.4-3zm37.9 53c7.1 0 11.6-4 16.1-9.2h3.1c-5.2 8.3-12.9 16.8-25 16.8-8.5 0-14.2-4.2-14.2-14.5 0-10.5 5.9-32.3 24.6-32.3 8.1 0 10 4.2 10 8.7 0 10.5-10 18.5-20.9 19.2-.1 1.3-.2 2.5-.2 3.6 0 6.2 2.2 7.7 6.5 7.7zm5.3-34.4c-4.6 0-9.1 9.7-10.9 18.7 7-.5 13.2-7.4 13.2-15 0-2.2-.5-3.7-2.3-3.7zm28.6 33.4c3.4 0 7.8-2.3 10.8-4.8-2 10.4-8.4 13.4-15.8 13.4-8.4 0-14.1-4.2-14.1-14.5 0-10.5 5.9-32.3 24.6-32.3 8.1 0 10 4.2 10 8.7 0 10.6-10 18.5-20.9 19.2-.1.9-.2 2-.2 2.7 0 5.7 2.5 7.6 5.6 7.6zm6.2-33.4c-4.5 0-9.1 10.1-11 18.7 7.1-.4 13.3-7.3 13.3-15 0-2.2-.6-3.7-2.3-3.7zm51.3-6.7c-1.7 0-3-.6-4.2-1.9 2.4-1.5 4.1-4.8 4.1-7.8 0-3.1-1.8-6.1-6.8-6.1s-8.3 2.8-8.3 8.2c0 13.3 20.5 15.2 20.5 34.8 0 15.3-12.3 22.7-25.6 22.7-10.4 0-19.3-4.5-19.3-15.7 0-9.8 7-14.9 13.3-14.9 3.1 0 7.7 1.3 8 6-4.9 0-10.7 2.3-10.7 8.5 0 4.5 2.9 8.7 8.7 8.7 6.1 0 10.6-4.4 10.6-12 0-15.6-18.6-21.1-18.6-34.5 0-9.5 9.3-16.3 21-16.3 4.3 0 14.6.9 14.6 10.9.1 5.5-2.8 9.4-7.3 9.4zm36.2 10.3c0-2.3-.8-3.7-2.5-3.7-5.7 0-11.7 16.6-11.7 26.7 0 6.2 2.2 7.6 6.6 7.6 7.1 0 11.6-4 16.1-9.2h3.1c-5.2 8.3-12.9 16.8-25 16.8-8.5 0-14.2-4.2-14.2-14.5 0-10.6 6-32.3 24.5-32.3 8.1 0 10.1 4.2 10.1 8.3 0 4.4-2.2 6.7-4.8 6.7-1 0-2.1-.4-3.1-1.1.5-1.9.9-3.6.9-5.3zm27.7-7.6l-1.2 5.7c3.1-2.7 6.7-5.7 11-5.7 4.1 0 6.3 3.3 6.3 6.9 0 3.1-2.1 6.7-6.6 6.7-5.1 0-2.5-6-5.3-6-2.7 0-4.4 1.4-6.7 3.4l-7.2 34.6h-13.1l9.6-45.4 13.2-.2zm34.2 0l-6.6 30.9c-.3 1.2-.4 2.1-.4 2.9 0 2.5 1.2 3.3 3.7 3.3 3.5 0 6.9-3.4 8.1-8h3.8c-5.2 14.8-14.2 16.8-19.1 16.8-5.5 0-9.7-3.2-9.7-10.9 0-1.8.3-3.7.7-5.9l6.2-29.2 13.3.1zm-4.1-19.4c4 0 7.2 3.2 7.2 7.2s-3.2 7.1-7.2 7.1-7.1-3.1-7.1-7.1c-.1-4 3.2-7.2 7.1-7.2zm29.1 16l-1.5 6.9c2.6-2.3 6.1-3.9 10.7-3.9 6.2 0 11.1 3.5 11.1 14.4 0 12.2-4.7 32.1-22.3 32.1-4.5 0-6.8-1.6-7.7-3.2l-4.7 22.1-13.7 3.2 15.2-71.5 12.9-.1zm7.8 17c0-7-2.9-7.5-4.5-7.5-2 0-4.5 1.6-6.3 4.4l-5.4 25.5c.4 1 1.4 2.1 3.4 2.1 9.7 0 12.8-15.9 12.8-24.5zm27.8 17.3c-.3 1.1-.5 2.2-.5 3.1 0 1.9.7 3.2 3.1 3.2.7 0 1.7 0 2.4-.3-2.5 7.8-6.6 8.9-9.6 8.9-6.4 0-9.1-4.4-9.1-10.3 0-1.6.2-3.1.6-4.8l5.8-27.2h-3l.7-3.6h3L528 366l13.4-1.9s-1.4 6.2-3.1 14.4h5.5l-.7 3.6h-5.5l-5.7 27.4z"/>
</svg>

Before

Width:  |  Height:  |  Size: 4.7 KiB

View File

@@ -0,0 +1,16 @@
## Annotated Source
You can browse the CoffeeScript <%= fullVersion %> source in readable, annotated form [here](annotated-source/). You can also jump directly to a particular source file:
- [Grammar Rules — src/grammar](annotated-source/grammar.html)
- [Lexing Tokens — src/lexer](annotated-source/lexer.html)
- [The Rewriter — src/rewriter](annotated-source/rewriter.html)
- [The Syntax Tree — src/nodes](annotated-source/nodes.html)
- [Lexical Scope — src/scope](annotated-source/scope.html)
- [Helpers &amp; Utility Functions — src/helpers](annotated-source/helpers.html)
- [The CoffeeScript Module — src/coffeescript](annotated-source/coffeescript.html)
- [Cake &amp; Cakefiles — src/cake](annotated-source/cake.html)
- [“coffee” Command-Line Utility — src/command](annotated-source/command.html)
- [Option Parsing — src/optparse](annotated-source/optparse.html)
- [Interactive REPL — src/repl](annotated-source/repl.html)
- [Source Maps — src/sourcemap](annotated-source/sourcemap.html)

View File

@@ -0,0 +1,78 @@
# Announcing CoffeeScript 2
We are pleased to announce CoffeeScript 2! This new release of the CoffeeScript language and compiler aims to bring CoffeeScript into the modern JavaScript era, closing gaps in compatibility with JavaScript while preserving the clean syntax that is CoffeeScripts hallmark. In a nutshell:
- The CoffeeScript 2 compiler now translates CoffeeScript code into modern JavaScript syntax. So a CoffeeScript `=>` is now output as `=>`, a CoffeeScript `class` is now output using the `class` keyword, and so on. This means you may need to [transpile the CoffeeScript compilers output](../#es2015plus-output).
- CoffeeScript 2 adds support for [async functions](../#async-functions) syntax, for the future [object destructuring](../#destructuring) syntax, and for [JSX](../#jsx). Some features, such as [modules](../#modules) (`import` and `export` statements), [`for…of`](../#generator-iteration), and [tagged template literals](../#tagged-template-literals) were backported into CoffeeScript versions 1.11 and 1.12.
- All of the above was achieved with very few [breaking changes from 1.x](../#breaking-changes). Most current CoffeeScript projects should be able to upgrade with little or no refactoring necessary.
CoffeeScript 2 was developed with two primary goals: remove any incompatibilities with modern JavaScript that might prevent CoffeeScript from being used on a project; and preserve as much backward compatibility as possible. [Install now](../#installation): `npm install -g coffeescript@2`
## Modern JavaScript Output
From the beginning, CoffeeScript has been described as being “just JavaScript.” And today, JavaScript is ES2015 (well, ES2017; also commonly known as ES6). CoffeeScript welcomes the changes in the JavaScript world and were happy to stop outputting circa-1999 syntax for modern features.
Many new JavaScript features, such as `=>`, were informed by CoffeeScript and are one-to-one compatible, or very nearly so. This has made outputting many of CoffeeScripts innovations into new JS syntax straightforward: not only does `=>` become `=>`, but `{ a } = obj` becomes `{ a } = obj`, `"a#{b}c"` becomes `` `a${b}c` `` and so on.
The following CoffeeScript features were updated in 2.0 to output using modern JavaScript syntax (or added in CoffeeScript 1.11 through 2.0, output using modern syntax):
- Modules: `import`/`export`
- Classes: `class Animal`
- Async functions: `await someFunction()`
- Bound/arrow functions: `=>`
- Function default parameters: `(options = {}) ->`
- Function splat/rest parameters: `(items...) ->`
- Destructuring, for both arrays and objects: `[first, second] = items`, `{length} = items`
- Object rest/spread properties: `{options..., force: yes}`, `{force, otherOptions...} = options`
- Interpolated strings/template literals (JS backticked strings): `"Hello, #{user}!"`
- Tagged template literals: `html"<strong>coffee</strong>"`
- JavaScripts `for…of` is now available as CoffeeScripts `for…from` (we already had a `for…of`): `for n from generatorFunction()`
Not all CoffeeScript features were adopted into JavaScript in 100% the same way; most notably, [default values](../#breaking-changes-default-values) in JavaScript (and also in CoffeeScript 2) are only applied when a variable is `undefined`, not `undefined` or `null` as in CoffeeScript 1; and [classes](../#breaking-changes-classes) have their own differences. See the [breaking changes](../#breaking-changes) for the fine details.
In our experience, most breaking changes are edge cases that should affect very few people, like JavaScripts [lack of an `arguments` object inside arrow functions](../#breaking-change-fat-arrow). There seem to be two breaking changes that affect a significant number of projects:
- In CoffeeScript 2, “bare” `super` (calling `super` without arguments) is now no longer allowed, and one must use `super()` or `super arguments...` instead.
- References to `this`/`@` cannot occur before a call to `super`, per the JS spec.
See the [full details](../#breaking-changes-super-extends). Either the CoffeeScript compiler or your transpiler will throw errors for either of these cases, so updating your code is a matter of fixing each occurrence as the compiler errors on it, until your code compiles successfully.
## Other Features
Besides supporting new JavaScript features and outputting older CoffeeScript features in modern JS syntax, CoffeeScript 2 has added support for the following:
- [JSX](../#jsx)
- [Line comments](../#comments) are now output (in CoffeeScript 1 they were discarded)
- Block comments are now allowed anywhere, enabling [static type annotations](../#type-annotations) using Flows comment-based syntax
There are many smaller improvements as well, such as to the `coffee` command-line tool. You can read all the details in the [changelog](../#changelog) for the 2.0.0 betas.
## “What About …?”
A few JavaScript features have been intentionally omitted from CoffeeScript. These include `let` and `const` (and `var`), named functions and the `get` and `set` keywords. These get asked about so often that we added a section to the docs called [Unsupported ECMAScript Features](../#unsupported). CoffeeScripts lack of equivalents for these features does not affect compatibility or interoperability with JavaScript modules or libraries.
## Future Compatibility
Back when CoffeeScript 1 was created, ES2015 JavaScript and transpilers like [Babel](http://babeljs.io/), [Bublé](https://buble.surge.sh/) or [Traceur Compiler](https://github.com/google/traceur-compiler) were several years away. The CoffeeScript compiler itself had to do what todays transpilers do, converting modern features like destructuring and arrow functions into equivalent lowest-common-denominator JavaScript.
But transpilers exist now, and they do their job well. With them around, theres no need for the CoffeeScript compiler to duplicate this functionality. All the CoffeeScript compiler needs to worry about now is converting the CoffeeScript version of new syntax into the JS version of that syntax, e.g. `"Hello, #{name}!"` into `` `Hello, ${name}!` ``. This makes adding support for new JavaScript features much easier than before.
Most features added by ECMA in recent years havent required any updates at all in CoffeeScript. New global objects, or new methods on global objects, dont require any updates on CoffeeScripts part to work. Some proposed future JS features _do_ involve new syntax, like [class fields](https://github.com/tc39/proposal-class-fields). We have adopted a policy of supporting new syntax only when it reaches Stage 4 in ECMAs process, which means that the syntax is final and will be in the next ES release. On occasion we might support a _feature_ before it has reached Stage 4, but output it using equivalent non-experimental syntax instead of the newly-proposed syntax; thats whats happening in 2.0.0 for [object destructuring](../#splats), where our output uses the same polyfill that Babel uses. When the new syntax is finalized, we will update our output to use the final syntax.
## Credits
The major features of 2.0.0 would not have been possible without the following people:
- [@GeoffreyBooth](https://github.com/GeoffreyBooth): Organizer of the CoffeeScript 2 effort, developer for modules; arrow functions, function default parameters and function rest parameters output using ES2015 syntax; line comments output and block comments output anywhere; block embedded JavaScript via triple backticks; improved parsing of Literate CoffeeScript; and the new docs website.
- [@connec](https://github.com/connec): Classes; destructuring; splats/rest syntax in arrays and function calls; and computed properties all output using ES2015 syntax.
- [@GabrielRatener](https://github.com/GabrielRatener): Async functions.
- [@xixixao](https://github.com/xixixao): JSX.
- [@zdenko](https://github.com/zdenko): Object rest/spread properties (object destructuring).
- [@greghuc](https://github.com/greghuc): Tagged template literals, interpolated strings output in ES2015 syntax.
- [@atg](https://github.com/atg): ES2015 `for…of`, supported as CoffeeScripts `for…from`.
- [@lydell](https://github.com/lydell) and [@jashkenas](https://github.com/jashkenas): Guidance, code reviews and feedback.
See the full [honor roll](https://github.com/jashkenas/coffeescript/wiki/CoffeeScript-2-Honor-Roll).
Thanks and we hope you enjoy CoffeeScript 2!

View File

@@ -0,0 +1,9 @@
## Async Functions
ES2017s [async functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) are supported through the `await` keyword. Like with generators, there's no need for an `async` keyword; an async function in CoffeeScript is simply a function that awaits.
Similar to how `yield return` forces a generator, `await return` may be used to force a function to be async.
```
codeFor('async', true)
```

View File

@@ -0,0 +1,7 @@
### Bound (fat arrow) functions
In CoffeeScript 1.x, `=>` compiled to a regular `function` but with references to `this`/`@` rewritten to use the outer scopes `this`, or with the inner function bound to the outer scope via `.bind` (hence the name “bound function”). In CoffeeScript 2, `=>` compiles to [ES2015s `=>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), which behaves slightly differently. The largest difference is that in ES2015, `=>` functions lack an `arguments` object:
```
codeFor('breaking_change_fat_arrow', 'outer(1, 2)')
```

View File

@@ -0,0 +1,3 @@
## Breaking Changes From CoffeeScript 1.x to 2
CoffeeScript 2 aims to output as much idiomatic ES2015+ syntax as possible with as few breaking changes from CoffeeScript 1.x as possible. Some breaking changes, unfortunately, were unavoidable.

View File

@@ -0,0 +1,34 @@
### Argument parsing and shebang (`#!`) lines
In CoffeeScript 1.x, `--` was required after the path and filename of the script to be run, but before any arguments passed to that script. This convention is now deprecated. So instead of:
```bash
coffee [options] path/to/script.coffee -- [args]
```
Now you would just type:
```bash
coffee [options] path/to/script.coffee [args]
```
The deprecated version will still work, but it will print a warning before running the script.
On non-Windows platforms, a `.coffee` file can be made executable by adding a shebang (`#!`) line at the top of the file and marking the file as executable. For example:
```coffee
#!/usr/bin/env coffee
x = 2 + 2
console.log x
```
If this were saved as `executable.coffee`, it could be made executable and run:
```bash
▶ chmod +x ./executable.coffee
▶ ./executable.coffee
4
```
In CoffeeScript 1.x, this used to fail when trying to pass arguments to the script. Some users on OS X worked around the problem by using `#!/usr/bin/env coffee --` as the first line of the file. That didnt work on Linux, however, which cannot parse shebang lines with more than a single argument. While such scripts will still run on OS X, CoffeeScript will now display a warning before compiling or evaluating files that begin with a too-long shebang line. Now that CoffeeScript 2 supports passing arguments without needing `--`, we recommend simply changing the shebang lines in such scripts to just `#!/usr/bin/env coffee`.

View File

@@ -0,0 +1,14 @@
### Bound generator functions
Bound generator functions, a.k.a. generator arrow functions, [arent allowed in ECMAScript](http://stackoverflow.com/questions/27661306/can-i-use-es6s-arrow-function-syntax-with-generators-arrow-notation). You can write `function*` or `=>`, but not both. Therefore, CoffeeScript code like this:
```coffee
f = => yield this
# Throws a compiler error
```
Needs to be rewritten the old-fashioned way:
```
codeFor('breaking_change_bound_generator_function')
```

View File

@@ -0,0 +1,41 @@
### Classes are compiled to ES2015 classes
ES2015 classes and their methods have some restrictions beyond those on regular functions.
Class constructors cant be invoked without `new`:
```coffee
(class)()
# Throws a TypeError at runtime
```
ES2015 classes dont allow bound (fat arrow) methods. The CoffeeScript compiler goes through some contortions to preserve support for them, but one thing that cant be accommodated is calling a bound method before it is bound:
```coffee
class Base
constructor: ->
@onClick() # This works
clickHandler = @onClick
clickHandler() # This throws a runtime error
class Component extends Base
onClick: =>
console.log 'Clicked!', @
```
Class methods cant be used with `new` (uncommon):
```coffee
class Namespace
@Klass = ->
new Namespace.Klass # Throws a TypeError at runtime
```
Due to the hoisting required to compile to ES2015 classes, dynamic keys in class methods cant use values from the executable class body unless the methods are assigned in prototype style.
```coffee
class A
name = 'method'
"#{name}": -> # This method will be named 'undefined'
@::[name] = -> # This will work; assigns to `A.prototype.method`
```

View File

@@ -0,0 +1,11 @@
### Default values for function parameters and destructured elements
Per the [ES2015 spec regarding function default parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters) and [destructuring default values](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Default_values), default values are only applied when a value is missing or `undefined`. In CoffeeScript 1.x, the default value would be applied in those cases but also if the value was `null`.
```
codeFor('breaking_change_function_parameter_default_values', 'f(null)')
```
```
codeFor('breaking_change_destructuring_default_values', 'a')
```

View File

@@ -0,0 +1,3 @@
### JSX and the `<` and `>` operators
With the addition of [JSX](#jsx), the `<` and `>` characters serve as both the “less than” and “greater than” operators and as the delimiters for XML tags, like `<div>`. For best results, in general you should always wrap the operators in spaces to distinguish them from XML tags: `i < len`, not `i<len`. The compiler tries to be forgiving when it can be sure what you intend, but always putting spaces around the “less than” and “greater than” operators will remove ambiguity.

View File

@@ -0,0 +1,7 @@
### Literate CoffeeScript parsing
CoffeeScript 2s parsing of Literate CoffeeScript has been refactored to now be more careful about not treating indented lists as code blocks; but this means that all code blocks (unless they are to be interpreted as comments) must be separated by at least one blank line from lists.
Code blocks should also now maintain a consistent indentation level—so an indentation of one tab (or whatever you consider to be a tab stop, like 2 spaces or 4 spaces) should be treated as your codes “left margin,” with all code in the file relative to that column.
Code blocks that you want to be part of the commentary, and not executed, must have at least one line (ideally the first line of the block) completely unindented.

View File

@@ -0,0 +1,43 @@
### `super` and `extends`
Due to a syntax clash with `super` with accessors, “bare” `super` (the keyword `super` without parentheses) no longer compiles to a super call forwarding all arguments.
```coffee
class B extends A
foo: -> super
# Throws a compiler error
```
Arguments can be forwarded explicitly using splats:
```
codeFor('breaking_change_super_with_arguments')
```
Or if you know that the parent function doesnt require arguments, just call `super()`:
```
codeFor('breaking_change_super_without_arguments')
```
CoffeeScript 1.x allowed the `extends` keyword to set up prototypal inheritance between functions, and `super` could be used manually prototype-assigned functions:
```coffee
A = ->
B = ->
B extends A
B.prototype.foo = -> super arguments...
# Last two lines each throw compiler errors in CoffeeScript 2
```
Due to the switch to ES2015 `extends` and `super`, using these keywords for prototypal functions are no longer supported. The above case could be refactored to:
```
codeFor('breaking_change_super_in_non-class_methods_refactor_with_apply')
```
or
```
codeFor('breaking_change_super_in_non-class_methods_refactor_with_class')
```

View File

@@ -0,0 +1,20 @@
### `super` and `this`
In the constructor of a derived class (a class that `extends` another class), `this` cannot be used before calling `super`:
```coffee
class B extends A
constructor: -> this # Throws a compiler error
```
This also means you cannot pass a reference to `this` as an argument to `super` in the constructor of a derived class:
```coffee
class B extends A
constructor: (@arg) ->
super @arg # Throws a compiler error
```
This is a limitation of ES2015 classes. As a workaround, assign to `this` after the `super` call:
```
codeFor('breaking_change_super_this')
```

View File

@@ -0,0 +1,7 @@
## Chaining Function Calls
Leading `.` closes all open calls, allowing for simpler chaining syntax.
```
codeFor('chaining')
```

View File

@@ -1,4 +1,141 @@
## Change Log
## Changelog
```
releaseHeader('2018-03-29', '2.2.4', '2.2.3')
```
* When the `by` value in a `for` loop is a literal number, e.g. `for x in [2..1] by -1`, fewer checks are necessary to determine if the loop is in range.
* Bugfix for regression in 2.2.0 where a statement inside parentheses, e.g. `(fn(); break) while condition`, was compiling. Pure statements like `break` or `return` cannot turn a parenthesized block into an expression, and should throw an error.
```
releaseHeader('2018-03-11', '2.2.3', '2.2.2')
```
* Bugfix for object destructuring with an empty array as a keys value: `{ key: [] } = obj`.
* Bugfix for array destructuring onto targets attached to `this`: `[ @most... , @penultimate, @last ] = arr`.
```
releaseHeader('2018-02-21', '2.2.2', '2.2.1')
```
* Bugfix for regression in 2.2.0 where a range with a `by` (step) value that increments or decrements in the opposite direction as the range was returning an array containing the first value of the range, whereas it should be returning an empty array. In other words, `x for x in [2..1] by 1` should equal `[]`, not `[2]` (because the step value is positive 1, counting up, whereas the range goes from 2 to 1, counting down).
* Bugfixes for allowing backslashes in `import` and `export` statements and lines that trigger the start of an indented block, like an `if` statement.
```
releaseHeader('2018-02-06', '2.2.1', '2.2.0')
```
* Bugfix for regression in 2.2.0 involving an error thrown by the compiler in certain cases when using destructuring with a splat or expansion in an array.
* Bugfix for regression in 2.2.0 where in certain cases a range iterator variable was declared in the global scope.
```
releaseHeader('2018-02-01', '2.2.0', '2.1.1')
```
* This release fixes *all* currently open bugs, dating as far back as 2014, 2012 and 2011.
* **Potential breaking change:** An inline `if` or `switch` statement with an ambiguous `else`, such as `if no then if yes then alert 1 else alert 2`, now compiles where the `else` always corresponds to the closest open `then`. Previously the behavior of an ambiguous `else` was unpredictable. If your code has any `if … then` or `switch … then` statements with multiple `then`s (and one or more `else`s) the compiled output might be different now, unless you had resolved ambiguity via parentheses. We made this change because the previous behavior was inconsistent and basically a bug: depending on what grammar was where, for example if there was an inline function or something that implied a block, the `else` might bind to an earlier `then` rather than a later `then`. Now an `else` essentially closes a block opened by a `then`, similar to closing an open parenthesis.
* When a required `then` is missing, the error more accurately points out the location of the mistake.
* An error is thrown when the `coffee` command is run in an environment that doesnt support some ES2015 JavaScript features that the CoffeeScript compiler itself requires. This can happen if CoffeeScript is installed in Node older than version 6.
* Destructuring with a non-final splat/spread, e.g. `[open, contents..., close] = tag.split('')` is now output using ES2015 rest syntax.
* Functions named `get` or `set` can be used without parentheses in more cases, including when attached to `this` or `@` or `?.`; or when the first argument is an implicit object, e.g. `@set key: 'val'`.
* Statements such as `break` can now be used inside parentheses, e.g. `(doSomething(); break) while condition` or `(pick(key); break) for key of obj`.
* Bugfix for assigning to a property attached to `this`/`@` in destructuring, e.g. `({@prop = yes, @otherProp = no}) ->`.
* Bugfix for incorrect errors being thrown about calling `super` with a parameter attached to `this` when said parameter is in a lower scope, e.g. `class Child extends Parent then constructor: -> super(-> @prop)`.
* Bugfix to prevent a possible infinite loop when a `for` loop is given a variable to step by, e.g. `for x in [1..3] by step` (as opposed to `by 0.5` or some other primitive numeric value).
* Bugfix to no longer declare iterator variables twice when evaluating a range, e.g. `end = 3; fn [0..end]`.
* Bugfix for incorrect scope of variables in chained calls, e.g. `start(x = 3).then(-> x = 4)`.
* Bugfix for incorrect scope of variables in a function passed to `do`, e.g. `for [1..3] then masked = 10; do -> alert masked`.
* Bugfix to no longer throw a syntax error for a trailing comma in a function call, e.g. `fn arg1, arg2,`.
* Bugfix for an expression in a property access, e.g. `a[!b in c..]`.
* Bugfix to allow a line continuation backslash (`\`) at any point in a `for` line.
```
releaseHeader('2017-12-29', '2.1.1', '2.1.0')
```
* Bugfix to set the correct context for executable class bodies. So in `class @B extends @A then @property = 1`, the `@` in `@property` now refers to the class, not the global object.
* Bugfix where anonymous classes were getting created using the same automatic variable name. They now each receive unique names, so as not to override each other.
```
releaseHeader('2017-12-10', '2.1.0', '2.0.3')
```
* Computed property keys in object literals are now supported: `obj = { ['key' + i]: 42 }`, or `obj = [Symbol.iterator]: -> yield i++`.
* Skipping of array elements, a.k.a. elision, is now supported: `arr = [a, , b]`, or `[, protocol] = url.match /^(.*):\/\//`.
* [JSX fragments syntax](https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html) is now supported.
* Bugfix where `///` within a `#` line comment inside a `///` block regex was erroneously closing the regex, rather than being treated as part of the comment.
* Bugfix for incorrect output for object rest destructuring inside array destructuring.
```
releaseHeader('2017-11-26', '2.0.3', '2.0.2')
```
* Bugfix for `export default` followed by an implicit object that contains an explicit object, for example `exportedMember: { obj... }`.
* Bugfix for `key, val of obj` after an implicit object member, e.g. `foo: bar for key, val of obj`.
* Bugfix for combining array and object destructuring, e.g. `[ ..., {a, b} ] = arr`.
* Bugfix for an edge case where it was possible to create a bound (`=>`) generator function, which should throw an error as such functions arent allowed in ES2015.
* Bugfix for source maps: `.map` files should always have the same base filename as the requested output filename. So `coffee --map --output foo.js test.coffee` should generate `foo.js` and `foo.js.map`.
* Bugfix for incorrect source maps generated when using `--transpile` with `--map` for multiple input files.
* Bugfix for comments at the beginning or end of input into the REPL (`coffee --interactive`).
```
releaseHeader('2017-10-26', '2.0.2', '2.0.1')
```
* `--transpile` now also applies to `require`d or `import`ed CoffeeScript files.
* `--transpile` can be used with the REPL: `coffee --interactive --transpile`.
* Improvements to comments output that should now cover all of the [Flow comment-based syntax](https://flow.org/en/docs/types/comments/). Inline `###` comments near [variable](https://flow.org/en/docs/types/variables/) initial assignments are now output in the variable declaration statement, and `###` comments near a [class and method names](https://flow.org/en/docs/types/generics/) are now output where Flow expects them.
* Importing CoffeeScript keywords is now allowed, so long as theyre aliased: `import { and as andFn } from 'lib'`. (You could also do `import lib from 'lib'` and then reference `lib.and`.)
* Calls to functions named `get` and `set` no longer throw an error when given a bracketless object literal as an argument: `obj.set propertyName: propertyValue`.
* In the constructor of a derived class (a class that `extends` another class), you cannot call `super` with an argument that references `this`: `class Child extends Parent then constructor: (@arg) -> super(@arg)`. This isnt allowed in JavaScript, and now the CoffeeScript compiler will throw an error. Instead, assign to `this` after calling `super`: `(arg) -> super(arg); @arg = arg`.
* Bugfix for incorrect output when backticked statements and hoisted expressions were both in the same class body. This allows a backticked line like `` `field = 3` ``, for people using the experimental [class fields](https://github.com/tc39/proposal-class-fields) syntax, in the same class along with traditional class body expressions like `prop: 3` that CoffeeScript outputs as part of the class prototype.
* Bugfix for comments not output before a complex `?` operation, e.g. `@a ? b`.
* All tests now pass in Windows.
```
releaseHeader('2017-09-26', '2.0.1', '2.0.0')
```
* `babel-core` is no longer listed in `package.json`, even as an `optionalDependency`, to avoid it being automatically installed for most users. If you wish to use `--transpile`, simply install `babel-core` manually. See [Transpilation](#transpilation).
* `--transpile` now relies on Babel to find its options, i.e. the `.babelrc` file in the path of the file(s) being compiled. (Previously the CoffeeScript compiler was duplicating this logic, so nothing has changed from a users perspective.) This provides automatic support for additional ways to pass options to Babel in future versions, such as the `.babelrc.js` file coming in Babel 7.
* Backticked expressions in a class body, outside any class methods, are now output in the JavaScript class body itself. This allows for passing through experimental JavaScript syntax like the [class fields proposal](https://github.com/tc39/proposal-class-fields), assuming your [transpiler supports it](https://babeljs.io/docs/plugins/transform-class-properties/).
```
releaseHeader('2017-09-18', '2.0.0', '2.0.0-beta5')
```
* Added `--transpile` flag or `transpile` Node API option to tell the CoffeeScript compiler to pipe its output through Babel before saving or returning it; see [Transpilation](#transpilation). Also changed the `-t` short flag to refer to `--transpile` instead of `--tokens`.
* Always populate source maps `sourcesContent` property.
* Bugfixes for destructuring and for comments in JSX.
* _Note that these are only the changes between 2.0.0-beta5 and 2.0.0. See below for all changes since 1.x._
```
releaseHeader('2017-09-02', '2.0.0-beta5', '2.0.0-beta4')
```
* Node 6 is now supported, and we will try to maintain that as the minimum required version for CoffeeScript 2 via the `coffee` command or Node API. Older versions of Node, or non-evergreen browsers, can compile via the [browser compiler](./browser-compiler/coffeescript.js).
* The command line `--output` flag now allows you to specify an output filename, not just an output folder.
* The command line `--require` flag now properly handles filenames or module names that are invalid identifiers (like an NPM module with a hyphen in the name).
* `Object.assign`, output when object destructuring is used, is polyfilled using the same polyfill that Babel outputs. This means that polyfills shouldnt be required unless support for Internet Explorer 8 or below is desired (or your own code uses a feature that requires a polyfill). See [ES2015+ Output](#es2015plus-output).
* A string or JSX interpolation that contains only a comment (`"a#{### comment ###}b"` or `<div>{### comment ###}</div>`) is now output (`` `a${/* comment */}b` ``)
* Interpolated strings (ES2015 template literals) that contain quotation marks no longer have the quotation marks escaped: `` `say "${message}"` ``
* It is now possible to chain after a function literal (for example, to define a function and then call `.call` on it).
* The results of the async tests are included in the output when you run `cake test`.
* Bugfixes for object destructuring; expansions in function parameters; generated reference variables in function parameters; chained functions after `do`; splats after existential operator soaks in arrays (`[a?.b...]`); trailing `if` with splat in arrays or function parameters (`[a if b...]`); attempting to `throw` an `if`, `for`, `switch`, `while` or other invalid construct.
* Bugfixes for syntactical edge cases: semicolons after `=` and other “mid-expression” tokens; spaces after `::`; and scripts that begin with `:` or `*`.
* Bugfixes for source maps generated via the Node API; and stack trace line numbers when compiling CoffeeScript via the Node API from within a `.coffee` file.
```
releaseHeader('2017-08-03', '2.0.0-beta4', '2.0.0-beta3')
```
* This release includes [all the changes from 1.12.6 to 1.12.7](#1.12.7).
* [Line comments](#comments) (starting with `#`) are now output in the generated JavaScript.
* [Block comments](#comments) (delimited by `###`) are now allowed anywhere, including inline where they previously werent possible. This provides support for [static type annotations](#type-annotations) using Flows comments-based syntax.
* Spread syntax (`...` for objects) is now supported in JSX tags: `<div {props...} />`.
* Argument parsing for scripts run via `coffee` is improved. See [breaking changes](#breaking-changes-argument-parsing-and-shebang-lines).
* CLI: Propagate `SIGINT` and `SIGTERM` signals when node is forked.
* `await` in the REPL is now allowed without requiring a wrapper function.
* `do super` is now allowed, and other accesses of `super` like `super.x.y` or `super['x'].y` now work.
* Splat/spread syntax triple dots are now allowed on either the left or the right (so `props...` or `...props` are both valid).
* Tagged template literals are recognized as callable functions.
* Bugfixes for object spread syntax in nested properties.
* Bugfixes for destructured function parameter default values.
```
releaseHeader('2017-07-16', '1.12.7', '1.12.6')
@@ -7,6 +144,33 @@ releaseHeader('2017-07-16', '1.12.7', '1.12.6')
* Fix regressions in 1.12.6 related to chained function calls and indented `return` and `throw` arguments.
* The REPL no longer warns about assigning to `_`.
```
releaseHeader('2017-06-30', '2.0.0-beta3', '2.0.0-beta2')
```
* [JSX](#jsx) is now supported.
* [Object rest/spread properties](#object-spread) are now supported.
* Bound (fat arrow) methods are once again supported in classes; though an error will be thrown if you attempt to call the method before it is bound. See [breaking changes for classes](#breaking-changes-classes).
* The REPL no longer warns about assigning to `_`.
* Bugfixes for destructured nested default values and issues related to chaining or continuing expressions across multiple lines.
```
releaseHeader('2017-05-16', '2.0.0-beta2', '2.0.0-beta1')
```
* This release includes [all the changes from 1.12.5 to 1.12.6](#1.12.6).
* Bound (fat arrow) methods in classes must be declared in the class constructor, after `super()` if the class is extending a parent class. See [breaking changes for classes](#breaking-changes-classes).
* All unnecessary utility helper functions have been removed, including the polyfills for `indexOf` and `bind`.
* The `extends` keyword now only works in the context of classes; it cannot be used to extend a function prototype. See [breaking changes for `extends`](#breaking-changes-super-extends).
* Literate CoffeeScript is now parsed entirely based on indentation, similar to the 1.x implementation; there is no longer a dependency for parsing Markdown. See [breaking changes for Literate CoffeeScript parsing](#breaking-changes-literate-coffeescript).
* JavaScript reserved words used as properties are no longer wrapped in quotes.
* `require('coffeescript')` should now work in non-Node environments such as the builds created by Webpack or Browserify. This provides a more convenient way to include the browser compiler in builds intending to run in a browser environment.
* Unreachable `break` statements are no longer added after `switch` cases that `throw` exceptions.
* The browser compiler is now compiled using Babili and transpiled down to Babels `env` preset (should be safe for use in all browsers in current use, not just evergreen versions).
* Calling functions `@get` or `@set` no longer throws an error about required parentheses. (Bare `get` or `set`, not attached to an object or `@`, [still intentionally throws a compiler error](#unsupported-get-set).)
* If `$XDG_CACHE_HOME` is set, the REPL `.coffee_history` file is saved there.
```
releaseHeader('2017-05-15', '1.12.6', '1.12.5')
```
@@ -18,6 +182,16 @@ releaseHeader('2017-05-15', '1.12.6', '1.12.5')
* Bugfixes for incorrect code generated by the `?` operator within a termary `if` statement.
* Fixed some tests, and failing tests now result in a nonzero exit code.
```
releaseHeader('2017-04-14', '2.0.0-beta1', '2.0.0-alpha1')
```
* Initial beta release of CoffeeScript 2. No further breaking changes are anticipated.
* Destructured objects and arrays now output using ES2015+ syntax whenever possible.
* Literate CoffeeScript now has much better support for parsing Markdown, thanks to using [Markdown-It](https://github.com/markdown-it/markdown-it) to detect Markdown sections rather than just looking at indentation.
* Calling a function named `get` or `set` now requires parentheses, to disambiguate from the `get` or `set` keywords (which are [disallowed](#unsupported-get-set)).
* The compiler now requires Node 7.6+, the first version of Node to support asynchronous functions without requiring a flag.
```
releaseHeader('2017-04-10', '1.12.5', '1.12.4')
```
@@ -25,6 +199,24 @@ releaseHeader('2017-04-10', '1.12.5', '1.12.4')
* Better handling of `default`, `from`, `as` and `*` within `import` and `export` statements. You can now import or export a member named `default` and the compiler wont interpret it as the `default` keyword.
* Fixed a bug where invalid octal escape sequences werent throwing errors in the compiler.
```
releaseHeader('2017-02-21', '2.0.0-alpha1', '1.12.4')
```
* Initial alpha release of CoffeeScript 2. The CoffeeScript compiler now outputs ES2015+ syntax whenever possible. See [breaking changes](#breaking-changes).
* Classes are output using ES2015 `class` and `extends` keywords.
* Added support for `async`/`await`.
* Bound (arrow) functions now output as `=>` functions.
* Function parameters with default values now use ES2015 default values syntax.
* Splat function parameters now use ES2015 spread syntax.
* Computed properties now use ES2015 syntax.
* Interpolated strings (template literals) now use ES2015 backtick syntax.
* Improved support for recognizing Markdown in Literate CoffeeScript files.
* Mixing tabs and spaces in indentation is now disallowed.
* Browser compiler is now minified using the Google Closure Compiler (JavaScript version).
* Node 7+ required for CoffeeScript 2.
```
releaseHeader('2017-02-18', '1.12.4', '1.12.3')
```
@@ -87,7 +279,6 @@ releaseHeader('2016-09-24', '1.11.0', '1.10.0')
* CoffeeScript now supports ES2015 [`import` and `export` syntax](#modules).
* Added the `-M, --inline-map` flag to the compiler, allowing you embed the source map directly into the output JavaScript, rather than as a separate file.
* A bunch of fixes for `yield`:
* `yield return` can no longer mistakenly be used as an expression.
* `yield` now mirrors `return` in that it can be used stand-alone as well as with expressions. Where you previously wrote `yield undefined`, you may now write simply `yield`. However, this means also inheriting the same syntax limitations that `return` has, so these examples no longer compile:
```
@@ -98,7 +289,6 @@ releaseHeader('2016-09-24', '1.11.0', '1.10.0')
yield
2 * 3
```
* The JavaScript output is a bit nicer, with unnecessary parentheses and spaces, double indentation and double semicolons around `yield` no longer present.
* `&&=`, `||=`, `and=` and `or=` no longer accidentally allow a space before the equals sign.
* Improved several error messages.
@@ -106,7 +296,6 @@ releaseHeader('2016-09-24', '1.11.0', '1.10.0')
* Bugfix for renamed destructured parameters with defaults. `({a: b = 1}) ->` no longer crashes the compiler.
* Improved the internal representation of a CoffeeScript program. This is only noticeable to tools that use `CoffeeScript.tokens` or `CoffeeScript.nodes`. Such tools need to update to take account for changed or added tokens and nodes.
* Several minor bug fixes, including:
* The caught error in `catch` blocks is no longer declared unnecessarily, and no longer mistakenly named `undefined` for `catch`-less `try` blocks.
* Unassignable parameter destructuring no longer crashes the compiler.
* Source maps are now used correctly for errors thrown from .coffee.md files.
@@ -122,7 +311,6 @@ releaseHeader('2015-09-03', '1.10.0', '1.9.3')
* CoffeeScript now supports ES2015-style destructuring defaults.
* `(offsetHeight: height) ->` no longer compiles. That syntax was accidental and partly broken. Use `({offsetHeight: height}) ->` instead. Object destructuring always requires braces.
* Several minor bug fixes, including:
* A bug where the REPL would sometimes report valid code as invalid, based on what you had typed earlier.
* A problem with multiple JS contexts in the jest test framework.
* An error in io.js where strict mode is set on internal modules.
@@ -180,7 +368,7 @@ releaseHeader('2014-08-26', '1.8.0', '1.7.1')
* Fixed a slight formatting error in CoffeeScripts source map-patched stack traces.
* The `%%` operator now coerces its right operand only once.
* It is now possible to require CoffeeScript files from Cakefiles without having to register the compiler first.
* The CoffeeScript REPL is now exported and can be required using `require 'coffee-script/repl'`.
* The CoffeeScript REPL is now exported and can be required using `require 'coffeescript/repl'`.
* Fixes for the REPL in Node 0.11.
```
@@ -193,14 +381,9 @@ releaseHeader('2014-01-29', '1.7.1', '1.7.0')
releaseHeader('2014-01-28', '1.7.0', '1.6.3')
```
* When requiring CoffeeScript files in Node you must now explicitly register the compiler. This can be done with `require 'coffee-script/register'` or `CoffeeScript.register()`. Also for configuration such as Mochas, use **coffee-script/register**.
* When requiring CoffeeScript files in Node you must now explicitly register the compiler. This can be done with `require 'coffeescript/register'` or `CoffeeScript.register()`. Also for configuration such as Mochas, use **coffeescript/register**.
* Improved error messages, source maps and stack traces. Source maps now use the updated `//#` syntax.
* Leading `.` now closes all open calls, allowing for simpler chaining syntax.
```
codeFor('chaining')
```
* Added `**`, `//` and `%%` operators and `...` expansion in parameter lists and destructuring expressions.
* Multiline strings are now joined by a single space and ignore all indentation. A backslash at the end of a line can denote the amount of whitespace between lines, in both strings and heredocs. Backslashes correctly escape whitespace in block regexes.
* Closing brackets can now be indented and therefore no longer cause unexpected error.
@@ -293,7 +476,7 @@ releaseHeader('2011-11-08', '1.1.3', '1.1.2')
* Ahh, whitespace. CoffeeScripts compiled JS now tries to space things out and keep it readable, as you can see in the examples on this page.
* You can now call `super` in class level methods in class bodies, and bound class methods now preserve their correct context.
* JavaScript has always supported octal numbers `010 is 8`, and hexadecimal numbers `0xf is 15`, but CoffeeScript now also supports binary numbers: `0b10 is 2`.
* The CoffeeScript module has been nested under a subdirectory to make it easier to `require` individual components separately, without having to use **npm**. For example, after adding the CoffeeScript folder to your path: `require('coffee-script/lexer')`
* The CoffeeScript module has been nested under a subdirectory to make it easier to `require` individual components separately, without having to use **npm**. For example, after adding the CoffeeScript folder to your path: `require('coffeescript/lexer')`
* Theres a new “link” feature in Try CoffeeScript on this webpage. Use it to get a shareable permalink for your example script.
* The `coffee --watch` feature now only works on Node.js 0.6.0 and higher, but now also works properly on Windows.
* Lots of small bug fixes from **[@michaelficarra](https://github.com/michaelficarra)**, **[@geraldalewis](https://github.com/geraldalewis)**, **[@satyr](https://github.com/satyr)**, and **[@trevorburnham](https://github.com/trevorburnham)**.
@@ -412,7 +595,7 @@ Trailing commas are now allowed, a-la Python. Static properties may be assigned
releaseHeader('2010-03-23', '0.5.6', '0.5.5')
```
Interpolation can now be used within regular expressions and heredocs, as well as strings. Added the `<-` bind operator. Allowing assignment to half-expressions instead of special `||=`-style operators. The arguments object is no longer automatically converted into an array. After requiring `coffee-script`, Node.js can now directly load `.coffee` files, thanks to **registerExtension**. Multiple splats can now be used in function calls, arrays, and pattern matching.
Interpolation can now be used within regular expressions and heredocs, as well as strings. Added the `<-` bind operator. Allowing assignment to half-expressions instead of special `||=`-style operators. The arguments object is no longer automatically converted into an array. After requiring `coffeescript`, Node.js can now directly load `.coffee` files, thanks to **registerExtension**. Multiple splats can now be used in function calls, arrays, and pattern matching.
```
releaseHeader('2010-03-08', '0.5.5', '0.5.4')
@@ -437,7 +620,7 @@ releaseHeader('2010-02-25', '0.5.2', '0.5.1')
```
Added a compressed version of the compiler for inclusion in web pages as
`/v<%= majorVersion %>/browser-compiler/coffee-script.js`. Itll automatically run any script tags with type `text/coffeescript` for you. Added a `--stdio` option to the `coffee` command, for piped-in compiles.
`/v<%= majorVersion %>/browser-compiler/coffeescript.js`. Itll automatically run any script tags with type `text/coffeescript` for you. Added a `--stdio` option to the `coffee` command, for piped-in compiles.
```
releaseHeader('2010-02-24', '0.5.1', '0.5.0')
@@ -526,7 +709,7 @@ Bugfix for running `coffee --interactive` and `--run` from outside of the Coffee
releaseHeader('2009-12-26', '0.1.5', '0.1.4')
```
Array slice literals and array comprehensions can now both take Ruby-style ranges to specify the start and end. JavaScript variable declaration is now pushed up to the top of the scope, making all assignment statements into expressions. You can use `\` to escape newlines. The `coffee-script` command is now called `coffee`.
Array slice literals and array comprehensions can now both take Ruby-style ranges to specify the start and end. JavaScript variable declaration is now pushed up to the top of the scope, making all assignment statements into expressions. You can use `\` to escape newlines. The `coffeescript` command is now called `coffee`.
```
releaseHeader('2009-12-25', '0.1.4', '0.1.3')

View File

@@ -1,5 +1,3 @@
## Web Chat (IRC)
Quick help and advice can usually be found in the CoffeeScript IRC room. Join `#coffeescript` on `irc.freenode.net`, or click the button below to open a webchat session on this page.
<button id="open_webchat">click to open #coffeescript</button>
Quick help and advice can often be found in the CoffeeScript IRC room `#coffeescript` on `irc.freenode.net`, which you can [join via your web browser](http://webchat.freenode.net/?channels=coffeescript).

View File

@@ -1,20 +1,15 @@
## Classes, Inheritance, and Super
## Classes
JavaScripts prototypal inheritance has always been a bit of a brain-bender, with a whole family tree of libraries that provide a cleaner syntax for classical inheritance on top of JavaScripts prototypes: [Base2](https://code.google.com/p/base2/), [Prototype.js](http://prototypejs.org/), [JS.Class](http://jsclass.jcoglan.com/), etc. The libraries provide syntactic sugar, but the built-in inheritance would be completely usable if it werent for a couple of small exceptions: its awkward to call **super** (the prototype objects implementation of the current function), and its awkward to correctly set the prototype chain.
Instead of repetitively attaching functions to a prototype, CoffeeScript provides a basic `class` structure that allows you to name your class, set the superclass, assign prototypal properties, and define the constructor, in a single assignable expression.
Constructor functions are named, to better support helpful stack traces. In the first class in the example below, `this.constructor.name is "Animal"`.
CoffeeScript 1 provided the `class` and `extends` keywords as syntactic sugar for working with prototypal functions. With ES2015, JavaScript has adopted those keywords; so CoffeeScript 2 compiles its `class` and `extends` keywords to ES2015 classes.
```
codeFor('classes', true)
```
If structuring your prototypes classically isnt your cup of tea, CoffeeScript provides a couple of lower-level conveniences. The `extends` operator helps with proper prototype setup, and can be used to create an inheritance chain between any pair of constructor functions; `::` gives you quick access to an objects prototype; and `super()` is converted into a call against the immediate ancestors method of the same name.
Static methods can be defined using `@` before the method name:
```
codeFor('prototypes', '"one_two".dasherize()')
codeFor('static', 'Teenager.say("Are we there yet?")')
```
Finally, class definitions are blocks of executable code, which make for interesting metaprogramming possibilities. Because in the context of a class definition, `this` is the class object itself (the constructor function), you can assign static properties by using
`@property: value`, and call functions defined in parent classes: `@attr 'title', type: 'text'`
Finally, class definitions are blocks of executable code, which make for interesting metaprogramming possibilities. In the context of a class definition, `this` is the class object itself; therefore, you can assign static properties by using `@property: value`.

View File

@@ -0,0 +1 @@
## CoffeeScript 2

View File

@@ -0,0 +1,40 @@
### Command Line
Once installed, you should have access to the `coffee` command, which can execute scripts, compile `.coffee` files into `.js`, and provide an interactive REPL. The `coffee` command takes the following options:
| Option | Description |
| --- | --- |
| `-c, --compile` | Compile a `.coffee` script into a `.js` JavaScript file of the same name. |
| `-t, --transpile` | Pipe the CoffeeScript compilers output through Babel before saving or running the generated JavaScript. Requires `babel-core` to be installed, and options to pass to Babel in a `.babelrc` file or a `package.json` with a `babel` key in the path of the file or folder to be compiled. See [Transpilation](#transpilation).
| `-m, --map` | Generate source maps alongside the compiled JavaScript files. Adds `sourceMappingURL` directives to the JavaScript as well. |
| `-M, --inline-map` | Just like `--map`, but include the source map directly in the compiled JavaScript files, rather than in a separate file. |
| `-i, --interactive` | Launch an interactive CoffeeScript session to try short snippets. Identical to calling `coffee` with no arguments. |
| `-o, --output [DIR]` | Write out all compiled JavaScript files into the specified directory. Use in conjunction with `--compile` or `--watch`. |
| `-w, --watch` | Watch files for changes, rerunning the specified command when any file is updated. |
| `-p, --print` | Instead of writing out the JavaScript as a file, print it directly to **stdout**. |
| `-s, --stdio` | Pipe in CoffeeScript to STDIN and get back JavaScript over STDOUT. Good for use with processes written in other languages. An example:<br>`cat src/cake.coffee | coffee -sc` |
| `-l, --literate` | Parses the code as Literate CoffeeScript. You only need to specify this when passing in code directly over **stdio**, or using some sort of extension-less file name. |
| `-e, --eval` | Compile and print a little snippet of CoffeeScript directly from the command line. For example:<br>`coffee -e "console.log num for num in [10..1]"` |
| `-r, --require [MODULE]`&emsp; | `require()` the given module before starting the REPL or evaluating the code given with the `--eval` flag. |
| `-b, --bare` | Compile the JavaScript without the [top-level function safety wrapper](#lexical-scope). |
| `--no-header` | Suppress the “Generated by CoffeeScript” header. |
| `--nodejs` | The `node` executable has some useful options you can set, such as `--debug`, `--debug-brk`, `--max-stack-size`, and `--expose-gc`. Use this flag to forward options directly to Node.js. To pass multiple flags, use `--nodejs` multiple times. |
| `--tokens` | Instead of parsing the CoffeeScript, just lex it, and print out the token stream. Used for debugging the compiler. |
| `-n, --nodes` | Instead of compiling the CoffeeScript, just lex and parse it, and print out the parse tree. Used for debugging the compiler. |
#### Examples:
* Compile a directory tree of `.coffee` files in `src` into a parallel tree of `.js` files in `lib`:<br>
`coffee --compile --output lib/ src/`
* Watch a file for changes, and recompile it every time the file is saved:<br>
`coffee --watch --compile experimental.coffee`
* Concatenate a list of files into a single script:<br>
`coffee --join project.js --compile src/*.coffee`
* Print out the compiled JS from a one-liner:<br>
`coffee -bpe "alert i for i in [0..10]"`
* All together now, watch and recompile an entire project as you work on it:<br>
`coffee -o lib/ -cw src/`
* Start the CoffeeScript REPL (`Ctrl-D` to exit, `Ctrl-V`for multi-line):<br>
`coffee`
To use `--transpile`, see [Transpilation](#transpilation).

View File

@@ -0,0 +1,9 @@
## Comments
In CoffeeScript, comments are denoted by the `#` character to the end of a line, or from `###` to the next appearance of `###`. Comments are ignored by the compiler, though the compiler makes its best effort at reinserting your comments into the output JavaScript after compilation.
```
codeFor('comment')
```
Inline `###` comments make [type annotations](#type-annotations) possible.

View File

@@ -0,0 +1,5 @@
### Compatibility
With the exception of [modules](#modules) (`import` and `export` statements) and [JSX](#jsx), all the modern JavaScript features that CoffeeScript supports can run natively in Node 7.6+, meaning that Node can run CoffeeScripts output without any further processing required. You can [run the tests in your browser](test.html) to see if your browser can do the same. For older browsers or older versions of Node, however, [transpilation](#transpilation) is required.
Support for modern JavaScript syntax is important to ensure compatibility with frameworks that assume modern features. Now that CoffeeScript compiles classes to the `class` keyword, its possible to `extend` a JavaScript class; that wasnt possible in CoffeeScript 1. Parity in how language features work is also important on its own; CoffeeScript “is just JavaScript,” and so things like [function parameter default values](#breaking-changes-default-values) should behave the same in CoffeeScript as in JavaScript. Some such features behave slightly differently in JavaScript than they did in CoffeeScript 1; in such cases we are conforming with the JavaScript spec, and weve documented the differences as [breaking changes](#breaking-changes).

View File

@@ -1,8 +1,8 @@
## If, Else, Unless, and Conditional Assignment
**If/else** statements can be written without the use of parentheses and curly brackets. As with functions and other block expressions, multi-line conditionals are delimited by indentation. Theres also a handy postfix form, with the `if` or `unless` at the end.
`if`/`else` statements can be written without the use of parentheses and curly brackets. As with functions and other block expressions, multi-line conditionals are delimited by indentation. Theres also a handy postfix form, with the `if` or `unless` at the end.
CoffeeScript can compile **if** statements into JavaScript expressions, using the ternary operator when possible, and closure wrapping otherwise. There is no explicit ternary statement in CoffeeScript — you simply use a regular **if** statement on a single line.
CoffeeScript can compile `if` statements into JavaScript expressions, using the ternary operator when possible, and closure wrapping otherwise. There is no explicit ternary statement in CoffeeScript — you simply use a regular `if` statement on a single line.
```
codeFor('conditionals')

View File

@@ -0,0 +1,16 @@
## Contributing
Contributions are welcome! Feel free to fork [the repo](https://github.com/jashkenas/coffeescript) and submit a pull request.
[Some features of ECMAScript are intentionally unsupported](#unsupported). Please review both the open and closed [issues on GitHub](https://github.com/jashkenas/coffeescript/issues) to see if the feature youre looking for has already been discussed. As a general rule, we dont support ECMAScript syntax for features that arent yet finalized (at Stage 4 in the proposal approval process).
For more resources on adding to CoffeeScript, please see [the Wiki](https://github.com/jashkenas/coffeescript/wiki/%5BHowto%5D-Hacking-on-the-CoffeeScript-Compiler), especially [How The Parser Works](https://github.com/jashkenas/coffeescript/wiki/%5BHowTo%5D-How-parsing-works).
There are several things you can do to increase your odds of having your pull request accepted:
* Create tests! Any pull request should probably include basic tests to verify you didnt break anything, or future changes wont break your code.
* Follow the style of the rest of the CoffeeScript codebase.
* Ensure any ECMAScript syntax is mature (at Stage 4), with no further potential changes.
* Add only features that have broad utility, rather than a feature aimed at a specific use case or framework.
Of course, its entirely possible that you have a great addition, but it doesnt fit within these constraints. Feel free to roll your own solution; you will have [plenty of company](https://github.com/jashkenas/coffeescript/wiki/In-The-Wild).

View File

@@ -36,4 +36,4 @@ Destructuring assignment is also useful when combined with class constructors to
codeFor('constructor_destructuring', 'tim.age + " " + tim.height')
```
The above example also demonstrates that if properties are missing in the destructured object or array, you can, just like in JavaScript, provide defaults. The difference with JavaScript is that CoffeeScript, as always, treats both null and undefined the same.
The above example also demonstrates that if properties are missing in the destructured object or array, you can, just like in JavaScript, provide defaults. Note though that unlike with the existential operator, the default is only applied with the value is missing or `undefined`—[passing `null` will set a value of `null`](#breaking-changes-default-values), not the default.

View File

@@ -1,17 +1,37 @@
## The Existential Operator
Its a little difficult to check for the existence of a variable in JavaScript. `if (variable) …` comes close, but fails for zero, the empty string, and false. CoffeeScripts existential operator `?` returns true unless a variable is **null** or **undefined**, which makes it analogous to Rubys `nil?`
Its a little difficult to check for the existence of a variable in JavaScript. `if (variable) …` comes close, but fails for zero, the empty string, and false (to name just the most common cases). CoffeeScripts existential operator `?` returns true unless a variable is `null` or `undefined` or undeclared, which makes it analogous to Rubys `nil?`.
It can also be used for safer conditional assignment than `||=` provides, for cases where you may be handling numbers or strings.
It can also be used for safer conditional assignment than the JavaScript pattern `a = a || value` provides, for cases where you may be handling numbers or strings.
```
codeFor('existence', 'footprints')
```
The accessor variant of the existential operator `?.` can be used to soak up null references in a chain of properties. Use it instead of the dot accessor `.` in cases where the base value may be **null** or **undefined**. If all of the properties exist then youll get the expected result, if the chain is broken, **undefined** is returned instead of the **TypeError** that would be raised otherwise.
Note that if the compiler knows that `a` is in scope and therefore declared, `a?` compiles to `a != null`, _not_ `a !== null`. The `!=` makes a loose comparison to `null`, which does double duty also comparing against `undefined`. The reverse also holds for `not a?` or `unless a?`.
```
codeFor('existence_declared')
```
If a variable might be undeclared, the compiler does a thorough check. This is what JavaScript coders _should_ be typing when they want to check if a mystery variable exists.
```
codeFor('existence_undeclared')
```
The accessor variant of the existential operator `?.` can be used to soak up null references in a chain of properties. Use it instead of the dot accessor `.` in cases where the base value may be `null` or `undefined`. If all of the properties exist then youll get the expected result, if the chain is broken, `undefined` is returned instead of the `TypeError` that would be raised otherwise.
```
codeFor('soaks')
```
Soaking up nulls is similar to Rubys [andand gem](https://rubygems.org/gems/andand), and to the [safe navigation operator](http://docs.groovy-lang.org/latest/html/documentation/index.html#_safe_navigation_operator) in Groovy.
For completeness:
| Example | Definition |
| --- | --- |
| `a?` | tests that `a` is in scope and `a != null` |
| `a ? b` | returns `a` if `a` is in scope and `a != null`; otherwise, `b` |
| `a?.b` or `a?['b']` | returns `a.b` if `a` is in scope and `a != null`; otherwise, `undefined` |
| `a?(b, c)` or `a? b, c`&emsp; | returns the result of calling `a` (with arguments `b` and `c`) if `a` is in scope and callable; otherwise, `undefined` |
| `a ?= b` | assigns the value of `b` to `a` if `a` is not in scope or if `a == null`; produces the new value of `a` |

View File

@@ -20,7 +20,7 @@ Things that would otherwise be statements in JavaScript, when used as part of an
codeFor('expressions_comprehension', 'globals')
```
As well as silly things, like passing a **try/catch** statement directly into a function call:
As well as silly things, like passing a `try`/`catch` statement directly into a function call:
```
codeFor('expressions_try', true)

View File

@@ -1,4 +1,4 @@
## Bound Functions, Generator Functions
## Bound (Fat Arrow) Functions
In JavaScript, the `this` keyword is dynamically scoped to mean the object that the current function is attached to. If you pass a function as a callback or attach it to a different object, the original value of `this` will be lost. If youre not familiar with this behavior, [this Digital Web article](http://64.13.255.16/articles/scope_in_javascript/) gives a good overview of the quirks.
@@ -10,22 +10,4 @@ codeFor('fat_arrow')
If we had used `->` in the callback above, `@customer` would have referred to the undefined “customer” property of the DOM element, and trying to call `purchase()` on it would have raised an exception.
When used in a class definition, methods declared with the fat arrow will be automatically bound to each instance of the class when the instance is constructed.
<div id="generator-functions" class="bookmark"></div>
CoffeeScript functions also support [ES2015 generator functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) through the `yield` keyword. Theres no `function*(){}` nonsense — a generator in CoffeeScript is simply a function that yields.
```
codeFor('generators', 'ps.next().value')
```
`yield*` is called `yield from`, and `yield return` may be used if you need to force a generator that doesnt yield.
<div id="generator-iteration" class="bookmark"></div>
You can iterate over a generator function using `for…from`.
```
codeFor('generator_iteration', 'getFibonacciNumbers(10)')
```
The fat arrow was one of the most popular features of CoffeeScript, and ES2015 [adopted it](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions); so CoffeeScript 2 compiles `=>` to ES `=>`.

View File

@@ -6,7 +6,7 @@ Functions are defined by an optional list of parameters in parentheses, an arrow
codeFor('functions', 'cube(5)')
```
Functions may also have default values for arguments, which will be used if the incoming argument is missing (`null` or `undefined`).
Functions may also have default values for arguments, which will be used if the incoming argument is missing (`undefined`).
```
codeFor('default_args', 'fill("cup")')

View File

@@ -0,0 +1,17 @@
## Generator Functions
CoffeeScript supports ES2015 [generator functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) through the `yield` keyword. There's no `function*(){}` nonsense — a generator in CoffeeScript is simply a function that yields.
```
codeFor('generators', 'ps.next().value')
```
`yield*` is called `yield from`, and `yield return` may be used if you need to force a generator that doesnt yield.
<div id="generator-iteration" class="bookmark"></div>
You can iterate over a generator function using `for…from`.
```
codeFor('generator_iteration', 'getFibonacciNumbers(10)')
```

View File

@@ -1,6 +1,6 @@
## Installation
The command-line version of `coffee` is available as a [Node.js](https://nodejs.org/) utility. The [core compiler](/v<%= majorVersion %>/browser-compiler/coffee-script.js) however, does not depend on Node, and can be run in any JavaScript environment, or in the browser (see [Try CoffeeScript](#try)).
The command-line version of `coffee` is available as a [Node.js](https://nodejs.org/) utility, requiring Node 6 or later. The [core compiler](/v<%= majorVersion %>/browser-compiler/coffeescript.js) however, does not depend on Node, and can be run in any JavaScript environment, or in the browser (see [Try CoffeeScript](#try)).
To install, first make sure you have a working copy of the latest stable version of [Node.js](https://nodejs.org/). You can then install CoffeeScript globally with [npm](https://www.npmjs.com/):
@@ -10,10 +10,12 @@ npm install --global coffeescript
This will make the `coffee` and `cake` commands available globally.
When you need CoffeeScript as a dependency of a project, within that projects folder you can install it locally:
If you are using CoffeeScript in a project, you should install it locally for that project so that the version of CoffeeScript is tracked as one of your projects dependencies. Within that projects folder:
```bash
npm install --save coffeescript
npm install --save-dev coffeescript
```
The `coffee` and `cake` commands will first look in the current folder to see if CoffeeScript is installed locally, and use that version if so. This allows different versions of CoffeeScript to be installed globally and locally.
The `coffee` and `cake` commands will first look in the current folder to see if CoffeeScript is installed locally, and use that version if so. This allows different versions of CoffeeScript to be installed globally and locally.
If you plan to use the `--transpile` option (see [Transpilation](#transpilation)) you will need to also install `babel-core` either globally or locally, depending on whether you are running a globally or locally installed version of CoffeeScript.

View File

@@ -1,13 +1,13 @@
**CoffeeScript is a little language that compiles into JavaScript.** Underneath that awkward Java-esque patina, JavaScript has always had a gorgeous heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.
The golden rule of CoffeeScript is: _“Its just JavaScript”_. The code compiles one-to-one into the equivalent JS, and there is no interpretation at runtime. You can use any existing JavaScript library seamlessly from CoffeeScript (and vice-versa). The compiled output is readable, pretty-printed, and tends to run as fast or faster than the equivalent handwritten JavaScript.
The CoffeeScript compiler goes to great lengths to generate output JavaScript that runs in every JavaScript runtime, but there are exceptions. Use [generator functions](#generator-functions), [`for…from`](#generator-iteration), or [tagged template literals](#tagged-template-literals) only if you know that your [target runtimes can support them](http://kangax.github.io/compat-table/es6/). If you use [modules](#modules), you will need to [use an additional tool to resolve them](#modules-note).
The golden rule of CoffeeScript is: _“Its just JavaScript._ The code compiles one-to-one into the equivalent JS, and there is no interpretation at runtime. You can use any existing JavaScript library seamlessly from CoffeeScript (and vice-versa). The compiled output is readable, pretty-printed, and tends to run as fast or faster than the equivalent handwritten JavaScript.
**Latest Version:** [<%= fullVersion %>](https://github.com/jashkenas/coffeescript/tarball/<%= fullVersion %>)
```bash
npm install -g coffeescript
```
# Install locally for a project:
npm install --save-dev coffeescript
**CoffeeScript 2 is coming!** It adds support for [ES2015 classes](/v2/#classes), [`async`/`await`](/v2/#fat-arrow), [JSX](/v2/#jsx), <span class="nowrap">[object rest/spread syntax](/v2/#splats)</span>, and JavaScript generated using ES2015+ syntax. [Learn more](/v2/).
# Install globally to execute .coffee files anywhere:
npm install --global coffeescript
```

View File

@@ -0,0 +1,13 @@
## JSX
[JSX](https://facebook.github.io/react/docs/introducing-jsx.html) is JavaScript containing interspersed XML elements. While conceived for [React](https://facebook.github.io/react/), it is not specific to any particular library or framework.
CoffeeScript supports interspersed XML elements, without the need for separate plugins or special settings. The XML elements will be compiled as such, outputting JSX that could be parsed like any normal JSX file, for example by [Babel with the React JSX transform](https://babeljs.io/docs/plugins/transform-react-jsx/). CoffeeScript does _not_ output `React.createElement` calls or any code specific to React or any other framework. It is up to you to attach another step in your build chain to convert this JSX to whatever function calls you wish the XML elements to compile to.
Just like in JSX and HTML, denote XML tags using `<` and `>`. You can interpolate CoffeeScript code inside a tag using `{` and `}`. To avoid compiler errors, when using `<` and `>` to mean “less than” or “greater than,” you should wrap the operators in spaces to distinguish them from XML tags. So `i < len`, not `i<len`. The compiler tries to be forgiving when it can be sure what you intend, but always putting spaces around the “less than” and “greater than” operators will remove ambiguity.
```
codeFor('jsx')
```
Older plugins or forks of CoffeeScript supported JSX syntax and referred to it as CSX or CJSX. They also often used a `.cjsx` file extension, but this is no longer necessary; regular `.coffee` will do.

View File

@@ -2,7 +2,7 @@
_This reference is structured so that it can be read from top to bottom, if you like. Later sections use ideas and syntax previously introduced. Familiarity with JavaScript is assumed. In all of the following examples, the source CoffeeScript is provided on the left, and the direct compilation into JavaScript is on the right._
_Many of the examples can be run (where it makes sense) by pressing the **run** button on the right, and can be loaded into the “Try CoffeeScript” console by pressing the **load** button on the left._
_Many of the examples can be run (where it makes sense) by pressing the_ <small>▶</small> _button on the right. The CoffeeScript on the left is editable, and the JavaScript will update as you edit._
First, the basics: CoffeeScript uses significant whitespace to delimit blocks of code. You dont need to use semicolons `;` to terminate expressions, ending the line will do just as well (although semicolons can still be used to fit multiple expressions onto a single line). Instead of using curly braces `{ }` to surround blocks of code in [functions](#literals), [if-statements](#conditionals), [switch](#switch), and [try/catch](#try), use indentation.

View File

@@ -6,10 +6,12 @@ The CoffeeScript compiler takes care to make sure that all of your variables are
codeFor('scope', 'inner')
```
Notice how all of the variable declarations have been pushed up to the top of the closest scope, the first time they appear. **outer** is not redeclared within the inner function, because its already in scope; **inner** within the function, on the other hand, should not be able to change the value of the external variable of the same name, and therefore has a declaration of its own.
Notice how all of the variable declarations have been pushed up to the top of the closest scope, the first time they appear. `outer` is not redeclared within the inner function, because its already in scope; `inner` within the function, on the other hand, should not be able to change the value of the external variable of the same name, and therefore has a declaration of its own.
This behavior is effectively identical to Rubys scope for local variables. Because you dont have direct access to the `var` keyword, its impossible to shadow an outer variable on purpose, you may only refer to it. So be careful that youre not reusing the name of an external variable accidentally, if youre writing a deeply nested function.
Because you dont have direct access to the `var` keyword, its impossible to shadow an outer variable on purpose, you may only refer to it. So be careful that youre not reusing the name of an external variable accidentally, if youre writing a deeply nested function.
Although suppressed within this documentation for clarity, all CoffeeScript output is wrapped in an anonymous function: `(function(){ … })();` This safety wrapper, combined with the automatic generation of the `var` keyword, make it exceedingly difficult to pollute the global namespace by accident.
Although suppressed within this documentation for clarity, all CoffeeScript output (except in files with `import` or `export` statements) is wrapped in an anonymous function: `(function(){ … })();`. This safety wrapper, combined with the automatic generation of the `var` keyword, make it exceedingly difficult to pollute the global namespace by accident. (The safety wrapper can be disabled with the [`bare` option](#usage), and is unnecessary and automatically disabled when using modules.)
If youd like to create top-level variables for other scripts to use, attach them as properties on **window**; attach them as properties on the **exports** object in CommonJS; or use an [`export` statement](#modules). If youre targeting both CommonJS and the browser, the **existential operator** (covered below), gives you a reliable way to figure out where to add them: `exports ? this`
If youd like to create top-level variables for other scripts to use, attach them as properties on `window`; attach them as properties on the `exports` object in CommonJS; or use an [`export` statement](#modules). If youre targeting both CommonJS and the browser, the [existential operator](#existential-operator) (covered below), gives you a reliable way to figure out where to add them: `exports ? this`.
Since CoffeeScript takes care of all variable declaration, it is not possible to declare variables with ES2015s `let` or `const`. [This is intentional](#unsupported-let-const); we feel that the simplicity gained by not having to think about variable declaration outweighs the benefit of having three separate ways to declare variables.

View File

@@ -1,5 +1,11 @@
## Literate CoffeeScript
Besides being used as an ordinary programming language, CoffeeScript may also be written in “literate” mode. If you name your file with a `.litcoffee` extension, you can write it as a Markdown document — a document that also happens to be executable CoffeeScript code. The compiler will treat any indented blocks (Markdowns way of indicating source code) as code, and ignore the rest as comments.
Besides being used as an ordinary programming language, CoffeeScript may also be written in “literate” mode. If you name your file with a `.litcoffee` extension, you can write it as a Markdown document — a document that also happens to be executable CoffeeScript code. The compiler will treat any indented blocks (Markdowns way of indicating source code) as executable code, and ignore the rest as comments. Code blocks must also be separated from comments by at least one blank line.
Just for kicks, a little bit of the compiler is currently implemented in this fashion: See it [as a document](https://gist.github.com/jashkenas/3fc3c1a8b1009c00d9df), [raw](https://raw.githubusercontent.com/jashkenas/coffeescript/master/src/scope.litcoffee), and [properly highlighted in a text editor](http://cl.ly/LxEu).
A few caveats:
* Code blocks need to maintain consistent indentation relative to each other. When the compiler parses your Literate CoffeeScript file, it first discards all the non-code block lines and then parses the remainder as a regular CoffeeScript file. Therefore the code blocks need to be written as if the comment lines dont exist, with consistent indentation (including whether they are indented with tabs or spaces).
* Along those lines, code blocks within list items or blockquotes are not treated as executable code. Since list items and blockquotes imply their own indentation, it would be ambiguous how to treat indentation between successive code blocks when some are within these other blocks and some are not.
* List items can be at most only one paragraph long. The second paragraph of a list item would be indented after a blank line, and therefore indistinguishable from a code block.

Some files were not shown because too many files have changed in this diff Show More