Compare commits

...

202 Commits

Author SHA1 Message Date
Sebastian McKenzie
8111ab28d7 v5.6.16 2015-07-09 16:13:06 +01:00
Sebastian McKenzie
ed25845152 remove accidental stackTraceLimit assignment 2015-07-09 16:12:06 +01:00
Sebastian McKenzie
457638e904 add type comments to t.valueToNode 2015-07-09 16:11:57 +01:00
Sebastian McKenzie
2e5255dbf5 peg recast version - fixes #1958 2015-07-09 16:11:46 +01:00
Sebastian McKenzie
205fab2ed8 split up badges 2015-07-08 14:58:31 +01:00
Sebastian McKenzie
d01b26951b channel -> community 2015-07-08 14:45:56 +01:00
Sebastian McKenzie
fc15c91b2a replace descriptor.writable assignment in createDecoraredObject helper - fixes #1949 2015-07-08 14:45:50 +01:00
Sebastian McKenzie
421b01865f add Generated/User/Directive virtual node types 2015-07-08 11:35:56 +01:00
Sebastian McKenzie
af7510adec fix some bugs in PathHoister - fixes babel-plugins/babel-plugin-react-constant-elements#1
- Don't hoist constant elements to the same function as their original paths function parent.
 - Push each violation paths ancestry to the breakOnScopePaths collection to avoid constant hoisting to nested paths.
2015-07-08 11:35:34 +01:00
Sebastian McKenzie
ec7c40fbf6 add quiet option to CLI - fixes #1931 2015-07-07 11:26:45 +01:00
Sebastian McKenzie
4a36a9fb31 check for functions in util.shouldIgnore - closes #1865, closes #1859 2015-07-07 11:23:31 +01:00
Sebastian McKenzie
4d25b0d96a Merge branch 'master' of github.com:babel/babel 2015-07-07 11:12:42 +01:00
Sebastian McKenzie
babc9c90b4 fix tail call recursion on functions with less arguments than parameters - fixes #1938 2015-07-07 11:11:58 +01:00
Sebastian McKenzie
288293ca11 Merge pull request #1936 from loganfsmyth/system-module-hoisting
Only special-case for..on declaration hoisting - fixes #1929
2015-07-07 10:54:26 +01:00
Sebastian McKenzie
a262e99abd strip flow directives in flow transformer - fixes #1934 2015-07-07 10:52:43 +01:00
Logan Smyth
b518394a3f Only special-case for..on/of declaration hoisting - fixes #1929 2015-07-06 21:06:11 -07:00
Sebastian McKenzie
337c51df5c fixes out of bounds check to default parameter template - #1845 - cc @RReverser 2015-07-06 21:25:33 +01:00
Sebastian McKenzie
0509fb148f add out of bounds check to default parameter template - addresses #1845 - cc @RReverser 2015-07-06 20:12:10 +01:00
Sebastian McKenzie
bb5f1120b7 Merge branch 'master' of github.com:babel/babel 2015-07-05 21:41:58 +01:00
Sebastian McKenzie
38d46012a7 Merge pull request #1926 from loganfsmyth/systemjs-modules-export
Optimize export-from in System.register - fixes #1722
2015-07-05 21:39:30 +01:00
Logan Smyth
cdb8e3aefa Optimize export-from in System.register - fixes #1722 2015-07-05 11:40:33 -07:00
Sebastian McKenzie
4a84cd785a Merge pull request #1915 from loganfsmyth/destructuring-default-hoisting
Ensure _blockHoist is set on function destructuring defaults
2015-07-05 19:24:01 +01:00
Logan Smyth
f47d17345c Ensure _blockHoist is set on function destructuring defaults - fixes #1908 2015-07-05 09:10:09 -07:00
Sebastian McKenzie
8746ca8d31 add Statement virtual type 2015-07-05 01:23:37 +02:00
Sebastian McKenzie
76e954bc36 add reference to issue #1920 2015-07-05 01:23:32 +02:00
Sebastian McKenzie
64903d0dcf Merge branch 'master' of github.com:babel/babel 2015-07-04 23:33:33 +02:00
Sebastian McKenzie
1fd0b1f741 delay this assignment when referencing this inside an arrow function pre-bare super in derived class constructors - fixes #1920 2015-07-04 23:32:11 +02:00
Sebastian McKenzie
cda2bfce38 enable do expression tests 2015-07-04 21:51:57 +02:00
Sebastian McKenzie
0e4bb5ee3f clean up verifyConstructor classes visitor and disallow super.* before super() in derived class constructors - fixes #1921 2015-07-04 21:38:22 +02:00
Sebastian McKenzie
e9793b1f16 Merge pull request #1916 from conradz/inline-single-child
Handle single child when using React inlining
2015-07-04 11:23:15 +02:00
Conrad Zimmerman
224db29c05 Handle single child when using React inlining
Changes optimisation.react.inlineElements to handle a single child as the
value of the `children` property instead of wrapping it with an array.
This matches the behavior of `React.createElement`.
2015-07-03 18:55:38 -04:00
Sebastian McKenzie
bd1bd38556 add undeclared type variable 2015-07-03 00:14:40 +02:00
Sebastian McKenzie
1f39114126 Merge branch 'master' into development 2015-07-03 00:07:53 +02:00
Sebastian McKenzie
4c0b8599f1 add optional context parameter to NodePath#get 2015-07-03 00:07:37 +02:00
Sebastian McKenzie
848909620c add more comments to path methods 2015-07-03 00:07:23 +02:00
Sebastian McKenzie
c40215497d Merge pull request #1900 from samccone/sjs/opt2
rework findCommonStringDelimiter
2015-07-02 23:54:52 +02:00
Sebastian McKenzie
6450f5263e Merge pull request #1901 from loganfsmyth/constructor-scope-fix
Properly regenerate scope for replaced nodes - fixes #1773
2015-07-02 23:54:28 +02:00
Sam Saccone
74c59c94ce 2015-07-02 16:57:12 -04:00
Logan Smyth
3f38a83600 Properly regenerate scope for replaced nodes - fixes #1773 2015-07-01 22:06:05 -07:00
Sam Saccone
1945f849c3 Move into for block
https://www.youtube.com/watch?v=FHDwRECFL8M
2015-07-01 20:36:24 -07:00
Sam Saccone
5b0b7ba226 🍴 Switch to ternary for return
https://www.youtube.com/watch?v=XAbY2cmEsS0
2015-07-01 20:36:17 -07:00
James Kyle
42de6bc716 Merge pull request #1894 from samccone/patch-4
🐳
2015-07-02 01:06:50 +01:00
James Kyle
fb66f347b9 Merge pull request #1895 from samccone/patch-5
remove 💀 comment lines
2015-07-02 01:05:51 +01:00
Brian Donovan
5e28bd4e68 Merge pull request #1893 from samccone/patch-1
🍕 Fix grammatical issue
2015-07-01 16:16:20 -07:00
Sam Saccone
9869566963 remove 💀 comment lines
Added in 
3561efdb86

if this is a style thing you want to keep around then my all means close away.
2015-07-01 15:59:05 -07:00
Sam Saccone
4a27b10e8a 👶 2015-07-01 15:56:11 -07:00
Sam Saccone
c3b5ed5b3d 💄 Fix grammatical issue 2015-07-01 15:51:56 -07:00
Sebastian McKenzie
afa4871a08 Merge pull request #1892 from samccone/patch-1
📝 better english
2015-07-02 00:48:57 +02:00
Sam Saccone
70c739250b 📝 better english 2015-07-01 15:48:00 -07:00
Sebastian McKenzie
722e706a8c Merge pull request #1891 from samccone/patch-1
️  this that this
2015-07-02 00:42:05 +02:00
Sam Saccone
f3973c8397 📝 clarify how it inherits this 2015-07-01 15:41:15 -07:00
Sebastian McKenzie
47c3792d34 Merge pull request #1890 from samccone/patch-1
️  Add link to ESTree
2015-07-02 00:39:23 +02:00
Sam Saccone
456accb4b3 📝 Add link to ESTree 2015-07-01 15:37:20 -07:00
Sebastian McKenzie
72771ed439 update escape regex test to use new lodash result 2015-06-30 23:56:47 +01:00
Sebastian McKenzie
7cb7ea4248 Merge pull request #1884 from arthurvr/resolve
Add `resolve` to `CONTRIBUTING.md`
2015-06-30 23:39:33 +01:00
Arthur Verschaeve
301df15921 Add resolve to CONTRIBUTING.md
Introduced in aaf4cbf06f
2015-06-30 23:56:30 +02:00
Sebastian McKenzie
15535406bd Merge pull request #1883 from arthurvr/patch-1
Remove `user-home` from `CONTRIBUTING.md`
2015-06-30 22:43:42 +01:00
Arthur Verschaeve
63f53e3773 Remove user-home from CONTRIBUTING.md
In favor of `user-or-tmp`

Ref 90b8826e73
2015-06-30 23:40:24 +02:00
Brian Donovan
03a979a6bd Merge pull request #1867 from arthurvr/deps
Add `path-exists` to `CONTRIBUTING.md`
2015-06-30 14:31:24 -07:00
Sebastian McKenzie
910622e66e fix linting errors 2015-06-30 15:17:26 +01:00
Sebastian McKenzie
c5a8702021 clean up derived classes, fixes super path referencing user constructor instead of our new function - #1877 2015-06-30 14:55:11 +01:00
Sebastian McKenzie
336c65fe2c restructure classes transformer, fix class name inference - #1877 2015-06-30 14:49:04 +01:00
Sebastian McKenzie
092d98fb27 add constructor to body in order that it was supplied in - fixes #1877 2015-06-30 10:10:52 +01:00
Sebastian McKenzie
e55ce575cd move up template literal simplification logic - fixes #1874 2015-06-29 23:36:06 +01:00
Sebastian McKenzie
d63ae5fce8 remove loose console.log 2015-06-29 22:59:23 +01:00
Sebastian McKenzie
541309c4bb fix collisions for getBindingIdentifiers 2015-06-29 22:04:17 +01:00
Sebastian McKenzie
2d289150d1 Merge pull request #1868 from benjamn/patch-2
Upgrade Regenerator to 0.8.32.
2015-06-29 20:47:05 +01:00
Ben Newman
b9f6169ed4 Upgrade Regenerator to 0.8.32.
This includes some major runtime performance improvements:
https://github.com/facebook/regenerator/pull/207
https://github.com/facebook/regenerator/pull/208

And also some bug fixes relating to async generator functions:
https://github.com/facebook/regenerator/commit/29d81b6929
https://github.com/facebook/regenerator/commit/7d2a052ddb
https://github.com/facebook/regenerator/commit/5b9dd1086d
2015-06-29 10:43:54 -04:00
Arthur Verschaeve
ce372281cd Add path-exists to CONTRIBUTING.md 2015-06-29 12:35:37 +02:00
Sebastian McKenzie
0044100e3d perform function name inference on functions in properties before they're properly visited - fixes #1860 2015-06-29 00:20:47 +01:00
Sebastian McKenzie
81edc4c6ab add make comment-issues skeleton 2015-06-28 00:59:24 +01:00
Sebastian McKenzie
3b1a9a0adb trim eval code in babel-node 2015-06-28 00:59:12 +01:00
Sebastian McKenzie
8ab90aacd3 add babel-core version to babel-cli version - closes #1861 2015-06-28 00:59:05 +01:00
Sebastian McKenzie
a1a46882fd v5.6.15 2015-06-27 00:07:24 +01:00
Sebastian McKenzie
12b4e6db40 v5.6.13 2015-06-27 00:06:40 +01:00
Sebastian McKenzie
7f06bb79c0 attempt to fix master fetching for automatic travis merge 2015-06-26 23:58:57 +01:00
Sebastian McKenzie
34218afdae clean up build website script 2015-06-26 23:41:19 +01:00
Sebastian McKenzie
b94118db5e output debug current branch/commit info 2015-06-26 23:32:45 +01:00
Sebastian McKenzie
54819b94e9 skip flow types when finding rest parameter references 2015-06-26 23:29:09 +01:00
Sebastian McKenzie
50ca6b1018 clean up inType tracking in flow parser plugin 2015-06-26 23:26:32 +01:00
Sebastian McKenzie
2d195c4843 add logging for publish cli 2015-06-26 20:30:24 +01:00
Sebastian McKenzie
2f0d0c94ef try alternate merge parameter 2015-06-26 20:30:16 +01:00
Sebastian McKenzie
5e3ea5b6e7 add update-ref master to merge-development-with-master script 2015-06-26 19:48:48 +01:00
Sebastian McKenzie
95128f98bc Merge branch 'master' into development 2015-06-26 16:59:49 +01:00
Sebastian McKenzie
c4d1d58167 +x 2015-06-26 16:59:43 +01:00
Sebastian McKenzie
7da1d9fadd wrap TRAVIS_COMMIT variable in curlies for consistency 2015-06-26 16:48:52 +01:00
Sebastian McKenzie
6ab57fd367 rebuild website on new version, automatically merge development branch with master - closes #1854, closes #1849 2015-06-26 16:46:52 +01:00
Sebastian McKenzie
d4edce6559 only publish babel-cli when the directory has had changes since the last version - fixes #1848 2015-06-26 16:21:37 +01:00
Sebastian McKenzie
9c8cb33a09 remove babel-core from babel-cli packag.ejson 2015-06-26 16:19:22 +01:00
Sebastian McKenzie
a2fb70bae3 fix deprecated return from visitor method api 2015-06-26 15:16:31 +01:00
Sebastian McKenzie
273a81fe1f fix up babel-eslint dependency 2015-06-26 15:15:19 +01:00
Sebastian McKenzie
72a0ac5e02 v5.6.14 2015-06-26 15:09:03 +01:00
Sebastian McKenzie
c5ace10536 update babel-eslint 2015-06-26 15:07:56 +01:00
Sebastian McKenzie
b833614b87 update travis with new npm api key 2015-06-26 14:10:05 +01:00
Sebastian McKenzie
ae067a08b7 switch to mocha dot reporter 2015-06-26 13:23:15 +01:00
Sebastian McKenzie
f56337541f change readme tagline 2015-06-26 13:23:08 +01:00
Sebastian McKenzie
1fe8447a1a add test release explanation to changelog 2015-06-26 12:25:40 +01:00
Sebastian McKenzie
13bbfa041d v5.6.13 2015-06-26 12:25:00 +01:00
Sebastian McKenzie
c43bbb9bf6 use npm to publis new version - fixes #1847 2015-06-26 12:24:01 +01:00
Sebastian McKenzie
1bca59a921 clean up readme - add back badges 2015-06-26 11:54:51 +01:00
Sebastian McKenzie
f80fdf7359 5.6.12 2015-06-26 11:41:34 +01:00
Sebastian McKenzie
aefd69d31e v5.6.12 2015-06-26 11:40:40 +01:00
Sebastian McKenzie
e328031b19 add 5.6.12 changelog 2015-06-26 11:39:47 +01:00
Sebastian McKenzie
571b6a4cd7 check parent node alongside path in shadow functions 2015-06-26 11:39:10 +01:00
Sebastian McKenzie
41cf942391 clean up shadow functions findParent logic - fixes #1846 2015-06-26 11:34:13 +01:00
Sebastian McKenzie
98f28b8e89 5.6.11 2015-06-26 02:40:00 +01:00
Sebastian McKenzie
8f88afc037 v5.6.11 2015-06-26 02:39:04 +01:00
Sebastian McKenzie
6359675a4f make shadowed function findParent target finder more reliable 2015-06-26 02:38:14 +01:00
Sebastian McKenzie
a265c3f25c add missing semi 2015-06-26 02:25:46 +01:00
Sebastian McKenzie
29eb99ee93 rejigger shadowd function findParent logic 2015-06-26 02:24:42 +01:00
Sebastian McKenzie
0c5c1ff989 remove unused variable 2015-06-26 02:22:10 +01:00
Sebastian McKenzie
499951123a add 5.6.11 changelog 2015-06-26 02:21:34 +01:00
Sebastian McKenzie
c0fd4c1f9e merge es6.parameters.rest and es6.parameters.default transformers
This is necessary in order to retain correct function arity and to have
completely correct semantics. Sometimes features are tied together so much
that they would require so much desugaring to retain the correct semantics
that they'd be equivalent to... the normal transpiled output.
2015-06-26 02:20:16 +01:00
Sebastian McKenzie
579e6fecee upgrade internal dev babel dependency to 5.6.10 2015-06-26 02:05:43 +01:00
Sebastian McKenzie
bb3665a3b6 5.6.10 2015-06-26 01:12:50 +01:00
Sebastian McKenzie
e6de688234 v5.6.10 2015-06-26 01:11:32 +01:00
Sebastian McKenzie
4c233e88ff add use strict 2015-06-26 01:09:47 +01:00
Sebastian McKenzie
ae2ba0b5a3 add 5.6.10 changelog 2015-06-26 01:08:36 +01:00
Sebastian McKenzie
e34d950793 require babel-core at the top of the file 2015-06-26 01:07:54 +01:00
Sebastian McKenzie
e4083fbbd7 add support for trailing commas in arrow function parameter lists - fixes #1841 2015-06-26 00:37:33 +01:00
Sebastian McKenzie
59ed7977ef 5.6.9 2015-06-25 23:59:12 +01:00
Sebastian McKenzie
dc441e9a8f v5.6.9 2015-06-25 23:58:07 +01:00
Sebastian McKenzie
2e21795f57 add index.js to fix internal api error 2015-06-25 23:57:16 +01:00
Sebastian McKenzie
5c988f7fc8 5.6.8 2015-06-25 23:35:34 +01:00
Sebastian McKenzie
493826973e v5.6.8 2015-06-25 23:34:30 +01:00
Sebastian McKenzie
1acc71aa4e fix api module id relative tests 2015-06-25 23:32:43 +01:00
Sebastian McKenzie
bbab5f72ec add 5.6.8 changelog 2015-06-25 23:31:07 +01:00
Sebastian McKenzie
58ff9e387a remove root internals protect 2015-06-25 23:30:43 +01:00
Sebastian McKenzie
5a0d099984 don't add protect to register either 2015-06-25 23:28:27 +01:00
Sebastian McKenzie
05c95e04f7 don't add protect to polyfill 2015-06-25 23:26:24 +01:00
Sebastian McKenzie
88430b4be2 forgive hotlinking to polyfill 2015-06-25 23:24:45 +01:00
Sebastian McKenzie
19adcfae4d add type import 2015-06-25 23:22:42 +01:00
Sebastian McKenzie
7c4fe984ce start linting babel-cli/bin - fixes #1836 2015-06-25 23:22:38 +01:00
Sebastian McKenzie
4476e8311c use relative tools/protect.js filenames 2015-06-25 23:20:18 +01:00
Sebastian McKenzie
2a3142273d add path-exists dependency to babel-cli 2015-06-25 23:20:08 +01:00
Sebastian McKenzie
bbcb889a49 Merge branch 'master' of github.com:babel/babel 2015-06-25 23:04:24 +01:00
Sebastian McKenzie
c87f85815b used filter rather than setting init properties to null in properties.computed transformer - fixes #1831 2015-06-25 23:04:17 +01:00
Sebastian McKenzie
48d0df17d0 Merge pull request #1832 from Mark-Simulacrum/path-exists
Use path-exists module instead of fs.exists.
2015-06-25 22:57:27 +01:00
Sebastian McKenzie
01b243347f add NodePath#baseTypeStrictlyMatches method 2015-06-25 22:55:46 +01:00
Sebastian McKenzie
45a5cbf72f use capitalised builder method 2015-06-25 22:55:35 +01:00
Sebastian McKenzie
05efae1c58 complete t.createTypeAnnotationBasedOnTypeof 2015-06-25 22:55:25 +01:00
Sebastian McKenzie
c08fff4b44 add node builder for normal AST node type 2015-06-25 22:55:12 +01:00
Sebastian McKenzie
13e910ea83 force spaces for binary expressions - fixes #1835 2015-06-25 22:55:00 +01:00
Mark-Simulacrum
b308602098 Use path-exists instead of fs.exists.
fs.exists is being deprecated, see: https://github.com/nodejs/io.js/issues/103.
2015-06-25 12:39:39 -06:00
Sebastian McKenzie
560a044d8f Merge pull request #1821 from kpdecker/destructure-performance
Avoid deopt in iterable destructure template
2015-06-25 15:23:53 +01:00
Sebastian McKenzie
619fbe4c3b Merge pull request #1830 from kpdecker/avoid-define-property
Avoid defineProperty when not needed
2015-06-25 15:23:39 +01:00
kpdecker
1d83ad6cce Avoid defineProperty when not needed
This lets us use the fast path for most object literal assignments and then utilizes the defineProperty path when there is a chance that we could hit the setter issue described in #357.

10x performance boosts seen for the six-speed test case, going from 200k operations/sec to 2M ops/sec.
2015-06-25 09:22:03 -05:00
kpdecker
5353ccd773 Move slice iterator helper out of primary call
Avoids overhead of instantiating the helper on each call to the slice to array helper.
2015-06-25 09:18:12 -05:00
Sebastian McKenzie
a8e23d2eb9 ignore templates folder in protect plugin 2015-06-25 14:33:38 +01:00
Sebastian McKenzie
95d830fde0 don't output comma separator for decorator list and output Property decorators - fixes #1811 2015-06-25 12:23:45 +01:00
Sebastian McKenzie
c8a5d7d970 Merge branch 'arthurvr-dep' 2015-06-25 12:12:21 +01:00
Sebastian McKenzie
43481eb2cc Merge branch 'dep' of https://github.com/arthurvr/babel into arthurvr-dep 2015-06-25 12:12:19 +01:00
Sebastian McKenzie
b8bb665691 Merge branch 'arthurvr-tests' 2015-06-25 12:12:05 +01:00
Sebastian McKenzie
e6846b2730 Merge branch 'tests' of https://github.com/arthurvr/babel into arthurvr-tests 2015-06-25 12:12:05 +01:00
Sebastian McKenzie
31c1286a3c protect internal files from hotlinking 2015-06-25 12:10:22 +01:00
Arthur Verschaeve
489f9e92b5 Add tests for util.resolve 2015-06-25 10:10:56 +02:00
Arthur Verschaeve
073809efac Remove leven dependency 2015-06-25 09:37:27 +02:00
Brian Donovan
c9b8e2f3ce Merge pull request #1822 from azu/patch-1
Add missing asterisk in CHANGELOG
2015-06-24 21:23:51 -07:00
azu
c6cb871355 Add missing asterisk in CHANGELOG 2015-06-25 13:17:23 +09:00
kpdecker
1b0e5b3ed1 Avoid deopt in iterable destructure template
The try/catch was forcing deoptimization under most engines. This roughly doubles throughput under V8 and 7x increases were seen under Firefox.

Performance numbers based on https://github.com/kpdecker/six-speed/tree/master/tests/destructuring
2015-06-24 22:42:13 -05:00
Sebastian McKenzie
0f70c76312 5.6.7 2015-06-25 04:18:49 +01:00
Sebastian McKenzie
e8c672bf4f v5.6.7 2015-06-25 04:17:52 +01:00
Sebastian McKenzie
7083ac61ff remove test.js 2015-06-25 04:16:06 +01:00
Sebastian McKenzie
d256809120 Merge branch 'master' of github.com:babel/babel
# Conflicts:
#	src/babel/traversal/path/replacement.js
2015-06-25 04:12:13 +01:00
Sebastian McKenzie
26a19f82d2 add 5.6.7 changelog 2015-06-25 04:11:40 +01:00
Sebastian McKenzie
128d3b5c91 add missing computed loose test - ref #1820 2015-06-25 04:11:32 +01:00
Sebastian McKenzie
c1a080d0ca supress duplicate deprecation messages 2015-06-25 04:11:13 +01:00
Sebastian McKenzie
0b1ce6c9a4 always coerce leading computed property initialisers into the init object - fixes #1820 2015-06-25 04:10:56 +01:00
Sebastian McKenzie
a6f04055c0 fix block scoping transformer 2015-06-25 04:10:32 +01:00
Sebastian McKenzie
c3219e8b88 deprecate returning source strings from visitor methods 2015-06-25 03:51:25 +01:00
Sebastian McKenzie
a35c863341 deprecate returning source strings from visitor methods 2015-06-25 03:50:10 +01:00
Sebastian McKenzie
6f862a4c45 actually push for left declaration to the returned block scoping body - fixes #1819 2015-06-25 03:48:29 +01:00
Sebastian McKenzie
cf38210fd2 5.6.6 2015-06-24 23:28:44 +01:00
Sebastian McKenzie
5c9d564339 v5.6.6 2015-06-24 23:27:44 +01:00
Sebastian McKenzie
031a61515b add labels, and inX properties to lookahead getState 2015-06-24 23:26:59 +01:00
Sebastian McKenzie
d3884fd53b add inType assignment in flow parse declare method 2015-06-24 23:26:48 +01:00
Sebastian McKenzie
c6eef3080e add 5.6.6 changelog 2015-06-24 23:26:35 +01:00
Sebastian McKenzie
25be0a974d fixing linting errors 2015-06-24 23:20:03 +01:00
Sebastian McKenzie
7ccd135e83 fix isKeyword flow overload 2015-06-24 23:18:21 +01:00
Sebastian McKenzie
4fc1bbeb60 acorn resync 2015-06-24 23:15:27 +01:00
Sebastian McKenzie
32a4d7172b optimise generator for compact mode 2015-06-24 23:15:22 +01:00
Sebastian McKenzie
aa25903c05 parse void as an identifier when inside a type annotation to avoid setting void keyword token - cc @DmitrySoshnikov 2015-06-24 23:15:00 +01:00
Sebastian McKenzie
23ec1a455e upgrade babel-plugin-dead-code-elimination 2015-06-24 23:14:08 +01:00
Sebastian McKenzie
e6ac2d049b add 5.6.5 changelog 2015-06-24 13:50:53 +01:00
Sebastian McKenzie
084ae31816 5.6.5 2015-06-24 13:48:43 +01:00
Sebastian McKenzie
8e530afd78 v5.6.5 2015-06-24 13:47:54 +01:00
Sebastian McKenzie
6c66a82b37 Merge branch 'master' of github.com:babel/babel 2015-06-24 13:46:05 +01:00
Sebastian McKenzie
737abca3a9 use this.space() instead of manually pushing 2015-06-24 13:45:56 +01:00
Sebastian McKenzie
9db43ca7a9 clean up t.isReferenced 2015-06-24 13:45:48 +01:00
Sebastian McKenzie
25b0683316 add Path#couldBeBaseType 2015-06-24 13:45:32 +01:00
Sebastian McKenzie
a096f6b1c5 fix noOptimise state being incorrect when recursing into multiple nested functions - fixes #1815 2015-06-24 13:45:14 +01:00
Sebastian McKenzie
e41ab2ab0c Merge pull request #1807 from benjamn/patch-1
Update Regenerator dependency to 0.8.31.
2015-06-23 17:07:25 +01:00
Ben Newman
6a6764fa7b Update Regenerator dependency to 0.8.31.
Fixes #1805.
2015-06-23 12:06:48 -04:00
Sebastian McKenzie
a2358d6863 5.6.4 2015-06-22 20:39:14 +01:00
Sebastian McKenzie
612ef79d35 v5.6.4 2015-06-22 20:38:12 +01:00
Sebastian McKenzie
2dfa6ddf36 add 5.6.4 changelog 2015-06-22 20:37:00 +01:00
Sebastian McKenzie
2910d4f82c fix Program can only be replaced with another Program error 2015-06-22 20:36:34 +01:00
Sebastian McKenzie
4b6c954f5e add ParenthesizedExpression node type for plugins to generate 2015-06-22 20:36:12 +01:00
Sebastian McKenzie
b7e23e3410 5.6.3 2015-06-22 11:57:53 +01:00
Sebastian McKenzie
a19f10e124 v5.6.3 2015-06-22 11:56:46 +01:00
Sebastian McKenzie
8e1f134635 fix rest parameter array allocation loop being incorrectly aliased - fixes #1800 2015-06-22 11:54:57 +01:00
Sebastian McKenzie
aa151016f5 5.6.2 2015-06-22 00:10:56 +01:00
204 changed files with 1927 additions and 707 deletions

View File

@@ -2,5 +2,6 @@
"stage": 0,
"loose": ["all"],
"blacklist": ["es6.tailCall"],
"optional": ["optimisation.flow.forOf"]
"optional": ["optimisation.flow.forOf"],
"plugins": ["./tools/build-plugins/protect"]
}

View File

@@ -18,7 +18,8 @@
"new-cap": 0,
"no-loop-func": 0,
"no-unreachable": 0,
"no-labels": 0
"no-labels": 0,
"no-process-exit": 0
},
"env": {
"node": true

1
.gitignore vendored
View File

@@ -15,3 +15,4 @@ test/core/tmp
/packages/babel-runtime/helpers/*.js
/packages/babel-runtime/regenerator/*.js
/lib
_babel.github.io

View File

@@ -13,3 +13,4 @@
/vendor
/packages
/src
_babel.github.io

View File

@@ -1,14 +1,34 @@
#sudo: false
language: node_js
cache:
directories:
- node_modules
- node_modules
node_js:
- "0.12"
- "iojs"
- "0.12"
- iojs
before_script: "npm install -g codeclimate-test-reporter"
script: "make test-travis"
before_script: ./tools/setup-git.sh
script: make test-travis
after_success: ./tools/merge-development-with-master.sh
notifications:
slack: babeljs:5Wy4QX13KVkGy9CnU0rmvgeK
before_deploy:
- make prepublish
deploy:
provider: npm
email: sebmck@gmail.com
skip_cleanup: true
api_key:
secure: Q/pZStwherdYPCqCa0aUuiEktLcx6ccBxieyH8j9IXdDgty0ydmnajZfUnlZuCjN13XI9esM44nSJFTWZvntTryDQAQm37c63VXhAEnw/qrAINI06yt0gLBTT69/fKvIAkH8l48nmW32ZS2dse3rHRPZF1CwyQLC/pdMip8I4sM=
on:
branch: master
tags: true
repo: babel/babel
after_deploy:
- make publish-cli
- make publish-runtime
- make build-website
- make comment-issues

View File

@@ -9,10 +9,70 @@
> - [Internal]
> - [Polish]
_Note: Gaps between patch versions are faulty/broken releases._
_Note: Gaps between patch versions are faulty, broken or test releases._
See [CHANGELOG - 6to5](CHANGELOG-6to5.md) for the pre-4.0.0 version changelog.
## 5.6.12
* **Bug Fix**
* Fix finding parent for top-level shadowed functions.
## 5.6.11
** **Internal**
* Merge `es6.parameters.rest` and `es6.parameters.default` transformers. See commit [c0fd4c1f9e0b18231f585c4fa793e4cb0e01aed1](https://github.com/babel/babel/commit/c0fd4c1f9e0b18231f585c4fa793e4cb0e01aed1) for more info.
## 5.6.10
* **Bug Fix**
* Fix faulty internal require check.
* **Polish**
* Add support for trailing commas in arrow function parameter lists.
## 5.6.8
* **Bug Fix**
* Fix binary expressions colliding with unary expression operators in compact mode.
* Fix node properties being set to `null` when using computed properties.
## 5.6.7
* **Bug Fix**
* Fix hoisting of `ForXStatement` `left` `var`s when inserting a block scoping IIFE.
* **Polish**
* Combine all leading computed property initialisers into the root object in loose mode.
* **Internal**
* Deprecate returning of replacement strings from visitor methods.
## 5.6.6
* **Bug Fix**
* Fix weird parser bug where `void` type annotations were being parsed as keywords causing the tokeniser to lose track of context.
## 5.6.5
* **Bug Fix**
* Fix nested functions causing rest parameter optimisation to not properly detect when it should deopt on a reference.
* **Internal**
* Update Regenerator `0.8.31`.
## 5.6.4
* **Internal**
* Add `ParenthesizedExpression` node type.
## 5.6.3
* **Bug Fix**
* Fix rest parameter array allocation loop being incorrectly aliased.
## 5.6.2
* **Bug Fix**
* Fix method key literals not turning into computed member expression in loose mode.
* Elect rest parameters in spread element position as candidates instead of replacing them in place.
## 5.6.0
* **Bug Fix**

View File

@@ -113,8 +113,6 @@ your [`$PATH`](http://unix.stackexchange.com/questions/26047/how-to-correctly-ad
+ [js-tokens](http://ghub.io/js-tokens) This is used to get tokens for syntax error highlighting.
+ [leven](http://ghub.io/leven) A levenstein algorithm to determine how close a word is to another. This is used to offer suggestions when using the utility.undeclaredVariableCheck transformer.
+ [line-numbers](http://ghub.io/line-numbers) Used to produce the code frames in syntax errors.
+ [lodash](http://ghub.io/lodash) Used for various utilities.
@@ -145,8 +143,11 @@ your [`$PATH`](http://unix.stackexchange.com/questions/26047/how-to-correctly-ad
+ [trim-right](http://ghub.io/trim-right) Trims the rightside whitespace.
+ [user-home](http://ghub.io/user-home) Gets the users home directory. This is used to resolve the babel-node/babel/register cache.
+ [path-exists](https://www.npmjs.com/package/path-exists) Checks if a path exists. (replaces the deprecated `fs.exists` methods)
+ [home-or-tmp](https://github.com/sindresorhus/home-or-tmp) Gets the user home directory with fallback to the system temporary directory. This is used to resolve the babel-node/babel/register cache.
+ [resolve](https://www.npmjs.com/package/resolve) Implements the [`require.resolve()` algorithm](http://nodejs.org/docs/v0.12.0/api/all.html#all_require_resolve) such that we can `require.resolve()` on behalf of a file asynchronously and synchronously.
#### Code Standards

View File

@@ -9,7 +9,7 @@ BROWSERIFY_IGNORE = -i esprima-fb
export NODE_ENV = test
.PHONY: clean test test-cov test-clean test-travis test-simple test-all test-browser test-parser publish build bootstrap publish-core publish-runtime build-core watch-core build-core-test clean-core
.PHONY: clean test test-cov test-clean test-travis test-simple test-all test-browser test-parser publish build bootstrap publish-core publish-runtime build-website build-core watch-core build-core-test clean-core prepublish
build-core: clean-core
node $(BABEL_CMD) src --out-dir lib --copy-files
@@ -24,7 +24,7 @@ clean-core:
rm -rf lib
lint:
eslint src/babel
eslint src/babel packages/babel-cli/bin
build:
mkdir -p dist
@@ -81,34 +81,20 @@ test-browser:
publish: lint
git pull --rebase
make test
read -p "Version: " version; \
npm version $$version --message "v%s"
make build
cp dist/browser.js browser.js
cp dist/browser.min.js browser.min.js
cp dist/polyfill.js browser-polyfill.js
cp dist/polyfill.min.js browser-polyfill.min.js
cp dist/external-helpers.js external-helpers.js
cp dist/external-helpers.min.js external-helpers.min.js
node tools/cache-templates
test -f templates.json
npm publish
git push --follow-tags
make publish-cli
make publish-runtime
rm -rf templates.json browser.js browser.min.js browser-polyfill.js browser-polyfill.min.js external-helpers.js external-helpers.min.js
prepublish: build
cp dist/browser.js browser.js
cp dist/browser.min.js browser.min.js
cp dist/polyfill.js browser-polyfill.js
cp dist/polyfill.min.js browser-polyfill.min.js
cp dist/external-helpers.js external-helpers.js
cp dist/external-helpers.min.js external-helpers.min.js
node tools/cache-templates
test -f templates.json
publish-runtime:
cd packages; \
@@ -117,10 +103,13 @@ publish-runtime:
npm publish
publish-cli:
cd packages; \
node build-cli.js; \
cd babel-cli; \
npm publish
@./tools/publish-cli.sh
build-website:
@./tools/build-website.sh
comment-issues:
@./tools/comment-issues.sh
bootstrap:
npm list --global --depth 1 babel >/dev/null 2>&1 && npm uninstall -g babel || true

View File

@@ -5,15 +5,24 @@
</p>
<p align="center">
<strong>Babel</strong> is a compiler for writing next generation JavaScript.
The compiler for writing next generation JavaScript.
</p>
<p align="center">
For questions and support please visit the <a href="https://babel-slack.herokuapp.com">slack channel</a> or <a href="http://stackoverflow.com/questions/tagged/babeljs">StackOverflow</a>. The Babel issue tracker is <strong>exclusively</strong> for bug reports and feature requests.
<a href="https://travis-ci.org/babel/babel"><img alt="Build Status" src="https://img.shields.io/travis/babel/babel.svg?style=flat"></a>
<a href="http://badge.fury.io/js/babel-core"><img alt="npm version" src="https://badge.fury.io/js/babel-core.svg"></a>
<a href="https://npmjs.org/package/babel-core"><img alt="Downloads" src="http://img.shields.io/npm/dm/babel-core.svg"></a>
</p>
<p align="center">
Issues without instructions to reproduce <strong>will be immediately closed<strong>.
<a href="http://issuestats.com/github/babel/babel"><img alt="Issue Stats" src="http://issuestats.com/github/babel/babel/badge/pr?style=flat"></a>
<a href="http://issuestats.com/github/babel/babel"><img alt="Issue Stats" src="http://issuestats.com/github/babel/babel/badge/issue?style=flat"></a>
</p>
----
<p align="center">
For questions and support please visit the <a href="https://babel-slack.herokuapp.com">Slack community</a> or <a href="http://stackoverflow.com/questions/tagged/babeljs">StackOverflow</a>. The Babel issue tracker is <strong>exclusively</strong> for bug reports and feature requests.
</p>
<p align="center">

View File

@@ -1,5 +1,5 @@
# Properties of nodes
These are properties babel stores in AST node objects for internal use, as opposed to properties that are part of the AST spec (ESTree at the time of this writing).
These are properties babel stores in AST node objects for internal use, as opposed to properties that are part of the AST spec ([ESTree](https://github.com/estree/estree) at the time of this writing).
## `_blockHoist`
`node._blockHoist != null` triggers the [block-hoist transformer](/src/babel/transformation/transformers/internal/block-hoist.js). Value should be `true` or an integer in the range `0..3`. `true` is equivalent to `2`. The value indicates whether the node should be hoisted and to what degree. See the source code for more detailed information.
@@ -8,4 +8,4 @@ These are properties babel stores in AST node objects for internal use, as oppos
Stores a representation of a node's position in the tree and relationship to other nodes.
## `shadow`
A truthy value on a function node triggers the [shadow-functions transformer](/src/babel/transformation/transformers/internal/shadow-functions.js), which transforms the node so that it references (or inherits) `arguments` and `this` from the parent scope. It is invoked for arrow functions, for example.
A truthy value on a function node triggers the [shadow-functions transformer](/src/babel/transformation/transformers/internal/shadow-functions.js), which transforms the node so that it references (or inherits) `arguments` and the `this` context from the parent scope. It is invoked for arrow functions, for example.

1
index.js Normal file
View File

@@ -0,0 +1 @@
module.exports = require("./lib/babel/api/node.js");

View File

@@ -1,27 +1,26 @@
{
"name": "babel-core",
"description": "A compiler for writing next generation JavaScript",
"version": "5.6.2",
"version": "5.6.16",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
"license": "MIT",
"repository": "babel/babel",
"main": "lib/babel/api/node.js",
"browser": {
"./lib/babel/api/register/node.js": "./lib/babel/api/register/browser.js"
},
"keywords": [
"harmony",
"6to5",
"babel",
"classes",
"modules",
"let",
"const",
"var",
"es6",
"harmony",
"let",
"modules",
"transpile",
"transpiler",
"6to5",
"babel"
"var"
],
"scripts": {
"bench": "make bench",
@@ -31,7 +30,7 @@
"acorn-jsx": "^1.0.0",
"ast-types": "~0.7.0",
"babel-plugin-constant-folding": "^1.0.1",
"babel-plugin-dead-code-elimination": "^1.0.1",
"babel-plugin-dead-code-elimination": "^1.0.2",
"babel-plugin-eval": "^1.0.1",
"babel-plugin-inline-environment-variables": "^1.0.1",
"babel-plugin-jscript": "^1.0.1",
@@ -57,14 +56,15 @@
"home-or-tmp": "^1.0.0",
"is-integer": "^1.0.4",
"js-tokens": "1.0.1",
"leven": "^1.0.1",
"line-numbers": "0.2.0",
"lodash": "^3.6.0",
"minimatch": "^2.0.3",
"output-file-sync": "^1.1.0",
"path-exists": "^1.0.0",
"path-is-absolute": "^1.0.0",
"private": "^0.1.6",
"regenerator": "0.8.30",
"recast": "0.10.16",
"regenerator": "0.8.32",
"regexpu": "^1.1.2",
"repeating": "^1.1.2",
"resolve": "^1.1.6",
@@ -77,11 +77,11 @@
"trim-right": "^1.0.0"
},
"devDependencies": {
"babel": "5.5.7",
"babel": "5.6.10",
"babel-eslint": "^3.1.19",
"browserify": "^9.0.8",
"chai": "^2.2.0",
"eslint": "^0.21.2",
"babel-eslint": "^3.1.9",
"esvalid": "^1.1.0",
"istanbul": "^0.3.5",
"matcha": "^0.6.0",

View File

@@ -41,6 +41,7 @@ babel.register({
//
var _eval = function (code, filename) {
code = code.trim();
if (!code) return undefined;
code = babel.transform(code, {

View File

@@ -1,9 +1,10 @@
#!/usr/bin/env node
var readline = require("readline");
var child = require("child_process");
var path = require("path");
var fs = require("fs");
var pathExists = require("path-exists");
var readline = require("readline");
var child = require("child_process");
var path = require("path");
var fs = require("fs");
function spawn(cmd, args, callback) {
console.log(">", cmd, args);
@@ -34,7 +35,7 @@ function spawnMultiple(cmds) {
}
function template(name, data) {
var source = fs.readFileSync(__dirname + "/templates/" + name, "utf8");
var source = fs.readFileSync(path.join(__dirname, "templates", name), "utf8");
source = source.replace(/[A-Z_]+/g, function (key) {
return data[key] === undefined ? key : data[key];
});
@@ -98,7 +99,7 @@ var cmds = {
write("README.md", template("README.md", templateData));
if (!fs.existsSync("src")) {
if (!pathExists.sync("src")) {
fs.mkdirSync("src");
write("src/index.js", template("index.js", templateData));
}

View File

@@ -1,4 +1,5 @@
var outputFileSync = require("output-file-sync");
var pathExists = require("path-exists");
var chokidar = require("chokidar");
var slash = require("slash");
var path = require("path");
@@ -6,7 +7,7 @@ var util = require("./util");
var fs = require("fs");
var _ = require("lodash");
module.exports = function (commander, filenames, opts) {
module.exports = function (commander, filenames) {
var write = function (src, relative) {
// remove extension and then append back on .js
relative = relative.replace(/\.(\w*?)$/, "") + ".js";
@@ -27,7 +28,7 @@ module.exports = function (commander, filenames, opts) {
outputFileSync(dest, data.code);
console.log(src + " -> " + dest);
util.log(src + " -> " + dest);
};
var handleFile = function (src, filename) {
@@ -41,7 +42,7 @@ module.exports = function (commander, filenames, opts) {
};
var handle = function (filename) {
if (!fs.existsSync(filename)) return;
if (!pathExists.sync(filename)) return;
var stat = fs.statSync(filename);

View File

@@ -1,4 +1,5 @@
var convertSourceMap = require("convert-source-map");
var pathExists = require("path-exists");
var sourceMap = require("source-map");
var chokidar = require("chokidar");
var slash = require("slash");
@@ -100,7 +101,7 @@ module.exports = function (commander, filenames, opts) {
results = [];
_.each(filenames, function (filename) {
if (!fs.existsSync(filename)) return;
if (!pathExists.sync(filename)) return;
var stat = fs.statSync(filename);
if (stat.isDirectory()) {
@@ -134,7 +135,7 @@ module.exports = function (commander, filenames, opts) {
ignoreInitial: true
}).on("all", function (type, filename) {
if (type === "add" || type === "change") {
console.log(type, filename);
util.log(type + " " + filename);
try {
walk();
} catch (err) {

View File

@@ -1,6 +1,9 @@
#!/usr/bin/env node
require("babel-core");
var moduleFormatters = require("babel-core/lib/babel/transformation/modules");
var pathExists = require("path-exists");
var commander = require("commander");
var transform = require("babel-core").transform;
var kebabCase = require("lodash/string/kebabCase");
@@ -9,7 +12,6 @@ var util = require("babel-core").util;
var uniq = require("lodash/array/uniq");
var each = require("lodash/collection/each");
var keys = require("lodash/object/keys");
var fs = require("fs");
var glob = require("glob");
each(options, function (option, key) {
@@ -43,6 +45,7 @@ commander.option("-w, --watch", "Recompile files on changes");
commander.option("-o, --out-file [out]", "Compile all input files into a single file");
commander.option("-d, --out-dir [out]", "Compile an input directory of modules into an output directory");
commander.option("-D, --copy-files", "When compiling a directory copy over non-compilable files");
commander.option("-q, --quiet", "Don't log anything");
commander.on("--help", function () {
var outKeys = function (title, obj) {
@@ -65,7 +68,7 @@ commander.on("--help", function () {
});
var pkg = require("../../package.json");
commander.version(pkg.version);
commander.version(pkg.version + " (babel-core " + require("babel-core").version + ")");
commander.usage("[options] <files ...>");
commander.parse(process.argv);
@@ -88,7 +91,7 @@ var filenames = commander.args.reduce(function (globbed, input) {
filenames = uniq(filenames);
each(filenames, function (filename) {
if (!fs.existsSync(filename)) {
if (!pathExists.sync(filename)) {
errors.push(filename + " doesn't exist");
}
});

View File

@@ -25,6 +25,10 @@ exports.addSourceMappingUrl = function (code, loc) {
return code + "\n//# sourceMappingURL=" + path.basename(loc);
};
exports.log = function (msg) {
if (!commander.quiet) console.log(msg);
};
exports.transform = function (filename, code, opts) {
opts = _.defaults(opts || {}, index.opts);
opts.filename = filename;

View File

@@ -1,14 +1,12 @@
{
"name": "babel",
"description": "Turn ES6 code into readable vanilla ES5 with source maps",
"version": "5.6.1",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
"license": "MIT",
"repository": "babel/babel",
"preferGlobal": true,
"dependencies": {
"babel-core": "^5.6.1",
"chokidar": "^1.0.0",
"commander": "^2.6.0",
"convert-source-map": "^1.1.0",
@@ -16,6 +14,7 @@
"glob": "^5.0.5",
"lodash": "^3.2.0",
"output-file-sync": "^1.1.0",
"path-exists": "^1.0.0",
"path-is-absolute": "^1.0.0",
"source-map": "^0.4.0",
"slash": "^1.0.0"
@@ -26,4 +25,4 @@
"babel-external-helpers": "./bin/babel-external-helpers",
"babel-plugin": "./bin/babel-plugin/index.js"
}
}
}

View File

@@ -1,11 +1,10 @@
{
"name": "babel-runtime",
"description": "babel selfContained runtime",
"version": "5.6.1",
"license": "MIT",
"repository": "babel/babel",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"dependencies": {
"core-js": "^0.9.0"
}
}
}

View File

@@ -73,7 +73,6 @@ each(File.helpers, function (helperName) {
writeFile("regenerator/index.js", readFile("regenerator/runtime-module", true));
writeFile("regenerator/runtime.js", selfContainify(readFile("regenerator/runtime")));
//
var coreDefinitions = require("babel-plugin-runtime/lib/definitions");
@@ -93,6 +92,5 @@ each(paths, function (path) {
writeFile("core-js/" + path + ".js", defaultify('require("core-js/library/fn/' + path + '")'));
});
//
updatePackage();

View File

@@ -15,6 +15,15 @@ pp.expectRelational = function (op) {
}
}
pp.flow_parseTypeInitialiser = function (tok) {
var oldInType = this.inType
this.inType = true
this.expect(tok || tt.colon)
var type = this.flow_parseType()
this.inType = oldInType
return type;
}
pp.flow_parseDeclareClass = function (node) {
this.next()
this.flow_parseInterfaceish(node, true)
@@ -40,9 +49,7 @@ pp.flow_parseDeclareFunction = function (node) {
typeNode.params = tmp.params
typeNode.rest = tmp.rest
this.expect(tt.parenR)
this.expect(tt.colon)
typeNode.returnType = this.flow_parseType()
typeNode.returnType = this.flow_parseTypeInitialiser()
typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation")
id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation")
@@ -153,15 +160,7 @@ pp.flow_parseTypeAlias = function (node) {
node.typeParameters = null
}
var oldInType = this.inType;
this.inType = true;
this.expect(tt.eq)
node.right = this.flow_parseType()
this.inType = oldInType;
node.right = this.flow_parseTypeInitialiser(tt.eq)
this.semicolon()
return this.finishNode(node, "TypeAlias")
@@ -214,11 +213,9 @@ pp.flow_parseObjectTypeIndexer = function (node, isStatic) {
this.expect(tt.bracketL)
node.id = this.flow_parseObjectPropertyKey()
this.expect(tt.colon)
node.key = this.flow_parseType()
node.key = this.flow_parseTypeInitialiser()
this.expect(tt.bracketR)
this.expect(tt.colon)
node.value = this.flow_parseType()
node.value = this.flow_parseTypeInitialiser()
this.flow_objectTypeSemicolon()
return this.finishNode(node, "ObjectTypeIndexer")
@@ -245,8 +242,7 @@ pp.flow_parseObjectTypeMethodish = function (node) {
node.rest = this.flow_parseFunctionTypeParam()
}
this.expect(tt.parenR)
this.expect(tt.colon)
node.returnType = this.flow_parseType()
node.returnType = this.flow_parseTypeInitialiser()
return this.finishNode(node, "FunctionTypeAnnotation")
}
@@ -265,7 +261,7 @@ pp.flow_parseObjectTypeCallProperty = function (node, isStatic) {
var valueNode = this.startNode()
node.static = isStatic
node.value = this.flow_parseObjectTypeMethodish(valueNode)
this.flow_objectTypeSemicolon()
this.flow_objectTypeSemicolon()
return this.finishNode(node, "ObjectTypeCallProperty")
}
@@ -310,9 +306,8 @@ pp.flow_parseObjectType = function (allowStatic) {
if (this.eat(tt.question)) {
optional = true
}
this.expect(tt.colon)
node.key = propertyKey
node.value = this.flow_parseType()
node.value = this.flow_parseTypeInitialiser()
node.optional = optional
node.static = isStatic
this.flow_objectTypeSemicolon()
@@ -352,12 +347,6 @@ pp.flow_parseGenericType = function (start, id) {
return this.finishNode(node, "GenericTypeAnnotation")
}
pp.flow_parseVoidType = function () {
var node = this.startNode()
this.expect(tt._void)
return this.finishNode(node, "VoidTypeAnnotation")
}
pp.flow_parseTypeofType = function () {
var node = this.startNode()
this.expect(tt._typeof)
@@ -386,9 +375,8 @@ pp.flow_parseFunctionTypeParam = function () {
if (this.eat(tt.question)) {
optional = true
}
this.expect(tt.colon)
node.optional = optional
node.typeAnnotation = this.flow_parseType()
node.typeAnnotation = this.flow_parseTypeInitialiser()
return this.finishNode(node, "FunctionTypeParam")
}
@@ -411,6 +399,9 @@ pp.flow_identToTypeAnnotation = function (start, node, id) {
case "any":
return this.finishNode(node, "AnyTypeAnnotation")
case "void":
return this.finishNode(node, "VoidTypeAnnotation")
case "bool":
case "boolean":
return this.finishNode(node, "BooleanTypeAnnotation")
@@ -524,14 +515,8 @@ pp.flow_parsePrimaryType = function () {
return this.finishNode(node, "StringLiteralTypeAnnotation")
default:
if (this.type.keyword) {
switch (this.type.keyword) {
case "void":
return this.flow_parseVoidType()
case "typeof":
return this.flow_parseTypeofType()
}
if (this.type.keyword === "typeof") {
return this.flow_parseTypeofType()
}
}
@@ -588,13 +573,7 @@ pp.flow_parseType = function () {
pp.flow_parseTypeAnnotation = function () {
var node = this.startNode()
var oldInType = this.inType
this.inType = true
this.expect(tt.colon)
node.typeAnnotation = this.flow_parseType()
this.inType = oldInType
node.typeAnnotation = this.flow_parseTypeInitialiser()
return this.finishNode(node, "TypeAnnotation")
}
@@ -694,6 +673,18 @@ acorn.plugins.flow = function (instance) {
}
})
// don't consider `void` to be a keyword as then it'll use the void token type
// and set startExpr
instance.extend("isKeyword", function (inner) {
return function(name) {
if (this.inType && name === "void") {
return false
} else {
return inner.call(this, name)
}
}
})
instance.extend("readToken", function (inner) {
return function(code) {
if (this.inType && (code === 62 || code === 60)) {

View File

@@ -432,9 +432,18 @@ pp.parseParenAndDistinguishExpression = function(start, isAsync, canBeArrow) {
}
let innerStart = this.markPosition(), exprList = [], first = true
let refShorthandDefaultPos = {start: 0}, spreadStart, innerParenStart
let refShorthandDefaultPos = {start: 0}, spreadStart, innerParenStart, optionalCommaStart
while (this.type !== tt.parenR) {
first ? first = false : this.expect(tt.comma)
if (first) {
first = false;
} else {
this.expect(tt.comma)
if (this.type === tt.parenR && this.options.features["es7.trailingFunctionCommas"]) {
optionalCommaStart = this.start
break
}
}
if (this.type === tt.ellipsis) {
let spreadNodeStart = this.markPosition()
spreadStart = this.start
@@ -462,6 +471,7 @@ pp.parseParenAndDistinguishExpression = function(start, isAsync, canBeArrow) {
this.unexpected(this.lastTokStart)
}
}
if (optionalCommaStart) this.unexpected(optionalCommaStart)
if (spreadStart) this.unexpected(spreadStart)
if (refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start)

View File

@@ -19,7 +19,11 @@ var STATE_KEYS = [
"exprAllowed",
"potentialArrowAt",
"currLine",
"input"
"input",
"inType",
"inFunction",
"inGenerator",
"labels"
];
pp.getState = function () {
@@ -29,6 +33,7 @@ pp.getState = function () {
state[key] = this[key]
}
state.context = this.context.slice()
state.labels = this.labels.slice()
return state
};

View File

@@ -4,11 +4,11 @@ import {lineBreak} from "./whitespace"
export function Parser(options, input, startPos) {
this.options = options
this.loadPlugins(this.options.plugins)
this.sourceFile = this.options.sourceFile || null
this.isKeyword = keywords[this.options.ecmaVersion >= 6 ? 6 : 5]
this.isReservedWord = reservedWords[this.options.ecmaVersion]
this.input = input
this.loadPlugins(this.options.plugins)
// Set up token state

View File

@@ -112,7 +112,7 @@ kw("case", beforeExpr)
kw("catch")
kw("continue")
kw("debugger")
kw("default")
kw("default", beforeExpr)
kw("do", {isLoop: true})
kw("else", beforeExpr)
kw("finally")

View File

@@ -1,6 +1,7 @@
import path from "path";
import fs from "fs";
import homeOrTmp from "home-or-tmp";
import pathExists from "path-exists";
const FILENAME = process.env.BABEL_CACHE_PATH || path.join(homeOrTmp, ".babel.json");
var data = {};
@@ -15,7 +16,7 @@ export function load() {
process.on("exit", save);
process.nextTick(save);
if (!fs.existsSync(FILENAME)) return;
if (!pathExists.sync(FILENAME)) return;
try {
data = JSON.parse(fs.readFileSync(FILENAME));

View File

@@ -54,9 +54,10 @@ export default class Buffer {
this.space();
}
space() {
if (this.format.compact) return;
if (this.buf && !this.isLast(" ") && !this.isLast("\n")) {
space(force?) {
if (!force && this.format.compact) return;
if (force || this.buf && !this.isLast(" ") && !this.isLast("\n")) {
this.push(" ");
}
}
@@ -155,8 +156,12 @@ export default class Buffer {
this.buf += str;
}
endsWith(str) {
return this.buf.slice(-str.length) === str;
endsWith(str, buf = this.buf) {
if (str.length === 1) {
return buf[buf.length - 1] === str;
} else {
return buf.slice(-str.length) === str;
}
}
isLast(cha) {

View File

@@ -1,5 +1,5 @@
export function ClassDeclaration(node, print) {
print.list(node.decorators);
print.list(node.decorators, { separator: "" });
this.push("class");
if (node.id) {
@@ -43,7 +43,7 @@ export function ClassBody(node, print) {
export function ClassProperty(node, print) {
print.list(node.decorators);
print.list(node.decorators, { separator: "" });
if (node.static) this.push("static ");
print.plain(node.key);
@@ -58,7 +58,7 @@ export function ClassProperty(node, print) {
}
export function MethodDefinition(node, print) {
print.list(node.decorators);
print.list(node.decorators, { separator: "" });
if (node.static) {
this.push("static ");

View File

@@ -2,19 +2,19 @@ import isNumber from "lodash/lang/isNumber";
import * as t from "../../types";
export function UnaryExpression(node, print) {
var hasSpace = /[a-z]$/.test(node.operator);
var needsSpace = /[a-z]$/.test(node.operator);
var arg = node.argument;
if (t.isUpdateExpression(arg) || t.isUnaryExpression(arg)) {
hasSpace = true;
needsSpace = true;
}
if (t.isUnaryExpression(arg) && arg.operator === "!") {
hasSpace = false;
needsSpace = false;
}
this.push(node.operator);
if (hasSpace) this.push(" ");
if (needsSpace) this.push(" ");
print.plain(node.argument);
}
@@ -24,6 +24,12 @@ export function DoExpression(node, print) {
print.plain(node.body);
}
export function ParenthesizedExpression(node, print) {
this.push("(");
print.plain(node.expression);
this.push(")");
}
export function UpdateExpression(node, print) {
if (node.prefix) {
this.push(node.operator);
@@ -77,19 +83,16 @@ export function CallExpression(node, print) {
this.push("(");
var separator = ",";
var isPrettyCall = node._prettyCall && !this.format.retainLines;
var isPrettyCall = node._prettyCall && !this.format.retainLines && !this.format.compact;
var separator;
if (isPrettyCall) {
separator += "\n";
separator = ",\n";
this.newline();
this.indent();
} else {
separator += " ";
}
print.list(node.arguments, { separator: separator });
print.list(node.arguments, { separator });
if (isPrettyCall) {
this.newline();
@@ -135,9 +138,23 @@ export function AssignmentPattern(node, print) {
export function AssignmentExpression(node, print) {
// todo: add cases where the spaces can be dropped when in compact mode
print.plain(node.left);
this.push(" ");
var spaces = node.operator === "in" || node.operator === "instanceof";
spaces = true; // todo: https://github.com/babel/babel/issues/1835
this.space(spaces);
this.push(node.operator);
this.push(" ");
if (!spaces) {
// space is mandatory to avoid outputting <!--
// http://javascript.spec.whatwg.org/#comment-syntax
spaces = node.operator === "<" &&
t.isUnaryExpression(node.right, { prefix: true, operator: "!" }) &&
t.isUnaryExpression(node.right.argument, { prefix: true, operator: "--" });
}
this.space(spaces);
print.plain(node.right);
}

View File

@@ -42,7 +42,7 @@ export function _method(node, print) {
}
this._params(value, print);
this.push(" ");
this.space();
print.plain(value.body);
}

View File

@@ -33,13 +33,13 @@ export function ForStatement(node, print) {
this.push(";");
if (node.test) {
this.push(" ");
this.space();
print.plain(node.test);
}
this.push(";");
if (node.update) {
this.push(" ");
this.space();
print.plain(node.update);
}
@@ -190,16 +190,29 @@ export function VariableDeclaration(node, print, parent) {
}
}
var sep = ",";
//
// use a pretty separator when we aren't in compact mode, have initializers and don't have retainLines on
// this will format declarations like:
//
// var foo = "bar", bar = "foo";
//
// into
//
// var foo = "bar",
// bar = "foo";
//
var sep;
if (!this.format.compact && !this.format.concise && hasInits && !this.format.retainLines) {
sep += `\n${repeating(" ", node.kind.length + 1)}`;
} else {
sep += " ";
sep = `,\n${repeating(" ", node.kind.length + 1)}`;
}
//
print.list(node.declarations, { separator: sep });
if (t.isFor(parent)) {
// don't give semicolons to these nodes since they'll be inserted in the parent generator
if (parent.left === node || parent.init === node) return;
}

View File

@@ -33,6 +33,8 @@ export function ObjectExpression(node, print) {
export { ObjectExpression as ObjectPattern };
export function Property(node, print) {
print.list(node.decorators, { separator: "" });
if (node.method || node.kind === "get" || node.kind === "set") {
this._method(node, print);
} else {
@@ -80,7 +82,7 @@ export function ArrayExpression(node, print) {
// both (all) of the holes.
this.push(",");
} else {
if (i > 0) this.push(" ");
if (i > 0) this.space();
print.plain(elem);
if (i < len - 1) this.push(",");
}

View File

@@ -57,34 +57,16 @@ class CodeGenerator {
return format;
}
static findCommonStringDelimiter(code, tokens) {
var occurences = {
single: 0,
double: 0
};
var checked = 0;
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (token.type.label !== "string") continue;
var raw = code.slice(token.start, token.end);
if (raw[0] === "'") {
occurences.single++;
} else {
occurences.double++;
}
checked++;
if (checked >= 3) break;
static findCommonStringDelimiter(code, tokens, occurences = {"'": 0, "\"": 0}) {
if (tokens.length === 0 || occurences["'"] + occurences["\""] >= 3) {
return occurences["'"] > occurences["\""] ? "single" : "double";
}
if (occurences.single > occurences.double) {
return "single";
} else {
return "double";
if (tokens[0].type.label === "string") {
occurences[code[tokens[0].start]]++;
}
return this.findCommonStringDelimiter(code, tokens.slice(1), occurences);
}
static generators = {
@@ -128,8 +110,7 @@ class CodeGenerator {
// catch up to this nodes newline if we're behind
if (node.loc && this.format.retainLines && this.buffer.buf) {
var needsParens = false;
if (!leftParenPrinted && parent &&
this.position.line < node.loc.start.line && t.isTerminatorless(parent)) {
if (!leftParenPrinted && parent && this.position.line < node.loc.start.line && t.isTerminatorless(parent)) {
needsParens = true;
this._push("(");
}

View File

@@ -18,7 +18,11 @@ export default class NodePrinter {
}
list(items, opts = {}) {
if (opts.separator == null) opts.separator = ", ";
if (opts.separator == null) {
opts.separator = ",";
if (!this.generator.format.compact) opts.separator += " ";
}
return this.join(items, opts);
}

View File

@@ -1,7 +1,7 @@
import * as util from "util";
export const MESSAGES = {
tailCallReassignmentDeopt: "Function reference has been reassigned so it's probably be dereferenced so we can't optimise this with confidence",
tailCallReassignmentDeopt: "Function reference has been reassigned, so it will probably be dereferenced, therefore we can't optimise this with confidence",
JSXNamespacedTags: "Namespace tags are not supported. ReactJSX is not XML.",
classesIllegalBareSuper: "Illegal use of bare super",
classesIllegalSuperCall: "Direct super call is illegal in non-constructor, use super.$1() instead",
@@ -17,7 +17,7 @@ export const MESSAGES = {
missingTemplatesDirectory: "no templates directory - this is most likely the result of a broken `npm publish`. Please report to https://github.com/babel/babel/issues",
unsupportedOutputType: "Unsupported output type $1",
illegalMethodName: "Illegal method name $1",
lostTrackNodePath: "We lost track of this nodes position, likely because the AST was directly manipulated",
lostTrackNodePath: "We lost track of this node's position, likely because the AST was directly manipulated",
modulesIllegalExportName: "Illegal export $1",
modulesDuplicateDeclarations: "Duplicate module declarations with the same source but in different scopes",
@@ -26,7 +26,7 @@ export const MESSAGES = {
undeclaredVariableType: "Referencing a type alias outside of a type annotation",
undeclaredVariableSuggestion: "Reference to undeclared variable $1 - did you mean $2?",
traverseNeedsParent: "Must pass a scope and parentPath unless traversing a Program/File got a $1 node",
traverseNeedsParent: "You must pass a scope and parentPath unless traversing a Program/File got a $1 node",
traverseVerifyRootFunction: "You passed `traverse()` a function when it expected a visitor object, are you sure you didn't mean `{ enter: Function }`?",
traverseVerifyVisitorProperty: "You passed `traverse()` a visitor object with the property $1 that has the invalid property $2",
traverseVerifyNodeType: "You gave us a visitor for the node type $1 but it's not a valid type",
@@ -37,7 +37,7 @@ export const MESSAGES = {
pluginNotTransformer: "The plugin $1 didn't export a Plugin instance",
pluginUnknown: "Unknown plugin $1",
pluginNotFile: "Plugin $1 is resolving to a different Babel version to what is doing the actual transformation..."
pluginNotFile: "Plugin $1 is resolving to a different Babel version than what is performing the transformation."
};
export function get(key: String, ...args) {

View File

@@ -0,0 +1,9 @@
import path from "path";
var root = path.resolve(__dirname, "../../../");
export default function (module) {
if (module.parent && module.parent.filename.indexOf(root) !== 0) {
throw new Error("Don't hotlink internal Babel files.");
}
}

View File

@@ -4,6 +4,8 @@ import buildDebug from "debug/node";
var verboseDebug = buildDebug("babel:verbose");
var generalDebug = buildDebug("babel");
var seenDeprecatedMessages = [];
export default class Logger {
constructor(file: File, filename: string) {
this.filename = filename;
@@ -25,9 +27,17 @@ export default class Logger {
}
deprecate(msg) {
if (!this.file.opts.suppressDeprecationMessages) {
console.error(this._buildMessage(msg));
}
if (this.file.opts.suppressDeprecationMessages) return;
msg = this._buildMessage(msg);
// already seen this message
if (seenDeprecatedMessages.indexOf(msg) >= 0) return;
// make sure we don't see it again
seenDeprecatedMessages.push(msg);
console.error(msg);
}
verbose(msg: string) {

View File

@@ -3,16 +3,15 @@ import { normaliseOptions } from "./index";
import merge from "../../../helpers/merge";
import path from "path";
import fs from "fs";
import pathExists from "path-exists";
var cache = {};
var jsons = {};
function exists(filename) {
if (!fs.existsSync) return false;
var cached = cache[filename];
if (cached != null) return cached;
return cache[filename] = fs.existsSync(filename);
return cache[filename] = pathExists.sync(filename);
}
export default function (loc, opts = {}) {

View File

@@ -33,8 +33,7 @@ var hoistVariablesVisitor = {
}
// for (var i in test)
// for (var i = 0;;)
if (t.isFor(parent) && (parent.left === node || parent.init === node)) {
if (t.isFor(parent) && parent.left === node) {
return node.declarations[0].id;
}
@@ -78,6 +77,7 @@ export default class SystemFormatter extends AMDFormatter {
constructor(file) {
super(file);
this._setters = null;
this.exportIdentifier = file.scope.generateUidIdentifier("export");
this.noInteropRequireExport = true;
this.noInteropRequireImport = true;
@@ -178,11 +178,14 @@ export default class SystemFormatter extends AMDFormatter {
var block = t.blockStatement(program.body);
var setterListNode = this._buildRunnerSetters(block, hoistDeclarators);
this._setters = setterListNode;
var runner = util.template("system", {
MODULE_DEPENDENCIES: t.arrayExpression(this.buildDependencyLiterals()),
EXPORT_IDENTIFIER: this.exportIdentifier,
MODULE_NAME: moduleNameLiteral,
SETTERS: this._buildRunnerSetters(block, hoistDeclarators),
SETTERS: setterListNode,
EXECUTE: t.functionExpression(null, [], block)
}, true);

View File

@@ -1 +1 @@
let VARIABLE_NAME = ARGUMENTS[ARGUMENT_KEY] === undefined ? DEFAULT_VALUE : ARGUMENTS[ARGUMENT_KEY];
let VARIABLE_NAME = ARGUMENTS.length <= ARGUMENT_KEY || ARGUMENTS[ARGUMENT_KEY] === undefined ? DEFAULT_VALUE : ARGUMENTS[ARGUMENT_KEY];

View File

@@ -13,7 +13,7 @@
descriptor.enumerable = true;
descriptor.configurable = true;
descriptor.writable = true;
if ("value" in descriptor || descriptor.initializer) descriptor.writable = true;
if (decorators) {
for (var f = 0; f < decorators.length; f++) {

View File

@@ -1,8 +1,18 @@
(function (obj, key, value) {
return Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
// Shortcircuit the slow defineProperty path when possible.
// We are trying to avoid issues where setters defined on the
// prototype cause side effects under the fast path of simple
// assignment. By checking for existence of the property with
// the in operator, we can optimize most of this overhead away.
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
});

View File

@@ -1,7 +1,7 @@
(function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
(function () {
// Broken out into a separate function to avoid deoptimizations due to the try/catch for the
// array iterator case.
function sliceIterator(arr, i) {
// this is an expanded form of `for...of` that properly supports abrupt completions of
// iterators etc. variable names have been minimised to reduce the size of this massive
// helper. sometimes spec compliancy is annoying :(
@@ -32,7 +32,15 @@
}
}
return _arr;
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
});
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
})();

View File

@@ -8,5 +8,8 @@
"utility.inlineExpressions": "minification.constantFolding",
"utility.deadCodeElimination": "minification.deadCodeElimination",
"utility.removeConsoleCalls": "minification.removeConsole",
"utility.removeDebugger": "minification.removeDebugger"
"utility.removeDebugger": "minification.removeDebugger",
"es6.parameters.rest": "es6.parameters",
"es6.parameters.default": "es6.parameters"
}

View File

@@ -162,6 +162,7 @@ var hoistVarDeclarationsVisitor = {
} else if (this.isFor()) {
if (isVar(node.left, node)) {
node.left = node.left.declarations[0].id;
self.pushDeclar(node.left);
}
} else if (isVar(node, parent)) {
return self.pushDeclar(node).map(t.expressionStatement);

View File

@@ -0,0 +1,23 @@
import LooseTransformer from "./loose";
import VanillaTransformer from "./vanilla";
import * as t from "../../../../types";
import { bare } from "../../../helpers/name-method";
export var visitor = {
ClassDeclaration(node) {
return t.variableDeclaration("let", [
t.variableDeclarator(node.id, t.toExpression(node))
]);
},
ClassExpression(node, parent, scope, file) {
var inferred = bare(node, parent, scope);
if (inferred) return inferred;
if (file.isLoose("es6.classes")) {
return new LooseTransformer(this, file).run();
} else {
return new VanillaTransformer(this, file).run();
}
}
};

View File

@@ -0,0 +1,24 @@
import VanillaTransformer from "./vanilla";
import * as t from "../../../../types";
export default class LooseClassTransformer extends VanillaTransformer {
constructor() {
super(...arguments);
this.isLoose = true;
}
_processMethod(node) {
if (!node.decorators) {
// use assignments instead of define properties for loose classes
var classRef = this.classRef;
if (!node.static) classRef = t.memberExpression(classRef, t.identifier("prototype"));
var methodName = t.memberExpression(classRef, node.key, node.computed || t.isLiteral(node.key));
var expr = t.expressionStatement(t.assignmentExpression("=", methodName, node.value));
t.inheritsComments(expr, node);
this.body.push(expr);
return true;
}
}
}

View File

@@ -1,27 +1,15 @@
import type NodePath from "../../../traversal/path";
import type File from "../../file";
import memoiseDecorators from "../../helpers/memoise-decorators";
import ReplaceSupers from "../../helpers/replace-supers";
import * as nameMethod from "../../helpers/name-method";
import * as defineMap from "../../helpers/define-map";
import * as messages from "../../../messages";
import * as util from "../../../util";
import * as t from "../../../types";
import type NodePath from "../../../../traversal/path";
import type File from "../../../file";
import memoiseDecorators from "../../../helpers/memoise-decorators";
import ReplaceSupers from "../../../helpers/replace-supers";
import * as nameMethod from "../../../helpers/name-method";
import * as defineMap from "../../../helpers/define-map";
import * as messages from "../../../../messages";
import * as util from "../../../../util";
import * as t from "../../../../types";
const PROPERTY_COLLISION_METHOD_NAME = "__initializeProperties";
export var visitor = {
ClassDeclaration(node) {
return t.variableDeclaration("let", [
t.variableDeclarator(node.id, t.toExpression(node))
]);
},
ClassExpression(node, parent, scope, file) {
return new ClassTransformer(this, file).run();
}
};
var collectPropertyReferencesVisitor = {
Identifier: {
enter(node, parent, scope, state) {
@@ -37,16 +25,12 @@ var collectPropertyReferencesVisitor = {
};
var verifyConstructorVisitor = {
MethodDefinition: {
enter() {
this.skip();
}
MethodDefinition() {
this.skip();
},
Property: {
enter(node) {
if (node.method) this.skip();
}
Property(node) {
if (node.method) this.skip();
},
CallExpression: {
@@ -55,35 +39,45 @@ var verifyConstructorVisitor = {
state.hasBareSuper = true;
state.bareSuper = this;
if (!state.hasSuper) {
if (!state.isDerived) {
throw this.errorWithNode("super call is only allowed in derived constructor");
}
}
}
},
FunctionDeclaration: {
enter() {
this.skip();
}
"FunctionDeclaration|FunctionExpression"() {
this.skip();
},
FunctionExpression: {
enter() {
this.skip();
}
},
ThisExpression(node, parent, scope, state) {
if (state.isDerived && !state.hasBareSuper) {
if (this.inShadow()) {
// https://github.com/babel/babel/issues/1920
var thisAlias = state.constructorPath.getData("this");
ThisExpression: {
enter(node, parent, scope, state) {
if (state.hasSuper && !state.hasBareSuper) {
if (!thisAlias) {
thisAlias = state.constructorPath.setData(
"this",
state.constructorPath.scope.generateUidIdentifier("this")
);
}
return thisAlias;
} else {
throw this.errorWithNode("'this' is not allowed before super()");
}
}
},
Super(node, parent, scope, state) {
if (state.isDerived && !state.hasBareSuper && !this.parentPath.isCallExpression({ callee: node })) {
throw this.errorWithNode("'super.*' is not allowed before super()");
}
}
};
class ClassTransformer {
export default class ClassTransformer {
/**
* Description
@@ -96,26 +90,29 @@ class ClassTransformer {
this.path = path;
this.file = file;
this.hasInstanceDescriptors = false;
this.hasStaticDescriptors = false;
this.instanceMutatorMap = {};
this.staticMutatorMap = {};
this.clearDescriptors();
this.instancePropBody = [];
this.instancePropRefs = {};
this.staticPropBody = [];
this.body = [];
this.hasConstructor = false;
this.hasDecorators = false;
this.className = this.node.id;
this.classRef = this.node.id || this.scope.generateUidIdentifier("class");
this.pushedConstructor = false;
this.pushedInherits = false;
this.hasDecorators = false;
this.isLoose = false;
// class id
this.classId = this.node.id;
// this is the name of the binding that will **always** reference the class we've constructed
this.classRef = this.node.id || this.scope.generateUidIdentifier("class");
// this is a direct reference to the class we're building, class decorators can shadow the classRef
this.directRef = null;
this.superName = this.node.superClass || t.identifier("Function");
this.hasSuper = !!this.node.superClass;
this.isLoose = file.isLoose("es6.classes");
this.isDerived = !!this.node.superClass;
}
/**
@@ -126,7 +123,6 @@ class ClassTransformer {
run() {
var superName = this.superName;
var classRef = this.classRef;
var file = this.file;
//
@@ -136,16 +132,7 @@ class ClassTransformer {
//
var constructorBody = this.constructorBody = t.blockStatement([]);
var constructor;
if (this.className) {
constructor = t.functionDeclaration(this.className, [], constructorBody);
body.push(constructor);
} else {
constructor = t.functionExpression(null, [], constructorBody);
}
this.constructor = constructor;
this.constructor = this.buildConstructor();
//
@@ -153,26 +140,22 @@ class ClassTransformer {
var closureArgs = [];
//
if (this.hasSuper) {
if (this.isDerived) {
closureArgs.push(superName);
superName = this.scope.generateUidIdentifierBasedOnNode(superName);
closureParams.push(superName);
this.superName = superName;
body.push(t.expressionStatement(t.callExpression(file.addHelper("inherits"), [classRef, superName])));
}
//
var decorators = this.node.decorators;
if (decorators) {
// create a class reference to use later on
this.classRef = this.scope.generateUidIdentifier(classRef);
// this is so super calls and the decorators have access to the raw function
body.push(t.variableDeclaration("var", [
t.variableDeclarator(this.classRef, classRef)
]));
this.directRef = this.scope.generateUidIdentifier(this.classRef);
} else {
this.directRef = this.classRef;
}
//
@@ -181,46 +164,21 @@ class ClassTransformer {
// make sure this class isn't directly called
constructorBody.body.unshift(t.expressionStatement(t.callExpression(file.addHelper("class-call-check"), [
t.thisExpression(),
this.classRef
this.directRef
])));
//
if (decorators) {
// reverse the decorators so we execute them in the right order
decorators = decorators.reverse();
for (var i = 0; i < decorators.length; i++) {
var decorator = decorators[i];
var decoratorNode = util.template("class-decorator", {
DECORATOR: decorator.expression,
CLASS_REF: classRef
}, true);
decoratorNode.expression._ignoreModulesRemap = true;
body.push(decoratorNode);
}
}
this.pushDecorators();
body = body.concat(this.staticPropBody);
if (this.className) {
if (this.classId) {
// named class with only a constructor
if (body.length === 1) return t.toExpression(body[0]);
} else {
// infer class name if this is a nameless class expression
constructor = nameMethod.bare(constructor, this.parent, this.scope) || constructor;
body.unshift(t.variableDeclaration("var", [
t.variableDeclarator(classRef, constructor)
]));
t.inheritsComments(body[0], this.node);
}
//
body.push(t.returnStatement(classRef));
body.push(t.returnStatement(this.classRef));
return t.callExpression(
t.functionExpression(null, closureParams, t.blockStatement(body)),
@@ -228,6 +186,14 @@ class ClassTransformer {
);
}
/**
* Description
*/
buildConstructor() {
return t.functionDeclaration(this.classRef, [], this.constructorBody);
}
/**
* Description
*/
@@ -258,23 +224,26 @@ class ClassTransformer {
*/
constructorMeMaybe() {
if (!this.hasSuper) return;
var hasConstructor = false;
var paths = this.path.get("body.body");
for (var path of (paths: Array)) {
hasConstructor = path.equals("kind", "constructor");
if (hasConstructor) break;
}
if (hasConstructor) return;
if (!hasConstructor) {
this.path.get("body").unshiftContainer("body", t.methodDefinition(
t.identifier("constructor"),
util.template("class-derived-default-constructor"),
"constructor"
));
var constructor;
if (this.isDerived) {
constructor = util.template("class-derived-default-constructor");
} else {
constructor = t.functionExpression(null, [], t.blockStatement([]));
}
this.path.get("body").unshiftContainer("body", t.methodDefinition(
t.identifier("constructor"),
constructor,
"constructor"
));
}
/**
@@ -283,10 +252,25 @@ class ClassTransformer {
buildBody() {
this.constructorMeMaybe();
this.pushBody();
this.placePropertyInitializers();
var constructorBody = this.constructorBody;
var classBodyPaths = this.path.get("body.body");
var body = this.body;
if (this.userConstructor) {
var constructorBody = this.constructorBody;
constructorBody.body = constructorBody.body.concat(this.userConstructor.body.body);
t.inherits(this.constructor, this.userConstructor);
t.inherits(constructorBody, this.userConstructor.body);
}
this.pushDescriptors();
}
/**
* Description
*/
pushBody() {
var classBodyPaths = this.path.get("body.body");
for (var path of (classBodyPaths: Array)) {
var node = path.node;
@@ -302,7 +286,7 @@ class ClassTransformer {
var replaceSupers = new ReplaceSupers({
methodPath: path,
methodNode: node,
objectRef: this.classRef,
objectRef: this.directRef,
superRef: this.superName,
isStatic: node.static,
isLoose: this.isLoose,
@@ -321,16 +305,28 @@ class ClassTransformer {
this.pushProperty(node, path);
}
}
}
//
this.placePropertyInitializers();
/**
* Description
*/
//
if (this.userConstructor) {
constructorBody.body = constructorBody.body.concat(this.userConstructor.body.body);
t.inherits(this.constructor, this.userConstructor);
t.inherits(this.constructorBody, this.userConstructor.body);
}
clearDescriptors() {
this.hasInstanceDescriptors = false;
this.hasStaticDescriptors = false;
this.instanceMutatorMap = {};
this.staticMutatorMap = {};
}
/**
* Description
*/
pushDescriptors() {
this.pushInherits();
var body = this.body;
var instanceProps;
var staticProps;
@@ -378,8 +374,14 @@ class ClassTransformer {
t.callExpression(this.file.addHelper(classHelper), args)
));
}
this.clearDescriptors();
}
/**
* Description
*/
buildObjectAssignment(id) {
return t.variableDeclaration("var", [
t.variableDeclarator(id, t.objectExpression([]))
@@ -405,18 +407,14 @@ class ClassTransformer {
t.functionExpression(null, [], t.blockStatement(body))
), null, true);
if (this.hasSuper) {
if (this.isDerived) {
this.bareSuper.insertAfter(call);
} else {
this.constructorBody.body.unshift(call);
}
} else {
if (this.hasSuper) {
if (this.hasConstructor) {
this.bareSuper.insertAfter(body);
} else {
this.constructorBody.body = this.constructorBody.body.concat(body);
}
if (this.isDerived) {
this.bareSuper.insertAfter(body);
} else {
this.constructorBody.body = body.concat(this.constructorBody.body);
}
@@ -437,7 +435,7 @@ class ClassTransformer {
}
return false;
}
}
/**
* Description
@@ -445,17 +443,25 @@ class ClassTransformer {
verifyConstructor(path: NodePath) {
var state = {
hasBareSuper: false,
bareSuper: null,
hasSuper: this.hasSuper,
file: this.file
constructorPath: path.get("value"),
hasBareSuper: false,
bareSuper: null,
isDerived: this.isDerived,
file: this.file,
};
path.get("value").traverse(verifyConstructorVisitor, state);
state.constructorPath.traverse(verifyConstructorVisitor, state);
var thisAlias = state.constructorPath.getData("this");
if (thisAlias && state.bareSuper) {
state.bareSuper.insertAfter(t.variableDeclaration("var", [
t.variableDeclarator(thisAlias, t.thisExpression())
]));
}
this.bareSuper = state.bareSuper;
if (!state.hasBareSuper && this.hasSuper) {
if (!state.hasBareSuper && this.isDerived) {
throw path.errorWithNode("Derived constructor must call super()");
}
}
@@ -471,24 +477,16 @@ class ClassTransformer {
if (node.kind === "method") {
nameMethod.property(node, this.file, path ? path.get("value").scope : this.scope);
if (this.isLoose && !node.decorators) {
// use assignments instead of define properties for loose classes
var classRef = this.classRef;
if (!node.static) classRef = t.memberExpression(classRef, t.identifier("prototype"));
var methodName = t.memberExpression(classRef, node.key, node.computed || t.isLiteral(node.key));
var expr = t.expressionStatement(t.assignmentExpression("=", methodName, node.value));
t.inheritsComments(expr, node);
this.body.push(expr);
return;
}
if (this._processMethod(node)) return;
}
this.pushToMap(node);
}
_processMethod() {
return false;
}
/**
* Description
*/
@@ -568,5 +566,61 @@ class ClassTransformer {
construct.params = fn.params;
t.inherits(construct.body, fn.body);
// push constructor to body
this._pushConstructor();
}
_pushConstructor() {
if (this.pushedConstructor) return;
this.pushedConstructor = true;
// we haven't pushed any descriptors yet
if (this.hasInstanceDescriptors || this.hasStaticDescriptors) {
this.pushDescriptors();
}
this.body.push(this.constructor);
this.pushInherits();
}
/**
* Push inherits helper to body.
*/
pushInherits() {
if (!this.isDerived || this.pushedInherits) return;
this.pushedInherits = true;
this.body.push(t.expressionStatement(t.callExpression(
this.file.addHelper("inherits"),
[this.classRef, this.superName]
)));
}
/**
* Push decorators to body.
*/
pushDecorators() {
var decorators = this.node.decorators;
if (!decorators) return;
this.body.push(t.variableDeclaration("var", [
t.variableDeclarator(this.directRef, this.classRef)
]));
// reverse the decorators so we execute them in the right order
decorators = decorators.reverse();
for (var decorator of (decorators: Array)) {
var decoratorNode = util.template("class-decorator", {
DECORATOR: decorator.expression,
CLASS_REF: this.classRef
}, true);
decoratorNode.expression._ignoreModulesRemap = true;
this.body.push(decoratorNode);
}
}
}

View File

@@ -70,7 +70,15 @@ export var visitor = {
let pattern = node.params[i];
if (!t.isPattern(pattern)) continue;
var ref = node.params[i] = scope.generateUidIdentifier("ref");
var ref = scope.generateUidIdentifier("ref");
if (t.isAssignmentPattern(pattern)) {
var _pattern = pattern;
pattern = pattern.left;
_pattern.left = ref;
} else {
node.params[i] = ref;
}
t.inherits(ref, pattern);
var destructuring = new DestructuringTransformer({
@@ -308,9 +316,12 @@ class DestructuringTransformer {
var left = pattern.left;
if (t.isPattern(left)) {
this.nodes.push(t.expressionStatement(
var tempValueDefault = t.expressionStatement(
t.assignmentExpression("=", tempValueRef, tempConditional)
));
);
tempValueDefault._blockHoist = this.blockHoist;
this.nodes.push(tempValueDefault);
this.push(left, tempValueRef);
} else {
this.nodes.push(this.buildVariableAssignment(left, tempConditional));

View File

@@ -1,7 +1,7 @@
import callDelegate from "../../helpers/call-delegate";
import getFunctionArity from "../../helpers/get-function-arity";
import * as util from "../../../util";
import * as t from "../../../types";
import callDelegate from "../../../helpers/call-delegate";
import getFunctionArity from "../../../helpers/get-function-arity";
import * as util from "../../../../util";
import * as t from "../../../../types";
var hasDefaults = function (node) {
for (var i = 0; i < node.params.length; i++) {
@@ -38,7 +38,7 @@ export var visitor = {
//
var argsIdentifier = t.identifier("arguments");
argsIdentifier._shadowedFunctionLiteral = true;
argsIdentifier._shadowedFunctionLiteral = this;
// push a default parameter definition
function pushDefNode(left, right, i) {

View File

@@ -0,0 +1,10 @@
import * as visitors from "../../../../traversal/visitors";
import * as def from "./default";
import * as rest from "./rest";
export var metadata = {
group: "builtin-advanced"
};
export var visitor = visitors.merge([rest.visitor, def.visitor]);

View File

@@ -1,5 +1,5 @@
import * as util from "../../../util";
import * as t from "../../../types";
import * as util from "../../../../util";
import * as t from "../../../../types";
var memberExpressionOptimisationVisitor = {
Scope(node, parent, scope, state) {
@@ -9,12 +9,18 @@ var memberExpressionOptimisationVisitor = {
}
},
Flow() {
// don't touch reference in type annotations
this.skip();
},
Function(node, parent, scope, state) {
// skip over functions as whatever `arguments` we reference inside will refer
// to the wrong function
var oldNoOptimise = state.noOptimise;
state.noOptimise = true;
this.traverse(memberExpressionOptimisationVisitor, state);
state.noOptimise = false;
state.noOptimise = oldNoOptimise;
this.skip();
},
@@ -27,7 +33,9 @@ var memberExpressionOptimisationVisitor = {
// is this a referenced identifier and is it referencing the rest parameter?
if (node.name !== state.name) return;
if (!state.noOptimise) {
if (state.noOptimise) {
state.deopted = true;
} else {
if (this.parentPath.isMemberExpression({ computed: true, object: node })) {
// if we know that this member expression is referencing a number then we can safely
// optimise it
@@ -46,11 +54,7 @@ var memberExpressionOptimisationVisitor = {
return;
}
}
}
if (state.noOptimise) {
state.deopted = true;
} else {
state.references.push(this);
}
}
@@ -85,7 +89,7 @@ export var visitor = {
var argsId = t.identifier("arguments");
// otherwise `arguments` will be remapped in arrow functions
argsId._shadowedFunctionLiteral = true;
argsId._shadowedFunctionLiteral = this;
// support patterns
if (t.isPattern(rest)) {
@@ -100,7 +104,6 @@ export var visitor = {
}
// check and optimise for extremely common cases
var state = {
references: [],
offset: node.params.length,
@@ -135,6 +138,9 @@ export var visitor = {
state.references = state.references.concat(state.candidates);
}
// deopt shadowed functions as transforms like regenerator may try touch the allocation loop
state.deopted = state.deopted || !!node.shadow;
//
var start = t.literal(node.params.length);
@@ -173,13 +179,13 @@ export var visitor = {
LEN: len
});
if (!state.deopted) {
if (state.deopted) {
loop._blockHoist = node.params.length + 1;
node.body.body.unshift(loop);
} else {
// perform allocation at the lowest common denominator of all references
loop._blockHoist = 1;
this.getEarliestCommonAncestorFrom(state.references).getStatementParent().insertBefore(loop);
return;
}
loop._blockHoist = node.params.length + 1;
node.body.body.unshift(loop);
}
};

View File

@@ -1,9 +1,7 @@
import * as t from "../../../types";
function loose(node, body, objId) {
for (var i = 0; i < node.properties.length; i++) {
var prop = node.properties[i];
for (var prop of (node.properties: Array)) {
body.push(t.expressionStatement(
t.assignmentExpression(
"=",
@@ -15,31 +13,15 @@ function loose(node, body, objId) {
}
function spec(node, body, objId, initProps, file) {
var props = node.properties;
// add all non-computed properties and `__proto__` properties to the initializer
var broken = false;
for (let i = 0; i < props.length; i++) {
let prop = props[i];
if (prop.computed) {
broken = true;
}
if (prop.kind !== "init" || !broken || t.isLiteral(t.toComputedKey(prop, prop.key), { value: "__proto__" })) {
initProps.push(prop);
props[i] = null;
}
}
// add a simple assignment for all Symbol member expressions due to symbol polyfill limitations
// otherwise use Object.defineProperty
for (let i = 0; i < props.length; i++) {
let prop = props[i];
if (!prop) continue;
for (let prop of (node.properties: Array)) {
// this wont work with Object.defineProperty
if (t.isLiteral(t.toComputedKey(prop), { value: "__proto__" })) {
initProps.push(prop);
continue;
}
let key = prop.key;
if (t.isIdentifier(key) && !prop.computed) {
@@ -68,14 +50,34 @@ export var visitor = {
exit(node, parent, scope, file) {
var hasComputed = false;
for (var prop of (node.properties: Array)) {
for (let prop of (node.properties: Array)) {
hasComputed = t.isProperty(prop, { computed: true, kind: "init" });
if (hasComputed) break;
}
if (!hasComputed) return;
// put all getters/setters into the first object expression as well as all initialisers up
// to the first computed property
var initProps = [];
var stopInits = false;
node.properties = node.properties.filter(function (prop) {
if (prop.computed) {
stopInits = true;
}
if (prop.kind !== "init" || !stopInits) {
initProps.push(prop);
return false;
} else {
return true;
}
});
//
var objId = scope.generateUidIdentifierBasedOnNode(parent);
//

View File

@@ -43,6 +43,10 @@ function build(props, scope) {
return nodes;
}
export var metadata = {
group: "builtin-advanced"
};
export var visitor = {
ArrayExpression(node, parent, scope) {
var elements = node.elements;

View File

@@ -211,7 +211,7 @@ class TailCallTransformer {
var decl = t.variableDeclarator(this.argumentsId);
if (this.argumentsId) {
decl.init = t.identifier("arguments");
decl.init._shadowedFunctionLiteral = true;
decl.init._shadowedFunctionLiteral = this.path;
}
topVars.push(decl);
}
@@ -337,10 +337,6 @@ class TailCallTransformer {
args = t.arrayExpression(node.arguments);
}
if (t.isArrayExpression(args) && args.elements.length > this.node.params.length) {
this.needsArguments = true;
}
var argumentsId = this.getArgumentsId();
var params = this.getParams();
@@ -354,17 +350,30 @@ class TailCallTransformer {
if (t.isArrayExpression(args)) {
var elems = args.elements;
for (let i = 0; i < elems.length && i < params.length; i++) {
// pad out the args so all the function args are reset - https://github.com/babel/babel/issues/1938
while (elems.length < params.length) {
elems.push(t.identifier("undefined"));
}
for (let i = 0; i < elems.length; i++) {
let param = params[i];
let elem = elems[i] || (elems[i] = t.identifier("undefined"));
if (!param._isDefaultPlaceholder) {
let elem = elems[i];
if (param && !param._isDefaultPlaceholder) {
elems[i] = t.assignmentExpression("=", param, elem);
} else {
// exceeds parameters but push it anyway to ensure correct execution
}
}
if (!this.needsArguments) {
for (let elem of (elems: Array)) {
body.push(t.expressionStatement(elem));
// only push expressions that we really need, this will skip pure arguments that exceed the
// parameter length of the current function
if (!this.scope.isPure(elem)) {
body.push(t.expressionStatement(elem));
}
}
}
} else {

View File

@@ -60,20 +60,16 @@ export var visitor = {
if (expr) nodes.push(expr);
}
// filter out empty string literals
nodes = nodes.filter(n => !t.isLiteral(n, { value: "" }));
// since `+` is left-to-right associative
// ensure the first node is a string if first/second isn't
if (!isString(nodes[0]) && !isString(nodes[1])) {
nodes.unshift(t.literal(""));
}
if (nodes.length > 1) {
// filter out empty string literals
nodes = nodes.filter(n => !t.isLiteral(n, { value: "" }));
if (nodes.length === 1 && isString(nodes[0])) {
return nodes[0];
}
// since `+` is left-to-right associative
// ensure the first node is a string if first/second isn't
if (!isString(nodes[0]) && !isString(nodes[1])) {
nodes.unshift(t.literal(""));
}
var root = buildBinaryExpression(nodes.shift(), nodes.shift());
for (let node of (nodes: Array)) {

View File

@@ -46,9 +46,6 @@ export default {
"es6.regex.sticky": require("./es6/regex.sticky"),
"es6.regex.unicode": require("./es6/regex.unicode"),
"es6.constants": require("./es6/constants"),
"es6.parameters.rest": require("./es6/parameters.rest"),
"es6.spread": require("./es6/spread"),
"es6.parameters.default": require("./es6/parameters.default"),
"es7.exportExtensions": require("./es7/export-extensions"),
"spec.protoToAssign": require("babel-plugin-proto-to-assign"),
"es7.doExpressions": require("./es7/do-expressions"),
@@ -57,6 +54,8 @@ export default {
"spec.undefinedToVoid": require("babel-plugin-undefined-to-void"),
//- builtin-advanced
"es6.spread": require("./es6/spread"),
"es6.parameters": require("./es6/parameters"),
"es6.destructuring": require("./es6/destructuring"),
"es6.blockScoping": require("./es6/block-scoping"),
"es6.spec.blockScoping": require("./es6/spec.block-scoping"),
@@ -85,4 +84,5 @@ export default {
_blockHoist: require("./internal/block-hoist"),
jscript: require("babel-plugin-jscript"),
flow: require("./other/flow"),
"optimisation.modules.system": require("./optimisation/modules.system"),
};

View File

@@ -6,9 +6,33 @@ export var metadata = {
function remap(path, key, create) {
// ensure that we're shadowed
if (!path.inShadow()) return;
var shadowPath = path.inShadow();
if (!shadowPath || shadowPath.isArrowFunctionExpression()) return;
var fnPath = path.findParent((path) => !path.is("shadow") && (path.isFunction() || path.isProgram()));
var shadowFunction = path.node._shadowedFunctionLiteral;
var currentFunction;
var fnPath = path.findParent(function (path) {
if (path.isProgram() || path.isFunction()) {
// catch current function in case this is the shadowed one and we can ignore it
currentFunction = currentFunction || path;
}
if (path.isProgram()) {
return true;
} else if (path.isFunction()) {
if (shadowFunction) {
return path === shadowFunction || path.node === shadowFunction.node;
} else {
return !path.is("shadow");
}
}
return false;
});
// no point in realiasing if we're in this function
if (fnPath === currentFunction) return;
var cached = fnPath.getData(key);
if (cached) return cached;
@@ -28,7 +52,7 @@ export var visitor = {
},
ReferencedIdentifier(node) {
if (node.name === "arguments" && !node._shadowedFunctionLiteral) {
if (node.name === "arguments") {
return remap(this, "arguments", () => t.identifier("arguments"));
}
}

View File

@@ -0,0 +1,50 @@
import * as t from "../../../types";
export var metadata = {
optional: true,
group: "builtin-trailing"
};
export var visitor = {
Program(node, parent, scope, file){
if (file.moduleFormatter._setters){
scope.traverse(file.moduleFormatter._setters, optimizeSettersVisitor, {
exportFunctionIdentifier: file.moduleFormatter.exportIdentifier
});
}
}
};
/**
* Setters are optimized to avoid slow export behavior in modules that rely on deep hierarchies
* of export-from declarations.
* More info in https://github.com/babel/babel/pull/1722 and
* https://github.com/ModuleLoader/es6-module-loader/issues/386.
*
* TODO: Ideally this would be optimized during construction of the setters, but the current
* architecture of the module formatters make that difficult.
*/
var optimizeSettersVisitor = {
FunctionExpression: {
enter: (node, parent, scope, state) => {
state.hasExports = false;
state.exportObjectIdentifier = scope.generateUidIdentifier("exportObj");
},
exit: (node, parent, scope, state) => {
if (!state.hasExports) return;
node.body.body.unshift(t.variableDeclaration("var", [
t.variableDeclarator(t.cloneDeep(state.exportObjectIdentifier), t.objectExpression([]))
]));
node.body.body.push(t.expressionStatement(t.callExpression(
t.cloneDeep(state.exportFunctionIdentifier), [t.cloneDeep(state.exportObjectIdentifier)])));
}
},
CallExpression: (node, parent, scope, state) => {
if (!t.isIdentifier(node.callee, {name: state.exportFunctionIdentifier.name})) return;
state.hasExports = true;
var memberNode = t.memberExpression(t.cloneDeep(state.exportObjectIdentifier), node.arguments[0], true);
return t.assignmentExpression("=", memberNode, node.arguments[1]);
}
};

View File

@@ -49,7 +49,9 @@ export var visitor = {
pushElemProp("ref", t.literal(null));
if (node.children.length) {
pushProp(props.properties, t.identifier("children"), t.arrayExpression(react.buildChildren(node)));
var children = react.buildChildren(node);
children = children.length === 1 ? children[0] : t.arrayExpression(children);
pushProp(props.properties, t.identifier("children"), children);
}
// props

View File

@@ -5,6 +5,14 @@ export var metadata = {
};
export var visitor = {
Program(node, parent, scope, file) {
for (var comment of (file.ast.comments: Array)) {
if (comment.value.indexOf("@flow") >= 0) {
comment._displayed = true;
}
}
},
Flow() {
this.dangerouslyRemove();
},

View File

@@ -4,8 +4,24 @@ export var metadata = {
group: "builtin-basic"
};
// visit Property functions first - https://github.com/babel/babel/issues/1860
export var visitor = {
"ArrowFunctionExpression|FunctionExpression": {
exit: bare
exit() {
if (!this.parentPath.isProperty()) {
return bare.apply(this, arguments);
}
}
},
ObjectExpression() {
var props = this.get("properties");
for (var prop of (props: Array)) {
var value = prop.get("value");
if (value.isFunction()) {
var newNode = bare(value.node, prop.node, value.scope);
if (newNode) value.replaceWith(newNode);
}
}
}
};

View File

@@ -2,20 +2,28 @@ import * as t from "../../types";
import NodePath from "./index";
/**
* Description
* Call the provided `callback` with the `NodePath`s of all the parents.
* When the `callback` returns a truthy value, we return that node path.
*/
export function findParent(callback) {
var path = this;
while (path) {
while (path = path.parentPath) {
if (callback(path)) return path;
path = path.parentPath;
}
return null;
}
/**
* Description
* Get the parent function of the current path.
*/
export function getFunctionParent() {
return this.findParent((path) => path.isFunction() || path.isProgram());
}
/**
* Walk up the tree until we hit a parent node path in a list.
*/
export function getStatementParent() {
@@ -139,7 +147,9 @@ export function getDeepestCommonAncestorFrom(paths: Array<NodePath>, filter?: Fu
}
/**
* Description
* Build an array of node paths containing the entire ancestry of the current node path.
*
* NOTE: The current node path is included in this.
*/
export function getAncestry() {
@@ -168,14 +178,14 @@ export function inType() {
}
/**
* Description
* Check if we're inside a shadowed function.
*/
export function inShadow() {
var path = this;
while (path) {
if (path.isFunction()) {
if (path.node.shadow) {
if (path.node.shadow || path.isArrowFunctionExpression()) {
return path;
} else {
return null;

View File

@@ -230,6 +230,7 @@ export function unshiftContext(context) {
*/
export function setup(parentPath, container, listKey, key) {
this.inList = !!listKey;
this.listKey = listKey;
this.parentKey = listKey || key;
this.container = container;

View File

@@ -1,3 +1,4 @@
import type TraversalContext from "../index";
import NodePath from "./index";
import * as t from "../../types";
@@ -39,7 +40,7 @@ export function getOpposite() {
* Description
*/
export function getCompletionRecords(): Array<NodePath> {
export function getCompletionRecords(): Array {
var paths = [];
var add = function (path) {
@@ -80,12 +81,13 @@ export function getSibling(key) {
* Description
*/
export function get(key: string): NodePath {
export function get(key: string, context?: boolean | TraversalContext): NodePath {
if (context === true) context = this.context;
var parts = key.split(".");
if (parts.length === 1) { // "foo"
return this._getKey(key);
return this._getKey(key, context);
} else { // "foo.bar"
return this._getPattern(parts);
return this._getPattern(parts, context);
}
}
@@ -93,7 +95,7 @@ export function get(key: string): NodePath {
* Description
*/
export function _getKey(key) {
export function _getKey(key, context?) {
var node = this.node;
var container = node[key];
@@ -106,7 +108,7 @@ export function _getKey(key) {
parent: node,
container: container,
key: i
}).setContext();
}).setContext(context);
});
} else {
return NodePath.get({
@@ -114,7 +116,7 @@ export function _getKey(key) {
parent: node,
container: node,
key: key
}).setContext();
}).setContext(context);
}
}
@@ -122,7 +124,7 @@ export function _getKey(key) {
* Description
*/
export function _getPattern(parts) {
export function _getPattern(parts, context) {
var path = this;
for (var part of (parts: Array)) {
if (part === ".") {
@@ -131,7 +133,7 @@ export function _getPattern(parts) {
if (Array.isArray(path)) {
path = path[part];
} else {
path = path.get(part);
path = path.get(part, context);
}
}
}
@@ -142,6 +144,6 @@ export function _getPattern(parts) {
* Description
*/
export function getBindingIdentifiers() {
return t.getBindingIdentifiers(this.node);
export function getBindingIdentifiers(duplicates?) {
return t.getBindingIdentifiers(this.node, duplicates);
}

View File

@@ -21,6 +21,7 @@ export default class NodePath {
this.context = null;
this.container = null;
this.listKey = null;
this.inList = false;
this.parentKey = null;
this.key = null;
this.node = null;

View File

@@ -1,3 +1,4 @@
import type NodePath from "./index";
import * as inferers from "./inferers";
import * as t from "../../../types";
@@ -61,9 +62,11 @@ export function _getTypeAnnotation(): ?Object {
* Description
*/
export function isBaseType(baseName: string): boolean {
var type = this.getTypeAnnotation();
export function isBaseType(baseName: string, soft?): boolean {
return _isBaseType(baseName, this.getTypeAnnotation(), soft);
}
function _isBaseType(baseName: string, type?, soft?): boolean {
if (baseName === "string") {
return t.isStringTypeAnnotation(type);
} else if (baseName === "number") {
@@ -74,8 +77,47 @@ export function isBaseType(baseName: string): boolean {
return t.isAnyTypeAnnotation(type);
} else if (baseName === "mixed") {
return t.isMixedTypeAnnotation(type);
} else if (baseName === "void") {
return t.isVoidTypeAnnotation(type);
} else {
throw new Error(`Unknown base type ${baseName}`);
if (soft) {
return false;
} else {
throw new Error(`Unknown base type ${baseName}`);
}
}
}
/**
* Description
*/
export function couldBeBaseType(name: string): boolean {
var type = this.getTypeAnnotation();
if (t.isAnyTypeAnnotation(type)) return true;
if (t.isUnionTypeAnnotation(type)) {
for (var type2 of (type.types: Array)) {
if (t.isAnyTypeAnnotation(type2) || _isBaseType(name, type2, true)) {
return true;
}
}
return false;
} else {
return _isBaseType(name, type, true);
}
}
/**
* Description
*/
export function baseTypeStrictlyMatches(right: NodePath) {
var left = this.getTypeAnnotation();
right = right.getTypeAnnotation();
if (!t.isAnyTypeAnnotation() && t.isFlowBaseAnnotation(left)) {
return right.type === left.type;
}
}

View File

@@ -140,7 +140,7 @@ export function ObjectExpression() {
//
export function ArrayExpression () {
export function ArrayExpression() {
return t.genericTypeAnnotation(t.identifier("Array"));
}

View File

@@ -147,18 +147,6 @@ export function isCompletionRecord(allowInsideFunction?) {
return true;
}
/**
* Description
*/
export function isDirective() {
if (this.isExpressionStatement()) {
return this.get("expression").isLiteral();
} else {
return this.isLiteral() && this.parentPath.isExpressionStatement();
}
}
/**
* Check whether or not the current `key` allows either a single statement or block statement
* so we can explode it if necessary.
@@ -172,22 +160,6 @@ export function isStatementOrBlock() {
}
}
/**
* Check whether this node was a part of the original AST.
*/
export function isUser() {
return this.node && !!this.node.loc;
}
/**
* Check whether this node was generated by us and not a part of the original AST.
*/
export function isGenerated() {
return !this.isUser();
}
/**
* Check if the currently assigned path references the `importName` of `moduleSource`.
*/
@@ -226,7 +198,7 @@ export function referencesImport(moduleSource, importName) {
}
/**
* Description
* Get the source code associated with this node.
*/
export function getSource() {

View File

@@ -19,7 +19,7 @@ var referenceVisitor = {
state.bindings[node.name] = binding;
} else {
for (var violationPath of (binding.constantViolations: Array)) {
state.breakOnScopePaths.push(violationPath.scope.path);
state.breakOnScopePaths = state.breakOnScopePaths.concat(violationPath.getAncestry());
}
}
}
@@ -106,12 +106,15 @@ export default class PathHoister {
this.getCompatibleScopes();
var path = this.getAttachmentPath();
if (!path) return;
var attachTo = this.getAttachmentPath();
if (!attachTo) return;
var uid = path.scope.generateUidIdentifier("ref");
// don't bother hoisting to the same function as this will cause multiple branches to be evaluated more than once leading to a bad optimisation
if (attachTo.getFunctionParent() === this.path.getFunctionParent()) return;
path.insertBefore([
var uid = attachTo.scope.generateUidIdentifier("ref");
attachTo.insertBefore([
t.variableDeclaration("var", [
t.variableDeclarator(uid, this.path.node)
])
@@ -122,7 +125,7 @@ export default class PathHoister {
if (parent.isJSXElement() && this.path.container === parent.node.children) {
// turning the `span` in `<div><span /></div>` to an expression so we need to wrap it with
// an expression container
uid = t.jSXExpressionContainer(uid);
uid = t.JSXExpressionContainer(uid);
}
this.path.replaceWith(uid);

View File

@@ -25,6 +25,22 @@ export var BindingIdentifier = {
}
};
export var Statement = {
types: ["Statement"],
checkPath({ node, parent }) {
if (t.isStatement(node)) {
if (t.isVariableDeclaration(node)) {
if (t.isForXStatement(parent, { left: node })) return false;
if (t.isForStatement(parent, { init: node })) return false;
}
return true;
} else {
return false;
}
}
};
export var Expression = {
types: ["Expression"],
checkPath(path) {
@@ -61,3 +77,29 @@ export var Var = {
return t.isVar(path.node);
}
};
export var DirectiveLiteral = {
types: ["Literal"],
checkPath(path) {
return path.isLiteral() && path.parentPath.isExpressionStatement();
}
};
export var Directive = {
types: ["ExpressionStatement"],
checkPath(path) {
return path.get("expression").isLiteral();
}
};
export var User = {
checkPath(path) {
return path.node && !!path.node.loc;
}
};
export var Generated = {
checkPath(path) {
return !path.isUser();
}
};

View File

@@ -3,7 +3,7 @@ import NodePath from "./index";
import * as t from "../../types";
/**
* Description
* Insert the provided nodes before the current one.
*/
export function insertBefore(nodes) {
@@ -75,7 +75,8 @@ export function _maybePopFromStatements(nodes) {
}
/**
* Description
* Insert the provided nodes after the current one. When inserting nodes after an
* expression, ensure that the completion record is correct by pushing the current node.
*/
export function insertAfter(nodes) {
@@ -108,7 +109,7 @@ export function insertAfter(nodes) {
}
/**
* Description
* Update all sibling node paths after `fromIndex` by `incrementBy`.
*/
export function updateSiblingKeys(fromIndex, incrementBy) {
@@ -121,10 +122,6 @@ export function updateSiblingKeys(fromIndex, incrementBy) {
}
}
/**
* Description
*/
/**
* Description
*/
@@ -200,7 +197,8 @@ export function pushContainer(listKey, nodes) {
}
/**
* Description
* Hoist the current node to the highest scope possible and return a UID
* referencing it.
*/
export function hoist(scope = this.scope) {

View File

@@ -11,7 +11,8 @@ export function remove() {
}
/**
* Description
* Dangerously remove the current node. This may sometimes result in a tainted
* invalid AST so use with caution.
*/
export function dangerouslyRemove() {

View File

@@ -32,7 +32,11 @@ var hoistVariablesVisitor = {
};
/**
* Description
* Replace a node with an array of multiple. This method performs the following steps:
*
* - Inherit the comments of first provided node with that of the current node.
* - Insert the provided nodes after the current node.
* - Remove the current node.
*/
export function replaceWithMultiple(nodes: Array<Object>) {
@@ -46,7 +50,11 @@ export function replaceWithMultiple(nodes: Array<Object>) {
}
/**
* Description
* Parse a string as an expression and replace the current node with the result.
*
* NOTE: This is typically not a good idea to use. Building source strings when
* transforming ASTs is an antipattern and SHOULD NOT be encouraged. Even if it's
* easier to use, your transforms will be extremely brittle.
*/
export function replaceWithSourceString(replacement) {
@@ -70,7 +78,7 @@ export function replaceWithSourceString(replacement) {
}
/**
* Description
* Replace the current node with another.
*/
export function replaceWith(replacement, whateverAllowed) {
@@ -92,14 +100,14 @@ export function replaceWith(replacement, whateverAllowed) {
return;
}
if (this.isProgram() && !t.isProgram(replacement)) {
throw new Error("You can only replace a Program root node with another Program node");
}
// normalise inserting an entire AST
if (t.isProgram(replacement) && !this.isProgram()) {
replacement = replacement.body;
whateverAllowed = true;
} else {
if (this.isProgram()) {
throw new Error("You can only replace a Program root node with another Program node");
}
}
if (Array.isArray(replacement)) {
@@ -112,6 +120,13 @@ export function replaceWith(replacement, whateverAllowed) {
if (typeof replacement === "string") {
if (whateverAllowed) {
this.hub.file.log.deprecate("Returning a string from a visitor method will be removed in the future. String " +
"building is NOT a substitute for AST generation. String building leads to " +
"terrible performance due to the additional parsing overhead and will lead to " +
"extremely brittle transformers. For those extreme cases where you're dealing " +
"with strings from a foreign source you may continue to use " +
"`path.replaceWithSourceString(code)`. Please don't abuse this. Bad plugins " +
"hurt the ecosystem.");
return this.replaceWithSourceString(replacement);
} else {
throw new Error("Don't use `path.replaceWith()` with a string, use `path.replaceWithSourceString()`");
@@ -140,7 +155,9 @@ export function replaceWith(replacement, whateverAllowed) {
}
/**
* Description
* This method takes an array of statements nodes and then explodes it
* into expressions. This method retains completion records which is
* extremely important to retain original semantics.
*/
export function replaceExpressionWithStatements(nodes: Array) {

View File

@@ -146,7 +146,7 @@ export default class Scope {
}
var cached = path.getData("scope");
if (cached && cached.parent === parent) {
if (cached && cached.parent === parent && cached.block === path.node) {
return cached;
} else {
path.setData("scope", this);
@@ -491,32 +491,32 @@ export default class Scope {
}
var parent = this.getProgramParent();
var ids = path.getBindingIdentifiers();
var ids = path.getBindingIdentifiers(true);
for (var name in ids) {
var id = ids[name];
for (var id of (ids[name]: Array)) {
var local = this.getOwnBinding(name);
if (local) {
// don't ever let a type alias shadow a local binding
if (kind === "type") continue;
var local = this.getOwnBinding(name);
if (local) {
// don't ever let a type alias shadow a local binding
if (kind === "type") continue;
// same identifier so continue safely as we're likely trying to register it
// multiple times
if (local.identifier === id) continue;
// same identifier so continue safely as we're likely trying to register it
// multiple times
if (local.identifier === id) continue;
this.checkBlockScopedCollisions(local, kind, name, id);
}
this.checkBlockScopedCollisions(local, kind, name, id);
parent.references[name] = true;
this.bindings[name] = new Binding({
identifier: id,
existing: local,
scope: this,
path: path,
kind: kind
});
}
parent.references[name] = true;
this.bindings[name] = new Binding({
identifier: id,
existing: local,
scope: this,
path: path,
kind: kind
});
}
}

View File

@@ -126,6 +126,8 @@ export function merge(visitors) {
var rootVisitor = {};
for (var visitor of (visitors: Array)) {
explode(visitor);
for (var type in visitor) {
var nodeVisitor = rootVisitor[type] = rootVisitor[type] || {};
mergePair(nodeVisitor, visitor[type]);

View File

@@ -71,6 +71,7 @@
"MetaProperty": ["Expression"],
"NewExpression": ["Expression"],
"ObjectExpression": ["Expression"],
"ParenthesizedExpression": ["Expression"],
"SequenceExpression": ["Expression"],
"TaggedTemplateExpression": ["Expression"],
"ThisExpression": ["Expression"],

View File

@@ -261,18 +261,22 @@ export function toBlock(node: Object, parent: Object): Object {
*/
export function valueToNode(value: any): Object {
// undefined
if (value === undefined) {
return t.identifier("undefined");
}
// null, booleans, strings, numbers, regexs
if (value === true || value === false || value === null || isString(value) || isNumber(value) || isRegExp(value)) {
return t.literal(value);
}
// array
if (Array.isArray(value)) {
return t.arrayExpression(value.map(t.valueToNode));
}
// object
if (isPlainObject(value)) {
var props = [];
for (var key in value) {

View File

@@ -112,5 +112,9 @@ export function createTypeAnnotationBasedOnTypeof(type) {
return t.genericTypeAnnotation(t.identifier("Function"));
} else if (type === "object") {
return t.genericTypeAnnotation(t.identifier("Object"));
} else if (type === "symbol") {
return t.genericTypeAnnotation(t.identifier("Symbol"));
} else {
throw new Error("Invalid typeof value");
}
}

View File

@@ -108,7 +108,7 @@ each(t.VISITOR_KEYS, function (keys, type) {
});
each(t.BUILDER_KEYS, function (keys, type) {
t[type[0].toLowerCase() + type.slice(1)] = function () {
var builder = function () {
var node = {};
node.start = null;
node.type = type;
@@ -123,6 +123,9 @@ each(t.BUILDER_KEYS, function (keys, type) {
return node;
};
t[type] = builder;
t[type[0].toLowerCase() + type.slice(1)] = builder;
});
/*

View File

@@ -5,7 +5,7 @@ import * as t from "./index";
* Return a list of binding identifiers associated with the input `node`.
*/
export function getBindingIdentifiers(node: Object): Object {
export function getBindingIdentifiers(node: Object, duplicates?): Object {
var search = [].concat(node);
var ids = object();
@@ -16,7 +16,12 @@ export function getBindingIdentifiers(node: Object): Object {
var key = t.getBindingIdentifiers.keys[id.type];
if (t.isIdentifier(id)) {
ids[id.name] = id;
if (duplicates) {
var _ids = ids[id.name] = ids[id.name] || [];
_ids.push(id);
} else {
ids[id.name] = id;
}
} else if (t.isExportDeclaration(id)) {
if (t.isDeclaration(node.declaration)) {
search.push(node.declaration);

View File

@@ -23,7 +23,7 @@ export function isReferenced(node: Object, parent: Object): boolean {
switch (parent.type) {
// yes: PARENT[NODE]
// yes: NODE.child
// no: parent.CHILD
// no: parent.NODE
case "MemberExpression":
case "JSXMemberExpression":
if (parent.property === node && parent.computed) {
@@ -73,21 +73,17 @@ export function isReferenced(node: Object, parent: Object): boolean {
return parent.local === node;
}
// no: import NODE from "foo";
case "ImportDefaultSpecifier":
return false;
// no: import * as NODE from "foo";
case "ImportNamespaceSpecifier":
return false;
// no: <div NODE="foo" />
case "JSXAttribute":
return parent.name !== node;
// no: import NODE from "foo";
// no: import * as NODE from "foo";
// no: import { NODE as foo } from "foo";
// no: import { foo as NODE } from "foo";
// no: import NODE from "bar";
case "ImportDefaultSpecifier":
case "ImportNamespaceSpecifier":
case "ImportSpecifier":
return false;
@@ -112,12 +108,16 @@ export function isReferenced(node: Object, parent: Object): boolean {
case "RestElement":
return false;
// no: [NODE = foo] = [];
// yes: [foo = NODE] = [];
// yes: left = NODE;
// no: NODE = right;
case "AssignmentExpression":
case "AssignmentPattern":
return parent.right === node;
// no: [NODE = foo] = [];
// no: [foo = NODE] = [];
case "AssignmentPattern":
return false;
// no: [NODE] = [];
// no: ({ NODE }) = [];
case "ObjectPattern":
@@ -195,7 +195,7 @@ export function isImmutable(node: Object): boolean {
if (t.isLiteral(node)) {
if (node.regex) {
// regexes are mutable
// regexs are mutable
return false;
} else {
// immutable!

View File

@@ -46,6 +46,7 @@
"Noop": [],
"ObjectExpression": ["properties"],
"ObjectPattern": ["properties", "typeAnnotation"],
"ParenthesizedExpression": ["expression"],
"Program": ["body"],
"Property": ["key", "value", "decorators"],
"RestElement": ["argument", "typeAnnotation"],

View File

@@ -18,6 +18,7 @@ import has from "lodash/object/has";
import fs from "fs";
import * as t from "./types";
import slash from "slash";
import pathExists from "path-exists";
export { inherits, inspect } from "util";
@@ -55,7 +56,7 @@ export function resolveRelative(loc: string) {
}
}
export function list(val: string): Array<string> {
export function list(val: string): Array {
if (!val) {
return [];
} else if (Array.isArray(val)) {
@@ -113,18 +114,26 @@ export function shouldIgnore(filename, ignore, only) {
if (only) {
for (let pattern of (only: Array)) {
if (pattern.test(filename)) return false;
if (_shouldIgnore(pattern, filename)) return false;
}
return true;
} else if (ignore.length) {
for (let pattern of (ignore: Array)) {
if (pattern.test(filename)) return true;
if (_shouldIgnore(pattern, filename)) return true;
}
}
return false;
}
function _shouldIgnore(pattern, filename) {
if (typeof pattern === "function") {
return pattern(filename);
} else {
return pattern.test(filename);
}
}
var templateVisitor = {
noScope: true,
@@ -182,7 +191,7 @@ function loadTemplates() {
var templates = {};
var templatesLoc = path.join(__dirname, "transformation/templates");
if (!fs.existsSync(templatesLoc)) {
if (!pathExists.sync(templatesLoc)) {
throw new ReferenceError(messages.get("missingTemplatesDirectory"));
}

View File

@@ -3374,6 +3374,49 @@ test("class Foo { bar(a,) { } }", {
features: { "es7.trailingFunctionCommas": true }
});
test("(x, y, ) => 1;", {
start: 0,
body: [{
start: 0,
expression: {
start: 0,
id: null,
generator: false,
expression: true,
params: [
{
start: 1,
name: "x",
type: "Identifier",
end: 2
},
{
start: 4,
name: "y",
type: "Identifier",
end: 5
}
],
body: {
start: 12,
value: 1,
raw: "1",
type: "Literal",
end: 13
},
type: "ArrowFunctionExpression",
end: 13
},
type: "ExpressionStatement",
end: 14
}],
type: "Program",
end: 14
}, {
ecmaVersion: 7,
features: { "es7.trailingFunctionCommas": true }
});
testFail("log(,);", "Unexpected token (1:4)", {
ecmaVersion: 7,
features: { "es7.trailingFunctionCommas": true }
@@ -3383,3 +3426,8 @@ testFail("function log(,) { }", "Unexpected token (1:13)", {
ecmaVersion: 7,
features: { "es7.trailingFunctionCommas": true }
});
testFail("('foo',)", "Unexpected token (1:7)", {
ecmaVersion: 7,
features: { "es7.trailingFunctionCommas": true }
});

View File

@@ -9965,6 +9965,95 @@ var fbTestFixture = {
end: { line: 1, column: 49 }
}
},
'declare class IViewFactory { didAnimate(view:Object, prop:string) :void; }': {
start: 0,
id: {
start: 14,
name: "IViewFactory",
type: "Identifier",
end: 26
},
typeParameters: null,
extends: [],
body: {
start: 27,
callProperties: [],
properties: [
{
start: 29,
value: {
start: 29,
params: [
{
start: 40,
name: {
start: 40,
name: "view",
type: "Identifier",
end: 44
},
optional: false,
typeAnnotation: {
start: 45,
typeParameters: null,
id: {
start: 45,
name: "Object",
type: "Identifier",
end: 51
},
type: "GenericTypeAnnotation",
end: 51
},
type: "FunctionTypeParam",
end: 51
},
{
start: 53,
name: {
start: 53,
name: "prop",
type: "Identifier",
end: 57
},
optional: false,
typeAnnotation: {
start: 58,
type: "StringTypeAnnotation",
end: 64
},
type: "FunctionTypeParam",
end: 64
}
],
rest: null,
typeParameters: null,
returnType: {
start: 67,
type: "VoidTypeAnnotation",
end: 71
},
type: "FunctionTypeAnnotation",
end: 71
},
key: {
start: 29,
name: "didAnimate",
type: "Identifier",
end: 39
},
optional: false,
type: "ObjectTypeProperty",
end: 72
}
],
indexers: [],
type: "ObjectTypeAnnotation",
end: 74
},
type: "DeclareClass",
end: 74
},
'declare class A {}': {
type: 'DeclareClass',
id: {
@@ -11148,3 +11237,9 @@ for (var ns in fbTestFixture) {
});
}
}
test("<Foo foo={function (): void {}} />", {}, {
ecmaVersion: 6,
sourceType: "module",
plugins: { jsx: true, flow: true },
});

View File

@@ -15328,3 +15328,5 @@ test("({ ['__proto__']: 1, __proto__: 2 })", {}, {ecmaVersion: 6});
test("({ __proto__() { return 1 }, __proto__: 2 })", {}, {ecmaVersion: 6});
test("({ get __proto__() { return 1 }, __proto__: 2 })", {}, {ecmaVersion: 6});
test("({ __proto__, __proto__: 2 })", {}, {ecmaVersion: 6});
test("export default /foo/", {}, {ecmaVersion: 6, sourceType: "module"});

View File

@@ -1,8 +1,9 @@
var esvalid = require("esvalid");
var util = require("../../lib/babel/util");
var path = require("path");
var fs = require("fs");
var _ = require("lodash");
var pathExists = require("path-exists");
var esvalid = require("esvalid");
var util = require("../../lib/babel/util");
var path = require("path");
var fs = require("fs");
var _ = require("lodash");
var humanize = function (val, noext) {
if (noext) val = path.basename(val, path.extname(val));
@@ -10,7 +11,7 @@ var humanize = function (val, noext) {
};
var readFile = exports.readFile = function (filename) {
if (fs.existsSync(filename)) {
if (pathExists.sync(filename)) {
var file = fs.readFileSync(filename, "utf8").trim();
file = file.replace(/\r\n/g, "\n");
return file;
@@ -31,7 +32,7 @@ exports.esvalid = function (ast, code, loc) {
};
exports.assertVendor = function (name) {
if (!fs.existsSync(__dirname + "/../../vendor/" + name)) {
if (!pathExists.sync(__dirname + "/../../vendor/" + name)) {
console.error("No vendor/" + name + " - run `make bootstrap`");
process.exit(1);
}
@@ -130,13 +131,13 @@ exports.get = function (entryName, entryLoc) {
suite.tests.push(test);
var sourceMappingsLoc = taskDir + "/source-mappings.json";
if (fs.existsSync(sourceMappingsLoc)) {
if (pathExists.sync(sourceMappingsLoc)) {
test.options.sourceMap = true;
test.sourceMappings = require(sourceMappingsLoc);
}
var sourceMap = taskDir + "/source-map.json";
if (fs.existsSync(sourceMap)) {
if (pathExists.sync(sourceMap)) {
test.options.sourceMap = true;
test.sourceMap = require(sourceMap);
}

View File

@@ -70,7 +70,7 @@ suite("api", function () {
assert.deepEqual(transform('import localName from "./array";', {
resolveModuleSource: function() {
return 'override-source';
return "override-source";
}
}).metadata.modules.imports, [
{
@@ -219,7 +219,7 @@ suite("api", function () {
function getModuleNameTest(moduleFormat, expected) {
var result = transform("foo('bar');", {
filename: "foo/bar/index",
filename: "/foo/bar/index",
modules: moduleFormat,
moduleIds: true,
getModuleId: function (name) {
@@ -232,7 +232,7 @@ suite("api", function () {
test("amd", function () {
var expected = [
"define('foo/bar', ['exports'], function (exports) {",
"define('/foo/bar', ['exports'], function (exports) {",
" 'use strict';",
"",
" foo('bar');",
@@ -246,7 +246,7 @@ suite("api", function () {
var expected = [
"(function (global, factory) {",
" if (typeof define === 'function' && define.amd) {",
" define('foo/bar', ['exports'], factory);",
" define('/foo/bar', ['exports'], factory);",
" } else if (typeof exports !== 'undefined') {",
" factory(exports);",
" } else {",
@@ -268,7 +268,7 @@ suite("api", function () {
test("system", function () {
var expected = [
"System.register('foo/bar', [], function (_export) {",
"System.register('/foo/bar', [], function (_export) {",
" 'use strict';",
"",
" return {",

View File

@@ -9,6 +9,7 @@ var child = require("child_process");
var path = require("path");
var chai = require("chai");
var fs = require("fs");
var pathExists = require("path-exists");
var _ = require("lodash");
var fixtureLoc = __dirname + "/fixtures/bin";
@@ -16,7 +17,7 @@ var tmpLoc = __dirname + "/tmp";
var readDir = function (loc) {
var files = {};
if (fs.existsSync(loc)) {
if (pathExists.sync(loc)) {
_.each(readdir(loc), function (filename) {
var contents = helper.readFile(loc + "/" + filename);
files[filename] = contents;
@@ -112,7 +113,7 @@ var buildTest = function (binName, testName, opts) {
var clear = function () {
process.chdir(__dirname);
if (fs.existsSync(tmpLoc)) rimraf.sync(tmpLoc);
if (pathExists.sync(tmpLoc)) rimraf.sync(tmpLoc);
fs.mkdirSync(tmpLoc);
process.chdir(tmpLoc);
};
@@ -132,11 +133,11 @@ _.each(fs.readdirSync(fixtureLoc), function (binName) {
};
var optionsLoc = testLoc + "/options.json"
if (fs.existsSync(optionsLoc)) _.merge(opts, require(optionsLoc));
if (pathExists.sync(optionsLoc)) _.merge(opts, require(optionsLoc));
_.each(["stdout", "stdin", "stderr"], function (key) {
var loc = testLoc + "/" + key + ".txt";
if (fs.existsSync(loc)) {
if (pathExists.sync(loc)) {
opts[key] = helper.readFile(loc);
} else {
opts[key] = opts[key] || "";

View File

@@ -0,0 +1,31 @@
var obj = {
@foo
@bar
foo: "bar",
@foo
@bar
foo() {},
@foo
get foo() {},
@bar
set bar(foo) {}
};
class Foo {
@foo
@bar
foo() {}
@foo
@bar
foo() {}
@foo
get foo() {}
@bar
set bar(foo) {}
}

View File

@@ -0,0 +1,31 @@
var obj = {
@foo
@bar
foo: "bar",
@foo
@bar
foo() {},
@foo
get foo() {},
@bar
set bar(foo) {}
};
class Foo {
@foo
@bar
foo() {}
@foo
@bar
foo() {}
@foo
get foo() {}
@bar
set bar(foo) {}
}

View File

@@ -1 +0,0 @@
assert.ok(false);

View File

@@ -1,3 +0,0 @@
assert.equal(do {
do { "foo" };
}, "foo");

View File

@@ -1 +0,0 @@
assert.ok(false);

View File

@@ -1,9 +1,9 @@
"use strict";
var some = function some() {
var count = arguments[0] === undefined ? "30" : arguments[0];
var count = arguments.length <= 0 || arguments[0] === undefined ? "30" : arguments[0];
console.log("count", count);
};
some();
some();

View File

@@ -0,0 +1,13 @@
class x {
f() {
1
2
3
}
constructor() {
4
5
6
}
}

View File

@@ -0,0 +1,18 @@
"use strict";
var x = (function () {
x.prototype.f = function f() {
1;
2;
3;
};
function x() {
4;
5;
6;
babelHelpers.classCallCheck(this, x);
}
return x;
})();

View File

@@ -10,3 +10,12 @@ class Foo extends Bar {
this.state = "test";
}
}
class ConstructorScoping {
constructor(){
let bar;
{
let bar;
}
}
}

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