Compare commits

..

1207 Commits

Author SHA1 Message Date
Sebastian McKenzie
d28716cf93 v5.6.20 2015-07-13 20:50:20 +01:00
Sebastian McKenzie
a286a86b6d Revert "remove do expressions"
This reverts commit 420492388b.
2015-07-13 20:45:49 +01:00
Sebastian McKenzie
2b32a2781e Revert "remove DoExpression generator"
This reverts commit 5cd8822888.
2015-07-13 20:45:43 +01:00
Sebastian McKenzie
86a49e2b1d v5.6.19 2015-07-13 16:41:15 +01:00
Sebastian McKenzie
5cd8822888 remove DoExpression generator 2015-07-13 16:39:30 +01:00
Sebastian McKenzie
420492388b remove do expressions 2015-07-13 16:37:08 +01:00
Sebastian McKenzie
d5be4bb5b9 v5.6.18 2015-07-12 00:39:50 +01:00
Sebastian McKenzie
d6dc29ec6a remove templates doc 2015-07-12 00:37:55 +01:00
James Kyle
f3e77c7a0d Merge pull request #1983 from chicoxyzzy/code-docs-additions-by-chicoxyzzy
add some useful links
2015-07-11 15:09:29 -07:00
chico
b08012cf12 add some useful links 2015-07-12 01:05:50 +03:00
Sebastian McKenzie
ef275da1c2 Merge pull request #1897 from babel/code-docs
Code docs
2015-07-11 22:56:24 +01:00
James Kyle
cc6eb50f28 parenthesis -> parentheses 2015-07-11 14:48:40 -07:00
James Kyle
a260b6859f Clarify what the arrow function transformer does 2015-07-11 14:27:14 -07:00
James Kyle
eb182ccbe0 fix typo 2015-07-11 13:09:11 -07:00
James Kyle
fe1e99c799 Create generation/generators README 2015-07-11 12:53:46 -07:00
James Kyle
deeb75a5d1 Add descriptions to transformation/transformers/es6/destructuring 2015-07-11 12:53:46 -07:00
James Kyle
961d482269 Add content to tools README 2015-07-11 12:53:46 -07:00
James Kyle
1c8f0dcab4 Add content to helpers README 2015-07-11 12:53:46 -07:00
James Kyle
5dc39439ed Add content to generation README 2015-07-11 12:53:46 -07:00
James Kyle
58e029a064 Add content to api README 2015-07-11 12:53:46 -07:00
James Kyle
01ea72790d Add descriptions to types/flow 2015-07-11 12:53:45 -07:00
James Kyle
118ac2e62d Add descriptions to traversal/scope/index 2015-07-11 12:53:45 -07:00
James Kyle
3207a387a7 Add descriptions to transformation/transformers/es6/constants 2015-07-11 12:53:45 -07:00
James Kyle
90a5b96480 Add descriptions to transformation/transformers/es6/arrow-functions 2015-07-11 12:53:45 -07:00
James Kyle
74cf5ac552 Add descriptions to transformation/transformers/es5/properties.mutators 2015-07-11 12:53:45 -07:00
James Kyle
dce1a3548c Add descriptions to transformation/transformers/es3/property-literals 2015-07-11 12:53:45 -07:00
James Kyle
d67ba39d1c Add descriptions to transformation/transformers/es3/member-expression-literals 2015-07-11 12:53:45 -07:00
James Kyle
894c3fe481 Add descriptions to transformation/file/options/parsers 2015-07-11 12:53:29 -07:00
James Kyle
27cce1446c Add descriptions to transformation/file/options/index 2015-07-11 12:53:28 -07:00
James Kyle
7e64bcd85a Add descriptions to tools/protect 2015-07-11 12:53:28 -07:00
James Kyle
4a851130ee Add descriptions to helpers/parse 2015-07-11 12:53:28 -07:00
James Kyle
6a9b14563e Add descriptions to helpers/object 2015-07-11 12:53:28 -07:00
James Kyle
4f11c6a4be Add descriptions to helpers/normalize-ast 2015-07-11 12:53:28 -07:00
James Kyle
d7a669e96b Add descriptions to helpers/merge 2015-07-11 12:53:28 -07:00
James Kyle
4b6a5f4ea9 Add descriptions to helpers/code-frame 2015-07-11 12:53:28 -07:00
James Kyle
9c60c633d2 Add descriptions to generation/whitespace 2015-07-11 12:53:27 -07:00
James Kyle
3b428e45a3 Add descriptions to generation/source-map 2015-07-11 12:53:27 -07:00
James Kyle
d961e2d291 Add descriptions to generation/position 2015-07-11 12:53:27 -07:00
James Kyle
2d884c282a Add descriptions to generation/index 2015-07-11 12:53:27 -07:00
James Kyle
350a3b664f Add descriptions to generation/buffer 2015-07-11 12:53:27 -07:00
James Kyle
9e4ec19487 Add descriptions to generation/node/whitespace 2015-07-11 12:53:27 -07:00
James Kyle
d613975feb Add descriptions to generation/node/printer 2015-07-11 12:53:27 -07:00
James Kyle
77e9387c5f Add descriptions to generation/node/parenthesis 2015-07-11 12:53:26 -07:00
James Kyle
ac00de44a7 Add descriptions to generation/node/index 2015-07-11 12:53:26 -07:00
James Kyle
8e03a2b720 Add descriptions to generation/generators/types 2015-07-11 12:53:26 -07:00
James Kyle
4e660f7b3e Add descriptions to generation/generators/template-literals 2015-07-11 12:53:26 -07:00
James Kyle
63618f876c Add descriptions to generation/generators/statements 2015-07-11 12:53:26 -07:00
James Kyle
155f3407bc Add descriptions to generation/generators/modules 2015-07-11 12:53:26 -07:00
James Kyle
bf62042fe6 Add descriptions to generation/generators/methods 2015-07-11 12:53:26 -07:00
James Kyle
2a226b3a2b Add descriptions to generation/generators/jsx 2015-07-11 12:53:26 -07:00
James Kyle
f996d6bfa6 Add descriptions to generation/generators/flow 2015-07-11 12:53:25 -07:00
James Kyle
89b1c387a0 Add descriptions to generation/generators/expressions 2015-07-11 12:53:25 -07:00
James Kyle
dfea7368e1 Add descriptions to generation/generators/comprehensions 2015-07-11 12:53:25 -07:00
James Kyle
06867dd52b Add descriptions to generation/generators/classes 2015-07-11 12:53:25 -07:00
James Kyle
3f72a4b200 Add descriptions to generation/generators/base 2015-07-11 12:53:25 -07:00
James Kyle
ee286ed482 Add descriptions to api/node 2015-07-11 12:53:25 -07:00
James Kyle
8604c0c2cd Add descriptions to api/browser 2015-07-11 12:53:25 -07:00
James Kyle
b2476b3603 Add descriptions to api/register/node 2015-07-11 12:53:24 -07:00
James Kyle
c2ebe7f26d Add descriptions to api/register/cache 2015-07-11 12:53:24 -07:00
James Kyle
4809747304 Add placeholders 2015-07-11 12:53:23 -07:00
James Kyle
e572d25640 Add README files to be filled out 2015-07-11 12:43:56 -07:00
James Kyle
07e3d9a8df Add intro inside of src/ directory 2015-07-11 12:43:56 -07:00
Sebastian McKenzie
7763c74563 Merge branch 'master' of github.com:babel/babel 2015-07-11 10:35:57 +01:00
Sebastian McKenzie
e45dc0fbaf Merge pull request #1974 from loganfsmyth/hoist-class-inherits
Hoist class inheritance call so it runs before prototype use.
2015-07-11 09:59:47 +01:00
Sebastian McKenzie
8539182452 Merge pull request #1976 from cpojer/import-typeof
Add support for `import typeof`, fixes #1975
2015-07-11 09:58:49 +01:00
cpojer
18380d2aee Add support for import typeof, fixes #1975 2015-07-11 01:54:25 -07:00
Logan Smyth
19b1032474 Hoist class inheritance call so it runs before prototype use - fixes #1972 2015-07-10 19:51:53 -07:00
Sebastian McKenzie
f7761982cd fix logo url 2015-07-10 16:21:38 +01:00
Sebastian McKenzie
950d3d2280 Merge pull request #1969 from christophehurpeau/patch-1
option help add "separated by comma" for options whitelist, blacklist…
2015-07-10 15:29:36 +01:00
Christophe Hurpeau
12d7b33f62 option help add "separated by comma" for options whitelist, blacklist and optional 2015-07-10 16:29:07 +02:00
Sebastian McKenzie
f9c7d0d095 add validation to plugins 2015-07-10 02:59:50 +01:00
Sebastian McKenzie
efaa0608af removed unused variable 2015-07-09 21:28:53 +01:00
Sebastian McKenzie
b522bfe822 update babel/register to work with new option manager and add filename option type 2015-07-09 21:25:06 +01:00
Sebastian McKenzie
9efb02f60f rewrite options handling to be MUCH more maintainable and less like spaghetti 2015-07-09 21:11:51 +01:00
Sebastian McKenzie
9805c0387f reenable travis node 0.10 testing 2015-07-09 19:17:12 +01:00
Sebastian McKenzie
81019ec76d v5.6.17 2015-07-09 19:04:26 +01:00
Sebastian McKenzie
b0d0adda9b add 5.6.17 changelog 2015-07-09 19:03:32 +01:00
Sebastian McKenzie
d335535f04 Revert "Move into for block"
This reverts commit 1945f849c3.

# Conflicts:
#	src/babel/generation/index.js
2015-07-09 19:01:37 +01:00
Sebastian McKenzie
f738c95c8d Merge branch 'master' into development 2015-07-09 18:22:22 +01:00
Sebastian McKenzie
7fec1c98e5 Merge pull request #1962 from benjamn/development
Update regenerator to v0.8.34, and remove recast and ast-types from package.json.
2015-07-09 18:21:17 +01:00
Sebastian McKenzie
33ae022e4d add ClassProperty handling to t.isReferenced - fixes #1961 2015-07-09 18:19:20 +01:00
Ben Newman
eac9e9b372 Update regenerator to v0.8.34, and remove recast and ast-types.
This version of Regenerator pegs recast to v0.10.18, which pegs ast-types
to v0.8.2, which contains special support for all Babel AST types:
https://github.com/benjamn/ast-types/blob/master/def/babel.js

This version of Regenerator also exports the ast-types module object that
it uses (as regenerator.types), so that consumers like Babel can refer to
the exact same copy of ast-types when necessary, rather than requiring
ast-types themselves. Why that was risky: #1958.
2015-07-09 13:12:58 -04:00
Sebastian McKenzie
eb6b38d3a8 add 5.6.13-5.6.16 changelogs 2015-07-09 16:30:45 +01:00
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
Brian Donovan
86095d9dac Merge pull request #1951 from zbraniecki/traverse-in-plugins-typo
Fix a typo in plugin-manager import of traverse
2015-07-08 13:13:19 -07:00
Zibi Braniecki
02dd785d02 Fix a typo in plugin-manager import of traverse 2015-07-08 13:06:59 -07: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
Sebastian McKenzie
ce3c6289a2 v5.6.2 2015-06-22 00:08:52 +01:00
Sebastian McKenzie
0364519869 remove unused import 2015-06-22 00:06:43 +01:00
Sebastian McKenzie
58cda35831 log spread element rest parameter as a candidate instead of replacing it in place - fixes #1796 2015-06-22 00:06:03 +01:00
Sebastian McKenzie
ebaa06f4a2 add ensureBlock path method 2015-06-21 23:59:14 +01:00
Sebastian McKenzie
4b0f624fb3 turn method literal keys into assignments in loose mode - fixes #1797 2015-06-21 23:59:06 +01:00
Sebastian McKenzie
aa0f3ac5d0 5.6.1 2015-06-21 00:07:07 +01:00
Sebastian McKenzie
725906a7dc v5.6.1 2015-06-21 00:05:13 +01:00
Sebastian McKenzie
13d5c94b8b update transformation tests 2015-06-21 00:03:29 +01:00
Sebastian McKenzie
85308a1e8c fix super spread in loose mode 2015-06-21 00:01:19 +01:00
Sebastian McKenzie
83bcaba1a5 downgrade to babel 5.5.7 2015-06-21 00:01:11 +01:00
Sebastian McKenzie
185648cb2c 5.6.0 2015-06-20 23:44:46 +01:00
Sebastian McKenzie
be355fc1c6 fix build-runtime script 2015-06-20 23:37:46 +01:00
Sebastian McKenzie
7795e11d58 v5.6.0 2015-06-20 23:35:51 +01:00
Sebastian McKenzie
8f74e8068c fix generation tests to reflect acorn update 2015-06-20 23:35:02 +01:00
Sebastian McKenzie
4f08a77230 resync with upstream acorn 2015-06-20 23:28:49 +01:00
Sebastian McKenzie
4ac33d62af move spec.functionName transformer to builtin-basic - fixes #1743 2015-06-20 22:51:20 +01:00
Sebastian McKenzie
2710a914e8 add noop transform method to IgnoreFormatter 2015-06-20 22:48:45 +01:00
Sebastian McKenzie
8934e7f9da Merge branch 'master' of github.com:babel/babel 2015-06-20 22:48:00 +01:00
Sebastian McKenzie
b4f18e05fa Merge pull request #1776 from zertosh/matches-pattern-this
matchPattern fixes and "this" handling
2015-06-20 22:47:52 +01:00
Sebastian McKenzie
c07540a2c4 extend module IgnoreFormatter from DefaultFormatter - fixes #1763, closes #1771 2015-06-20 22:47:32 +01:00
Sebastian McKenzie
c409f63bbe Merge pull request #1772 from arthurvr/booleanify-tests
Add tests for util.booleanify
2015-06-20 22:22:08 +01:00
Sebastian McKenzie
d3c30b669f update babel-plugin-runtime 2015-06-20 22:21:44 +01:00
Sebastian McKenzie
d10856d16c don't terminate CLI when watching files fail compilation on init - fixes #1678 2015-06-20 22:14:21 +01:00
Sebastian McKenzie
fb08a519c8 register labels as bindings - fixes #1747 2015-06-20 22:10:29 +01:00
Sebastian McKenzie
6a8ecf2507 add uniq to filenames in babel-cli - fixes #1731 2015-06-20 22:04:33 +01:00
Sebastian McKenzie
100317e0c8 split react displayName addition into a plugin - fixes #1761 2015-06-20 22:01:40 +01:00
Sebastian McKenzie
a32f744341 disable module import receiver when in loose mode - fixes #1788 2015-06-20 21:49:31 +01:00
Sebastian McKenzie
c4feff3cb7 add more whitespace 2015-06-20 21:49:01 +01:00
Sebastian McKenzie
498297ce6b check for invalid binding identifiers when generating inferred method names - fixes #1794 2015-06-20 21:48:42 +01:00
Sebastian McKenzie
2412c1d502 remove bluebird 2015-06-20 21:48:18 +01:00
Sebastian McKenzie
d92e1a4fb8 Merge pull request #1793 from lydell/patch-1
Update to js-tokens@1.0.1
2015-06-20 13:28:27 +01:00
Simon Lydell
1d0d050413 Update to js-tokens@1.0.1 2015-06-20 09:03:26 +02:00
Sebastian McKenzie
a607ac0077 Merge pull request #1786 from callumacrae/update-regenerator
Update regenerator
2015-06-18 17:57:43 +01:00
Callum Macrae
41f5e7c077 removed ^ from regenerator 2015-06-18 17:57:04 +01:00
Callum Macrae
99604362ed update regenerator 2015-06-18 17:52:16 +01:00
Sebastian McKenzie
2c8e374eaf add back non-es5 number guard in literal code gen 2015-06-17 22:56:08 +01:00
Sebastian McKenzie
238c68f829 fix member expression generation on object integers 2015-06-17 22:54:45 +01:00
Ingvar Stepanyan
09b334ad21 Add guard against non-ES5 integer literals. 2015-06-17 21:11:20 +03:00
Sebastian McKenzie
d647ede94b fix up raw number literal 2015-06-17 17:58:03 +01:00
Sebastian McKenzie
6386b60b9a add comments to types generator 2015-06-17 16:53:23 +01:00
Sebastian McKenzie
25749a9933 clear properties to undefined in traverse.removeProperties 2015-06-17 16:53:08 +01:00
Ingvar Stepanyan
fd4c0dae95 Generate original number representation when value was not changed. 2015-06-17 18:20:35 +03:00
Andres Suarez
80d362c534 fix matchesPattern with deep member expressions 2015-06-16 23:37:32 -04:00
Andres Suarez
59820b9a84 matchesPattern recognizes "this" 2015-06-16 22:48:50 -04:00
Sebastian McKenzie
f6ff366edf add getEarliestCommonAncestorFrom jsdoc description 2015-06-17 02:40:15 +01:00
Sebastian McKenzie
c7cac7aaba add deply nested smart insertion of rest parameter allocation 2015-06-17 02:34:42 +01:00
Sebastian McKenzie
0647d374a3 add more comments 2015-06-17 02:09:38 +01:00
Sebastian McKenzie
25c2816a85 fix ancestry index loopup in Path#getEarliestCommonAncestorFrom 2015-06-17 02:07:35 +01:00
Sebastian McKenzie
b57a80ecae optimise rest parameters in spread element position and allocate rest array at the earliest common ancestor of all references - fixes #1768 2015-06-17 01:57:14 +01:00
Sebastian McKenzie
574d47a571 finish removal of esquery 2015-06-17 01:56:01 +01:00
Sebastian McKenzie
7c5d2b19b7 remove esquery 2015-06-17 01:38:49 +01:00
Arthur Verschaeve
c7669f44c1 Add tests for util.booleanify 2015-06-16 20:18:33 +02:00
Sebastian McKenzie
0ed5c5f480 add check for JSXMemberExpression to t.isReferenced 2015-06-16 02:29:59 +01:00
Sebastian McKenzie
94c34e0132 throw error when attemping to replace a Program root node with another node not of type Program - closes #1762 2015-06-16 01:53:53 +01:00
Sebastian McKenzie
92c4bbd003 remove unused import 2015-06-16 00:43:41 +01:00
Sebastian McKenzie
ec8e840841 upgrade babel-plugin-undeclared-variables-check 2015-06-16 00:42:30 +01:00
Sebastian McKenzie
1c3c64c12c add modulesDuplicateDeclarations message 2015-06-16 00:42:21 +01:00
Sebastian McKenzie
cae80d6e9b add scope to addImport importSpecifier call 2015-06-16 00:42:13 +01:00
Sebastian McKenzie
aaf29ddd82 move validation.undeclaredVariableCheck up 2015-06-16 00:42:03 +01:00
Sebastian McKenzie
fb485567b9 support module live bindings in arbitary positions not in Program statement position - fixes #1760 2015-06-16 00:41:53 +01:00
Sebastian McKenzie
050bcec617 add messages property to plugin context and add --copy-files flag to babel-plugin build 2015-06-15 18:55:03 +01:00
Sebastian McKenzie
6231015557 fix spelling mistake in CONTRIBUTING 2015-06-15 18:54:23 +01:00
Sebastian McKenzie
822eb47ee7 move more transformers into plugins 2015-06-15 18:54:14 +01:00
Sebastian McKenzie
91161ae9a1 Merge pull request #1758 from pygy/master
Add tests for IIFEs as default exports.
2015-06-15 18:36:27 +01:00
Pierre-Yves Gerardy
4c1b4b6490 Add tests for IIFEs as default exports. 2015-06-15 19:28:17 +02:00
Sebastian McKenzie
e792256087 add parse and traverse to plugin babel context 2015-06-15 16:36:56 +01:00
Sebastian McKenzie
19ad22f6e8 update tests to reflect new plugin api 2015-06-15 16:36:45 +01:00
Sebastian McKenzie
01818a50fa fix up babel-plugin CLI 2015-06-15 16:36:34 +01:00
Sebastian McKenzie
3247851019 yank out more transformers and put them into plugins 2015-06-15 16:35:41 +01:00
Sebastian McKenzie
939c00d33c Merge branch 'master' of github.com:babel/babel 2015-06-15 15:18:35 +01:00
Sebastian McKenzie
8b096ac705 start movement of core into plugins 2015-06-15 15:17:04 +01:00
Sebastian McKenzie
30c4a0cf06 Merge pull request #1726 from tikotzky/fix-require-hook-under-istanbul
Fix require hook under istanbul
2015-06-15 11:09:41 +01:00
Sebastian McKenzie
e08d400b36 Merge pull request #1733 from hzoo/i-1732
remove empty strings from beginning of template - fixes #1732
2015-06-15 10:46:28 +01:00
Sebastian McKenzie
7e080aa9d2 Merge pull request #1753 from loganfsmyth/optimize-call
Optimize NodePath#call a bit
2015-06-15 10:46:10 +01:00
Sebastian McKenzie
c0e5059634 Merge pull request #1752 from loganfsmyth/hidden-class-change
Initialize properties to avoid hidden class thrashing.
2015-06-15 10:45:30 +01:00
Logan Smyth
f8f5684faa Avoid concatenating callbacks and ensure that callback lists are arrays ahead of time. 2015-06-14 23:00:38 -07:00
Logan Smyth
2c3e9fbc07 Initialize properties to avoid hidden class thrashing. 2015-06-14 22:26:44 -07:00
Sebastian McKenzie
b9d066d953 add special case for null in get helper 2015-06-15 00:15:22 +01:00
Sebastian McKenzie
94e15b0750 remove unused variable 2015-06-14 23:52:09 +01:00
Sebastian McKenzie
3256c1d120 Merge branch 'master' of github.com:babel/babel 2015-06-14 23:44:30 +01:00
Sebastian McKenzie
eba9f0ffbd clean up default constructor in derived classes - fixes #1748 2015-06-14 23:44:21 +01:00
Sebastian McKenzie
52c3c143f9 add BindingIdentifier virtual type 2015-06-14 20:21:02 +01:00
Brian Donovan
b0f797205b Merge pull request #1744 from silfverstrom/bugg/typo-in-messages
Fixed very minor typo in messages.js.
2015-06-14 07:57:25 -07:00
Niklas Silfverström
dd52c6a687 Fixed very minor typo in messages.js. 2015-06-14 08:06:55 +02:00
Mordy Tikotzky
3cf773b528 fix register hook when not registering for .js extension. 2015-06-14 00:31:14 -04:00
Henry Zhu
98424f80af template-literals: remove unnecessary strings, only add "" to beginning if second node isn't a string - fixes #1732 2015-06-13 14:34:33 -04:00
Sebastian McKenzie
708879ff1b fix auxiliary comment option in makefile 2015-06-13 19:01:50 +01:00
Sebastian McKenzie
70042bb0a8 update internal babel version to latest 2015-06-13 18:57:22 +01:00
Sebastian McKenzie
0f7711a202 5.5.8 2015-06-13 18:54:52 +01:00
Sebastian McKenzie
27f039488e v5.5.8 2015-06-13 18:53:41 +01:00
Sebastian McKenzie
e3ce82e12f remove console.log 2015-06-13 18:50:51 +01:00
Sebastian McKenzie
4934ea56a0 change NodePath#inType to use arguments instead of types 2015-06-13 18:50:19 +01:00
Sebastian McKenzie
ce03457b19 add getOpposite path method 2015-06-13 18:50:05 +01:00
Sebastian McKenzie
1298c67949 rename getOwnBindingInfo to getOwnBinding 2015-06-13 18:49:59 +01:00
Sebastian McKenzie
668274edcb remove resolve-rc file 2015-06-13 18:49:37 +01:00
Sebastian McKenzie
0694a7dd06 5.5.7 2015-06-13 02:23:28 +01:00
Sebastian McKenzie
20d19735fc v5.5.7 2015-06-13 02:22:20 +01:00
Sebastian McKenzie
b5b6bf4ad5 add isDirective method, 2015-06-13 02:21:22 +01:00
Sebastian McKenzie
844c10cac0 fix reference to inferers 2015-06-13 02:20:04 +01:00
Sebastian McKenzie
43583e4e9d pick only current constant violation if it's of the same scope 2015-06-13 02:19:57 +01:00
Sebastian McKenzie
f5b921cda9 better errorWithNode that's consolidated across paths and files 2015-06-13 02:19:44 +01:00
Sebastian McKenzie
763892aa79 remove unused variable 2015-06-13 02:19:30 +01:00
Sebastian McKenzie
3e6eae4d1a Merge branch 'master' of github.com:babel/babel 2015-06-13 02:00:22 +01:00
Sebastian McKenzie
7c090c8580 Merge pull request #1740 from zertosh/cli-fixes
Really fix "--help"
2015-06-13 01:56:58 +01:00
Andres Suarez
a5f6c1c389 Really fix "--help" 2015-06-12 20:54:53 -04:00
Sebastian McKenzie
c159f2d982 Merge branch 'master' of github.com:babel/babel 2015-06-13 01:54:33 +01:00
Sebastian McKenzie
9205f10244 Merge pull request #1719 from jmm/internals-docs2
Internals documentation
2015-06-13 01:53:04 +01:00
Sebastian McKenzie
4cd7bcad59 Merge pull request #1727 from zertosh/cli-fixes
Fix "--help" distinguish optional transforms
2015-06-13 01:52:46 +01:00
Andres Suarez
7e9660efd3 Fix "--help" distinguish optional transforms 2015-06-12 20:51:52 -04:00
Sebastian McKenzie
2d66ce5224 Merge pull request #1724 from arthurvr/bool
Update `util.booleanify()` return type
2015-06-13 01:48:30 +01:00
Sebastian McKenzie
1257b2cf40 Merge pull request #1736 from grncdr/patch-1
Remove duplicate keys from alias-keys.json
2015-06-12 20:33:54 +01:00
Stephen Sugden
f21d935de5 Add aliases from JSX* tags to Expression 2015-06-12 12:24:24 -07:00
Stephen Sugden
2e20364793 Remove duplicate keys from alias-keys.json
Fixes #1734
2015-06-12 20:58:41 +02:00
Sebastian McKenzie
e47e8a187a Merge branch 'master' of github.com:babel/babel 2015-06-11 19:06:41 +01:00
Ingvar Stepanyan
26924d5944 Fix dependency reference of Symbol.hasInstance 2015-06-10 22:07:40 +03:00
Arthur Verschaeve
5eb1850a55 Update util.booleanify() return type
Ref 62f37c1e62
2015-06-10 16:54:43 +02:00
Sebastian McKenzie
333e287226 remove special minification.removeConsole ExpressionStatement handling 2015-06-10 13:14:44 +01:00
Sebastian McKenzie
80a77bd6a2 fix linting error 2015-06-10 03:16:07 +01:00
Sebastian McKenzie
c9286a1de1 rewrite option handling - fixes #1636 2015-06-10 03:07:06 +01:00
Sebastian McKenzie
52f614dcdf add better path execution status algo 2015-06-10 01:36:36 +01:00
Sebastian McKenzie
600367ae25 add t.COMPARISON_BINARY_OPERATORS 2015-06-10 01:34:51 +01:00
Sebastian McKenzie
b761cba135 split auxiliary comment option into before and after - fixes #1721 2015-06-10 01:34:44 +01:00
Sebastian McKenzie
947d3e262d push newline after decorator when doing code gen - fixes #1713 2015-06-10 01:19:58 +01:00
Sebastian McKenzie
4061bea528 change execution order of module metadata visitor to resolve module source before building up metadata tree - fixes #1720 2015-06-10 01:15:11 +01:00
Sebastian McKenzie
de195e5bfc Merge branch 'master' of github.com:babel/babel 2015-06-10 01:10:41 +01:00
Sebastian McKenzie
3bcef86973 Merge pull request #1720 from chadhietala/failing-metadata-test
Metadata object does not take in account resolveModuleSource()
2015-06-10 01:10:09 +01:00
Sebastian McKenzie
fa670ac71e visually split up inference inferer methods 2015-06-09 22:52:21 +01:00
Sebastian McKenzie
572261f9ce add support for typecasts in path static evaluation 2015-06-09 22:52:00 +01:00
Chad Hietala
8a320d53a5 Metadata object does not take in account resolveModuleSource()
This adds a failing test to illustrate the metadata object not reflecting what is returned from resolveModuleSource(). I might also not understand resolveModuleSource's purpose. However, this was the hook mentioned here https://github.com/babel/babel/issues/1602.
2015-06-09 14:26:33 -07:00
Jesse McCarthy
0650eedeb6 Add reference to doc dir to CONTRIBUTING. 2015-06-09 15:37:01 -04:00
Jesse McCarthy
2282d066a2 Start doc dir for internals documentation. 2015-06-09 15:37:01 -04:00
Sebastian McKenzie
f4d7cc55c1 split inference logic into separate folder 2015-06-09 14:02:57 +01:00
Sebastian McKenzie
eaaa279aa5 add let binding collision todo 2015-06-09 04:08:44 +01:00
Sebastian McKenzie
0595e06e29 5.5.6 2015-06-09 04:08:36 +01:00
Sebastian McKenzie
9b27a170ae v5.5.6 2015-06-09 04:07:15 +01:00
Sebastian McKenzie
1db232da9e add 5.5.6 changelog 2015-06-09 04:06:06 +01:00
Sebastian McKenzie
4cc844f410 take into consideration assignment expressions in loop heads when replacing let references - fixes #1707 2015-06-09 04:04:14 +01:00
Sebastian McKenzie
024ae670cb fix traceur test blacklist 2015-06-09 03:48:22 +01:00
Sebastian McKenzie
429edda9c0 ignore StringIterator traceur test 2015-06-09 03:40:08 +01:00
Sebastian McKenzie
05b13b9ea3 fix mistyped parameter name of t.createTypeAnnotationBasedOnTypeof 2015-06-09 03:26:40 +01:00
Sebastian McKenzie
b7320ce400 add t.createTypeAnnotationBasedOnTypeof method 2015-06-09 03:23:28 +01:00
Sebastian McKenzie
0c37b7b973 add typeof conditional inference 2015-06-09 03:20:32 +01:00
Sebastian McKenzie
bb36dbd8d9 update to latest traceur and enable now passing tests 2015-06-09 03:20:02 +01:00
Sebastian McKenzie
2dd8c40618 heavily simplify constants transformer 2015-06-09 00:31:18 +01:00
Sebastian McKenzie
33128b0ccf remove unused declaration 2015-06-08 23:59:53 +01:00
Sebastian McKenzie
cf25424295 fix duplicate declaration 2015-06-08 23:49:00 +01:00
Sebastian McKenzie
7492074794 infer types of bindings inside of conditionals based on usage 2015-06-08 23:43:46 +01:00
Sebastian McKenzie
c4a491123e disallow line terminator after async contextual keyword - fixes #1711 2015-06-08 21:25:16 +01:00
Sebastian McKenzie
55ad88fe4e don't override types parameter 2015-06-08 14:59:19 +01:00
Sebastian McKenzie
7170dbced8 Merge branch 'master' of github.com:babel/babel 2015-06-08 14:53:54 +01:00
Sebastian McKenzie
b0971412a2 add inference for null, remove any type parameter from inferred arrays, add todo comment 2015-06-08 14:52:35 +01:00
Sebastian McKenzie
a6b374a681 save union type in _getTypeAnnotationBindingConstantViolations to prevent infinite recursion 2015-06-08 14:52:13 +01:00
Sebastian McKenzie
2d0355b3b9 merge previous bindings constantViolations and path onto new bindings constantViolations 2015-06-08 14:49:09 +01:00
Sebastian McKenzie
7fade101be move down module TypeAlias check 2015-06-08 14:47:58 +01:00
Sebastian McKenzie
0918da8569 Merge pull request #1708 from hawkrives/patch-2
Update README.md for the Slack channel
2015-06-08 12:35:08 +01:00
Hawken Rives
917db622c4 Update README.md
Switch out the gitter link for slack.
2015-06-08 20:33:09 +09:00
Sebastian McKenzie
f7ee6fbd20 move travis notifications from gitter to slack 2015-06-08 12:20:38 +01:00
Sebastian McKenzie
5899e9a0be don't consider type aliases to be a default declaration - fixes #1705 2015-06-08 12:20:30 +01:00
Sebastian McKenzie
d41cb11545 fix registerDeclaration for FlowDeclarations 2015-06-08 01:46:05 +01:00
Sebastian McKenzie
3ad909a4ae add 5.5.5 changelog 2015-06-08 01:45:56 +01:00
Sebastian McKenzie
4bafdf733c 5.5.5 2015-06-08 01:29:54 +01:00
Sebastian McKenzie
b825998c63 v5.5.5 2015-06-08 01:27:46 +01:00
Sebastian McKenzie
6b02ca47c3 add missing semicolon 2015-06-08 01:27:02 +01:00
Sebastian McKenzie
ea1b85bffa fix bug where templates were getting polluted with old traversal paths 2015-06-08 01:25:51 +01:00
Sebastian McKenzie
3cffe47eea fix NodePath#isGenericType method name 2015-06-08 01:00:01 +01:00
Sebastian McKenzie
e5d5a9fb27 remove unused variable 2015-06-08 00:33:41 +01:00
Sebastian McKenzie
ca97fa63a9 Merge branch 'master' of github.com:babel/babel 2015-06-08 00:30:05 +01:00
Sebastian McKenzie
f4cc27bc0e remove unused variable 2015-06-08 00:29:52 +01:00
Sebastian McKenzie
8cea575e2e change NodePath#findParent to only call callback with path instead of node 2015-06-08 00:29:46 +01:00
Sebastian McKenzie
c91baee4d5 add support for flow declarations in scope tracking 2015-06-08 00:04:17 +01:00
Sebastian McKenzie
8055ce29f7 add support for flow declarations in scope tracking 2015-06-07 23:57:19 +01:00
Sebastian McKenzie
4596ae48b8 remove acorn jsx tests as the jsx parser is no longer embedded 2015-06-07 23:57:11 +01:00
Sebastian McKenzie
6c268cdf21 split out path comment methods into a separate file 2015-06-07 23:49:29 +01:00
Sebastian McKenzie
fce977f1d7 update TraversalContext#shouldVisit to check for existence of visitor keys 2015-06-07 23:38:39 +01:00
Sebastian McKenzie
a298075949 check for loc value on comments before attempting to adjust it 2015-06-07 23:37:47 +01:00
Sebastian McKenzie
66599c3779 use scope paths hub instead of manually passing the hub to the scope 2015-06-07 23:37:33 +01:00
Sebastian McKenzie
60340244b1 when constructing a NodePath, inherit parent paths hub if one wasn't passed to us 2015-06-07 23:36:32 +01:00
Sebastian McKenzie
eb72ea3e5a rename path verification methods to introspection and add NodePath#getSource method 2015-06-07 23:36:12 +01:00
Sebastian McKenzie
ede6237b6f add NodePath#addComment method 2015-06-07 23:35:46 +01:00
Sebastian McKenzie
e91e10aae6 add FlowStatement and FlowDeclaration alias keys 2015-06-07 23:35:35 +01:00
Sebastian McKenzie
9c3cca0d25 rename NodePath#isTypeAnnotationGeneric to isTypeAnnotation 2015-06-07 23:35:09 +01:00
Sebastian McKenzie
8eee5367f3 add Noop node 2015-06-07 23:34:35 +01:00
Sebastian McKenzie
40d55a3d44 update makefile browser build filename 2015-06-07 20:24:21 +01:00
Sebastian McKenzie
75330304dc fix linting errors 2015-06-07 20:04:30 +01:00
Sebastian McKenzie
776c508418 add node build to Makefile 2015-06-07 19:41:28 +01:00
Sebastian McKenzie
e804741632 add module metadata - closes #1601 2015-06-07 19:41:20 +01:00
Sebastian McKenzie
3d3cb4be4f completely rework type inferrence, support coercing to union types and be more reliable in the inferrence and always be cautious 2015-06-07 19:39:53 +01:00
Sebastian McKenzie
64f4209119 recurse into type casts when trying to get it's expression - fixes #facebook/react-native#1526 2015-06-07 02:45:06 +01:00
Sebastian McKenzie
2ede226ef9 remove unused variables 2015-06-06 16:35:28 +01:00
Sebastian McKenzie
f5cf641c0a add support for async generators to type inferrence 2015-06-06 16:17:55 +01:00
Sebastian McKenzie
1abd3419f6 simplify NodePath.getScope 2015-06-06 16:17:43 +01:00
Sebastian McKenzie
75699db716 clean up options normalisation and add more comments 2015-06-06 16:17:30 +01:00
Sebastian McKenzie
7c3572f08c fix linting errors 2015-06-06 03:38:12 +01:00
Sebastian McKenzie
9dacde6d07 further implement the concept of a "Hub" that all traversal paths get access to, also add in some assertions to confirm path state when performing manipulation 2015-06-06 03:34:08 +01:00
Sebastian McKenzie
8c3aab9a26 add support for async functions to type inferrence 2015-06-06 03:33:32 +01:00
Sebastian McKenzie
ba4550c953 switch some node-parent based stuff to path-based 2015-06-06 03:33:22 +01:00
Sebastian McKenzie
d0ac65a934 add _paths in t.inherits 2015-06-06 03:32:35 +01:00
Sebastian McKenzie
a4c70bb029 this commit makes the following changes to the way paths are handled:
- store paths on parents instead of containers
 - implement one central hub that all traversal paths and scopes get access to in order to abstract out access to common functions
2015-06-06 03:32:22 +01:00
Sebastian McKenzie
795cf0c0b1 add ignore/only tests to ensure #1693 never happens again 2015-06-05 23:11:10 +01:00
Sebastian McKenzie
e64b90e322 5.5.4 2015-06-05 23:07:27 +01:00
Sebastian McKenzie
d69b0973e1 v5.5.4 2015-06-05 23:03:55 +01:00
Sebastian McKenzie
6296f49653 update minification.constantFolding transformer to deopt bindings that are reassigned in a different function scope 2015-06-05 23:01:31 +01:00
Sebastian McKenzie
9f2b739046 improve Scope#dump to print binding info 2015-06-05 23:00:50 +01:00
Sebastian McKenzie
da1d5e5577 simplify unary resolution and move operators to types 2015-06-05 23:00:06 +01:00
Sebastian McKenzie
7333b4e392 move staticPropBody class concat to after className check in es6.classes transformer 2015-06-05 22:44:03 +01:00
Sebastian McKenzie
b0442d0784 add back shouldIgnore check that went missing around 32f19aff99 - closes #1696, fixes #1693 2015-06-05 22:43:32 +01:00
Sebastian McKenzie
295e69f8f8 fix auxiliaryComment option name for istanbul interop - fixes #1695 2015-06-05 22:40:28 +01:00
Sebastian McKenzie
cfe844fa39 add boolean type to experimental option 2015-06-05 22:36:16 +01:00
Sebastian McKenzie
0f4ea2d2a6 use file.log.deprecate instead of throwing an error - fixes #1694 2015-06-05 22:35:46 +01:00
Sebastian McKenzie
4b85b05839 use actual parameter reference for non-last default parameters - fixes #1690 2015-06-05 14:08:18 +01:00
Sebastian McKenzie
2539d08dce 5.5.3 2015-06-05 14:07:34 +01:00
Sebastian McKenzie
c26fd7a819 fix regenerator version 2015-06-05 14:07:27 +01:00
Sebastian McKenzie
2053610429 v5.5.3 2015-06-05 12:20:22 +01:00
Sebastian McKenzie
cd4f83b299 fix linting errors 2015-06-05 12:19:32 +01:00
Sebastian McKenzie
ec29ba19a9 add 5.5.3 changelog 2015-06-05 12:18:43 +01:00
Sebastian McKenzie
9dc03e0978 traverse over ClassProperty path rather than node 2015-06-05 12:17:55 +01:00
Sebastian McKenzie
bc4258eca9 add type inferrence for template literals 2015-06-05 12:17:45 +01:00
Sebastian McKenzie
b0e58f9770 add completion statement test and enable experimental option on deadCodeElimination tests 2015-06-05 12:17:36 +01:00
Sebastian McKenzie
a1e2641c91 5.5.2 2015-06-05 12:17:18 +01:00
Sebastian McKenzie
9108422f99 v5.5.2 2015-06-05 12:03:38 +01:00
Sebastian McKenzie
9e8f4b25ca add missing semicolon 2015-06-05 12:02:30 +01:00
Sebastian McKenzie
1cecd24823 make experimental warning more scary 2015-06-05 12:01:52 +01:00
Sebastian McKenzie
97f6e1469b add 5.5.2 changelog 2015-06-05 12:01:44 +01:00
Sebastian McKenzie
ec46eaf224 add scary experimental warning for people who use obscure transformers that are still WIP 2015-06-05 11:55:09 +01:00
Sebastian McKenzie
a102692103 when using babel/register always use the cwd - fixes #1689 2015-06-05 11:54:52 +01:00
Sebastian McKenzie
0376ec8ff0 t.isPure -> this.isPure - fixes #1688 2015-06-05 11:33:25 +01:00
Sebastian McKenzie
5932a07610 5.5.1 2015-06-05 09:57:21 +01:00
Sebastian McKenzie
6110b0c0b3 v5.5.1 2015-06-05 09:56:27 +01:00
Sebastian McKenzie
365e221d95 fix deoptValue binding boolean - fixes #1687 2015-06-05 09:55:47 +01:00
Sebastian McKenzie
acbc4859c0 only remove ClassProperty in flow transformer when it has no value 2015-06-05 09:53:59 +01:00
Sebastian McKenzie
55750e05e7 Revert "enable es6.spec.symbols by default"
This reverts commit f3acedbf08.
2015-06-05 09:44:22 +01:00
Sebastian McKenzie
ba9c4db673 finish 5.5.1 changelog - ref #1686 2015-06-05 09:43:34 +01:00
Sebastian McKenzie
ba8a63a69e remove trailing json comma 2015-06-05 09:42:53 +01:00
Sebastian McKenzie
25581981b5 always remove ClassProperty nodes in flow transformer - fixes #1686 2015-06-05 09:42:46 +01:00
Sebastian McKenzie
02a6feed73 update template literal parsing to properly handle newlines 2015-06-05 09:36:37 +01:00
Sebastian McKenzie
f3acedbf08 enable es6.spec.symbols by default 2015-06-05 08:43:41 +01:00
Sebastian McKenzie
35ab4ffaab 5.5.0 2015-06-05 08:12:17 +01:00
Sebastian McKenzie
ddfb7f2c11 v5.5.0 2015-06-05 08:11:10 +01:00
Sebastian McKenzie
e2ca03f92d fix linting errors 2015-06-05 08:10:22 +01:00
Sebastian McKenzie
c75a3c68e5 add 5.5.0 changelog 2015-06-05 08:08:20 +01:00
Sebastian McKenzie
5d617ea99b upgrade regenerator - fixes #1685 2015-06-05 07:56:33 +01:00
Sebastian McKenzie
58059a2c48 add deoptValue method to Binding that ignores all subsequent setValue calls 2015-06-05 07:52:57 +01:00
Sebastian McKenzie
4c2936773a update type inferrence to support unary operators 2015-06-05 07:47:22 +01:00
Sebastian McKenzie
c7c16ad9c1 add control flow support and deopt bindings on assignments that we can't understand 2015-06-05 07:46:32 +01:00
Sebastian McKenzie
7b676d608b allow NodePaths to be returned in node removal/replacement methods and coerce them to nodes 2015-06-05 07:46:10 +01:00
Sebastian McKenzie
48ecec1e2e move more transformers to builtin-pre group 2015-06-05 07:45:32 +01:00
Sebastian McKenzie
9dc72e71d4 add skipKey method to skip traversal of subsequent keys 2015-06-05 07:45:19 +01:00
Sebastian McKenzie
4a7a02b9af rename builtin-setup transformer group to builtin-pre 2015-06-05 07:44:45 +01:00
Sebastian McKenzie
7cb460d2f3 add eval optional transformer 2015-06-05 07:44:29 +01:00
Sebastian McKenzie
0a7dac8744 move flow to builtin-trailing group 2015-06-05 07:44:15 +01:00
Sebastian McKenzie
667d595a73 use type inferrence to work out whether to wrap template literals with the String constructor 2015-06-05 07:43:58 +01:00
Sebastian McKenzie
2d2d957be5 add back ComprehensionBlock binding identifier keys and remove body form ComprehensionBlock visitor keys 2015-06-04 22:50:17 +01:00
Sebastian McKenzie
5aef7afade fix remaining AssignmentExpression LHS ReferencedIdentifier bugs 2015-06-04 22:43:50 +01:00
Sebastian McKenzie
d5e7b5616c Merge branch 'master' of github.com:babel/babel 2015-06-04 22:23:42 +01:00
Sebastian McKenzie
9aa17a6cc2 don't consider JSXIdentifier HTML tags to be references - fixes #1683 2015-06-04 22:23:24 +01:00
Sebastian McKenzie
0f13097f59 add basic naive constant folding of assignment expressions 2015-06-04 22:08:38 +01:00
Sebastian McKenzie
355ffbdaf8 don't consider the LHS of an AssignmentExpression to be a reference 2015-06-04 22:07:44 +01:00
Sebastian McKenzie
45b0d63d72 copy parent class binding to class in the collection visitor 2015-06-04 22:07:19 +01:00
Sebastian McKenzie
c515271fbd Merge pull request #1677 from jmm/node_modules-robust3
Complete "Fix flawed require hook node_modules check" properly
2015-06-03 19:23:41 +01:00
Jesse McCarthy
6f3501876a Add test for require-hook node_modules check. 2015-06-03 09:04:59 -04:00
Jesse McCarthy
f8afc5fa17 Revert "Add test for require-hook node_modules check."
This reverts commit 1488d88c81.

Wrong branch was accidentally merged. There is a better test.
2015-06-03 09:04:59 -04:00
Sebastian McKenzie
4ecda93147 move deprecated minification.inlineExpressions to aliases 2015-06-03 10:05:56 +01:00
Sebastian McKenzie
41847162b1 check if es7.exportExtensions ie enabled in parser 2015-06-03 10:05:39 +01:00
Sebastian McKenzie
0f7e010e3e remove isSpecifierDefault check for ExportDefaultSpecifier - fixes #1673 2015-06-03 10:05:19 +01:00
Sebastian McKenzie
8201ea0aa2 Merge branch 'master' of github.com:babel/babel
# Conflicts:
#	src/babel/api/register/node.js
2015-06-03 07:26:46 +01:00
Sebastian McKenzie
a7848c1822 Merge branch 'jmm-node_modules-robust' 2015-06-03 07:26:19 +01:00
Sebastian McKenzie
d4abaeeecf Merge branch 'node_modules-robust' of https://github.com/jmm/babel into jmm-node_modules-robust 2015-06-03 07:26:12 +01:00
Sebastian McKenzie
871a82df0a Merge pull request #1665 from Jabher/master
Making babel able to run in node_modules directory
2015-06-03 07:25:22 +01:00
Sebastian McKenzie
ffbf5b0b47 convert property key to computed before checking if it's a displayName property in the react transformer builder - closes #1671 2015-06-02 23:08:46 +01:00
Sebastian McKenzie
9dcceaeb40 move minification.deadCodeElimination back to the builtin-setup transformer group 2015-06-02 17:08:49 +01:00
Sebastian McKenzie
556e58a4ab register function declarations anyway as we may not have hit them 2015-06-02 17:08:31 +01:00
Sebastian McKenzie
b6c35743e6 add import types 2015-06-02 16:24:32 +01:00
Sebastian McKenzie
0abd34f7e6 Merge branch 'master' of github.com:babel/babel 2015-06-02 16:18:13 +01:00
Sebastian McKenzie
cafd7f8e39 add Infinity/NaN, string/number member expressions/calls and Math calls static evaluation 2015-06-02 16:18:08 +01:00
Sebastian McKenzie
43c0a0e65f remove all non-function statements after completion statements in blocks 2015-06-02 16:16:36 +01:00
Sebastian McKenzie
7b359f46fd rename minification.inlineExpressions to minification.constantFolding 2015-06-02 16:16:10 +01:00
Sebastian McKenzie
880827f6ce Merge pull request #1669 from wincent/mixed-type
Add "mixed" Flow type
2015-06-02 16:15:23 +01:00
Greg Hurrell
0c300058a3 Add "mixed" Flow type
"mixed" is one of the base types listed here:

http://flowtype.org/docs/base-types.html

So this commit adds support for it.
2015-06-02 07:15:06 -07:00
Sebastian McKenzie
d35be22f7d add support for resolving array expression elements 2015-06-02 00:32:18 +01:00
Sebastian McKenzie
ff8d90061f add "istanbul ignore next" auxiliary comment when using istanbul compat mode for babel/register 2015-06-02 00:32:07 +01:00
Vsevolod Rodionov
e66109f9d0 Making babel able to run in node_modules directory (while still ignoring node_modules packages)
In case if app is installed by npm install <git tarball url> which is very comfortable thing (postinstall hooks, automatic package installation and so on) babel is unable to run over packages, e.g.
```
 ~/node_modules/some_app$ node-babel app.js
  ```
 is crashing as babel do not want in node_modules directory.

 relative path gives ability to check whether lib is in node_modules _relative_ to current app, so that if app is ran in node_modules by itself it will not be captured.
2015-06-01 14:55:51 -07:00
Sebastian McKenzie
1934c16f0f don't use initializer property for decorators on concise methods in object literals 2015-06-01 22:32:04 +01:00
Sebastian McKenzie
012ac7d9ec remove accidental console.log introduced in 80a7f13460 2015-06-01 22:01:27 +01:00
Jesse McCarthy
efb3b04225 Make node_modules path check robust. 2015-06-01 16:54:56 -04:00
Jesse McCarthy
1488d88c81 Add test for require-hook node_modules check.
(Failing.)
2015-06-01 16:54:52 -04:00
Sebastian McKenzie
80a7f13460 register named method id as a reference to avoid collisions - fixes #1664 2015-06-01 21:53:34 +01:00
Sebastian McKenzie
8919fc22b1 only infer single identifier new expression callees 2015-06-01 21:52:54 +01:00
Sebastian McKenzie
b1273cb774 Merge pull request #1663 from pangratz/fix_for_referencesImport
Minor fix for `referencesImport`
2015-06-01 18:13:49 +01:00
pangratz
0843b8355e Minor fix for referencesImport 2015-06-01 19:09:33 +02:00
Sebastian McKenzie
6457677fb4 add support for NewExpression and reference plain node 2015-06-01 17:29:02 +01:00
Sebastian McKenzie
f8a860bf21 remove unused import 2015-06-01 14:32:58 +01:00
Sebastian McKenzie
f2bed33db8 add type inference for ConditionalExpression, SequenceExpression, AssignmentExpression and add support for base type aliases in isTypeAnnotationGeneric method 2015-06-01 14:25:06 +01:00
Sebastian McKenzie
7d2c6525d8 flesh out type inferrence some more, rename some of the NodePath methods to be less ambiguous, remove dead Binding type methods 2015-06-01 14:01:14 +01:00
Sebastian McKenzie
de652dc747 change getBindingIdentifier keys to be just a string instead of an array 2015-06-01 12:06:36 +01:00
Sebastian McKenzie
9f1053212b add EmptyStatement to t.toSequenceExpression 2015-06-01 12:06:16 +01:00
Sebastian McKenzie
76690a3deb renamed Path#isPreviousType to isType 2015-06-01 12:05:42 +01:00
Sebastian McKenzie
50f2f2fc98 remove DoExpression statement parsing and clear labels and set inFunction to false when parsing DoExpression body - fixes #1658 2015-06-01 03:36:14 +01:00
Sebastian McKenzie
5c27234d19 change TCO BlockStatement visitor back to enter 2015-06-01 00:17:44 +01:00
Sebastian McKenzie
6f5d16f397 remove TCOable check 2015-06-01 00:14:12 +01:00
Sebastian McKenzie
e42a43e3d1 remove unnecessary strict helper 2015-05-31 23:40:59 +01:00
Sebastian McKenzie
bfd307cd57 move some visitors out of deoptimising enter method 2015-05-31 23:40:42 +01:00
Sebastian McKenzie
beb5ee1333 remove useless generator test helpers 2015-05-31 21:26:22 +01:00
Sebastian McKenzie
cde871555d don't pass comments in tokens to estraverse 2015-05-31 21:26:12 +01:00
Sebastian McKenzie
51b0ffa7bf prepend Comment to comment node types 2015-05-31 20:25:26 +01:00
Sebastian McKenzie
255c819727 optimise ES6 tail call transformer to only try TOC on functions that include a call to themselves 2015-05-31 15:40:41 +01:00
Sebastian McKenzie
152ccb2ce8 check if ObjectExpression has any gets/sets before filtering 2015-05-31 15:40:07 +01:00
Sebastian McKenzie
bdb3adfeea revert parts of 07a992e 2015-05-31 09:47:27 +01:00
Sebastian McKenzie
236086bee5 ignore trailing commas when inferring newlines - fixes #1304 2015-05-31 09:46:05 +01:00
Sebastian McKenzie
1436753e6d fix linting errors 2015-05-31 09:24:12 +01:00
Sebastian McKenzie
eadf8ef799 fix syntax error in helpers/parse 2015-05-31 09:20:16 +01:00
Sebastian McKenzie
f1e20cf6ff remove useless comment 2015-05-31 09:16:34 +01:00
Sebastian McKenzie
82a0851526 push comments to token stream to avoid having to re-sort - #1486 2015-05-31 09:16:27 +01:00
Sebastian McKenzie
07a992e6d3 add support for tail calls when in completion record position - fixes #1572 2015-05-31 09:07:44 +01:00
Sebastian McKenzie
f642c2baa8 relax key aliases for plain methods - fixes #1649 2015-05-30 23:53:39 -04:00
Sebastian McKenzie
2f7743cafb optimise module metadata retrieval - #1486 2015-05-30 23:42:24 -04:00
Sebastian McKenzie
44112f2d87 remove unused variable 2015-05-30 23:18:50 -04:00
Sebastian McKenzie
99c4810770 add regeneratot transform to builtin-advanced group 2015-05-30 23:18:45 -04:00
Sebastian McKenzie
9f2ac15695 move jscript transformer to the builtin-trailing group and perform transform on exit - closes #1652, fixes #1651 2015-05-30 23:09:25 -04:00
Sebastian McKenzie
19c1ee157f simplify scope parent alias keys 2015-05-30 23:08:42 -04:00
Sebastian McKenzie
973270772b use ForX alias instead of manually listing all types 2015-05-30 23:08:28 -04:00
Sebastian McKenzie
7334326042 remove extra semicolon 2015-05-30 22:37:18 -04:00
Sebastian McKenzie
4043e8e8b9 fix destructuring transformer AssignmentExpression to properly handle completion records 2015-05-30 22:33:09 -04:00
Sebastian McKenzie
7fd403998c remove dead code 2015-05-30 22:32:48 -04:00
Sebastian McKenzie
1f7fcc2985 Merge branch 'master' of github.com:babel/babel 2015-05-30 22:13:59 -04:00
Sebastian McKenzie
ba19bd36a4 optimise scope tracking into a single pass - #1486 2015-05-30 22:07:03 -04:00
Sebastian McKenzie
e119681b1f return paths accordingly in insertBefore and insertAfter methods 2015-05-30 22:03:25 -04:00
Sebastian McKenzie
fbe22e53a9 add check for dynamic node and output error message accordingly 2015-05-30 22:02:56 -04:00
Sebastian McKenzie
79e826fcc8 attempt to optimise node printing by shifting it into a class 2015-05-30 22:02:29 -04:00
Sebastian McKenzie
cf940268b9 add noScope to template visitor 2015-05-30 22:02:15 -04:00
Sebastian McKenzie
96bb572307 use flow type shorthand for eaching over specifiers 2015-05-30 19:09:23 -04:00
Sebastian McKenzie
5dafe0b66a collapse t.getBindingIdentifiers comment 2015-05-30 19:08:14 -04:00
Sebastian McKenzie
29e24a4cbe don't evaluate non-referenced identifiers 2015-05-30 19:07:58 -04:00
Sebastian McKenzie
f979d55b71 remove special ExpressionStatement handling in destructuring transformer 2015-05-30 19:07:31 -04:00
Sebastian McKenzie
164b2116a3 switch expontentation evaluation to just use the operator 2015-05-30 19:05:31 -04:00
Dan Abramov
55e623a099 Merge pull request #1650 from jmm/contrib-build-version
Make note about buildable versions more prominent.
2015-05-30 11:29:59 +03:00
Jesse McCarthy
a60b4b1302 Make note about buildable versions more prominent. 2015-05-29 14:14:15 -04:00
Dan Abramov
bf23e59bbf Add a note about building older versions. Fixes #1643 2015-05-29 16:50:34 +03:00
Sebastian McKenzie
eb4cee89c5 add referencesImport path method - fixes #1423 2015-05-28 11:39:51 -04:00
Sebastian McKenzie
fb94a87a4d add support for cluster forking - fixes #1611 2015-05-28 10:36:29 -04:00
Sebastian McKenzie
9613c7fdb6 fix linting error 2015-05-28 10:30:09 -04:00
Sebastian McKenzie
d8c97fba15 check plugin.default and then just plugin to support ES6 modules - closes #1627 2015-05-28 10:25:50 -04:00
Sebastian McKenzie
0f663560d4 add --nolazy to babel-node - fixes #1639 2015-05-28 10:24:31 -04:00
Sebastian McKenzie
4901075960 deopt rest parameter member expression optimisation on child arrow functions - fixes #1631 2015-05-28 10:22:12 -04:00
Sebastian McKenzie
4aec242979 add some comments to some path methods and remove some dead code 2015-05-28 10:04:46 -04:00
Sebastian McKenzie
d1d95e0e49 check LHS of ForIn/ForOfStatement for constants - closes #1630 2015-05-28 10:04:32 -04:00
Sebastian McKenzie
d3c643b004 clean up path resolution and add in path resolution recursion detection - cc @RReverser 2015-05-25 19:08:08 +01:00
Sebastian McKenzie
98eb30c482 rename Path#remove to Path#dangerouslyRemove 2015-05-25 16:17:28 +01:00
Sebastian McKenzie
2d43ffb5b4 remove removal scope hooks 2015-05-25 15:57:22 +01:00
Sebastian McKenzie
a195701de2 remove dead code 2015-05-25 15:28:23 +01:00
Sebastian McKenzie
f639f4bea7 upgrade babel-eslint 2015-05-25 15:28:16 +01:00
Sebastian McKenzie
334cbb06c6 flesh out removal hooks more 2015-05-25 15:28:11 +01:00
Sebastian McKenzie
f4a3b2f01a add link to readme in contributing guide so people can't whinge and note in the README that issues without reproducible examples will be closed 2015-05-25 14:55:37 +01:00
Sebastian McKenzie
dbe6f1b9a9 merge remove parent context checks 2015-05-25 04:30:17 +01:00
Sebastian McKenzie
73ada57a17 don't inline classes and functions when they're in different scopes in the utility.deadCodeElimination transformer 2015-05-25 03:33:12 +01:00
Sebastian McKenzie
8e2b743f7e add support for resyncing container on changes 2015-05-25 03:32:25 +01:00
Sebastian McKenzie
a533042503 fix bad .gitignore paths resulting in some tests and path/lib files not being included... 2015-05-25 01:42:54 +01:00
Sebastian McKenzie
49953e3464 enable no-unused-vars in eslint 2015-05-25 01:32:06 +01:00
Sebastian McKenzie
0bf95d6aea even more split up of path methods 2015-05-25 01:01:21 +01:00
Sebastian McKenzie
7d88a1ca0b rename TraversalPath to NodePath and further split up methods into separate files 2015-05-25 00:43:46 +01:00
Sebastian McKenzie
ec74eb41cf reneable eslint and fix assorted linting errors 2015-05-25 00:42:59 +01:00
Sebastian McKenzie
3139482358 clean and fix up visitor merging 2015-05-24 18:15:46 +01:00
Sebastian McKenzie
32f19aff99 clean up file processing API 2015-05-24 18:15:34 +01:00
Sebastian McKenzie
23bead9226 Merge branch 'master' of github.com:babel/babel 2015-05-24 01:45:00 +01:00
Sebastian McKenzie
bd3812c255 handle SwitchStatements as a different type of path when pushing a declaration - fixes #1614 2015-05-24 01:43:04 +01:00
Sebastian McKenzie
e498185a76 Merge pull request #1610 from dekelcohen/master
Fixed Remove Debugger transformer to use DebuggerStatement
2015-05-22 23:36:47 +01:00
Dekel Cohen
167eda4750 Fixed Remove Debugger transformer to use DebuggerStatement 2015-05-23 01:13:23 +03:00
Sebastian McKenzie
3b52ddce6d 5.4.7 2015-05-21 19:00:16 +01:00
Sebastian McKenzie
0e771c5d38 v5.4.7 2015-05-21 18:59:30 +01:00
Sebastian McKenzie
2ec1544f2d add 5.4.7 changelog 2015-05-21 18:58:49 +01:00
Sebastian McKenzie
049ef430b2 5.4.6 2015-05-21 18:58:12 +01:00
Sebastian McKenzie
34eb2babdb don't consider JSXAttribute keys to be referenced identifiers - fixes #1596 2015-05-21 18:58:07 +01:00
Sebastian McKenzie
8706754550 v5.4.6 2015-05-21 18:46:22 +01:00
Sebastian McKenzie
c7b507e119 add 5.4.6 changelog 2015-05-21 18:45:31 +01:00
Sebastian McKenzie
221c632c05 deprecate custom module formatters 2015-05-21 18:44:02 +01:00
Sebastian McKenzie
7dbde208ef spec.functionName transformer: hasBinding(name) returns true for built-in globals, so we attempt to rename the binding but it doesn't exist so exits early, add a check that doesn't perform the renaming and instead uses the wrapper - fixes #1598 2015-05-21 18:43:55 +01:00
Sebastian McKenzie
52a2e3e17c return original input if glob returned nothing in babel-cli - fixes #1591 2015-05-21 10:57:37 +01:00
Sebastian McKenzie
fa22d7dca0 5.4.5 2015-05-21 01:52:03 +01:00
Sebastian McKenzie
9fcdebde08 v5.4.5 2015-05-21 01:44:29 +01:00
Sebastian McKenzie
92157161f0 fix prettyCall generation option 2015-05-21 01:43:02 +01:00
Sebastian McKenzie
82b5479436 add 5.4.5 changelog 2015-05-21 01:41:30 +01:00
Sebastian McKenzie
91a037af55 Merge pull request #1590 from Khan/fix_retainLines_with_jsx
tests for retainLines formatting
2015-05-21 01:39:33 +01:00
Kevin Barabash
067fccc2c9 tests for retainLines formatting 2015-05-20 18:36:47 -06:00
Sebastian McKenzie
348c0d2542 handle TCO for calls that exceed the functions parameter count - fixes #1589 2015-05-21 01:21:49 +01:00
Sebastian McKenzie
f2f6bbb02c clean up explosion of module declarations, remove and inherit comments when taking off the declaration - fixes #1583 2015-05-21 01:03:23 +01:00
Sebastian McKenzie
16f7b967b5 ignore CallExpression _prettyCall when retainLines is enabled - fixes #1585 2015-05-21 00:21:18 +01:00
Sebastian McKenzie
270a8be68d add JSXIdentifier as a valid ReferencedIdentifier - fixes #1584 2015-05-21 00:20:53 +01:00
Sebastian McKenzie
82254d9d9b force push space for await/async - fixes #1581 2015-05-20 12:45:04 +01:00
Sebastian McKenzie
759a265fb0 5.4.4 2015-05-20 10:52:28 +01:00
Sebastian McKenzie
ee46f45c90 v5.4.4 2015-05-20 10:50:35 +01:00
Sebastian McKenzie
c45ce61550 print assignment pattern shorthand with matching key nicely 2015-05-20 10:44:36 +01:00
Sebastian McKenzie
b36cf11ac8 add 5.4.4 changelog 2015-05-20 10:44:17 +01:00
Sebastian McKenzie
dca0f72e4d clarify default option descriptions - fixes #1577 2015-05-20 10:36:58 +01:00
Sebastian McKenzie
68a99ed1e9 fix es6.modules-system for head hoisting 2015-05-20 10:35:01 +01:00
Sebastian McKenzie
af4feb4d88 fix renaming of assignment expressions to fix pattern renaming in the es6.blockScoping transformer - fixes #1576 2015-05-20 10:34:50 +01:00
Sebastian McKenzie
de1e965fec fix placement of for loop in es6.modules-system hoisting test 2015-05-20 10:15:42 +01:00
Sebastian McKenzie
430c5df0e7 rename sourceMapName option to sourceMapTarget - closes #1568 2015-05-20 10:14:28 +01:00
Sebastian McKenzie
9b12f799f7 clean up system module formatter hoisting visitor and allow contextual replacement of variable declarations with expressions in for head positions - fixes #1570 2015-05-20 10:07:29 +01:00
Sebastian McKenzie
f3a9c6ee5d Merge pull request #1562 from clintwood/sourcemap-file
correct cli source map file: value, honor sourceRoot when using -o opion
2015-05-20 09:57:34 +01:00
Sebastian McKenzie
e0aceeafef Merge pull request #1570 from guybedford/system-hoist-bug
System format hoisting bug
2015-05-20 09:57:14 +01:00
Sebastian McKenzie
7643d86047 Merge branch 'master' of github.com:babel/babel 2015-05-20 09:57:03 +01:00
Sebastian McKenzie
98af01a73c update old 6to5 package.json description 2015-05-20 09:56:54 +01:00
Sebastian McKenzie
e280a810c3 add support for all completion record types when exploding an expression to statements 2015-05-20 09:56:45 +01:00
Sebastian McKenzie
7a59575d1e force space before class id when generating classes - fixes #1579 2015-05-20 09:56:19 +01:00
Sebastian McKenzie
b01d8448a0 Merge pull request #1558 from jquense/patch-2
Resolve "babel-plugin-" name before trying the plain name.
2015-05-19 01:28:02 +01:00
jquense
9b3c8569f7 Resolve 'babel-plugin-' name before the plain name
Otherwise you get situations like the following: `plugins: [
'object-assign']` resolves the module `object-assign` (an Object.assign
polyfill) instead of the intended babel plugin:
babel-plugin-object-assign.
2015-05-18 20:26:51 -04:00
Sebastian McKenzie
12104f822f add assignment pattern shorthand support to explode transformer - fixes #1566 2015-05-18 22:44:40 +01:00
Sebastian McKenzie
b4cd2df745 ignore this and arguments when performing TCO on shadowed functions - fixes #1564 2015-05-18 22:41:27 +01:00
guybedford
887ffed84c system hoist bug test case 2015-05-18 23:35:09 +02:00
Sebastian McKenzie
9be3d9c8e1 Merge branch 'master' of github.com:babel/babel 2015-05-18 10:33:12 +01:00
clintwood (Office)
9d3dff3b7a correct cli source map file: value, honor sourceRoot when using -o option 2015-05-18 10:11:20 +02:00
Sebastian McKenzie
55114ec631 update AMD module formatter to add import default remapping - #1150 2015-05-18 02:01:34 +01:00
Sebastian McKenzie
9c3d00d3c3 Merge pull request #1559 from sindresorhus/hometmp
use `home-or-tmp` module instead of `user-home`
2015-05-17 23:50:26 +01:00
Sindre Sorhus
90b8826e73 use home-or-tmp module instead of user-home
The main point about using this instead of just falling back in code is that it depends on an `os.tmpdir()` polyfill [0], which means the tmpdir handling is the same no matter node/iojs version. This is useful as the core `os.tmpdir()` function has changed a lot between node versions.

[0]: https://github.com/sindresorhus/os-tmpdir

---

`os.tmpdir()` diff between Node 0.10.38 and iojs 2.0.2

```diff
+const trailingSlashRe = isWindows ? /[^:]\\$/
+                                  : /.\/$/;
+
 exports.tmpdir = function() {
-  return process.env.TMPDIR ||
-         process.env.TMP ||
-         process.env.TEMP ||
-         (process.platform === 'win32' ? 'c:\\windows\\temp' : '/tmp');
+  var path;
+  if (isWindows) {
+    path = process.env.TEMP ||
+           process.env.TMP ||
+           (process.env.SystemRoot || process.env.windir) + '\\temp';
+  } else {
+    path = process.env.TMPDIR ||
+           process.env.TMP ||
+           process.env.TEMP ||
+           '/tmp';
+  }
+  if (trailingSlashRe.test(path))
+    path = path.slice(0, -1);
+  return path;
 };
```
2015-05-18 00:39:49 +02:00
Sebastian McKenzie
65f39bbf6f switch order of jsx/flow plugins to avoid precedence issues - fixes babel/babel-eslint#103 2015-05-17 22:00:38 +01:00
Sebastian McKenzie
e9eced846f 5.4.3 2015-05-16 02:00:20 +01:00
Sebastian McKenzie
a0befe349d v5.4.3 2015-05-16 01:58:52 +01:00
Sebastian McKenzie
04992effb3 improve lost node path tracking message 2015-05-16 01:54:35 +01:00
Sebastian McKenzie
9ae54d2a50 add 5.4.3 changelog 2015-05-16 01:54:25 +01:00
Sebastian McKenzie
fe72a40159 Revert "add back descriptor.initializer existence check"
This reverts commit 02dfd18023.
2015-05-16 01:50:31 +01:00
Sebastian McKenzie
ea510d09d0 fix module shadowing when using CommonJS-like module formatters - fixes #1544 2015-05-16 01:47:48 +01:00
Sebastian McKenzie
375689a1ff handle path contexts MUCH better, they're now only held during the traversal iteration and the previous context is released upon completion, also verify path keys and try and obtain a new one if invalid - fixes #1545 2015-05-16 01:37:55 +01:00
Sebastian McKenzie
9908e331b7 Merge pull request #1549 from Naddiseo/master
Added DCE tests for all the bugs I've reported so far.
2015-05-15 23:08:32 +01:00
Richard Eames
cd8655708d Added DCE tests for all the bugs I've reported so far. 2015-05-15 15:55:58 -06:00
Sebastian McKenzie
62b94f297a don't create a new binding for local class ids, just copy the parents - fixes #1547 2015-05-15 19:11:24 +01:00
Sebastian McKenzie
01d399ee3c check for existence of variable when checking if node is pure 2015-05-15 18:48:17 +01:00
Sebastian McKenzie
30e3908484 don't perform DCE on single references nested inside the binding initializer - fixes #1546 2015-05-15 18:48:05 +01:00
Sebastian McKenzie
ff12046009 move traverse replace test up 2015-05-15 18:35:15 +01:00
Sebastian McKenzie
1a058b4a6e Merge branch 'master' of github.com:babel/babel 2015-05-15 17:42:40 +01:00
Sebastian McKenzie
02dfd18023 add back descriptor.initializer existence check 2015-05-15 17:42:28 +01:00
Sebastian McKenzie
9ab7df5f47 remove wildcards from start of patterns 2015-05-15 17:42:10 +01:00
Sebastian McKenzie
7a5b140f92 minor generation style nits 2015-05-15 17:41:56 +01:00
Sebastian McKenzie
6f83111c55 Merge pull request #1542 from amasad/already-printed
Fix bug with paren printing in compact + line retained mode
2015-05-15 17:38:40 +01:00
Sebastian McKenzie
f3f60368da remove TraversalPath node getter/setter 2015-05-15 17:34:31 +01:00
Sebastian McKenzie
7a09640b20 add environment to register cache key 2015-05-15 17:34:06 +01:00
Amjad Masad
2916d1262b Don't print leftParen if already printed before the catchup 2015-05-14 23:57:35 -07:00
Amjad Masad
741abb73d2 Add failing test for printing with compact & retainLines 2015-05-14 23:57:05 -07:00
Sebastian McKenzie
2e46755260 5.4.2 2015-05-15 02:36:22 +01:00
Sebastian McKenzie
2cff9519e1 v5.4.2 2015-05-15 02:35:07 +01:00
Sebastian McKenzie
f9c2c6e988 Merge branch 'master' of github.com:babel/babel
# Conflicts:
#	CHANGELOG.md
2015-05-15 02:34:11 +01:00
Sebastian McKenzie
5ae3dc01f1 make path patterns used by only and ignore **very** liberal, this will ease a lot of pain in dealing with them 2015-05-15 02:33:40 +01:00
Sebastian McKenzie
af4fd69dd0 make path patterns used by only and ignore **very** liberal, this will ease a lot of pain in dealing with them 2015-05-15 02:33:22 +01:00
Sebastian McKenzie
4d4493f325 elaborate on shouldIgnore changes in 5.4.1 2015-05-15 02:03:02 +01:00
Sebastian McKenzie
e70d474b39 5.4.1 2015-05-15 02:01:42 +01:00
Sebastian McKenzie
1b45f64858 v5.4.1 2015-05-15 02:00:18 +01:00
Sebastian McKenzie
b89cf6768f fix shouldIgnore only matches switch 2015-05-15 01:57:10 +01:00
Sebastian McKenzie
36ad1108b4 fix loose mode loop being weirdly inserted 2015-05-15 01:56:34 +01:00
Sebastian McKenzie
4c04371ea4 remove loop label due to babel bug 2015-05-15 01:48:47 +01:00
Sebastian McKenzie
d3e385c554 one last try fixing the shouldIgnore only filter... 2015-05-15 01:46:36 +01:00
Sebastian McKenzie
6afcef9805 actually fix shouldIgnore algorithm this time, ugh 2015-05-15 01:44:57 +01:00
Sebastian McKenzie
ed861e230b fix shouldIgnore method for only 2015-05-15 01:41:49 +01:00
Sebastian McKenzie
e15ced2922 add 5.4.1 changelog 2015-05-15 01:37:48 +01:00
Sebastian McKenzie
93052e532f Merge branch 'master' of github.com:babel/babel 2015-05-15 01:35:43 +01:00
Sebastian McKenzie
198d51ddaa heavily improve shouldIgnore algorithm - fixes #1539 2015-05-15 01:34:58 +01:00
Sebastian McKenzie
8730b24def Merge pull request #1540 from browncolyn/master
Added slash as needed dependency
2015-05-15 01:30:50 +01:00
Colyn Brown
f09c0d5998 Added slash as needed dependency 2015-05-14 17:28:20 -07:00
Sebastian McKenzie
21e4481ab7 5.4.0 2015-05-15 00:32:36 +01:00
Sebastian McKenzie
2f61754a24 v5.4.0 2015-05-15 00:29:42 +01:00
Sebastian McKenzie
3910d18bc9 add 5.4.0 changelog 2015-05-15 00:28:47 +01:00
Sebastian McKenzie
583111ebfb expose file metadata object to transformers 2015-05-15 00:24:14 +01:00
Sebastian McKenzie
1b15481460 ignore "ignored files" when babel.transform has determined that it should be ignored, this is likely the result of an rc file resolution - fixes #1362 2015-05-15 00:24:03 +01:00
Sebastian McKenzie
fd9c98ff86 move strict transformer to builtin-setup group - fixes #1538 2015-05-15 00:18:42 +01:00
Sebastian McKenzie
41b5607ef3 fix env option tests 2015-05-15 00:11:28 +01:00
Sebastian McKenzie
ae77ea807f normalise source map file paths when using the CLI - fixes #1496 2015-05-15 00:05:11 +01:00
Sebastian McKenzie
ad44190c6b properly register for head variable declaration paths when performing scope tracking - fixes #1524 2015-05-14 23:53:04 +01:00
Sebastian McKenzie
024e4454a1 add env option - closes #1531 2015-05-14 23:47:56 +01:00
Sebastian McKenzie
14dddcda36 make PathHoister much more flexible, now ignores global references and will not deopt on reassignments and will instead hoist as high as it can, this also fixes #1529 since the order of operations has changed 2015-05-14 23:29:02 +01:00
Sebastian McKenzie
d4fb924b6a add tion comment to all function visitors 2015-05-14 22:37:15 +01:00
Sebastian McKenzie
b02c97af60 Merge pull request #1536 from benjamn/master
Invoke Regenerator on async/generator Function nodes, not whole AST.
2015-05-14 22:27:42 +01:00
Ben Newman
cc611cb71c Invoke Regenerator on async/generator Function nodes, not whole AST.
This should help (dramatically?) with
https://github.com/babel/babel/issues/1486#issuecomment-101491605,
although I'm not sure how to run the benchmarks myself.
2015-05-14 15:42:58 -05:00
Sebastian McKenzie
b8a01a9919 move traversal scope logic and binding into it's own folder, rename Scope#generateTemp to generateDeclaredUidIdentifier, rename Scope#generateUidBasedOnNode to Scope#generateUidIdentifierBasedOnNode 2015-05-14 19:12:26 +01:00
Sebastian McKenzie
55c99661be NFO 2015-05-14 18:07:36 +01:00
Sebastian McKenzie
1563b216df Merge branch 'master' of github.com:babel/babel 2015-05-14 17:56:33 +01:00
Sebastian McKenzie
a9d4b485d9 simplify getStaticContext in es7.functionBind transformer - thanks @RReverser! 2015-05-14 17:48:51 +01:00
Sebastian McKenzie
360daa6267 Merge pull request #1532 from dchambers/prefix-private-methods-with-underscore
Prefix private methods names with underscore.
2015-05-14 16:52:16 +01:00
Sebastian McKenzie
724bf52929 handle "static" contexts in es7.functionBind - #1518 2015-05-14 16:37:44 +01:00
Sebastian McKenzie
7407b37bd9 Merge pull request #1518 from babel/es7.functionBind
Add experimental support for ES7 function bind.
2015-05-14 16:22:21 +01:00
Ingvar Stepanyan
da765cc4c1 Flip the negation in if-else. 2015-05-14 18:05:55 +03:00
dchambers
4f862eee6e Prefix private methods names with underscore. 2015-05-14 13:19:41 +01:00
Ingvar Stepanyan
e05d7cf49a Fix some parsing edge cases for :: operator. 2015-05-14 12:47:51 +03:00
Ingvar Stepanyan
fd8e94a90f Preserve original execution order in :: operator. 2015-05-14 12:39:05 +03:00
Sebastian McKenzie
a6cf28c5b5 Merge pull request #1525 from nkt/exponentiation-operator-inline
Added missing exponential operator inlining
2015-05-13 23:09:57 +01:00
Nikita Gusakov
6b07b13a8e Added missing exponential operator inlining 2015-05-14 01:08:02 +03:00
Sebastian McKenzie
561c4dcc25 5.3.3 2015-05-13 22:09:37 +01:00
Sebastian McKenzie
b516ea596a v5.3.3 2015-05-13 22:08:32 +01:00
Sebastian McKenzie
248758eee3 fix version number 2015-05-13 22:07:33 +01:00
Sebastian McKenzie
a808602ae0 v3.5.3 2015-05-13 22:07:00 +01:00
Sebastian McKenzie
40e3436e95 add 3.5.3 changelog 2015-05-13 22:05:07 +01:00
Sebastian McKenzie
f704770b26 uncomment out return traversal path skipping - fixes #1523 2015-05-13 22:03:50 +01:00
Sebastian McKenzie
330665f150 ignore modules alongside param bindings in minification.deadCodeElimination transformer - fixes #1523 2015-05-13 21:49:28 +01:00
Sebastian McKenzie
af41899d74 5.3.2 2015-05-13 19:58:21 +01:00
Sebastian McKenzie
d12f4d0bc8 v5.3.2 2015-05-13 19:57:20 +01:00
Sebastian McKenzie
97680e9dfd properly hoist all var patterns when wrapping bodies in the es6.blockScoping transformer - fixes #1521 2015-05-13 19:55:40 +01:00
Sebastian McKenzie
51341ca6c3 fix and add missing module specifier reference detection - fixes #1520 2015-05-13 19:23:47 +01:00
Sebastian McKenzie
ab54bfa50e Merge pull request #1519 from zpao/package-licenses
Add license fields to packages
2015-05-13 18:36:25 +01:00
Paul O’Shannessy
60aa933fb6 Add license fields to packages 2015-05-13 10:21:42 -07:00
Ingvar Stepanyan
1a299b2bcc Small fixes to es7.functionBind and generation tests added. 2015-05-13 18:20:33 +03:00
Ingvar Stepanyan
37f662d790 Add experimental support for ES7 function bind. (issue #1287) 2015-05-13 17:58:21 +03:00
Sebastian McKenzie
b0317f9bab don't consider "globals" to cause incompatible scope hoist 2015-05-13 12:33:08 +01:00
Sebastian McKenzie
be2dfaf081 register variable declarator in scope when pushing 2015-05-13 09:11:09 +01:00
Sebastian McKenzie
2c8437ae92 ignore initializerless variable declaration when trying to inline single use variables - fixes #1516 2015-05-13 08:46:41 +01:00
Sebastian McKenzie
2a0bcfd086 add support for evaluating unary ~ 2015-05-13 08:45:16 +01:00
Sebastian McKenzie
2cf41afac3 move expression inlining to exit rather than enter in minification.inlineExpressions transformer 2015-05-13 08:45:06 +01:00
Sebastian McKenzie
e318f5f3be use ReferencedIdentifier virtual type in minification.deadCodeElimination transformer 2015-05-13 08:44:33 +01:00
Sebastian McKenzie
939decb86c stop entire unnecessary traversal for regenerator 2015-05-13 08:44:18 +01:00
Sebastian McKenzie
1baa0df948 clean up array inferrence for #1515 2015-05-13 08:44:03 +01:00
Sebastian McKenzie
e8956a8c44 upgrade dev dependency babel to 5.3.1 2015-05-13 08:43:25 +01:00
Sebastian McKenzie
2f0fdbbc26 5.3.1 2015-05-13 03:21:54 +01:00
Sebastian McKenzie
5f931525bc v5.3.1 2015-05-13 03:20:33 +01:00
Sebastian McKenzie
b86545a320 update 5.3.1 changelog 2015-05-13 03:19:39 +01:00
Sebastian McKenzie
06e75c42bf update module call remap tests 2015-05-13 03:18:55 +01:00
Sebastian McKenzie
05dd65244d add 5.3.1 changelog 2015-05-13 03:16:43 +01:00
Sebastian McKenzie
c4ebfeb0fa fix explosion of modules and colliding identifiers 2015-05-13 03:16:03 +01:00
Sebastian McKenzie
1aa0bbfac9 add TraversalPath#equals 2015-05-13 03:13:27 +01:00
Sebastian McKenzie
58f1e6cbc6 remove incorrect es6.tailCall visitor comment 2015-05-13 03:13:20 +01:00
Sebastian McKenzie
83e0be3038 make import calls sequence expressions - fixes #1514 2015-05-13 03:13:10 +01:00
Sebastian McKenzie
5fc242e4ec upgrade bable dev dependency to 5.3.0 2015-05-13 03:12:32 +01:00
Sebastian McKenzie
dc101adad3 more es6.tailCall transformer cleanup 2015-05-13 01:13:08 +01:00
Sebastian McKenzie
faade72787 optimise and clean up es6.tailCall transformer 2015-05-13 01:11:26 +01:00
Sebastian McKenzie
2a78ae9889 5.3.0 2015-05-13 01:07:11 +01:00
Sebastian McKenzie
9840639843 v5.3.0 2015-05-13 00:13:14 +01:00
Sebastian McKenzie
82c21a901e clean up es6.tailCall thirdPass visitor 2015-05-13 00:11:19 +01:00
Sebastian McKenzie
e1c83144c1 add 5.3.0 changelog 2015-05-13 00:11:08 +01:00
Sebastian McKenzie
ef2ac73215 fix export scope tracking reference counter - fixes #1513 2015-05-12 23:21:30 +01:00
Sebastian McKenzie
735d8955bf sync with upstream acorn 2015-05-12 23:21:30 +01:00
Sebastian McKenzie
3abee0a4fa fix switch case breaks not being correctly transformed when non top-level - fixes #1200 2015-05-12 23:21:30 +01:00
Sebastian McKenzie
b6f18b4f2b Merge pull request #1200 from lukasmlady/regenerator-let-fn-if-bug
Add failing tests that document ES 6 generators bug
2015-05-12 23:21:17 +01:00
Sebastian McKenzie
85cd0465fa Merge pull request #1511 from amasad/trailing-methods
Trailing commas in methods
2015-05-12 21:46:18 +01:00
Amjad Masad
0452e0fdd2 Allow trailing commas in methods 2015-05-12 13:20:36 -07:00
Amjad Masad
462ff572b3 Add failing test for trailing commas in methods 2015-05-12 13:19:21 -07:00
Sebastian McKenzie
d11099bb2b Merge branch 'master' of github.com:babel/babel 2015-05-12 19:13:53 +01:00
Sebastian McKenzie
f5c4684d3e force default parameter IIFE on reference to eval 2015-05-12 19:13:32 +01:00
Sebastian McKenzie
876a22578b Merge pull request #1506 from sverrejoh/patch-1
Added missing license field to package.json
2015-05-12 09:06:55 +01:00
Sverre Johansen
9f5e8b296b Added missing license field to package.json
Project says MIT, but license field missing in package.json
2015-05-12 08:54:56 +02:00
Sebastian McKenzie
d9deb02edc register as inside a type when parsing type aliases to avoid ambiguous jsx parsing - fixes #1378 2015-05-11 23:44:22 +01:00
Sebastian McKenzie
a402d0cdeb ensure that uids don't collide with **any** bindings contained in the program - fixes #1328 2015-05-11 23:37:31 +01:00
Sebastian McKenzie
683fb62505 fix acorn hacky lookahead with token contexts - fixes #1349 2015-05-11 23:20:51 +01:00
Sebastian McKenzie
941474983d clean up es6.objectSuper transformer - fixes #1502 2015-05-11 22:34:08 +01:00
Sebastian McKenzie
2b42773e01 explode duplicate identifiers in export/import specifiers and property shorthand - fixes #1458 2015-05-11 22:08:38 +01:00
Sebastian McKenzie
8277a532f4 skip loose mode for class methods when using decorators, addresses #1501 2015-05-11 17:40:36 +01:00
Sebastian McKenzie
539784b640 add Scope#moveBindingTo method and change more for array loops to for...of 2015-05-11 17:25:09 +01:00
Sebastian McKenzie
f373f8f003 refactor _shadowFunctions transformer to not do an entire traverse per function 2015-05-11 11:38:22 +01:00
Sebastian McKenzie
8605e835eb add exit visitor existence to unvisitable node shortcircuiting 2015-05-11 01:52:19 +01:00
Sebastian McKenzie
b4ace2043a fix shortcircuting of unvisitable nodes 2015-05-11 01:43:18 +01:00
Sebastian McKenzie
444a64e934 remove incorrect no eval in strict mode 2015-05-10 20:01:13 +01:00
Sebastian McKenzie
8ea2ae924d add existence check for ast.comments 2015-05-10 20:00:38 +01:00
Sebastian McKenzie
4ceb1d6f5e short circuit unnecessary visits 2015-05-10 20:00:26 +01:00
Sebastian McKenzie
3c81899ca7 add --harmony_generators to list of node flags - closes #1474, closes #1473 2015-05-10 20:00:12 +01:00
Sebastian McKenzie
ab59fd08e5 fix array type inferrence for file#toArray from being so wonky - fixes #1355 2015-05-10 19:35:41 +01:00
Sebastian McKenzie
19b05b5e61 change some manual array for loops to for..of 2015-05-10 19:35:05 +01:00
Sebastian McKenzie
65a44a1e13 remove use of exports 2015-05-10 16:09:43 +01:00
Sebastian McKenzie
d38f18af40 create null object when clearing internalRemap instead of using an object inherited plain object - fixes #1489 2015-05-09 18:39:59 +01:00
Sebastian McKenzie
2744b9f31f only print misisng ast.comments when available 2015-05-09 17:32:47 +01:00
Sebastian McKenzie
4deed35212 fix syntax errors introduced with previous lodash each removal 2015-05-09 17:27:33 +01:00
Sebastian McKenzie
bc9ae5ea8b remove many instances of lodash each in favor of for of loops 2015-05-09 17:22:01 +01:00
Sebastian McKenzie
87d879e236 Merge branch 'master' of github.com:babel/babel 2015-05-09 16:53:05 +01:00
Sebastian McKenzie
f657598c72 remove noop traversal visitors methods 2015-05-09 16:52:57 +01:00
Sebastian McKenzie
2a5cb9d21b move some utility transformers to minification 2015-05-09 16:52:31 +01:00
Sebastian McKenzie
cf7d6b655e Merge pull request #1487 from amasad/trailing-commas
[es7.trailingFunctionCommas] Allow in new expressions
2015-05-09 03:16:18 +01:00
Amjad Masad
6d2723eec5 New expressions is allowed to have trailing commas in es7 proposal 2015-05-08 19:12:53 -07:00
Amjad Masad
6834cc5b46 Add failing tests for trailing commas in new expressions 2015-05-08 19:12:10 -07:00
Sebastian McKenzie
9b949e574f use block scoped variables in es6.blockScoping transformer 2015-05-09 01:25:36 +01:00
Sebastian McKenzie
a75af0a5d2 optimise es6.constants transformer to use the same traversal path instead of spawning another one 2015-05-09 01:25:21 +01:00
Sebastian McKenzie
080b26769c remove compat-table 2015-05-09 00:09:19 +01:00
Sebastian McKenzie
e037ae7bc9 automatically explode visitors 2015-05-09 00:07:08 +01:00
Sebastian McKenzie
c60ad89937 add verbose mode to logging 2015-05-09 00:06:55 +01:00
Sebastian McKenzie
4194857086 fix system modules test to reflect strict hoisting behaviour 2015-05-08 23:58:25 +01:00
Sebastian McKenzie
1179c44c5b share comments with siblings when nodes are removed - fixes #1484 2015-05-08 23:57:12 +01:00
Sebastian McKenzie
f6d9b270c9 update to tracuer master 2015-05-08 23:48:30 +01:00
Sebastian McKenzie
1be0159b01 Merge pull request #1484 from amasad/type-comment-print
[Flow] Add failing tests for printing comments w/ type alias
2015-05-08 23:46:18 +01:00
Sebastian McKenzie
61ba8ad997 Merge pull request #1472 from babel/single-pass
Merge internal transformers into single traversal pass
2015-05-08 23:36:29 +01:00
Sebastian McKenzie
89e31085d2 ensure dynamic imports are hoisted 2015-05-08 23:33:30 +01:00
Sebastian McKenzie
920c84a1f2 move shadow function visitors to entrance instead of exit 2015-05-08 23:33:20 +01:00
Amjad Masad
ed56fecd04 [Flow] Add failing tests for printing comments w/ type alias 2015-05-08 15:33:00 -07:00
Sebastian McKenzie
f0bfdfb699 skip traversing back into ReturnStatement replacement when rewriting loops in the es6.blockScoping transformer 2015-05-08 23:13:27 +01:00
Sebastian McKenzie
b02a1112bc change ClassExpression visitor to enter instead of exist in the es6.classes transformer 2015-05-08 23:10:02 +01:00
Sebastian McKenzie
590a165776 move hoistDirectives transformer to builtin-setup 2015-05-08 23:09:45 +01:00
Sebastian McKenzie
2fd1b2a484 rename category metadata option to group 2015-05-08 22:54:15 +01:00
Sebastian McKenzie
8f9d02d689 further work splitting up transformers into their own "category" in order of what they need and what they actually do 2015-05-08 22:53:31 +01:00
Sebastian McKenzie
b376b6b33b store uncollapsed transformer pass stack so we have access to it when calling pre and post methods 2015-05-08 22:53:03 +01:00
Sebastian McKenzie
8292d6d8ad fix replacement requeue exiting too early 2015-05-08 22:52:38 +01:00
Sebastian McKenzie
d6a5c39079 update classes to reflect new transformer precedence 2015-05-08 22:52:19 +01:00
Sebastian McKenzie
2a9a59f784 remove incomplete ludicrous transformer 2015-05-08 22:52:02 +01:00
Sebastian McKenzie
abf4a5495a don't pretty print variable declarators in concise mode 2015-05-08 22:51:47 +01:00
Sebastian McKenzie
f8b8723bef Merge pull request #1483 from jquense/patch-1
Fix plugin api typo when an object is passed in
2015-05-08 22:26:45 +01:00
Jason Quense
6b9686f2dd Fix plugin api typo when an object is passed in 2015-05-08 17:25:14 -04:00
Sebastian McKenzie
4a439d8c8e update flow strip type annotations test 2015-05-08 15:52:08 +01:00
Sebastian McKenzie
c526a3eb04 move shadow-functions internal transformer to builtin-cleanup category 2015-05-08 15:51:56 +01:00
Sebastian McKenzie
ba516901af restructure transformers into multiple categories 2015-05-08 15:26:00 +01:00
Sebastian McKenzie
8f52229a86 add get function name to source map classes test 2015-05-08 15:25:50 +01:00
Sebastian McKenzie
5b793f8882 fix TraversalPath#_getPattern incorrectly iterating over the parts 2015-05-08 15:25:34 +01:00
Sebastian McKenzie
b31c14c52a Merge branch 'master' into single-pass 2015-05-08 00:24:33 +01:00
Sebastian McKenzie
78b72512cb better verify the type of the new node before requeueing it and also stop current node traversal on skip 2015-05-08 00:24:04 +01:00
Sebastian McKenzie
2fbb3cad9f add isUser and isGenerated path methods 2015-05-08 00:23:28 +01:00
Sebastian McKenzie
2621081a13 merge in astVisitor in runtime transformer - unsure why this was separate in the first place 2015-05-08 00:23:00 +01:00
Sebastian McKenzie
8daf95bf59 name additional methods that are now covered since the naming is done in tandem 2015-05-08 00:22:43 +01:00
Sebastian McKenzie
6e8ab16b25 run es6.spec.blockScoping transformer on exit rather than enter 2015-05-08 00:22:23 +01:00
Sebastian McKenzie
a5cda5caa7 hoist param declaration when performing tco - fixes #1478 2015-05-07 23:14:03 +01:00
Sebastian McKenzie
13a6c69668 add node existence check to each visitor call 2015-05-07 23:02:40 +01:00
Sebastian McKenzie
380293d030 add transformer dependencies - fixes #1477 2015-05-07 21:35:12 +01:00
Sebastian McKenzie
0b15a97013 Merge branch 'master' into single-pass 2015-05-07 20:15:34 +01:00
Sebastian McKenzie
11af066956 5.2.17 2015-05-07 20:15:17 +01:00
Sebastian McKenzie
d7b4d342c3 v5.2.17 2015-05-07 20:12:47 +01:00
Sebastian McKenzie
77aeebe2a8 add Super node type to ast-types patch 2015-05-07 20:11:37 +01:00
Sebastian McKenzie
c3a08d413f attach auxiliary comment to function declaration helpers - fixes #1476 2015-05-07 20:11:31 +01:00
Sebastian McKenzie
23ac2319af add Super node type to ast-types patch 2015-05-07 20:11:14 +01:00
Sebastian McKenzie
a1bc0704ab attach auxiliary comment to function declaration helpers - fixes #1476 2015-05-07 20:11:02 +01:00
Sebastian McKenzie
0bbfd427af do module formatter on program exit rather than entrance 2015-05-07 16:23:47 +01:00
Sebastian McKenzie
f17b268a71 do member expression and property literal conversion to computed on exit rather than on entrance 2015-05-07 16:23:33 +01:00
Sebastian McKenzie
9ffc265bea don't requeue node unless the type has changed 2015-05-07 16:01:00 +01:00
Sebastian McKenzie
6f664ca64e merge internal transformers into single traversal pass 2015-05-07 15:53:22 +01:00
Sebastian McKenzie
8a4a76000d correctly arrayify commander extensions - closes #1470, fixes #1460 2015-05-07 13:55:12 +01:00
Sebastian McKenzie
e83daf87d4 add this.stop() to secondary strict transformer #1465 2015-05-07 08:38:46 +01:00
Sebastian McKenzie
8ed90d3af2 ignore parameter bindings in minification.deadCodeElimination transformer - fixes #1464 2015-05-07 01:58:54 +01:00
Sebastian McKenzie
0bb311f8ce 5.2.16 2015-05-06 16:45:32 +01:00
Sebastian McKenzie
53f0f0302b v5.2.16 2015-05-06 16:44:28 +01:00
Sebastian McKenzie
c25a5d2480 add 5.2.16 changelog 2015-05-06 16:43:21 +01:00
Sebastian McKenzie
fc8540d88a inherit destructuring param replacement ref from original param - fixes #1461 2015-05-06 16:29:54 +01:00
Sebastian McKenzie
31a4195c81 fix incorrect extensions variable reference - fixes #1460 2015-05-06 16:23:15 +01:00
Sebastian McKenzie
bf0e4ede00 pass correct function scope to nameMethod.property when naming class methods - fixes #1456 2015-05-06 16:03:15 +01:00
Sebastian McKenzie
3757bc6b9a reverse method decorators - fixes #1457 2015-05-06 15:57:21 +01:00
Sebastian McKenzie
2e01f220da Merge branch 'master' of github.com:babel/babel 2015-05-06 15:44:05 +01:00
Sebastian McKenzie
8ae4e1fdf2 add --harmony_rest_parameters flag to babel-node - fixes #1446 2015-05-06 15:43:51 +01:00
Sebastian McKenzie
f6219ec15a Merge pull request #1455 from monsanto/fix-async-constructor
Disallow async constructors
2015-05-06 15:12:12 +01:00
Christopher Monsanto
6a82eb5a5c disallow async constructors -- fixes #1454 2015-05-06 02:50:11 -04:00
Sebastian McKenzie
a241300ff1 force plugins to be ran at all times - fixes #1450 2015-05-06 01:14:17 +01:00
Sebastian McKenzie
d5548a6ff9 5.2.15 2015-05-05 15:41:57 +01:00
Sebastian McKenzie
ba6cb112c3 v5.2.15 2015-05-05 15:41:00 +01:00
Sebastian McKenzie
8f1bb84930 add 5.2.15 changelog 2015-05-05 15:39:05 +01:00
Sebastian McKenzie
235726eee6 remove unnecessary descriptor.initializer check 2015-05-05 15:38:17 +01:00
Sebastian McKenzie
08183ef490 don't add descriptor if we can't find it 2015-05-05 15:37:24 +01:00
Sebastian McKenzie
dc6fc3b30a fix browser-polyfill.js post-make publish purging 2015-05-05 15:37:11 +01:00
Sebastian McKenzie
76f2eb5684 5.2.14 2015-05-05 15:14:59 +01:00
Sebastian McKenzie
4f33687957 v5.2.14 2015-05-05 15:12:19 +01:00
Sebastian McKenzie
74f37fe0a3 expose unminified and minified builds of dist scripts - fixes #1444 2015-05-05 15:11:00 +01:00
Sebastian McKenzie
cc5e4bce52 fix object/property decorator interop 2015-05-05 14:42:41 +01:00
Sebastian McKenzie
f441a7cae8 don't do pretty variable declaration formatting if retainLines is enabled 2015-05-05 14:04:51 +01:00
Sebastian McKenzie
fc2be81c43 expose retainLines option to CLI 2015-05-05 14:04:36 +01:00
Sebastian McKenzie
1277a8f67f 5.2.13 2015-05-05 08:58:35 +01:00
Sebastian McKenzie
86c6d4e769 v5.2.13 2015-05-05 08:57:41 +01:00
Sebastian McKenzie
bf2d527cfe upgrade esquery 2015-05-05 08:56:58 +01:00
Sebastian McKenzie
6b59ea8eac add 5.2.13 changelog 2015-05-05 08:56:28 +01:00
Sebastian McKenzie
72e3cb9243 trigger a reference for export declarations 2015-05-05 08:54:51 +01:00
Sebastian McKenzie
5e5ede6058 move down _modules transformer 2015-05-05 08:54:38 +01:00
Sebastian McKenzie
d25944ea1f move utility transformers to top - fixes #1440 2015-05-05 08:39:46 +01:00
Sebastian McKenzie
fce2aa8fa3 add support for esquery 2015-05-05 03:21:31 +01:00
Sebastian McKenzie
0112c63779 consolidate the concept of "virtual types" 2015-05-05 02:33:49 +01:00
Sebastian McKenzie
6a4e93bf0f make visitor validation more anal, add node type wrappers, add mixin support to visitor explosion, allow visitor entrance/exit to provide an array of callbacks to use rather than limiting it to a single callback 2015-05-05 01:44:01 +01:00
Sebastian McKenzie
4328e920d2 5.2.12 2015-05-05 00:15:48 +01:00
Sebastian McKenzie
bbbf0a895d v5.2.12 2015-05-05 00:13:57 +01:00
Sebastian McKenzie
3289b33806 remove no self node replacement error 2015-05-05 00:13:07 +01:00
Sebastian McKenzie
f4b9faa6b3 clean up module declaration based UID generation - fixes #1437 2015-05-04 22:36:18 +01:00
Sebastian McKenzie
239b77816f 5.2.11 2015-05-04 22:33:26 +01:00
Sebastian McKenzie
8565e2b4e5 v5.2.11 2015-05-04 22:32:28 +01:00
Sebastian McKenzie
4317a46a3e add 5.2.11 changelog 2015-05-04 22:31:44 +01:00
Sebastian McKenzie
81ca29adc3 5.2.10 2015-05-04 22:31:38 +01:00
Sebastian McKenzie
c1a6ff7f44 rename getModuleName option to getModuleId 2015-05-04 22:31:34 +01:00
Sebastian McKenzie
7e6e5d4746 v5.2.10 2015-05-04 22:23:39 +01:00
Sebastian McKenzie
12d650e195 checkSelf() for destructuring catch clauses 2015-05-04 22:22:39 +01:00
Sebastian McKenzie
8fb58492df fix default specifiers not taking into consideration sourced imports 2015-05-04 22:20:52 +01:00
Sebastian McKenzie
2c0c2f12df avoid trying to replace a node with itself, antipattern! 2015-05-04 22:20:52 +01:00
Sebastian McKenzie
01e5354fd9 disallow replacing a node with itself 2015-05-04 22:20:52 +01:00
Sebastian McKenzie
0b100c4273 Merge pull request #1386 from jayphelps/module-id-overload
Added getModuleName() option as a function
2015-05-04 22:20:31 +01:00
Jay Phelps
340e75eb59 Added getModuleName() option as a function, allowing you to manipulate the name as needed 2015-05-04 13:30:57 -07:00
Sebastian McKenzie
53808a6d45 fix test/core/path imports 2015-05-04 15:25:35 +01:00
Sebastian McKenzie
e6326332b6 properly coerce input code to string - fixes #1432 2015-05-04 15:08:18 +01:00
Sebastian McKenzie
9e0cf84505 adds test for #1431 2015-05-04 15:06:27 +01:00
Sebastian McKenzie
b7eea7b08c Merge pull request #1431 from pangratz/fix_replaceWithSourceString
Fix bugs in `replaceWithSourceString`
2015-05-04 15:00:27 +01:00
pangratz
92dd67856e Fix bugs in replaceWithSourceString
This fixes 2 bugs within `replaceWithSourceString`:

- `code` is undefined as it should be `replacement`
- the expression of the parsed replacement hasn't been accessed correctly
2015-05-04 09:33:32 +02:00
Sebastian McKenzie
a2bb587e24 remove embedded jsx plugin and use acorn-jsx 2015-05-04 04:33:46 +01:00
Sebastian McKenzie
0c570cb599 5.2.9 2015-05-04 04:03:41 +01:00
Sebastian McKenzie
db6fab2c8f v5.2.9 2015-05-04 04:02:30 +01:00
Sebastian McKenzie
d92deb52b6 v5.2.8 2015-05-04 04:00:13 +01:00
Sebastian McKenzie
b8b70f2f4a rejigger around parse mechanics 2015-05-04 03:57:28 +01:00
Sebastian McKenzie
a8a3f6d34d Merge branch 'master' of github.com:babel/babel 2015-05-04 03:55:25 +01:00
Sebastian McKenzie
9847d226e1 add transform import - closes babel/babel-eslint#83 2015-05-04 03:54:58 +01:00
Sebastian McKenzie
3d48a16305 Merge pull request #1417 from loganfsmyth/fix-phantom-issue-1405
Explicitly sort instead of relying on key ordering.
2015-05-04 03:29:30 +01:00
Sebastian McKenzie
3d24cc9ae5 Merge pull request #1224 from jcoglan/fix-source-map-pathnames
Correct relative pathnames in source maps.
2015-05-04 00:03:27 +01:00
Sebastian McKenzie
5acc58dd68 5.2.7 2015-05-03 23:48:48 +01:00
Sebastian McKenzie
34f02f06a6 v5.2.7 2015-05-03 23:47:50 +01:00
Sebastian McKenzie
6d3fe5b85c add 5.2.7 changelog 2015-05-03 23:45:33 +01:00
Sebastian McKenzie
3878bd812c remove native super inheritance from classes - fixes #1424 2015-05-03 23:45:26 +01:00
Sebastian McKenzie
0717eaddce normalise Program replacement nodes 2015-05-03 23:35:39 +01:00
Sebastian McKenzie
102cbbe493 fix up crazy parse argument order 2015-05-03 23:31:37 +01:00
Sebastian McKenzie
d981b30194 clean up file transform pipeline 2015-05-03 23:26:37 +01:00
Sebastian McKenzie
0fc02f2cf0 add support for replacing nodes with expression source strings 2015-05-03 23:02:19 +01:00
Sebastian McKenzie
f24b5164d4 add extensions option to babel cli 2015-05-03 22:43:20 +01:00
Sebastian McKenzie
4be27ee72c update bin tests to reflect new helper format 2015-05-03 17:47:31 +01:00
Sebastian McKenzie
f0070e4828 ignore _generated FunctionDeclarations too in es6.spec.symbols transformer 2015-05-03 17:40:30 +01:00
Sebastian McKenzie
ce8beec22c update tests to reflect new helper format 2015-05-03 17:28:32 +01:00
Sebastian McKenzie
b30bdf2294 turn inserted helper declarations into function declarations if possible 2015-05-03 17:22:51 +01:00
Sebastian McKenzie
63b44a3e6e fix transformer and module formatter list in $ babel --help - fixes #1421 2015-05-02 23:16:37 +01:00
Logan Smyth
74aaf848ed Explicitly sort instead of relying on implementation-defined numeric key ordering - fixes #1405. 2015-05-01 20:00:22 -07:00
Sebastian McKenzie
95de5400e6 remove dead if statement explosion code - fixes #1413 2015-05-01 23:30:26 +01:00
Sebastian McKenzie
fe7079802b move deadCodeElimination transformer up - fixes #1409, fixes #1408 2015-05-01 23:24:16 +01:00
Sebastian McKenzie
61ddb14e25 Merge branch 'master' of github.com:babel/babel 2015-05-01 23:14:58 +01:00
Sebastian McKenzie
ca7a93cd64 move utility.deadCodeElimination transformer to minification 2015-05-01 23:13:48 +01:00
Sebastian McKenzie
90a1c81d30 split up es3.xLiterals transformers - fixes #1415 2015-05-01 23:13:30 +01:00
Sebastian McKenzie
5e9089d104 Merge pull request #1411 from hzoo/jshint-cleanup
remove old references to jshint
2015-05-01 22:45:15 +01:00
Henry Zhu
1a716943bc remove old references to jshint 2015-05-01 14:08:47 -04:00
Sebastian McKenzie
c28415c38a handle shorthand objects properly when renaming bindings, create new ones and refresh the stored binding identifier if necessary - fixes #1406 2015-05-01 15:23:46 +01:00
Sebastian McKenzie
e1491de6b8 5.2.6 2015-05-01 13:09:33 +01:00
Sebastian McKenzie
253ea8cd18 v5.2.6 2015-05-01 13:08:28 +01:00
Sebastian McKenzie
d37bad3149 add 5.2.6 changelog 2015-05-01 13:07:38 +01:00
Sebastian McKenzie
a2b912bc77 add BABEL mention to deprecation message 2015-05-01 13:07:31 +01:00
Sebastian McKenzie
f1bfbe44e2 expose Pipeline as TransformerPipeline 2015-05-01 13:00:34 +01:00
Sebastian McKenzie
dbdd07d0b8 fix addAliases call 2015-05-01 13:00:26 +01:00
Sebastian McKenzie
166909998e 5.2.5 2015-05-01 13:00:15 +01:00
Sebastian McKenzie
a8ec4c965c v5.2.5 2015-05-01 11:41:15 +01:00
Sebastian McKenzie
d2aff67c6c 5.2.4 2015-05-01 11:39:43 +01:00
Sebastian McKenzie
3353de225d fix parse API not adding all the correct pipeline transformers 2015-05-01 11:39:38 +01:00
Sebastian McKenzie
203ebeef20 v5.2.4 2015-05-01 11:29:06 +01:00
Sebastian McKenzie
032cf990c3 add 5.2.4 changelog 2015-05-01 11:28:24 +01:00
Sebastian McKenzie
16cdb43c67 expose transform pipeline and require node api inside of the browser one to avoid race conditions 2015-05-01 11:27:23 +01:00
Sebastian McKenzie
6f622033c5 5.2.3 2015-05-01 11:27:02 +01:00
Sebastian McKenzie
531d4f1937 v5.2.3 2015-05-01 09:42:23 +01:00
Sebastian McKenzie
f155bc249c fix Program global reference catching for real this time 2015-05-01 09:41:35 +01:00
Sebastian McKenzie
452d0ef30e fix Program global reference catching 2015-05-01 09:40:03 +01:00
Sebastian McKenzie
005754ba98 Revert "Revert "make dead code elimination smarter and eliminate non-referenced "pure" nodes""
This reverts commit c3c4cf17e3.
2015-05-01 09:39:33 +01:00
Sebastian McKenzie
c3c4cf17e3 Revert "make dead code elimination smarter and eliminate non-referenced "pure" nodes"
This reverts commit 4e87809ff9.
2015-05-01 09:39:07 +01:00
Sebastian McKenzie
0866e5a403 add 5.2.3 changelog 2015-05-01 09:36:48 +01:00
Sebastian McKenzie
15f5e658fc Merge branch 'master' of github.com:babel/babel 2015-05-01 09:32:28 +01:00
Sebastian McKenzie
574e6da132 add Statement and Declaration aliases to flow types - fixes #1401 2015-05-01 09:32:11 +01:00
Sebastian McKenzie
da6d27ed16 Merge pull request #1404 from timbur/master
hopefully fixes #1402
2015-05-01 09:31:46 +01:00
Sebastian McKenzie
4e87809ff9 make dead code elimination smarter and eliminate non-referenced "pure" nodes 2015-05-01 09:31:28 +01:00
Sebastian McKenzie
f4267aaab0 Merge pull request #1403 from wyand/master
fix spelling
2015-05-01 09:28:46 +01:00
Sebastian McKenzie
4f255d103a Merge pull request #1400 from monsanto/flow-object-commas
Support commas as object property separators in flow
2015-05-01 09:24:08 +01:00
Tim Burgess
502cc13aed hopefully fixes #1402 2015-05-01 04:05:22 -04:00
Dan Wyand
0a1154e6fd fix spelling 2015-05-01 01:01:10 -04:00
Christopher Monsanto
f5b3d72730 support commas as obj property separators in flow 2015-05-01 00:09:26 -04:00
Sebastian McKenzie
e9bcccffbd futz the bundler idea 2015-05-01 03:26:12 +01:00
Sebastian McKenzie
aaf4cbf06f start on babel module bundling and type inferrence 2015-05-01 02:59:59 +01:00
Sebastian McKenzie
5080534974 5.2.2 2015-05-01 00:44:48 +01:00
Sebastian McKenzie
02cb397873 v5.2.2 2015-05-01 00:43:39 +01:00
Sebastian McKenzie
d9169a87ad allow util.arrayify to take arbitrary types and coerce it into an array - #1398 2015-05-01 00:41:47 +01:00
Sebastian McKenzie
f3b6f2fc61 5.2.1 2015-05-01 00:41:24 +01:00
Sebastian McKenzie
04cc24ee82 v5.2.1 2015-05-01 00:30:42 +01:00
Sebastian McKenzie
f32079ef42 fix regression in node/register that caused node_modules to not be ignored - fixes #1398 2015-05-01 00:29:57 +01:00
Sebastian McKenzie
d1b69656ae update 5.2.0 changelog 2015-04-30 23:28:39 +01:00
Sebastian McKenzie
09453a490b 5.2.0 2015-04-30 23:27:37 +01:00
Sebastian McKenzie
e2e7627f0f v5.2.0 2015-04-30 23:15:06 +01:00
Sebastian McKenzie
4fe24a9a3b Merge pull request #1392 from jden/jden-patch-1
process glob matching in babel-cli (windows compat)
2015-04-30 23:10:24 +01:00
Sebastian McKenzie
d26e7ad577 fix no RHS in class properties causing undefined to be used instead of a noop - fixes #1396 2015-04-30 23:09:17 +01:00
Sebastian McKenzie
571cb4928f add register-without-polyfill option 2015-04-30 22:27:52 +01:00
Sebastian McKenzie
c12e8122f8 fix browser tests 2015-04-30 20:11:32 +01:00
Sebastian McKenzie
92e7a01d14 remove regenerator and test262 git submodule and tests - closes #1393 2015-04-30 20:03:34 +01:00
jden
b9ca9d42dc fix formatting per feedback from @sebmck
https://github.com/babel/babel/pull/1392#discussion-diff-29454022
2015-04-30 11:06:51 -07:00
jden
479c3e477a process glob matching in babel-cli (windows compat) 2015-04-30 10:57:48 -07:00
Sebastian McKenzie
2c3d3d8105 DRY up plugin manager position definition 2015-04-30 18:13:33 +01:00
Sebastian McKenzie
ea03f67505 use a strict regex when splitting string plugins - fixes #1361 2015-04-30 18:13:17 +01:00
Sebastian McKenzie
ee0c88a070 clean up plugin manager constructor and add some basic plugin manager tests 2015-04-30 18:06:15 +01:00
Sebastian McKenzie
98206df864 fix retainLines for comments and block statements - fixes #1388 2015-04-30 17:43:31 +01:00
Sebastian McKenzie
1066a42fb2 fix weird path context state by clearing the context before we visit it 2015-04-30 17:19:27 +01:00
Sebastian McKenzie
062175586c add parens around LHS object patterns 2015-04-30 17:18:36 +01:00
Sebastian McKenzie
0dc6b582a6 Merge pull request #1385 from monsanto/fix-var-checker
fix reference check for shorthand properties
2015-04-30 16:43:36 +01:00
Sebastian McKenzie
d8d70ba137 Merge pull request #1388 from amasad/master
Add failing test for printing block line comments with retainLines option
2015-04-30 16:42:55 +01:00
Sebastian McKenzie
f23c916520 make function name inferrence smarter - fixes #1367 2015-04-30 16:41:25 +01:00
Sebastian McKenzie
8ae4601177 rename insertOntoContainerStart to unshiftContainer 2015-04-30 14:33:54 +01:00
Sebastian McKenzie
9a466d3ef9 add optimisation.flow.forOf internal usage 2015-04-30 14:31:52 +01:00
Sebastian McKenzie
713845d14c add Terminatorless alias key for node expression wrappers that don't accept new lines 2015-04-30 13:56:42 +01:00
Sebastian McKenzie
471d60e5cd Merge branch 'master' of github.com:babel/babel 2015-04-30 13:53:58 +01:00
Sebastian McKenzie
43864e0686 Merge pull request #1390 from amasad/retainLines-return
Parenthesize statement argument when on a different line
2015-04-30 13:53:52 +01:00
Amjad Masad
4c2ae5dd19 Parenthesize statement argument when on a different line 2015-04-30 05:43:08 -07:00
Amjad Masad
a540cbe801 Failing test with return not on the same line as it's expression
Note that this is not a parenthesis issue but this was the easiest way
to reproduce it. I ran into it when testing generators with `retainLines`
and the generated `return` statement (replacing yeild) was printed on
the line preceding the expression being yielded.
2015-04-30 05:06:56 -07:00
Amjad Masad
34cc577fa2 Add failing test for printing block line comments with retainLines option 2015-04-30 04:37:45 -07:00
Sebastian McKenzie
c855b55133 add additional comment test to comment statement with retainlines option generation test 2015-04-29 23:58:36 +01:00
Sebastian McKenzie
16c86c25b7 properly catch up to comments position - fixes #1384 2015-04-29 23:57:43 +01:00
Sebastian McKenzie
4345f7945b Merge pull request #1377 from Mark-Simulacrum/issue-1376
Allow passing an array of globs to "only" option.
2015-04-29 23:39:17 +01:00
Christopher Monsanto
f44c93add2 fix reference check for shorthand properties 2015-04-29 17:56:36 -04:00
Sebastian McKenzie
09e45c51a4 Merge pull request #1384 from amasad/master
Add failing test for printing comments with retainLines option
2015-04-29 22:44:03 +01:00
Amjad Masad
1a42b72b15 Add failing test for printing comments with retainLines option 2015-04-29 14:40:23 -07:00
Sebastian McKenzie
d30415d74a update es6.spec.symbols instanceof test to reflect Function.prototype[@@hasInstance] being nonwritable #1364 2015-04-29 21:20:35 +01:00
Sebastian McKenzie
616ef8d840 make jscript transformer more trigger happy - #1382 2015-04-29 12:03:15 +01:00
Sebastian McKenzie
56437f94bc Merge pull request #1382 from kondi/jscript
add optional jscript transformer for basic IE8 compatibility (fixes #1369)
2015-04-29 11:59:32 +01:00
Pusztai Tibor
881fa6430b add optional jscript transformer for basic IE8 compatibility (fixes #1369) 2015-04-29 12:36:12 +02:00
Sebastian McKenzie
b7971690f3 add additional comments to path class, really need to go and fill in all the dummy jsdoc descriptions... 2015-04-29 01:19:56 +01:00
Sebastian McKenzie
c01d0abbd3 add insertOntoContainerStart and insertOntoContainerEnd methods 2015-04-29 01:13:35 +01:00
Sebastian McKenzie
7043119346 fix PluginManager 2015-04-29 01:13:23 +01:00
Mark-Simulacrum
b5325df57f Allow passing an array of globs to "only" option. 2015-04-28 17:59:20 -06:00
Sebastian McKenzie
0fc958e0fc remove useless force parameter in Buffer#_newline 2015-04-29 00:22:10 +01:00
Sebastian McKenzie
9cb16711dd abstract plugin initialisation to a plugin manager 2015-04-29 00:20:49 +01:00
Sebastian McKenzie
04766b13f5 add retainLines code generator option 2015-04-29 00:20:35 +01:00
Sebastian McKenzie
433d704739 add null check to interop-require-wildcard helper 2015-04-28 16:56:57 +01:00
Sebastian McKenzie
30204d2ee6 disable sudo travis config option, it breaks the build since it's using a cached node_modules which has old major versions of dependencies, ugh 2015-04-28 16:31:00 +01:00
Sebastian McKenzie
374b7cca2c update interop-require-wildcard helper 2015-04-28 15:58:37 +01:00
Sebastian McKenzie
152ae388f0 remove excessive newline 2015-04-28 15:32:16 +01:00
Sebastian McKenzie
04344026bb remove typeof object check for interop-require-wildcard helper 2015-04-28 15:32:09 +01:00
Sebastian McKenzie
cfffaf6cdb upgrade to babel 5 2015-04-28 14:55:28 +01:00
Sebastian McKenzie
2952d94e60 wrap instanceof to support @@hasInstance - fixes #1364 2015-04-28 14:27:30 +01:00
Sebastian McKenzie
0276c3ae81 visit decorators key for ClassProperty nodes 2015-04-28 00:05:10 +01:00
Sebastian McKenzie
c00f8dce3f add make build to makefile and elaborate on build steps in CONTRIBUTING - #1357. 2015-04-27 03:16:39 +01:00
Sebastian McKenzie
4e24ae39cf Merge branch 'master' of github.com:babel/babel 2015-04-27 03:06:23 +01:00
Sebastian McKenzie
12bd6494b7 use class ref instead of class name when adding class super native constructor call - fixes #1358 2015-04-27 03:06:13 +01:00
Sebastian McKenzie
e35c7550fe Merge pull request #1356 from monsanto/clean-build
remove lib/ before building
2015-04-27 02:32:53 +01:00
Christopher Monsanto
e7046abe72 remove lib/ before building 2015-04-26 21:12:50 -04:00
Sebastian McKenzie
affa7f0c6f Merge pull request #1352 from monsanto/descriptor-initalizer
call descriptor.initializer with `target` as `this`
2015-04-26 21:17:50 +01:00
Sebastian McKenzie
be650ffc61 call decorator initializers with the proper context - #1350 - thanks @monsanto 2015-04-26 21:17:15 +01:00
Sebastian McKenzie
3078d48178 don't rely on sequence expressions for <= 1 sequence expressions in blockScoping transformer 2015-04-26 21:15:30 +01:00
Sebastian McKenzie
0be93563dd fix spec.blockScopedFunctions shouldVisit method 2015-04-26 21:15:08 +01:00
Christopher Monsanto
3e55980145 call descriptor.initializer with target as this 2015-04-26 16:11:11 -04:00
Sebastian McKenzie
470ebf3a46 various random optimisations 2015-04-26 21:04:06 +01:00
Sebastian McKenzie
b695369126 add babel brand to code gen deopt message 2015-04-26 21:03:54 +01:00
Sebastian McKenzie
f4611469b4 remove declarations transformer and instead do it whenever we push a generated declaration, better for perf and removes shitty bugs - fixes #1268 2015-04-26 15:46:06 +01:00
Sebastian McKenzie
68bfafe745 add missing ast-types definitions 2015-04-26 05:26:29 +01:00
Sebastian McKenzie
f72782b71c remove transformer prepass and various other optimisations 2015-04-26 05:26:21 +01:00
Sebastian McKenzie
0f1f5e3565 implement path-specific transformer skipping via the starting prepass 2015-04-26 02:42:15 +01:00
Sebastian McKenzie
dfe126f3d4 verify traversal visitors 2015-04-25 22:49:54 +01:00
Sebastian McKenzie
4c9cb957a9 5.1.13 2015-04-25 22:46:01 +01:00
Sebastian McKenzie
8f997f8825 v5.1.13 2015-04-25 18:32:53 +01:00
Sebastian McKenzie
d789a6e7aa remove symbol check from defineProperty helper #1348 2015-04-25 18:31:29 +01:00
Sebastian McKenzie
4007148d9f 5.1.12 2015-04-25 18:23:16 +01:00
Sebastian McKenzie
998f1d544e v5.1.12 2015-04-25 18:21:37 +01:00
Sebastian McKenzie
deed48a3db fix decorator interop - fixes #1277 2015-04-25 18:18:30 +01:00
Sebastian McKenzie
00c0a958db fix runtime tests to reflect core-js 0.9.0 2015-04-25 18:08:00 +01:00
Sebastian McKenzie
1511dcbd73 resolveModuleSource on ExportAllDeclarations - fixes #1342 2015-04-25 17:47:44 +01:00
Sebastian McKenzie
12fef25803 update to core-js 0.9.0 - closes #1348 2015-04-25 17:40:59 +01:00
Sebastian McKenzie
fd30eb1839 Merge branch 'master' of github.com:babel/babel 2015-04-24 19:28:58 +01:00
Sebastian McKenzie
63344eb0a4 only skip traversal of immutable JSX elements in the optimisation.react.constantElements transformer when we've actually hoisted them - closes #1344 2015-04-24 19:28:51 +01:00
Sebastian McKenzie
6e4e11a365 fix JSX literal children not being output correctly 2015-04-24 19:28:17 +01:00
Sebastian McKenzie
e330efe058 Merge pull request #1343 from isojs/fix-ignore-only-windows
Fix ignore/only on Windows
2015-04-24 15:21:33 +01:00
Sebastian McKenzie
ce86eca8b0 Merge pull request #1335 from lukescott/fix-resolve-rc
Fix resolve rc loading options twice
2015-04-24 15:21:18 +01:00
Luke Scott
03dbaa3e0e fix resolve-rc loading options twice - fixes #1329 2015-04-24 07:13:26 -07:00
George Stagas
2bd35fac6e normalize filename slashes for shouldIgnore 2015-04-24 16:58:52 +03:00
Sebastian McKenzie
cdca4e50d9 Merge pull request #1333 from isojs/fix-rimraf-tmp
Fix test temporary dir cleanup
2015-04-24 11:31:09 +01:00
Sebastian McKenzie
bb041c1bd6 Merge pull request #1330 from joemcbride/master
Bump convert-source-map version.
2015-04-24 11:30:47 +01:00
Sebastian McKenzie
a36c1b4a92 rewrite this in shadowed functions inside native derived class constructors - fixes #1340 2015-04-24 11:20:29 +01:00
George Stagas
b760daca21 fix test tmp dir cleanup 2015-04-23 21:27:14 +03:00
Joe McBride
ff63d8f60c Bump convert-source-map version.
Relates to #1014
2015-04-23 09:29:19 -07:00
Sebastian McKenzie
74f04ed6a1 clean up interop require 2015-04-22 00:14:55 +01:00
Sebastian McKenzie
74d880bf18 Merge pull request #1317 from jeffmo/copy_static_props_on_foreign_export_objs
Copy statics from foreign exports objects when doing an ES6 import
2015-04-21 22:44:52 +01:00
jeffmo
5ce38cacaa Copy statics off of foreign exports objects when doing an ES6 import 2015-04-21 12:17:43 -04:00
Sebastian McKenzie
829f642ad8 fix spread properties in assignment position - fixes #1315 2015-04-21 16:24:34 +01:00
Sebastian McKenzie
80a4b95da4 fix incorrect externalHelpers option definition - fixes #1307 2015-04-21 16:16:07 +01:00
Sebastian McKenzie
dc2a20dbcd Merge branch 'master' of github.com:babel/babel 2015-04-21 16:14:49 +01:00
Sebastian McKenzie
f6278e43ce properly handle shorthand JSX attributes in optimisation.react.inlineElements transformer - fixes #1309 2015-04-21 16:14:36 +01:00
Sebastian McKenzie
30bc80000b Merge pull request #1311 from jquense/fix-plugin-position
Fixes bug where position was never set
2015-04-20 17:37:45 +01:00
jquense
ef56042c93 Fixes bug where position was never set
The mallet operator was compiling to `if (!position) position =
name.position`. Since position is set earlier the conditional was always
true and position was never updated from the plugin object.
2015-04-20 12:34:39 -04:00
Sebastian McKenzie
b6498103db 5.1.11 2015-04-20 06:26:23 +01:00
Sebastian McKenzie
7af4302d07 v5.1.11 2015-04-20 06:25:37 +01:00
Sebastian McKenzie
543770960c update 5.1.11 changelog 2015-04-20 06:24:30 +01:00
Sebastian McKenzie
a2975a72cc add 5.1.11 changelog 2015-04-20 06:23:53 +01:00
Sebastian McKenzie
beb3fd51d8 clean up CONTRIBUTING TOC 2015-04-20 06:16:33 +01:00
Sebastian McKenzie
9360860601 memoise and bind member expression decorators - fixes #1296 2015-04-20 06:16:20 +01:00
Sebastian McKenzie
7d4ecea8fb move react children coercion to opening element visitor - fixes #1276 2015-04-20 05:49:59 +01:00
Sebastian McKenzie
a44831b3fa Merge pull request #1285 from bucaran/contributing-doc-deps
Improve formatting and add rundown of deps with links
2015-04-20 00:24:30 +01:00
Sebastian McKenzie
8357f3900f Merge pull request #1282 from bcamper/vanilla-generator-runtime
Use vanilla regenerator when building runtime
2015-04-20 00:23:14 +01:00
Sebastian McKenzie
6b1c5bc358 remove interop require on bluebird - fixes #1289 2015-04-20 00:22:41 +01:00
Sebastian McKenzie
3564309a77 allow plugins to be specified as an object with transformer and position - fixes #1300 2015-04-20 00:05:06 +01:00
Sebastian McKenzie
c9518bb60d consider switches to be a valid scope - fixes #1297 2015-04-19 21:45:43 +01:00
Sebastian McKenzie
0f1215e33e add title to logging - fixes #1292 2015-04-19 16:06:58 +01:00
Sebastian McKenzie
d7b0b5bec0 add space to do-while code gen - fixes #1290 2015-04-17 17:35:36 -07:00
Jorge
3e5af404ab improve formatting and add rundown of deps with links 2015-04-17 15:15:03 +09:00
Sebastian McKenzie
1818094577 validate this before super on exit, not enter - fixes #1284 2015-04-16 22:04:18 -07:00
Brett Camper
6d712b3d14 use vanilla regenerator when building runtime
see #1015
2015-04-16 15:17:58 -04:00
Sebastian McKenzie
11389fe165 add 5.1.10 changelog 2015-04-15 16:12:56 -07:00
Sebastian McKenzie
0ee9531db3 5.1.10 2015-04-15 15:24:49 -07:00
Sebastian McKenzie
1622d2498d v5.1.10 2015-04-15 15:24:00 -07:00
Sebastian McKenzie
b76e6f8e5b disable ludicrous tests 2015-04-15 15:23:14 -07:00
Sebastian McKenzie
beac006832 remove regenerator from bootstrap 2015-04-15 15:22:09 -07:00
Sebastian McKenzie
20d7603c0b remove redundant replaceExpressionWithStatements for statement or block nodes - fixes #1265 2015-04-15 15:16:34 -07:00
Sebastian McKenzie
24b13c5e49 remove unnecessary csp makePredicate - fixes #1267 2015-04-15 15:13:12 -07:00
Sebastian McKenzie
9e21074e88 remove regenerator tests 2015-04-15 15:05:30 -07:00
Sebastian McKenzie
9a825bced7 remove runtime compatibility check - closes #1266 2015-04-15 15:03:45 -07:00
Sebastian McKenzie
fcb78436c6 move es6.proxies to ludicrous 2015-04-15 14:59:37 -07:00
Sebastian McKenzie
bb30a64f8d add extra transform option 2015-04-15 14:59:26 -07:00
Sebastian McKenzie
b483c16fe2 Merge branch 'proxies'
# Conflicts:
#	src/babel/transformation/file/index.js
2015-04-15 13:32:28 -07:00
Sebastian McKenzie
569f046045 5.1.9 2015-04-14 08:32:47 -07:00
Sebastian McKenzie
4e969d3d92 v5.1.9 2015-04-14 08:30:54 -07:00
Sebastian McKenzie
0bca1de285 add 5.1.9 changelog 2015-04-14 08:29:31 -07:00
Sebastian McKenzie
3a5bd06a7e fix proeprty method assignment wrapper generator template 2015-04-14 08:28:02 -07:00
Sebastian McKenzie
66a908aaa7 Mark function token as able to start an expression 2015-04-14 08:18:06 -07:00
Sebastian McKenzie
cd0ed08237 Revert "delegate to babel-cli/babel-core if it's available #1244"
This reverts commit dd84b554e6.
2015-04-14 08:02:02 -07:00
Sebastian McKenzie
dd84b554e6 delegate to babel-cli/babel-core if it's available #1244 2015-04-14 07:53:29 -07:00
Sebastian McKenzie
b51411f090 Merge branch 'master' of github.com:babel/babel 2015-04-14 07:39:52 -07:00
Sebastian McKenzie
4cc843ded3 set hoisted to true for react constant elements optimisation 2015-04-14 07:39:44 -07:00
Sebastian McKenzie
47d253c732 set passModuleArg when handling default export specifiers in amd module formatter - fixes #1260 2015-04-14 07:39:34 -07:00
Sebastian McKenzie
09901274ab Merge pull request #1257 from zloirock/master
Update NATIVE_TYPE_NAMES
2015-04-14 07:28:00 -07:00
rock
35196e20c7 Update NATIVE_TYPE_NAMES 2015-04-14 18:24:13 +06:00
Sebastian McKenzie
35af771a29 Merge branch 'master' of github.com:babel/babel 2015-04-13 21:57:04 -07:00
Sebastian McKenzie
dee80caa09 move export reassignment to exit handler - fixes #1255 2015-04-13 21:56:55 -07:00
Sebastian McKenzie
46b7cc0a72 assorted minor cleanup of variables 2015-04-13 21:56:37 -07:00
Sebastian McKenzie
3b189e22b7 Merge pull request #1256 from jayphelps/fix-writable
class properties with an undefined value are now correctly writable
2015-04-13 21:52:46 -07:00
Jay Phelps
6ca565d7fb class properties with an undefined value are now correctly writable 2015-04-13 20:53:05 -07:00
Sebastian McKenzie
64f5480f96 fix pattern LHS error messages 2015-04-13 16:45:30 -07:00
Sebastian McKenzie
828fdc8769 make illegal LHS pattern error messages more user friendly 2015-04-13 16:40:13 -07:00
Sebastian McKenzie
6763c4415e make parenthesized array patterns illegal - cc @michaelficarra 2015-04-13 16:16:57 -07:00
Sebastian McKenzie
fb30e79e03 5.1.8 2015-04-13 15:46:45 -07:00
Sebastian McKenzie
85fb4304b0 v5.1.8 2015-04-13 15:45:46 -07:00
Sebastian McKenzie
c2da77d7ec only make parenthesized object patterns illegal - fixes #1254, ref jshint/jshint#2269 2015-04-13 15:44:54 -07:00
Sebastian McKenzie
c54c3d3c15 5.1.7 2015-04-13 15:44:02 -07:00
Sebastian McKenzie
2a7c954155 v5.1.7 2015-04-13 14:59:56 -07:00
Sebastian McKenzie
3fb7f7c7cc add 5.1.6-5.1.7 changelog 2015-04-13 14:56:33 -07:00
Sebastian McKenzie
c4b2818336 remove useless kind on import declarations 2015-04-13 14:55:46 -07:00
Sebastian McKenzie
061561bfd8 add proper ecmaVersion and sourceType to parse api 2015-04-13 14:55:37 -07:00
Sebastian McKenzie
d4944d606b 5.1.6 2015-04-13 14:29:21 -07:00
Sebastian McKenzie
736b689c3b v5.1.6 2015-04-13 14:27:09 -07:00
Sebastian McKenzie
e12b377014 don't fall back to runtime catch all on locally declared variables 2015-04-13 14:26:06 -07:00
Sebastian McKenzie
5fd5b815ab fix whitespace in resolveRc 2015-04-13 14:25:47 -07:00
Sebastian McKenzie
92db8312f6 add parse api 2015-04-13 14:25:37 -07:00
James Coglan
1f2f4ce4f3 Correct relative pathnames in source maps.
Say you have a file called `src/thing.js` and you run

    $ babel src/thing.js --out-file lib/thing.js --source-maps true

This generates a source map at `lib/thing.js.map` that contains
"src/thing.js" in its `sources` array. This is incorrect; since browsers
resolve all relative URLs relative to the directory containing the file
that refers to the URL, this resolves to `lib/src/thing.js`.

To make the source map refer to the source files correctly, the
`sources` array should contain "../src/thing.js".
2015-04-13 21:17:11 +01:00
Sebastian McKenzie
e080fe547d 5.1.5 2015-04-13 11:59:47 -07:00
Sebastian McKenzie
b967ecf063 v5.1.5 2015-04-13 11:58:58 -07:00
Sebastian McKenzie
365b7285d2 bump core-js version 2015-04-13 11:58:09 -07:00
Sebastian McKenzie
a40d532b0e 5.1.4 2015-04-13 09:38:21 -07:00
Sebastian McKenzie
0487bf911d v5.1.4 2015-04-13 09:36:21 -07:00
Sebastian McKenzie
57c72d1cd0 fix syntax error in runtime definitions 2015-04-13 09:35:35 -07:00
Sebastian McKenzie
335bdffec2 add missing Reflect methods to runtime transformer #1248 2015-04-13 09:34:45 -07:00
Sebastian McKenzie
e1d76a1dfe 5.1.3 2015-04-13 09:25:37 -07:00
Sebastian McKenzie
a4845323a2 v5.1.3 2015-04-13 09:24:00 -07:00
Sebastian McKenzie
792951b489 add 5.1.3 changelog 2015-04-13 09:23:12 -07:00
Sebastian McKenzie
5adda836af don't do TCO on generators and async functions - fixes #1251 2015-04-13 09:21:59 -07:00
Sebastian McKenzie
4c2c3098c3 Merge branch 'master' of github.com:babel/babel 2015-04-13 09:20:36 -07:00
Sebastian McKenzie
087c714098 simplify runtime transformer traversal and add a catch-all - fixes #1248 2015-04-13 09:20:28 -07:00
Sebastian McKenzie
5a33e4fe05 Merge pull request #1245 from deepsweet/travis-cache
let Travis cache node_modules
2015-04-13 08:29:59 -07:00
Sebastian McKenzie
5f8667eaa7 make parsing of decorators stateless - fixes shuhei/babel-angular2-app#4 2015-04-13 08:26:51 -07:00
Sebastian McKenzie
31b4468514 switch to vanilla regenerator - closes #1247, closes #1123 2015-04-13 08:08:00 -07:00
Kir Belevich
2be9678bbe let Travis cache node_modules 2015-04-13 17:54:50 +07:00
Sebastian McKenzie
b5210877cf 5.1.2 2015-04-13 00:54:00 -07:00
Sebastian McKenzie
a8702be756 add solo helpers 2015-04-11 14:33:04 -07:00
Sebastian McKenzie
0995cc3f4e add proxies 2015-04-11 14:32:52 -07:00
Lukáš Mladý
6491018c21 Add failing tests that document ES 6 generators bug 2015-04-08 14:14:45 +02:00
769 changed files with 18848 additions and 12120 deletions

View File

@@ -1,6 +1,7 @@
{
"experimental": true,
"playground": true,
"loose": true,
"blacklist": ["es6.tailCall"]
"stage": 0,
"loose": ["all"],
"blacklist": ["es6.tailCall"],
"optional": ["optimisation.flow.forOf"],
"plugins": ["./tools/build-plugins/protect"]
}

View File

@@ -3,18 +3,23 @@
"rules": {
"strict": 0,
"no-underscore-dangle": 0,
"no-unused-vars": 0,
"curly": 0,
"no-multi-spaces": 0,
"key-spacing": 0,
"no-return-assign": 0,
"consistent-return": 0,
"no-shadow": 0,
"no-comma-dangle": 0,
"comma-dangle": 0,
"no-use-before-define": 0,
"no-empty": 0,
"new-parens": 0,
"no-cond-assign": 0
"no-cond-assign": 0,
"no-fallthrough": 0,
"new-cap": 0,
"no-loop-func": 0,
"no-unreachable": 0,
"no-labels": 0,
"no-process-exit": 0
},
"env": {
"node": true

15
.gitignore vendored
View File

@@ -8,10 +8,11 @@ test/core/tmp
/browser.js
/browser-polyfill.js
/runtime.js
coverage
dist
.package.json
packages/babel-runtime/core-js
packages/babel-runtime/helpers/*.js
packages/babel-runtime/regenerator/*.js
lib
/coverage
/dist
/.package.json
/packages/babel-runtime/core-js
/packages/babel-runtime/helpers/*.js
/packages/babel-runtime/regenerator/*.js
/lib
_babel.github.io

9
.gitmodules vendored
View File

@@ -1,12 +1,3 @@
[submodule "vendor/traceur"]
path = vendor/traceur
url = https://github.com/google/traceur-compiler
[submodule "vendor/regenerator"]
path = vendor/regenerator
url = https://github.com/babel/regenerator-babel
[submodule "vendor/test262"]
path = vendor/test262
url = https://github.com/tc39/test262
[submodule "vendor/compat-table"]
path = vendor/compat-table
url = https://github.com/kangax/compat-table

View File

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

View File

@@ -1,16 +1,35 @@
sudo: false
language: node_js
cache:
directories:
- node_modules
node_js:
- "0.12"
- "iojs"
- "0.10"
- "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:
webhooks:
urls:
- https://webhooks.gitter.im/e/acf1870e9d223c65e8d5
on_success: always
on_failure: always
on_start: false
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,533 @@
> - [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.17
* **Bug Fix**
* Fix `CodeGenerator.findCommonStringDelimiter` causing a stack overflow.
## 5.6.16
* **Internal**
* Fix `recast` version to avoid pulling in a newer version.
* **New Feature**
* Add support for functions in `util.shouldIgnore`.
* **Polish**
* Strip flow directives in flow transformer.
* Add a check for out of bounds default parameters, drastically improving performance and removes engine deoptimisations.
* Various performance optimisations by [@samccone](https://github.com/samccone) 💅✨
* Delay `this` assignment when referencing this inside an arrow function pre-bare super in derived class constructors.
* Split up class body pushing if the constructor is in the wrong order.
* **Bug Fix**
* Fix hoisting of `ForInStatement` `init` variables in `system` module formatter.
* `PathHoister`: Don't hoist to the same function as their original paths function parent.
* `PathHoister`: Push each violation paths ancestry to the breakOnScopePaths collection to avoid constant hoisting to nested paths.fix tail call recursion on functions with less arguments than parameters.
* Disallow `super.*` before `super()` in derived class constructors.
* Properly regenerate scope for replaced nodes. Thanks [@loganfsmyth](https://github.com/loganfsmyth)!
* Move up template literal simplification logic to avoid breaking on single elements.
## 5.6.13-5.6.15
* Setting up automatic Travis releases.
## 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**
* Fix istanbul interop for register hook when registering for non-existence extension.
* Fix super class constructor call differing for no constructor in derived classes.
* Disable module import receiver when in loose mode.
* Fix duplicate filenames when using `babel` CLI when passing multiple matching patterns.
* Register labels as bindings to fix undeclared variable checks.
* **Polish**
* Remove unnecessary string binary expressions when transforming template literals.
* Support module live bindings in arbitary positions not in Program statement position.
* Throw error when attemping to replace a `Program` root node with another node not of type `Program`.
* Optimise rest parameters in spread element position and allocate rest array at the earliest common ancestor of all references.
* Generate original number representation when value was not changed.
* Check for invalid binding identifiers when generating inferred method names.
* Don't terminate CLI when watching files fail compilation on init.
* **New Feature**
* Add new plugin API.
* **Internal**
* Split react displayName addition into a plugin.
* Add check for `JSXMemberExpression` to `t.isReferenced`.
* Move `validation.undeclaredVariableCheck` transformer up.
* Start great core-to-plugin exodus.
* Add `BindingIdentifier` virtual type.
* Hidden class optimisations.
* Array allocation optimisations.
* Update `regenerator`.
* Update `js-tokens`.
* Sync with upstream Acorn.
## 5.5.8
* **Internal**
* Remove extremely unprofessional and harsh error message for those hotlinking to `resolve-rc`.
## 5.5.7
* **Bug Fix**
* Push newline after decorators when doing code gen.
* Rewriting error handling to normalise options before merging them.
* Remove duplicate keys in `alias-keys.json` causing errors in strict mode.
* Fix `$ babel --help` not showing optional transformers as such.
* **New Feature**
* Add `auxiliaryCommentBefore` and `auxiliaryCommentAfter` options.
## 5.5.6
* **Bug Fix**
* Fix `let` binding collision in loop head not properly replacing `AssignmentExpression`s.
## 5.5.5
* **Bug Fix**
* Fix `file.opts` not being set before `file.log.deprecate` was called causing a `ReferenceError` as it was checking for a property on it.
## 5.5.4
* **Bug Fix**
* Add back missing `shouldIgnore` check.
* Log message on deprecated options rather than throw an error.
* Fix name of `auxiliaryComment` option when attempting Istanbul interop in `babel/register`.
## 5.5.3
* **Bug Fix**
* Fix weird state bug when traversing overa `node` `ClassProperty` instead of `path` in the `es6.classes` transformer.
## 5.5.2
* **Bug Fix**
* Fix `NodePath#isPure` on `Property` nodes.
* Use cwd instead of entry file directory when working out relative directory for `babel/register`.
* **Internal**
* Add scary warning for those few who choose to use the WIP experimental transformers.
## 5.5.1
* **Bug Fix**
* Remove `ClassProperty` nodes always in the `Flow` transformer. This is fine now since class properties aren't supported in any engine that supports classes but the `es7.classProperties` transformer will need to be updated in the future to desugar to ES6 classes instead of relying on the `es6.classes` transformer from being ran.
## 5.5.0
* **Bug Fix**
* Allow pushing declarations to `SwitchStatement`s.
* Fix `minification.removeDebugger` to remove `DebuggerStatement`s rather than `ExpressionStatement`s with an identifier of `debugger`.
* Check LHS in `ForInStatement` and `ForOfStatement` for constant violations.
* Register function `id` as a reference when naming methods to avoid collisions.
* Support key literals when checking for the existence of `displayName` property when attempting to add it for `React.createClass`.
* Remove `ExportDefaultSpecifier` check from `t.isDefaultSpecifier`.
* Don't consider `JSXIdentifier` HTML tag identifiers to be references.
* **Polish**
* Update `minification.deadCodeElimination` transformer to remove all statements after completion statements.
* Update `minification.deadCodeElimination` transformer to not inline single used bindings that exist in different scopes.
* When performing Istanbul interop in `babel/register`, add the auxiliary comment `"istanbul ignore text"` to get more accurate coverage.
* Add `--nolazy` argument to `babel-node`.
* Add support for `cluster` forking.
* Perform scope tracking in a single pass instead of multiple.
* Smarten up type inferrence and resolution to support the whole array of language constructs.
* Optimise module metadata retrieval into a single pass.
* Ignore trailing commas when inferring newlines.
* Rename `minification.inlineExpressions` transformer to `minification.constantFolding`.
* Check path relative to entry file when checking to see if we're inside `node_modules` when using `babel/register`.
* Upgrade `regenerator`.
## 5.4.7
* **Bug Fix**
* Don't consider `JSXAttribute` `names` to be valid `ReferencedIdentifier`s.
## 5.4.6
* **Bug Fix**
* Fix `spec.functionName` transformer incorrectly attempting to rename a binding that doesn't exist as it's a global.
* **Internal**
* Deprecate custom module formatters.
## 5.4.5
* **Bug Fix**
* Add `JSXIdentifier` as a valid `ReferencedIdentifier` visitor virtual type.
* Ignore `CallExpression` `_prettyCall` when the `retainLines` option is enabled.
* Inherit comments to new declaration node when exploding module declarations.
* Fix `es6.tailCall` transformer failing on calls that exceed the max parameters of the function.
## 5.4.4
* **Bug Fix**
* Fix bug where replacing variable declarations in the head of a `for` loop would turn them into `ExpressionStatement`s.
* Fix renaming of assignment expressions that were non-identifiers ie. patterns.
* Force space before `class` `id` to avoid breaking named classes when using `compact` mode.
* Add assignment pattern explosion to avoid initial duplicate nodes.
* Ignore this and arguments when performing TCO on shadowed functions.
* **Polish**
* Rename `sourceMapName` option to `sourceMapTarget`. Thanks [@getify](https://github.com/getify)!
* Better detection of completion records, ignore those in `Function`s.
* Clarified descriptions of the options that are enabled by default.
* Resolve `\`babel-plugin-${name}\`` plugin names **before** just checking the `name`. Thanks [@jquense](https://github.com/jquense)!
* Update AMD module formatter to add import default remapping.
## 5.4.3
* **Bug Fix**
* Fix `module` being incorrectly rewritten when used as in an export declaration.
* When performing single-reference inlining, ensure that the single reference isn't a child of the binding itself.
* Fix a bug in `minification.deadCodeElimination` where a new binding instance was being created for local class bindings instead of just inheriting the parent one.
* Fix bug with paren printing in `compact` and `retainLines` mode where a left paren was already printed before catching up.
* **Internal**
* Handle contexts for paths much better. This will ensure that the path node location info is in sync.
## 5.4.2
* **Polish**
* `ignore` and `only` patterns are now **very** liberal. The pattern can now exist anywhere in the path.
## 5.4.1
* **Bug Fix**
* Add missing `slash` dependency. Thanks [@browncolyn](https://github.com/browncolyn)!
* **Polish**
* Clean up `shouldIgnore` algorithm to work how you'd expect rather than being a hacky piece of shit. It now crawls the entire path, checking each section of it against the input ignore/only patterns. This means that the pattern `foo` will ignore the paths `foo/bar.js`, `bar/foo` etc.
## 5.4.0
* **New Feature**
* Added [function bind syntax](https://github.com/zenparsing/es-function-bind) behind stage 0. Thanks [@RReverser](https://github.com/rreverser)!
* Added `env` option. Especially handy when using the `.babelrc`.
* **Bug Fix**
* Fix files not properly being ignored when `babel.transform` ignores them when using `$ babel`.
* Fix scope tracking registering loop head bindings to their `VariableDeclaration` instead of `VariableDeclarator`.
* **Polish**
* Normalise path separators for souce map paths when using `$ babel`.
* Rework `PathHoister` to ignore global references and to not deopt on reassignments to referenced bindings, instead it tries to hoist to the highest scope.
* Added missing exponential operator inlining. Thanks [@nkt](https://github.com/nkt)!
* Optimise `regenerator` transformer. Thanks [@benjamn](https://github.com/benjamn)!
## 5.3.3
* **Bug Fix**
* Fix `minification.deadCodeElimination` transformer incorrectly trying to inline import declarations.
* Fix `minification.inlineExpression` transformer getting into an infinite loop.
## 5.3.2
* **Bug Fix**
* Fix patterns not being considered when hoisting variables in the `es6.blockScoping` transformer.
## 5.3.1
* **Bug Fix**
* Fix unique export specifiers not being cloned when exploding class and function exports,
* **Polish**
* Turn import remaps to sequence expressions to remove their context and improve performance.
## 5.3.0
**Speeeeeeed**
![gifs lol](https://31.media.tumblr.com/568205a0e37ae15eca510fa639589a59/tumblr_n8kw8kpcSb1sg6cg8o1_500.gif)
* **Spec Compliancy**
* Allow trailing param commas for methods when using the `es7.trailingCommas` transformer.
* **Bug Fix**
* Fix `es6.blockScoping` transformer not properly ignoring `break` in `SwitchCase`.
* Fix lookahead context saving to avoid weird tokenizer state.
* Explode duplicate identifiers in export/import specifiers and property shorthand to create unique objects.
* Skip loose mode for class methods when they have decorators.
* When removing nodes, share their comments with their siblings.
* Properly hoist temp param declarations when doing TCO.
* **Internal**
* Add `--harmony_generators` flag to `$ babel-node`.
* Internal AST traversals have been minimised **drastically**. Transformers have been grouped together which means entire tree traversals are much fewer. Visiting nodes is now also skipped if the traversal context can detect that the handler is a noop. This sames precious cycles as it avoids constructing traversal paths and creating a new traversal context. See issues [#1472](https://github.com/babel/babel/issues/1472) and [#1486](https://github.com/babel/babel/issues/1486) for related discussion.
* **Polish**
* Move many `utility` transformers to `minification`.
## 5.2.17
* **Bug Fix**
* Fix auxiliary comments not properly being attached to function declaration helpers.
* Add `Super` node type to `ast-types` patch.
* Ignore parameter bindings when attempting to inline them in the `minification.deadCodeElimination` transformer.
* Correct `extensions` arguments when using the Babel CLI.
## 5.2.16
* **Bug Fix**
* Fix plugins being disabled when using the whitelist.
* Fix correct function scope being passed to `nameMethod.property` when inferring the function name for class methods.
* Fix incorrect extensions reference causing weird issues when using the Babel CLI.
* Fix destructuring param reference replacements not inheriting from their original param.
* **Spec Compliancy**
* Fix order that method decorators are ran in.
## 5.2.15
* **Bug Fix**
* Fix initializer descriptor add attempt if it doesn't exist.
## 5.2.14
* **Bug Fix**
* Fix bug with initializer decorators where the descriptors weren't being defined if there was no `initializer` property.
* **Internal**
* Expose `retainLines` option to CLI.
* Fix `retainLines` option not being taken into consideration when doing multiple variable declaration declarators generation.
* Expose minified and unminified copies of dist scripts.
## 5.2.13
* **Bug Fix**
* Fix `ExportDeclaration`s being incorrectly removed when using the `utility.deadCodeElimination` transformer.
* Fix position of `utility` transformers.
* **New Feature**
* Add built-in `esquery` support.
* **Internal**
* Consolidate notion of "virtual types".
## 5.2.12
* **Polish**
* Make UID generation based on module declarations **much** nicer.
* **Internal**
* Remove internal check for traversal path replacement of self. This is a pattern that **could** come up in the wild and it could lead to pretty nasty code and may lead to internal regressions as the test coverage isn't 100% :( Instead, just put it in the fast path.
## 5.2.11
* **Internal**
* Rename `getModuleName` option to `getModuleId`, doh.
## 5.2.10
* **Bug Fix**
* Fix numerous issues in `replaceWithSourceString`. Thanks [@pangratz](https://github.com/pangratz)!
* **New Feature**
* Add `getModuleName` option. Thanks [@jayphelps](https://github.com/jayphelps)!
## 5.2.9
* **Bug Fix**
* Fix `_blockHoist` transformer incorrectly sorting nodes on shitty environments that aren't spec compliant in their key order.
* Fix broken `parse` API method reference to an undeclared import.
## 5.2.7
* **Bug Fix**
* Move `utility.deadCodeElimination` transformer up to avoid race conditions.
* Fix shorthand property scope binding renaming.
* **Polish**
* Turn helper variable declarations into function declarations if possible.
* **Internal**
* Removed native inheritance support from classes.
* Added `replaceWithSourceString` path API.
* Split up `es3.propertyLiterals` and `es3.memberExpressionLiterals` transformers to `minfication.propertyLiterals` and `es3.memberExpressionLiterals`.
## 5.2.6
* **Internal**
* Fix transformer aliases being accidently set as deprecated ones.
* Expose `Pipeline` as `TransformerPipeline` instead.
## 5.2.5
* **Bug Fix**
* Fix `parse` API not adding all the correct pipeline transformers.
## 5.2.4
* **Bug Fix**
* Fix race condition with the Node API being loaded awkwardly and not being able to initialise itself when used in the browser.
* **Internal**
* Expose `transform.pipeline`.
## 5.2.3
* **Bug Fix**
* Fix plugin containers being called with an undefined import. Thanks [@timbur](https://github.com/timbur)!
* Allow Flow object separators to be commas. Thanks [@monsanto](https://github.com/monsanto)!
* Add missing `Statement` and `Declaration` node aliases to flow types.
## 5.2.2
* **Internal**
* Allow `util.arrayify` to take arbitrary types and coerce it into an array.
## 5.2.1
* **Bug Fix**
* Fix regression in `node/register` that caused `node_modules` to not be ignored.
## 5.2.0
* **Bug Fix**
* Fix plugin strings splitting arbitrarily on `:` which caused full paths on Windows to fail as they include `:` after the drive letter.
* Call class property `initializer`s with their target instead of their descriptor.
* Fix `ignore` and `only` not properly working on Windows path separators. Thanks [@stagas](https://github.com/stagas)!
* Fix `resolveRc` running on files twice causing issues. Thanks [@lukescott](https://github.com/lukescott)!
* Fix shorthand properties not correctly being target for `isReferenced` checks. Thanks [@monsanto](https://github.com/monsanto)!
* **Polish**
* Allow passing an array of globs to `babel/register` `only` and `ignore` options. Thanks [@Mark-Simulacrum](https://github.com/Mark-Simulacrum)!
* When inferring function names that collide with upper bindings, instead of doing the wrapper, instead rename them.
* Consider constant-like variable declaration functions to always refer to themselves so TOC can be performed.
* Process globs manually when using `$ babel` as some shells such as Windows don't explode them. Thanks [@jden](https://github.com/jden)!
* Add alternative way to execute plugins via a closure that's called with the current Babel instance.
* **Internal**
* Remove multiple internal transformers in favor of directly doing things when we need to. Previously, declarations such as `_ref` that we needed to create in specific scopes were done at the very end via the `_declarations` transformer. Now, they're done and added to the scope **right** when they're needed. This gets rid of the crappy `_declarations` property on scope nodes and fixes the crappy regenerator bug where it was creating a new `BlockStatement` so the declarations were being lost.
* Rework transformer traversal optimisation. Turns out that calling a `check` function for **every single node** in the AST is ridiculously expensive. 300,000 nodes timesed by ~30 transformers meant that it took tens of seconds to perform while it's quicker to just do the unnecessary traversal. Seems obvious in hindsight.
* **New Feature**
* Add `jscript` transformer that turns named function expressions into function declarations to get around [JScript's horribly broken function expression semantics](https://kangax.github.io/nfe/#jscript-bugs). Thanks [@kondi](https://github.com/kondi)!
* Add `@@hasInstance` support to objects when using the `es6.spec.symbols` transformer.
* Add `retainLines` option that retains the line (but not the columns!) of the input code.
## 5.1.13
* **Polish**
* Remove symbol check from `defineProperty` helper.
## 5.1.12
* **Bug Fix**
* Fix `resolveModuleSource` not being ran on `ExportAllDeclaration`s.
* Fix `.babelrc` being resolved multiple times when using the require hook.
* Fix parse error on spread properties in assignment position.
* Fix `externalHelpers` option being incorrectly listed as type `string`.
* **Internal**
* Upgrade `core-js` to `0.9.0`.
* **Spec Compliancy**
* Fix object decorators not using the `initializer` pattern.
* Remove property initializer descriptor reflection.
## 5.1.11
* **Bug Fix**
* Memoise and bind member expression decorators.
* Move JSX children cleaning to opening element visitor. Fixes elements not being cleaned in certain scenarios.
* Consider `SwitchStatement`s to be `Scopable`.
* Fix `bluebirdCoroutines` calling `interopRequireWildcard` before it's defined.
* Add space to `do...while` code generation.
* Validate `super` use before `this` on `super` exit rather than entrance.
* **Polish**
* Add Babel name to logger.
## 5.1.10
* **Bug Fix**
* Remove `makePredicate` from acorn in favor of an `indexOf`.
* Remove statements to expression explosion when inserting a block statement.
* **Internal**
* Remove runtime compatibility check.
## 5.1.9
* **Bug Fix**
* Fix class property initializers with `undefined` values not being correctly writable.
* Fix self inferring generators incorrectly causing a stack error.
* Fix default export specifiers not triggering AMD `module` argument inclusion.
* Fix assignments not having their module references properly remapped.
* **Internal**
* Upgrade to latest `acorn`.
* **Polish**
* Make invalid LHS pattern error messages nicer.
## 5.1.8
* **Bug Fix**
* Only make parenthesized object pattern LHS illegal.
## 5.1.7
* **Internal**
* Add `parse` node API.
## 5.1.6
* **Bug Fix**
* Fix `runtime` built-in catchall not properly checking for local variables.
## 5.1.5
* **Internal**
* Bump `core-js` version.
## 5.1.4
* **Polish**
* Add missing `Reflect` methods to runtime transformer.
## 5.1.3
* **Internal**
* Switch entirely to vanilla regenerator.
* Clean up and make the parsing of decorators stateless.
* **Bug Fix**
* Don't do TCO on generators and async functions.
* Add missing `core-js` runtime definitions.
## 5.1.2
* **Bug Fix**

View File

@@ -1,3 +1,23 @@
# NOTE: BEFORE OPENING AN ISSUE PLEASE SEE THE [README](https://github.com/babel/babel#readme).
----
<p align="center">
<strong><a href="#setup">Setup</a></strong>
|
<strong><a href="#running-tests">Running tests</a></strong>
|
<strong><a href="#workflow">Workflow</a></strong>
|
<strong><a href="#dependencies">Dependencies</a></strong>
|
<strong><a href="#code-standards">Code Standards</a></strong>
|
<strong><a href="#internals">Internals</a></strong>
</p>
----
# Contributing
Contributions are always welcome, no matter how large or small. Before
@@ -6,6 +26,9 @@ contributing, please read the
## Developing
> Note: Babel moves fast. Only the latest release is guaranteed to build correctly.
> Older releases are not officially supported. If you attempt to build them, do that at your own risk.
#### Setup
```sh
@@ -14,14 +37,19 @@ $ cd babel
$ make bootstrap
```
Then you need to run:
Then you can either run:
```sh
$ make build-core
```
to build Babel **once** or:
```sh
$ make watch-core
```
This will compile Babel and then sit in the background and on file modification
recompile the necessary files.
to have Babel build itself then incrementally build files on change.
#### Running tests
@@ -44,6 +72,11 @@ Use mocha's `--grep` option to run a subset of tests by name:
$ mocha test/core/transformation.js --grep es7
```
If you don't have `mocha` installed globally, you can still use it from Babel's
dependencies in `node_modules`, but make sure `node_modules/.bin` is added to
your [`$PATH`](http://unix.stackexchange.com/questions/26047/how-to-correctly-add-a-path-to-path) environment variable.
#### Workflow
* Fork the repository
@@ -54,24 +87,94 @@ $ mocha test/core/transformation.js --grep es7
* Ensure the test are passing (`make test`)
* Create new pull request explaining your proposed change or reference an issue in your commit message
#### Dependencies
+ [ast-types](http://ghub.io/ast-types) This is required to monkeypatch regenerators AST definitions. Could be improved in the future.
+ [chalk](http://ghub.io/chalk) This is used for terminal color highlighting for syntax errors.
+ [convert-source-map](http://ghub.io/convert-source-map) Turns a source map object into a comment etc.
+ [core-js](http://ghub.io/core-js) Used for the polyfill.
+ [debug](http://ghub.io/debug) Used to output debugging information when NODE_DEBUG is set to babel.
+ [detect-indent](http://ghub.io/detect-indent) This is used in the code generator so it can infer indentation.
+ [estraverse](http://ghub.io/estraverse) The only method on this is attachComments. I'd like to implement our own comment attachment algorithm eventually though.
+ [esutils](http://ghub.io/esutils) Various ES related utilities. Check whether something is a keyword etc.
+ [fs-readdir-recursive](http://ghub.io/fs-readdir-recursive) Recursively search a directory for.
+ [globals](http://ghub.io/globals) A list of JavaScript global variables. This is used by the scope tracking to check for colliding variables.
+ [is-integer](http://ghub.io/is-integer) Checks if something is an integer.
+ [js-tokens](http://ghub.io/js-tokens) This is used to get tokens for syntax error highlighting.
+ [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.
+ [minimatch](http://ghub.io/minimatch) This is used to match glob-style ignore/only filters.
+ [output-file-sync](http://ghub.io/output-file-sync) Synchronously writes a file and create its ancestor directories if needed.
+ [path-is-absolute](http://ghub.io/path-is-absolute) Checks if a path is absolute. C:\foo and \foo are considered absolute.
+ [regenerator](http://ghub.io/regenerator) This is used to transform generators/async functions.
+ [regexpu](http://ghub.io/regexpu) Used to transform unicode regex patterns.
+ [repeating](http://ghub.io/repeating) Repeats a string.
+ [shebang-regex](http://ghub.io/shebang-regex) Literally just a regex that matches shebangs.
+ [slash](http://ghub.io/slash) Normalises path separators.
+ [source-map](http://ghub.io/source-map) Generates sourcemaps.
+ [source-map-support](http://ghub.io/source-map-support) Adds source map support to babel-node/babel/register.
+ [strip-json-comments](http://ghub.io/strip-json-comments) Remove comments from a JSON string. This is used for .babelrc files.
+ [to-fast-properties](http://ghub.io/to-fast-properties) A V8 trick to put an object into fast properties mode.
+ [trim-right](http://ghub.io/trim-right) Trims the rightside whitespace.
+ [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
* **General**
* Max of five arguments for functions
* Max depth of four nested blocks
* 2-spaced soft tabs
* **Naming**
* CamelCase all class names
* camelBack all variable names
* **Spacing**
* Spaces after all keywords
* Spaces before all left curly braces
* **Comments**
* Use JSDoc-style comments for methods
* Single-line comments for ambiguous code
* **Quotes**
* Always use double quotes
* Only use single quotes when the string contains a double quote
* **Declaration**
* No unused variables
* No pollution of global variables and prototypes
#### Internals
Please see [`/doc`](/doc) for internals documentation relevant to developing babel.

View File

@@ -3,23 +3,29 @@ BROWSERIFY_CMD = node_modules/browserify/bin/cmd.js
ISTANBUL_CMD = node_modules/istanbul/lib/cli.js cover
UGLIFY_CMD = node_modules/uglify-js/bin/uglifyjs
#UGLIFY_CMD = node_modules/uglify-js/bin/uglifyjs --mangle sort
JSHINT_CMD = node_modules/jshint/bin/jshint
MOCHA_CMD = node_modules/mocha/bin/_mocha
BABEL_CMD = node_modules/babel/bin/babel
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
.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:
build-core: clean-core
node $(BABEL_CMD) src --out-dir lib --copy-files
build-core-test:
node $(BABEL_CMD) src --out-dir lib --copy-files --auxiliary-comment "istanbul ignore next"
build-core-test: clean-core
node $(BABEL_CMD) src --out-dir lib --copy-files --auxiliary-comment-before "istanbul ignore next"
watch-core:
watch-core: clean-core
node $(BABEL_CMD) src --out-dir lib --watch --copy-files
clean-core:
rm -rf lib
lint:
eslint src/babel packages/babel-cli/bin
build:
mkdir -p dist
make build-core
@@ -29,8 +35,10 @@ build:
node $(BROWSERIFY_CMD) -e lib/babel/polyfill.js >dist/polyfill.js
node $(UGLIFY_CMD) dist/polyfill.js >dist/polyfill.min.js
node $(BROWSERIFY_CMD) lib/babel/api/browser.js -s babel >dist/babel.js
node $(UGLIFY_CMD) dist/babel.js >dist/babel.min.js
node $(BROWSERIFY_CMD) lib/babel/api/browser.js -s babel $(BROWSERIFY_IGNORE) >dist/browser.js
node $(UGLIFY_CMD) dist/browser.js >dist/browser.min.js
node $(BROWSERIFY_CMD) lib/babel/api/node.js --node $(BROWSERIFY_IGNORE) >dist/node.js
node packages/babel-cli/bin/babel-external-helpers >dist/external-helpers.js
node $(UGLIFY_CMD) dist/external-helpers.js >dist/external-helpers.min.js
@@ -59,7 +67,7 @@ test-cov:
test-parser:
node test/acorn/run.js
test-travis: bootstrap build test
test-travis: bootstrap lint build test
test-browser:
mkdir -p dist
@@ -71,30 +79,22 @@ test-browser:
test -n "`which open`" && open test/browser.html
publish:
publish: lint
git pull --rebase
make test
read -p "Version: " version; \
npm version $$version --message "v%s"
make build
cp dist/babel.min.js browser.js
cp dist/polyfill.min.js browser-polyfill.js
cp dist/external-helpers.min.js external-helpers.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-polyfill.js external-helpers.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; \
@@ -103,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
@@ -114,5 +117,4 @@ bootstrap:
npm link
cd packages/babel-cli && npm install && npm link && npm link babel-core
git submodule update --init
cd vendor/regenerator && npm install
cd vendor/compat-table && npm install object-assign
make build

View File

@@ -1,15 +1,28 @@
<p align="center">
<a href="https://babeljs.io/">
<img alt="babel" src="https://raw.githubusercontent.com/babel/logo/master/logo.png" width="546">
<img alt="babel" src="https://raw.githubusercontent.com/babel/logo/master/babel.png" width="546">
</a>
</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://gitter.im/babel/babel">gitter room</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">
<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">

4
doc/index.md Normal file
View File

@@ -0,0 +1,4 @@
This is a collection of documentation about babel internals, for use in development of babel.
# [Properties of nodes](/doc/node-props.md)
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).

11
doc/node-props.md Normal file
View File

@@ -0,0 +1,11 @@
# 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](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.
## `_paths`
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 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,69 +1,85 @@
{
"name": "babel-core",
"description": "Turn ES6 code into readable vanilla ES5 with source maps",
"version": "5.1.2",
"description": "A compiler for writing next generation JavaScript",
"version": "5.6.20",
"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",
"test": "make test"
},
"dependencies": {
"ast-types": "~0.7.0",
"acorn-jsx": "^1.0.0",
"babel-plugin-constant-folding": "^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",
"babel-plugin-member-expression-literals": "^1.0.1",
"babel-plugin-property-literals": "^1.0.1",
"babel-plugin-proto-to-assign": "^1.0.3",
"babel-plugin-react-constant-elements": "^1.0.3",
"babel-plugin-react-display-name": "^1.0.3",
"babel-plugin-remove-console": "^1.0.1",
"babel-plugin-remove-debugger": "^1.0.1",
"babel-plugin-runtime": "^1.0.7",
"babel-plugin-undeclared-variables-check": "^1.0.2",
"babel-plugin-undefined-to-void": "^1.1.6",
"chalk": "^1.0.0",
"convert-source-map": "^1.0.0",
"core-js": "^0.8.1",
"convert-source-map": "^1.1.0",
"core-js": "^0.9.0",
"debug": "^2.1.1",
"detect-indent": "^3.0.0",
"estraverse": "^3.0.0",
"estraverse": "^4.0.0",
"esutils": "^2.0.0",
"fs-readdir-recursive": "^0.1.0",
"globals": "^6.4.0",
"home-or-tmp": "^1.0.0",
"is-integer": "^1.0.4",
"js-tokens": "1.0.0",
"leven": "^1.0.1",
"js-tokens": "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": "https://github.com/sebmck/regenerator/archive/block-hoist.tar.gz",
"regenerator": "0.8.34",
"regexpu": "^1.1.2",
"repeating": "^1.1.2",
"resolve": "^1.1.6",
"shebang-regex": "^1.0.0",
"slash": "^1.0.0",
"source-map": "^0.4.0",
"source-map-support": "^0.2.10",
"strip-json-comments": "^1.0.2",
"to-fast-properties": "^1.0.0",
"trim-right": "^1.0.0",
"user-home": "^1.1.1"
"trim-right": "^1.0.0"
},
"devDependencies": {
"babel": "4.7.13",
"babel": "5.6.10",
"babel-eslint": "^3.1.19",
"browserify": "^9.0.8",
"chai": "^2.2.0",
"eslint": "^0.18.0",
"babel-eslint": "^2.0.0",
"eslint": "^0.21.2",
"esvalid": "^1.1.0",
"istanbul": "^0.3.5",
"matcha": "^0.6.0",

View File

@@ -18,9 +18,9 @@ program.option("-p, --print [code]", "Evaluate script and print result");
program.option("-i, --ignore [regex]", "Ignore all files that match this regex when using the require hook");
program.option("-x, --extensions [extensions]", "List of extensions to hook into [.es6,.js,.es,.jsx]");
program.option("-r, --stage [stage]", "Enable support for specific ECMAScript stages");
program.option("-w, --whitelist [whitelist]", "Whitelist of transformers to ONLY use", util.list);
program.option("-b, --blacklist [blacklist]", "Blacklist of transformers to NOT use", util.list);
program.option("-o, --optional [optional]", "List of optional transformers to enable", util.list);
program.option("-w, --whitelist [whitelist]", "Whitelist of transformers separated by comma to ONLY use", util.list);
program.option("-b, --blacklist [blacklist]", "Blacklist of transformers separated by comma to NOT use", util.list);
program.option("-o, --optional [optional]", "List of optional transformers separated by comma to enable", util.list);
var pkg = require("../package.json");
program.version(pkg.version);
@@ -41,6 +41,7 @@ babel.register({
//
var _eval = function (code, filename) {
code = code.trim();
if (!code) return undefined;
code = babel.transform(code, {
@@ -107,6 +108,7 @@ if (program.eval || program.print) {
// add back on node and concat the sliced args
process.argv = ["node"].concat(args);
process.execArgv.unshift(__filename);
Module.runMain();
} else {

View File

@@ -55,6 +55,8 @@ babelArgs.forEach(function(arg){
case "--harmony_classes":
case "--harmony_object_literals":
case "--harmony_templates":
case "--harmony_rest_parameters":
case "--harmony_generators":
case "--compiled_keyed_generic_loads":
case "--pretenuring_call_new":
case "--allocation_site_pretenuring":
@@ -410,6 +412,7 @@ babelArgs.forEach(function(arg){
case "--prof_auto":
case "--prof_lazy":
case "--sliding_state_window":
case "--nolazy":
args.unshift(arg);
break;

View File

@@ -0,0 +1,141 @@
#!/usr/bin/env node
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);
var spawn = child.spawn(cmd, args, { stdio: "inherit" });
spawn.on("exit", function (code) {
if (code === 0) {
if (callback) callback();
} else {
console.log("Killing...");
process.exit(1);
}
});
}
function spawnMultiple(cmds) {
function next() {
var cmd = cmds.shift();
if (cmd) {
spawn(cmd.command, cmd.args, next);
} else {
process.exit();
}
}
next();
}
function template(name, data) {
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];
});
return source;
}
function write(filename, content) {
console.log(filename);
fs.writeFileSync(filename, content);
}
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var BABEL_PLUGIN_PREFIX = "babel-plugin-";
var cmds = {
init: function () {
var name = path.basename(process.cwd());
if (name.indexOf(BABEL_PLUGIN_PREFIX) === 0) {
name = name.slice(BABEL_PLUGIN_PREFIX.length);
}
rl.question("Description (optional): ", function (description) {
rl.question("GitHub Repository (eg. sebmck/babel-plugin-foobar) (optional): ", function (repo) {
rl.close();
var templateData = {
DESCRIPTION: description,
FULL_NAME: BABEL_PLUGIN_PREFIX + name,
NAME: name
};
write("package.json", JSON.stringify({
name: templateData.FULL_NAME,
version: "1.0.0",
description: templateData.DESCRIPTION,
repository: repo || undefined,
license: "MIT",
main: "lib/index.js",
devDependencies: {
babel: "^5.6.0"
},
scripts: {
build: "babel-plugin build",
push: "babel-plugin publish",
test: "babel-plugin test"
},
keywords: ["babel-plugin"]
}, null, " ") + "\n");
write(".npmignore", "node_modules\n*.log\nsrc\n");
write(".gitignore", "node_modules\n*.log\nlib\n");
write("README.md", template("README.md", templateData));
if (!pathExists.sync("src")) {
fs.mkdirSync("src");
write("src/index.js", template("index.js", templateData));
}
});
});
},
build: function () {
spawn("babel", ["src", "--out-dir", "lib", "--copy-files"]);
},
publish: function () {
var pkg = require(process.cwd() + "/package.json");
console.log("Current verison:", pkg.version);
rl.question("New version (enter nothing for patch): ", function (newVersion) {
rl.close();
newVersion = newVersion || "patch";
spawnMultiple([
{ command: "git", args: ["pull"] },
{ command: "git", args: ["push"] },
{ command: "babel-plugin", args: ["build"] },
{ command: "npm", args: ["version", newVersion] },
{ command: "npm", args: ["publish"] },
{ command: "git", args: ["push", "--follow-tags"] }
]);
});
}
};
var cmd = cmds[process.argv[2]];
if (cmd) {
cmd();
} else {
console.error("Unknown command:", cmd);
process.exit(1);
}

View File

@@ -0,0 +1,35 @@
# FULL_NAME
DESCRIPTION
## Installation
```sh
$ npm install FULL_NAME
```
## Usage
### Via `.babelrc` (Recommended)
**.babelrc**
```json
{
"plugins": ["NAME"]
}
```
### Via CLI
```sh
$ babel --plugins NAME script.js
```
### Via Node API
```javascript
require("babel-core").transform("code", {
plugins: ["NAME"]
});
```

View File

@@ -0,0 +1,7 @@
export default function ({ Plugin, types: t }) {
return new Plugin("NAME", {
visitor: {
// your visitor methods go here
}
});
}

View File

@@ -1,11 +1,13 @@
var outputFileSync = require("output-file-sync");
var pathExists = require("path-exists");
var chokidar = require("chokidar");
var slash = require("slash");
var path = require("path");
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";
@@ -13,8 +15,10 @@ module.exports = function (commander, filenames, opts) {
var dest = path.join(commander.outDir, relative);
var data = util.compile(src, {
sourceFileName: path.relative(dest + "/..", src)
sourceFileName: slash(path.relative(dest + "/..", src)),
sourceMapTarget: path.basename(relative)
});
if (data.ignored) return;
if (commander.sourceMaps && commander.sourceMaps !== "inline") {
var mapLoc = dest + ".map";
@@ -24,13 +28,13 @@ module.exports = function (commander, filenames, opts) {
outputFileSync(dest, data.code);
console.log(src + " -> " + dest);
util.log(src + " -> " + dest);
};
var handleFile = function (src, filename) {
if (util.shouldIgnore(src)) return;
if (util.canCompile(filename)) {
if (util.canCompile(filename, commander.extensions)) {
write(src, filename);
} else if (commander.copyFiles) {
outputFileSync(path.join(commander.outDir, filename), fs.readFileSync(src));
@@ -38,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,6 +1,8 @@
var convertSourceMap = require("convert-source-map");
var pathExists = require("path-exists");
var sourceMap = require("source-map");
var chokidar = require("chokidar");
var slash = require("slash");
var path = require("path");
var util = require("./util");
var fs = require("fs");
@@ -15,7 +17,8 @@ module.exports = function (commander, filenames, opts) {
var buildResult = function () {
var map = new sourceMap.SourceMapGenerator({
file: commander.outFile || "stdout"
file: path.basename(commander.outFile) || "stdout",
sourceRoot: opts.sourceRoot
});
var code = "";
@@ -28,8 +31,14 @@ module.exports = function (commander, filenames, opts) {
if (result.map) {
var consumer = new sourceMap.SourceMapConsumer(result.map);
map._sources.add(filename);
map.setSourceContent(filename, result.actual);
var sourceFilename = filename;
if (commander.outFile) {
sourceFilename = path.relative(path.dirname(commander.outFile), sourceFilename);
}
sourceFilename = slash(sourceFilename);
map._sources.add(sourceFilename);
map.setSourceContent(sourceFilename, result.actual);
consumer.eachMapping(function (mapping) {
map._mappings.add({
@@ -37,7 +46,7 @@ module.exports = function (commander, filenames, opts) {
generatedColumn: mapping.generatedColumn,
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
source: filename
source: sourceFilename
});
});
@@ -92,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()) {
@@ -109,7 +118,9 @@ module.exports = function (commander, filenames, opts) {
_.each(_filenames, function (filename) {
if (util.shouldIgnore(filename)) return;
results.push(util.compile(filename));
var data = util.compile(filename);
if (data.ignored) return;
results.push(data);
});
output();
@@ -124,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,13 +1,18 @@
#!/usr/bin/env node
var commander = require("commander");
var transform = require("babel-core").transform;
var kebabCase = require("lodash/string/kebabCase");
var options = require("babel-core").options;
var util = require("babel-core").util;
var each = require("lodash/collection/each");
var keys = require("lodash/object/keys");
var fs = require("fs");
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");
var options = require("babel-core").options;
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 glob = require("glob");
each(options, function (option, key) {
if (option.hidden) return;
@@ -33,12 +38,14 @@ each(options, function (option, key) {
if (option.description) desc.push(option.description);
commander.option(arg, desc.join(" "));
})
});
commander.option("-x, --extensions [extensions]", "List of extensions to compile when a directory has been input [.es6,.js,.es,.jsx]");
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) {
@@ -48,7 +55,7 @@ commander.on("--help", function () {
each(keys(obj).sort(), function (key) {
if (key[0] === "_") return;
if (obj[key].optional) key = "[" + key + "]";
if (obj[key].metadata && obj[key].metadata.optional) key = "[" + key + "]";
console.log(" - " + key);
});
@@ -56,23 +63,35 @@ commander.on("--help", function () {
console.log();
};
outKeys("Transformers", transform.transformers);
outKeys("Module formatters", transform.moduleFormatters);
outKeys("Transformers", transform.pipeline.transformers);
outKeys("Module formatters", moduleFormatters);
});
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);
//
if (commander.extensions) {
commander.extensions = util.arrayify(commander.extensions);
}
//
var errors = [];
var filenames = commander.args;
var filenames = commander.args.reduce(function (globbed, input) {
var files = glob.sync(input);
if (!files.length) files = [input];
return globbed.concat(files);
}, []);
filenames = uniq(filenames);
each(filenames, function (filename) {
if (!fs.existsSync(filename)) {
if (!pathExists.sync(filename)) {
errors.push(filename + " doesn't exist");
}
});
@@ -105,11 +124,16 @@ if (errors.length) {
var opts = exports.opts = {};
each(options, function (opt, key) {
opts[key] = commander[key];
if (commander[key] !== undefined) {
opts[key] = commander[key];
}
});
opts.ignore = util.arrayify(opts.ignore, util.regexify);
opts.only = util.arrayify(opts.only, util.regexify);
if (opts.only) {
opts.only = util.arrayify(opts.only, util.regexify);
}
var fn;

View File

@@ -1,10 +1,11 @@
var readdir = require("fs-readdir-recursive");
var index = require("./index");
var babel = require("babel-core");
var util = require("babel-core").util;
var path = require("path");
var fs = require("fs");
var _ = require("lodash");
var commander = require("commander");
var readdir = require("fs-readdir-recursive");
var index = require("./index");
var babel = require("babel-core");
var util = require("babel-core").util;
var path = require("path");
var fs = require("fs");
var _ = require("lodash");
exports.readdirFilter = function (filename) {
return readdir(filename).filter(function (filename) {
@@ -24,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;
@@ -37,6 +42,15 @@ exports.transform = function (filename, code, opts) {
};
exports.compile = function (filename, opts) {
var code = fs.readFileSync(filename, "utf8");
return exports.transform(filename, code, opts);
try {
var code = fs.readFileSync(filename, "utf8");
return exports.transform(filename, code, opts);
} catch (err) {
if (commander.watch) {
console.error(err.stack);
return { ignored: true };
} else {
throw err;
}
}
};

View File

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

View File

@@ -0,0 +1 @@
module.exports = require("babel-core/register-without-polyfill");

View File

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

View File

@@ -70,12 +70,11 @@ each(File.helpers, function (helperName) {
writeFile("helpers/" + helperName + ".js", buildHelper(helperName));
});
writeFile("regenerator/index.js", readFile("regenerator-babel/runtime-module", true));
writeFile("regenerator/runtime.js", selfContainify(readFile("regenerator-babel/runtime")));
writeFile("regenerator/index.js", readFile("regenerator/runtime-module", true));
writeFile("regenerator/runtime.js", selfContainify(readFile("regenerator/runtime")));
//
var coreDefinitions = require("../lib/babel/transformation/transformers/other/runtime/definitions");
var coreDefinitions = require("babel-plugin-runtime/lib/definitions");
var paths = ["is-iterable", "get-iterator"];
@@ -93,6 +92,5 @@ each(paths, function (path) {
writeFile("core-js/" + path + ".js", defaultify('require("core-js/library/fn/' + path + '")'));
});
//
updatePackage();

View File

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

View File

@@ -1 +1 @@
module.exports = require("./lib/babel/api/register/node");
module.exports = require("./lib/babel/api/register/node-polyfill");

48
sebmck-bjs.nfo Normal file
View File

@@ -0,0 +1,48 @@
====== ==========M=
============= == ======O= ======= MM ==
M==+=== ==M === ==== == === ==
=D === === ====MM ==M ==M ==M ===
===M ====M ==== =D ===M === === ==
==7 ====M ==M == ======== =========M ==M
=========== ======M ===MMM === ==M ==
=======MM==========MM== ==M ==M=== ==
==M === M== ==M == === === =D =
==M ===+ == == == ==$M =========== ============M
=== ====M == ==M ===M== ====?MMMM M M
== ===== ==M == ==MM M
==M===M=M =M =MM M M
==MM=M ==
MMM =M
M
> ú B ú A ú B ú E ú L ú <
ÕÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÑÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ͸
³ SOFTWARE .. : JavaScript Compiler ³ COMPANY ... : N/A ³
³ SUPPLIER .. : N/A ³ CRACKER ... : Sebastian McKenzie ³
³ RATING .... : depends.. ³ PACKAGER .. : Sebastian McKenzie ³
³ ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ ³
³ GRAFIX .... : - ³ SOUND ..... : - ³
ÔÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÏÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ;
Babel is a JavaScript compiler and transformation platform for writing NeXt
GeNeRaTiOn JavaScript.
ÆÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÏÍÍÍÍÍÍÍÍÍÍÍÍÍÍÏÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÏÍÍÍÍÍÍÍÏÍÍÍÍÍÍÍÍÍÍÍ͵
³ :: Greets :: ³
³ ³
³ sebmck, thejameskyle, RReverser, zloirock, monsanto, gaearon, zertosh, ³
³ stefanpenner, eventualbuddha, AluisioASG, Apoxx, Couto, dominicbarnes, ³
³ es128, gordonkristan, hkjels, jmeas, josh, loganfsmyth, nightire, ³
³ Rich-Harris, shinnn, shuhei, sindresorhus, tricknotes ³
³ ³
ÔÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ;
-*- JavaScripts for all , All for JavaScripts ! -*-
ÕÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ͸
³ If you want to Contact us, call 555-720-4228, Use the Handle "BABEL" w/ ³
³ password : VISITOR and leave a mail to Sebastian or James. ³
ÔÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ;
-=- We LoVe fun Too! -=-

27
src/README.md Normal file
View File

@@ -0,0 +1,27 @@
## Welcome to the Babel Codebase
Babel is broken down into three parts:
- Parsing
- [Transformation](babel/transformation/)
- [Generation](babel/generation/)
**Parsing** is the process of turning a piece of code into an [ESTree spec](https://github.com/estree/estree) compatible AST (Abstract
Syntax Tree) which is a tree-like object of nodes that _describes_ the code.
This makes it easier to transform the code over direct string manpulation.
**Transformation** is the process of taking an AST and manipulating it into
a new one. For example, Babel might take an ES2015 ArrowFunction and transform
it into a normal Function which will work in ES5 environments.
**Generation** is the process of turning an AST back into code. After Babel is
done transforming the AST, the generation takes over to return normal code.
---
Babel's parsing step is done by [Acorn](https://github.com/marijnh/acorn). However, because Babel is implementing
future standards it maintains a [fork of Acorn](acorn/) in order to do it's job. You can
see that fork in the "acorn" folder.
The transformation and generation steps are both handled inside of the Babel
codebase itself, which is in the "babel" folder here.

6
src/acorn/index.js Normal file
View File

@@ -0,0 +1,6 @@
export * from "./src/index";
import "./plugins/flow";
import inject from "acorn-jsx/inject";
import * as acorn from "./src/index";
inject(acorn);

View File

@@ -2,7 +2,7 @@
"name": "acorn",
"description": "ECMAScript parser",
"homepage": "https://github.com/marijnh/acorn",
"main": "src/index.js",
"main": "index.js",
"version": "1.0.0",
"engines": {
"node": ">=0.4.0"

View File

@@ -1,4 +1,4 @@
var acorn = require("..")
var acorn = require("../src/index")
var pp = acorn.Parser.prototype
var tt = acorn.tokTypes
@@ -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,10 +160,7 @@ pp.flow_parseTypeAlias = function (node) {
node.typeParameters = null
}
this.expect(tt.eq)
node.right = this.flow_parseType()
node.right = this.flow_parseTypeInitialiser(tt.eq)
this.semicolon()
return this.finishNode(node, "TypeAlias")
@@ -209,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")
@@ -240,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")
}
@@ -260,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")
}
@@ -305,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()
@@ -322,7 +322,7 @@ pp.flow_parseObjectType = function (allowStatic) {
}
pp.flow_objectTypeSemicolon = function () {
if (!this.eat(tt.semi) && this.type !== tt.braceR) {
if (!this.eat(tt.semi) && !this.eat(tt.comma) && this.type !== tt.braceR) {
this.unexpected()
}
}
@@ -347,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)
@@ -381,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")
}
@@ -406,10 +399,16 @@ 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")
case "mixed":
return this.finishNode(node, "MixedTypeAnnotation")
case "number":
return this.finishNode(node, "NumberTypeAnnotation")
@@ -516,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()
}
}
@@ -580,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")
}
@@ -686,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)) {
@@ -792,16 +791,15 @@ acorn.plugins.flow = function (instance) {
instance.extend("parseImportSpecifiers", function (inner) {
return function (node) {
node.isType = false
if (this.isContextual("type")) {
var start = this.markPosition()
var typeId = this.parseIdent()
if ((this.type === tt.name && this.value !== "from") || this.type === tt.braceL || this.type === tt.star) {
node.isType = true
} else {
node.specifiers.push(this.parseImportSpecifierDefault(typeId, start))
if (this.isContextual("from")) return
this.eat(tt.comma)
node.importKind = "value"
var kind =
(this.type === tt._typeof ? "typeof" :
(this.isContextual("type") ? "type" : null))
if (kind) {
var lh = this.lookahead()
if ((lh.type === tt.name && lh.value !== "from") || lh.type === tt.braceL || lh.type === tt.star) {
this.next()
node.importKind = kind
}
}
inner.call(this, node)

View File

@@ -1,658 +0,0 @@
var acorn = require("..")
var tt = acorn.tokTypes;
var tc = acorn.tokContexts;
tc.j_oTag = new acorn.TokContext("<tag", false);
tc.j_cTag = new acorn.TokContext("</tag", false);
tc.j_expr = new acorn.TokContext("<tag>...</tag>", true, true);
tt.jsxName = new acorn.TokenType("jsxName");
tt.jsxText = new acorn.TokenType("jsxText", {beforeExpr: true});
tt.jsxTagStart = new acorn.TokenType("jsxTagStart");
tt.jsxTagEnd = new acorn.TokenType("jsxTagEnd");
tt.jsxTagStart.updateContext = function() {
this.context.push(tc.j_expr); // treat as beginning of JSX expression
this.context.push(tc.j_oTag); // start opening tag context
this.exprAllowed = false;
};
tt.jsxTagEnd.updateContext = function(prevType) {
var out = this.context.pop();
if (out === tc.j_oTag && prevType === tt.slash || out === tc.j_cTag) {
this.context.pop();
this.exprAllowed = this.curContext() === tc.j_expr;
} else {
this.exprAllowed = true;
}
};
var pp = acorn.Parser.prototype;
// Reads inline JSX contents token.
pp.jsx_readToken = function() {
var out = "", chunkStart = this.pos;
for (;;) {
if (this.pos >= this.input.length)
this.raise(this.start, "Unterminated JSX contents");
var ch = this.input.charCodeAt(this.pos);
switch (ch) {
case 60: // '<'
case 123: // '{'
if (this.pos === this.start) {
if (ch === 60 && this.exprAllowed) {
++this.pos;
return this.finishToken(tt.jsxTagStart);
}
return this.getTokenFromCode(ch);
}
out += this.input.slice(chunkStart, this.pos);
return this.finishToken(tt.jsxText, out);
case 38: // '&'
out += this.input.slice(chunkStart, this.pos);
out += this.jsx_readEntity();
chunkStart = this.pos;
break;
default:
if (acorn.isNewLine(ch)) {
out += this.input.slice(chunkStart, this.pos);
++this.pos;
if (ch === 13 && this.input.charCodeAt(this.pos) === 10) {
++this.pos;
out += "\n";
} else {
out += String.fromCharCode(ch);
}
if (this.options.locations) {
++this.curLine;
this.lineStart = this.pos;
}
chunkStart = this.pos;
} else {
++this.pos;
}
}
}
};
pp.jsx_readString = function(quote) {
var out = "", chunkStart = ++this.pos;
for (;;) {
if (this.pos >= this.input.length)
this.raise(this.start, "Unterminated string constant");
var ch = this.input.charCodeAt(this.pos);
if (ch === quote) break;
if (ch === 38) { // '&'
out += this.input.slice(chunkStart, this.pos);
out += this.jsx_readEntity();
chunkStart = this.pos;
} else {
++this.pos;
}
}
out += this.input.slice(chunkStart, this.pos++);
return this.finishToken(tt.string, out);
};
var XHTMLEntities = {
quot: '\u0022',
amp: '&',
apos: '\u0027',
lt: '<',
gt: '>',
nbsp: '\u00A0',
iexcl: '\u00A1',
cent: '\u00A2',
pound: '\u00A3',
curren: '\u00A4',
yen: '\u00A5',
brvbar: '\u00A6',
sect: '\u00A7',
uml: '\u00A8',
copy: '\u00A9',
ordf: '\u00AA',
laquo: '\u00AB',
not: '\u00AC',
shy: '\u00AD',
reg: '\u00AE',
macr: '\u00AF',
deg: '\u00B0',
plusmn: '\u00B1',
sup2: '\u00B2',
sup3: '\u00B3',
acute: '\u00B4',
micro: '\u00B5',
para: '\u00B6',
middot: '\u00B7',
cedil: '\u00B8',
sup1: '\u00B9',
ordm: '\u00BA',
raquo: '\u00BB',
frac14: '\u00BC',
frac12: '\u00BD',
frac34: '\u00BE',
iquest: '\u00BF',
Agrave: '\u00C0',
Aacute: '\u00C1',
Acirc: '\u00C2',
Atilde: '\u00C3',
Auml: '\u00C4',
Aring: '\u00C5',
AElig: '\u00C6',
Ccedil: '\u00C7',
Egrave: '\u00C8',
Eacute: '\u00C9',
Ecirc: '\u00CA',
Euml: '\u00CB',
Igrave: '\u00CC',
Iacute: '\u00CD',
Icirc: '\u00CE',
Iuml: '\u00CF',
ETH: '\u00D0',
Ntilde: '\u00D1',
Ograve: '\u00D2',
Oacute: '\u00D3',
Ocirc: '\u00D4',
Otilde: '\u00D5',
Ouml: '\u00D6',
times: '\u00D7',
Oslash: '\u00D8',
Ugrave: '\u00D9',
Uacute: '\u00DA',
Ucirc: '\u00DB',
Uuml: '\u00DC',
Yacute: '\u00DD',
THORN: '\u00DE',
szlig: '\u00DF',
agrave: '\u00E0',
aacute: '\u00E1',
acirc: '\u00E2',
atilde: '\u00E3',
auml: '\u00E4',
aring: '\u00E5',
aelig: '\u00E6',
ccedil: '\u00E7',
egrave: '\u00E8',
eacute: '\u00E9',
ecirc: '\u00EA',
euml: '\u00EB',
igrave: '\u00EC',
iacute: '\u00ED',
icirc: '\u00EE',
iuml: '\u00EF',
eth: '\u00F0',
ntilde: '\u00F1',
ograve: '\u00F2',
oacute: '\u00F3',
ocirc: '\u00F4',
otilde: '\u00F5',
ouml: '\u00F6',
divide: '\u00F7',
oslash: '\u00F8',
ugrave: '\u00F9',
uacute: '\u00FA',
ucirc: '\u00FB',
uuml: '\u00FC',
yacute: '\u00FD',
thorn: '\u00FE',
yuml: '\u00FF',
OElig: '\u0152',
oelig: '\u0153',
Scaron: '\u0160',
scaron: '\u0161',
Yuml: '\u0178',
fnof: '\u0192',
circ: '\u02C6',
tilde: '\u02DC',
Alpha: '\u0391',
Beta: '\u0392',
Gamma: '\u0393',
Delta: '\u0394',
Epsilon: '\u0395',
Zeta: '\u0396',
Eta: '\u0397',
Theta: '\u0398',
Iota: '\u0399',
Kappa: '\u039A',
Lambda: '\u039B',
Mu: '\u039C',
Nu: '\u039D',
Xi: '\u039E',
Omicron: '\u039F',
Pi: '\u03A0',
Rho: '\u03A1',
Sigma: '\u03A3',
Tau: '\u03A4',
Upsilon: '\u03A5',
Phi: '\u03A6',
Chi: '\u03A7',
Psi: '\u03A8',
Omega: '\u03A9',
alpha: '\u03B1',
beta: '\u03B2',
gamma: '\u03B3',
delta: '\u03B4',
epsilon: '\u03B5',
zeta: '\u03B6',
eta: '\u03B7',
theta: '\u03B8',
iota: '\u03B9',
kappa: '\u03BA',
lambda: '\u03BB',
mu: '\u03BC',
nu: '\u03BD',
xi: '\u03BE',
omicron: '\u03BF',
pi: '\u03C0',
rho: '\u03C1',
sigmaf: '\u03C2',
sigma: '\u03C3',
tau: '\u03C4',
upsilon: '\u03C5',
phi: '\u03C6',
chi: '\u03C7',
psi: '\u03C8',
omega: '\u03C9',
thetasym: '\u03D1',
upsih: '\u03D2',
piv: '\u03D6',
ensp: '\u2002',
emsp: '\u2003',
thinsp: '\u2009',
zwnj: '\u200C',
zwj: '\u200D',
lrm: '\u200E',
rlm: '\u200F',
ndash: '\u2013',
mdash: '\u2014',
lsquo: '\u2018',
rsquo: '\u2019',
sbquo: '\u201A',
ldquo: '\u201C',
rdquo: '\u201D',
bdquo: '\u201E',
dagger: '\u2020',
Dagger: '\u2021',
bull: '\u2022',
hellip: '\u2026',
permil: '\u2030',
prime: '\u2032',
Prime: '\u2033',
lsaquo: '\u2039',
rsaquo: '\u203A',
oline: '\u203E',
frasl: '\u2044',
euro: '\u20AC',
image: '\u2111',
weierp: '\u2118',
real: '\u211C',
trade: '\u2122',
alefsym: '\u2135',
larr: '\u2190',
uarr: '\u2191',
rarr: '\u2192',
darr: '\u2193',
harr: '\u2194',
crarr: '\u21B5',
lArr: '\u21D0',
uArr: '\u21D1',
rArr: '\u21D2',
dArr: '\u21D3',
hArr: '\u21D4',
forall: '\u2200',
part: '\u2202',
exist: '\u2203',
empty: '\u2205',
nabla: '\u2207',
isin: '\u2208',
notin: '\u2209',
ni: '\u220B',
prod: '\u220F',
sum: '\u2211',
minus: '\u2212',
lowast: '\u2217',
radic: '\u221A',
prop: '\u221D',
infin: '\u221E',
ang: '\u2220',
and: '\u2227',
or: '\u2228',
cap: '\u2229',
cup: '\u222A',
'int': '\u222B',
there4: '\u2234',
sim: '\u223C',
cong: '\u2245',
asymp: '\u2248',
ne: '\u2260',
equiv: '\u2261',
le: '\u2264',
ge: '\u2265',
sub: '\u2282',
sup: '\u2283',
nsub: '\u2284',
sube: '\u2286',
supe: '\u2287',
oplus: '\u2295',
otimes: '\u2297',
perp: '\u22A5',
sdot: '\u22C5',
lceil: '\u2308',
rceil: '\u2309',
lfloor: '\u230A',
rfloor: '\u230B',
lang: '\u2329',
rang: '\u232A',
loz: '\u25CA',
spades: '\u2660',
clubs: '\u2663',
hearts: '\u2665',
diams: '\u2666'
};
var hexNumber = /^[\da-fA-F]+$/;
var decimalNumber = /^\d+$/;
pp.jsx_readEntity = function() {
var str = "", count = 0, entity;
var ch = this.input[this.pos];
if (ch !== "&")
this.raise(this.pos, "Entity must start with an ampersand");
var startPos = ++this.pos;
while (this.pos < this.input.length && count++ < 10) {
ch = this.input[this.pos++];
if (ch === ";") {
if (str[0] === "#") {
if (str[1] === "x") {
str = str.substr(2);
if (hexNumber.test(str))
entity = String.fromCharCode(parseInt(str, 16));
} else {
str = str.substr(1);
if (decimalNumber.test(str))
entity = String.fromCharCode(parseInt(str, 10));
}
} else {
entity = XHTMLEntities[str];
}
break;
}
str += ch;
}
if (!entity) {
this.pos = startPos;
return "&";
}
return entity;
};
// Read a JSX identifier (valid tag or attribute name).
//
// Optimized version since JSX identifiers can't contain
// escape characters and so can be read as single slice.
// Also assumes that first character was already checked
// by isIdentifierStart in readToken.
pp.jsx_readWord = function() {
var ch, start = this.pos;
do {
ch = this.input.charCodeAt(++this.pos);
} while (acorn.isIdentifierChar(ch) || ch === 45); // '-'
return this.finishToken(tt.jsxName, this.input.slice(start, this.pos));
};
// Transforms JSX element name to string.
function getQualifiedJSXName(object) {
if (object.type === "JSXIdentifier")
return object.name;
if (object.type === "JSXNamespacedName")
return object.namespace.name + ':' + object.name.name;
if (object.type === "JSXMemberExpression")
return getQualifiedJSXName(object.object) + '.' +
getQualifiedJSXName(object.property);
}
// Parse next token as JSX identifier
pp.jsx_parseIdentifier = function() {
var node = this.startNode();
if (this.type === tt.jsxName)
node.name = this.value;
else if (this.type.keyword)
node.name = this.type.keyword;
else
this.unexpected();
this.next();
return this.finishNode(node, "JSXIdentifier");
};
// Parse namespaced identifier.
pp.jsx_parseNamespacedName = function() {
var start = this.markPosition();
var name = this.jsx_parseIdentifier();
if (!this.eat(tt.colon)) return name;
var node = this.startNodeAt(start);
node.namespace = name;
node.name = this.jsx_parseIdentifier();
return this.finishNode(node, "JSXNamespacedName");
};
// Parses element name in any form - namespaced, member
// or single identifier.
pp.jsx_parseElementName = function() {
var start = this.markPosition();
var node = this.jsx_parseNamespacedName();
while (this.eat(tt.dot)) {
var newNode = this.startNodeAt(start);
newNode.object = node;
newNode.property = this.jsx_parseIdentifier();
node = this.finishNode(newNode, "JSXMemberExpression");
}
return node;
};
// Parses any type of JSX attribute value.
pp.jsx_parseAttributeValue = function() {
switch (this.type) {
case tt.braceL:
var node = this.jsx_parseExpressionContainer();
if (node.expression.type === "JSXEmptyExpression")
this.raise(node.start, "JSX attributes must only be assigned a non-empty expression");
return node;
case tt.jsxTagStart:
case tt.string:
return this.parseExprAtom();
default:
this.raise(this.start, "JSX value should be either an expression or a quoted JSX text");
}
};
// JSXEmptyExpression is unique type since it doesn't actually parse anything,
// and so it should start at the end of last read token (left brace) and finish
// at the beginning of the next one (right brace).
pp.jsx_parseEmptyExpression = function() {
var tmp = this.start;
this.start = this.lastTokEnd;
this.lastTokEnd = tmp;
tmp = this.startLoc;
this.startLoc = this.lastTokEndLoc;
this.lastTokEndLoc = tmp;
return this.finishNode(this.startNode(), "JSXEmptyExpression");
};
// Parses JSX expression enclosed into curly brackets.
pp.jsx_parseExpressionContainer = function() {
var node = this.startNode();
this.next();
node.expression = this.type === tt.braceR
? this.jsx_parseEmptyExpression()
: this.parseExpression();
this.expect(tt.braceR);
return this.finishNode(node, "JSXExpressionContainer");
};
// Parses following JSX attribute name-value pair.
pp.jsx_parseAttribute = function() {
var node = this.startNode();
if (this.eat(tt.braceL)) {
this.expect(tt.ellipsis);
node.argument = this.parseMaybeAssign();
this.expect(tt.braceR);
return this.finishNode(node, "JSXSpreadAttribute");
}
node.name = this.jsx_parseNamespacedName();
node.value = this.eat(tt.eq) ? this.jsx_parseAttributeValue() : null;
return this.finishNode(node, "JSXAttribute");
};
// Parses JSX opening tag starting after '<'.
pp.jsx_parseOpeningElementAt = function(start) {
var node = this.startNodeAt(start);
node.attributes = [];
node.name = this.jsx_parseElementName();
while (this.type !== tt.slash && this.type !== tt.jsxTagEnd)
node.attributes.push(this.jsx_parseAttribute());
node.selfClosing = this.eat(tt.slash);
this.expect(tt.jsxTagEnd);
return this.finishNode(node, "JSXOpeningElement");
};
// Parses JSX closing tag starting after '</'.
pp.jsx_parseClosingElementAt = function(start) {
var node = this.startNodeAt(start);
node.name = this.jsx_parseElementName();
this.expect(tt.jsxTagEnd);
return this.finishNode(node, "JSXClosingElement");
};
// Parses entire JSX element, including it's opening tag
// (starting after '<'), attributes, contents and closing tag.
pp.jsx_parseElementAt = function(start) {
var node = this.startNodeAt(start);
var children = [];
var openingElement = this.jsx_parseOpeningElementAt(start);
var closingElement = null;
if (!openingElement.selfClosing) {
contents: for (;;) {
switch (this.type) {
case tt.jsxTagStart:
start = this.markPosition();
this.next();
if (this.eat(tt.slash)) {
closingElement = this.jsx_parseClosingElementAt(start);
break contents;
}
children.push(this.jsx_parseElementAt(start));
break;
case tt.jsxText:
children.push(this.parseExprAtom());
break;
case tt.braceL:
children.push(this.jsx_parseExpressionContainer());
break;
default:
this.unexpected();
}
}
if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name))
this.raise(
closingElement.start,
"Expected corresponding JSX closing tag for <" + getQualifiedJSXName(openingElement.name) + ">");
}
node.openingElement = openingElement;
node.closingElement = closingElement;
node.children = children;
return this.finishNode(node, "JSXElement");
};
// Parses entire JSX element from current position.
pp.jsx_parseElement = function() {
var start = this.markPosition();
this.next();
return this.jsx_parseElementAt(start);
};
acorn.plugins.jsx = function(instance) {
instance.extend("parseExprAtom", function(inner) {
return function(refShortHandDefaultPos) {
if (this.type === tt.jsxText)
return this.parseLiteral(this.value);
else if (this.type === tt.jsxTagStart)
return this.jsx_parseElement();
else
return inner.call(this, refShortHandDefaultPos);
};
});
instance.extend("readToken", function(inner) {
return function(code) {
var context = this.curContext();
if (context === tc.j_expr) return this.jsx_readToken();
if (context === tc.j_oTag || context === tc.j_cTag) {
if (acorn.isIdentifierStart(code)) return this.jsx_readWord();
if (code == 62) {
++this.pos;
return this.finishToken(tt.jsxTagEnd);
}
if ((code === 34 || code === 39) && context == tc.j_oTag)
return this.jsx_readString(code);
}
if (code === 60 && this.exprAllowed) {
++this.pos;
return this.finishToken(tt.jsxTagStart);
}
return inner.call(this, code);
};
});
instance.extend("updateContext", function(inner) {
return function(prevType) {
if (this.type == tt.braceL) {
var curContext = this.curContext();
if (curContext == tc.j_oTag) this.context.push(tc.b_expr);
else if (curContext == tc.j_expr) this.context.push(tc.b_tmpl);
else inner.call(this, prevType);
this.exprAllowed = true;
} else if (this.type === tt.slash && prevType === tt.jsxTagStart) {
this.context.length -= 2; // do not consider JSX expr -> JSX open tag -> ... anymore
this.context.push(tc.j_cTag); // reconsider as closing tag context
this.exprAllowed = false;
} else {
return inner.call(this, prevType);
}
};
});
}

View File

@@ -29,14 +29,23 @@ const pp = Parser.prototype
// strict mode, init properties are also not allowed to be repeated.
pp.checkPropClash = function(prop, propHash) {
if (this.options.ecmaVersion >= 6) return
if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
return
let key = prop.key, name
switch (key.type) {
case "Identifier": name = key.name; break
case "Literal": name = String(key.value); break
default: return
}
let kind = prop.kind || "init", other
let kind = prop.kind
if (this.options.ecmaVersion >= 6) {
if (name === "__proto__" && kind === "init") {
if (propHash.proto) this.raise(key.start, "Redefinition of __proto__ property");
propHash.proto = true
}
return
}
let other
if (has(propHash, name)) {
other = propHash[name]
let isGetSet = kind !== "init"
@@ -104,10 +113,14 @@ pp.parseMaybeAssign = function(noIn, refShorthandDefaultPos, afterLeftParse) {
refShorthandDefaultPos.start = 0 // reset because shorthand default was used correctly
this.checkLVal(left)
if (left.parenthesizedExpression) {
let errorMsg
if (left.type === "ObjectPattern") {
this.raise(left.start, "You're trying to assign to a parenthesized expression, instead of `({ foo }) = {}` use `({ foo } = {})`");
} else {
this.raise(left.start, "Parenthesized left hand expressions are illegal");
errorMsg = "`({a}) = 0` use `({a} = 0)`"
} else if (left.type === "ArrayPattern") {
errorMsg = "`([a]) = 0` use `([a] = 0)`"
}
if (errorMsg) {
this.raise(left.start, `You're trying to assign to a parenthesized expression, eg. instead of ${errorMsg}`)
}
}
this.next()
@@ -210,7 +223,12 @@ pp.parseExprSubscripts = function(refShorthandDefaultPos) {
}
pp.parseSubscripts = function(base, start, noCalls) {
if (this.eat(tt.dot)) {
if (!noCalls && this.eat(tt.doubleColon)) {
let node = this.startNodeAt(start)
node.object = base
node.callee = this.parseNoCallExpr()
return this.parseSubscripts(this.finishNode(node, "BindExpression"), start, noCalls)
} else if (this.eat(tt.dot)) {
let node = this.startNodeAt(start)
node.object = base
node.property = this.parseIdent(true)
@@ -236,6 +254,13 @@ pp.parseSubscripts = function(base, start, noCalls) {
} return base
}
// Parse a no-call expression (like argument of `new` or `::` operators).
pp.parseNoCallExpr = function() {
let start = this.markPosition()
return this.parseSubscripts(this.parseExprAtom(), start, true)
}
// Parse an atomic expression — either a single token that is an
// expression, an expression started by a keyword like `function` or
// `new`, or an expression wrapped in punctuation like `()`, `[]`,
@@ -244,8 +269,10 @@ pp.parseSubscripts = function(base, start, noCalls) {
pp.parseExprAtom = function(refShorthandDefaultPos) {
let node, canBeArrow = this.potentialArrowAt == this.start
switch (this.type) {
case tt._this:
case tt._super:
if (!this.inFunction)
this.raise(this.start, "'super' outside of function or class")
case tt._this:
let type = this.type === tt._this ? "ThisExpression" : "Super"
node = this.startNode()
this.next()
@@ -258,7 +285,13 @@ pp.parseExprAtom = function(refShorthandDefaultPos) {
if (this.options.features["es7.doExpressions"]) {
let node = this.startNode()
this.next()
var oldInFunction = this.inFunction
var oldLabels = this.labels
this.labels = []
this.inFunction = false
node.body = this.parseBlock()
this.inFunction = oldInFunction
this.labels = oldLabels
return this.finishNode(node, "DoExpression")
}
@@ -270,7 +303,7 @@ pp.parseExprAtom = function(refShorthandDefaultPos) {
//
if (this.options.features["es7.asyncFunctions"]) {
// async functions!
if (id.name === "async") {
if (id.name === "async" && !this.canInsertSemicolon()) {
// arrow functions
if (this.type === tt.parenL) {
let expr = this.parseParenAndDistinguishExpression(start, true, true)
@@ -359,6 +392,15 @@ pp.parseExprAtom = function(refShorthandDefaultPos) {
case tt.backQuote:
return this.parseTemplate()
case tt.doubleColon:
node = this.startNode()
this.next()
node.object = null
let callee = node.callee = this.parseNoCallExpr()
if (callee.type !== "MemberExpression")
this.raise(callee.start, "Binding should be performed on object property.")
return this.finishNode(node, "BindExpression")
default:
this.unexpected()
}
@@ -390,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
@@ -420,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)
@@ -468,9 +520,11 @@ pp.parseNew = function() {
this.raise(node.property.start, "The only valid meta property for new is new.target")
return this.finishNode(node, "MetaProperty")
}
let start = this.markPosition()
node.callee = this.parseSubscripts(this.parseExprAtom(), start, true)
if (this.eat(tt.parenL)) node.arguments = this.parseExprList(tt.parenR, false)
node.callee = this.parseNoCallExpr()
if (this.eat(tt.parenL)) node.arguments = this.parseExprList(
tt.parenR,
this.options.features["es7.trailingFunctionCommas"]
)
else node.arguments = empty
return this.finishNode(node, "NewExpression")
}
@@ -480,7 +534,7 @@ pp.parseNew = function() {
pp.parseTemplateElement = function() {
let elem = this.startNode()
elem.value = {
raw: this.input.slice(this.start, this.end),
raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, '\n'),
cooked: this.value
}
this.next()
@@ -509,22 +563,24 @@ pp.parseTemplate = function() {
pp.parseObj = function(isPattern, refShorthandDefaultPos) {
let node = this.startNode(), first = true, propHash = {}
node.properties = []
let decorators = []
this.next()
while (!this.eat(tt.braceR)) {
if (!first) {
this.expect(tt.comma)
if (this.afterTrailingComma(tt.braceR)) break
} else first = false
while (this.type === tt.at) {
this.decorators.push(this.parseDecorator())
decorators.push(this.parseDecorator())
}
let prop = this.startNode(), isGenerator = false, isAsync = false, start
if (decorators.length) {
prop.decorators = decorators
decorators = []
}
if (this.options.features["es7.objectRestSpread"] && this.type === tt.ellipsis) {
prop = this.parseSpread()
prop.type = "SpreadProperty"
this.takeDecorators(prop)
node.properties.push(prop)
continue
}
@@ -550,10 +606,9 @@ pp.parseObj = function(isPattern, refShorthandDefaultPos) {
}
this.parseObjPropValue(prop, start, isGenerator, isAsync, isPattern, refShorthandDefaultPos);
this.checkPropClash(prop, propHash)
this.takeDecorators(prop)
node.properties.push(this.finishNode(prop, "Property"))
}
if (this.decorators.length) {
if (decorators.length) {
this.raise(this.start, "You have trailing decorators with no property");
}
return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
@@ -575,6 +630,14 @@ pp.parseObjPropValue = function (prop, start, isGenerator, isAsync, isPattern, r
prop.kind = prop.key.name
this.parsePropertyName(prop)
prop.value = this.parseMethod(false)
let paramCount = prop.kind === "get" ? 0 : 1
if (prop.value.params.length !== paramCount) {
let start = prop.value.start
if (prop.kind === "get")
this.raise(start, "getter should have no params");
else
this.raise(start, "setter should have exactly one param")
}
} else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
prop.kind = "init"
if (isPattern) {
@@ -600,12 +663,12 @@ pp.parsePropertyName = function(prop) {
prop.computed = true
prop.key = this.parseMaybeAssign()
this.expect(tt.bracketR)
return
return prop.key
} else {
prop.computed = false
}
}
prop.key = (this.type === tt.num || this.type === tt.string) ? this.parseExprAtom() : this.parseIdent(true)
return prop.key = (this.type === tt.num || this.type === tt.string) ? this.parseExprAtom() : this.parseIdent(true)
}
// Initialize empty function node.
@@ -627,7 +690,7 @@ pp.parseMethod = function(isGenerator, isAsync) {
let node = this.startNode()
this.initFunction(node, isAsync)
this.expect(tt.parenL)
node.params = this.parseBindingList(tt.parenR, false, false)
node.params = this.parseBindingList(tt.parenR, false, this.options.features["es7.trailingFunctionCommas"])
if (this.options.ecmaVersion >= 6) {
node.generator = isGenerator
}

View File

@@ -9,41 +9,9 @@
function makePredicate(words) {
words = words.split(" ")
let f = "", cats = []
out: for (let i = 0; i < words.length; ++i) {
for (let j = 0; j < cats.length; ++j)
if (cats[j][0].length == words[i].length) {
cats[j].push(words[i])
continue out
}
cats.push([words[i]])
return function(str) {
return words.indexOf(str) >= 0
}
function compareTo(arr) {
if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";"
f += "switch(str){"
for (let i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":"
f += "return true}return false;"
}
// When there are more than three length categories, an outer
// switch first dispatches on the lengths, to save on comparisons.
if (cats.length > 3) {
cats.sort((a, b) => b.length - a.length)
f += "switch(str.length){"
for (let i = 0; i < cats.length; ++i) {
let cat = cats[i]
f += "case " + cat[0].length + ":"
compareTo(cat)
}
f += "}"
// Otherwise, simply generate a flat `switch` statement.
} else {
compareTo(words)
}
return new Function("str", f)
}
// Reserved word lists for various dialects of the language

View File

@@ -38,9 +38,6 @@ export {isIdentifierChar, isIdentifierStart} from "./identifier"
export {Token} from "./tokenize"
export {isNewLine, lineBreak, lineBreakG} from "./whitespace"
import "../plugins/flow";
import "../plugins/jsx";
export const version = "1.0.0"
// The main exported interface (under `self.acorn` when in the

View File

@@ -9,12 +9,21 @@ var STATE_KEYS = [
"lastTokEnd",
"lineStart",
"startLoc",
"curLine",
"endLoc",
"start",
"pos",
"end",
"type",
"value"
"value",
"exprAllowed",
"potentialArrowAt",
"currLine",
"input",
"inType",
"inFunction",
"inGenerator",
"labels"
];
pp.getState = function () {
@@ -23,6 +32,8 @@ pp.getState = function () {
var key = STATE_KEYS[i]
state[key] = this[key]
}
state.context = this.context.slice()
state.labels = this.labels.slice()
return state
};

View File

@@ -21,6 +21,7 @@ pp.toAssignable = function(node, isBinding) {
node.type = "ObjectPattern"
for (let i = 0; i < node.properties.length; i++) {
let prop = node.properties[i]
if (prop.type === "SpreadProperty") continue;
if (prop.kind !== "init") this.raise(prop.key.start, "Object pattern can't contain getter or setter")
this.toAssignable(prop.value, isBinding)
}
@@ -34,6 +35,7 @@ pp.toAssignable = function(node, isBinding) {
case "AssignmentExpression":
if (node.operator === "=") {
node.type = "AssignmentPattern"
delete node.operator
} else {
this.raise(node.left.end, "Only '=' operator can be used for specifying default value.")
}
@@ -170,7 +172,7 @@ pp.checkLVal = function(expr, isBinding, checkClashes) {
break
case "ObjectPattern":
for (let i = 0; i < expr.properties.length; i++) {
for (let i = 0; i < expr.properties.length; i++) {
var prop = expr.properties[i];
if (prop.type === "Property") prop = prop.value;
this.checkLVal(prop, isBinding, checkClashes)
@@ -193,6 +195,10 @@ pp.checkLVal = function(expr, isBinding, checkClashes) {
this.checkLVal(expr.argument, isBinding, checkClashes)
break
case "ParenthesizedExpression":
this.checkLVal(expr.expression, isBinding, checkClashes)
break
default:
this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " rvalue")
}

View File

@@ -1,4 +1,4 @@
import {has, isArray} from "./util"
import {has} from "./util"
import {SourceLocation} from "./location"
// A second optional argument can be given to further configure
@@ -94,11 +94,11 @@ export function getOptions(opts) {
for (let opt in defaultOptions)
options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]
if (isArray(options.onToken)) {
if (Array.isArray(options.onToken)) {
let tokens = options.onToken
options.onToken = (token) => tokens.push(token)
}
if (isArray(options.onComment))
if (Array.isArray(options.onComment))
options.onComment = pushComment(options, options.onComment)
return options

View File

@@ -1,13 +1,14 @@
import {reservedWords, keywords} from "./identifier"
import {types as tt, lineBreak} from "./tokentype"
import {types as tt} from "./tokentype"
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

@@ -83,10 +83,13 @@ pp.parseStatement = function(declaration, topLevel) {
return starttype === tt._import ? this.parseImport(node) : this.parseExport(node)
case tt.name:
if (this.options.features["es7.asyncFunctions"] && this.value === "async" && this.lookahead().type === tt._function) {
this.next();
this.expect(tt._function);
return this.parseFunction(node, true, false, true);
if (this.options.features["es7.asyncFunctions"] && this.value === "async") {
var lookahead = this.lookahead();
if (lookahead.type === tt._function && !this.canInsertSemicolon.call(lookahead)) {
this.next();
this.expect(tt._function);
return this.parseFunction(node, true, false, true);
}
}
// If the statement does not start with a statement keyword or a
@@ -168,12 +171,6 @@ pp.parseDoStatement = function(node) {
this.labels.push(loopLabel)
node.body = this.parseStatement(false)
this.labels.pop()
if (this.options.features["es7.doExpressions"] && this.type !== tt._while) {
let container = this.startNodeAt(start)
container.expression = this.finishNode(node, "DoExpression")
this.semicolon()
return this.finishNode(container, "ExpressionStatement")
}
this.expect(tt._while)
node.test = this.parseParenExpression()
if (this.options.ecmaVersion >= 6)
@@ -350,7 +347,14 @@ pp.parseLabeledStatement = function(node, maybeName, expr) {
for (let i = 0; i < this.labels.length; ++i)
if (this.labels[i].name === maybeName) this.raise(expr.start, "Label '" + maybeName + "' is already declared")
let kind = this.type.isLoop ? "loop" : this.type === tt._switch ? "switch" : null
this.labels.push({name: maybeName, kind: kind})
for (let i = this.labels.length - 1; i >= 0; i--) {
let label = this.labels[i]
if (label.statementStart == node.start) {
label.statementStart = this.start;
label.kind = kind;
} else break;
}
this.labels.push({name: maybeName, kind: kind, statementStart: this.start})
node.body = this.parseStatement(true)
this.labels.pop()
node.label = expr
@@ -469,26 +473,29 @@ pp.parseClass = function(node, isStatement) {
this.parseClassId(node, isStatement)
this.parseClassSuper(node)
var classBody = this.startNode()
let hadConstructor = false
classBody.body = []
this.expect(tt.braceL)
let decorators = []
while (!this.eat(tt.braceR)) {
if (this.eat(tt.semi)) continue
if (this.type === tt.at) {
this.decorators.push(this.parseDecorator())
decorators.push(this.parseDecorator())
continue
}
var method = this.startNode()
this.takeDecorators(method)
if (decorators.length) {
method.decorators = decorators
decorators = []
}
let isMaybeStatic = this.type === tt.name && this.value === "static"
var isGenerator = this.eat(tt.star), isAsync = false
this.parsePropertyName(method)
if (this.type !== tt.parenL && !method.computed && method.key.type === "Identifier" &&
method.key.name === "static") {
method.static = isMaybeStatic && this.type !== tt.parenL
if (method.static) {
if (isGenerator) this.unexpected()
method['static'] = true
isGenerator = this.eat(tt.star)
this.parsePropertyName(method)
} else {
method['static'] = false
}
if (!isGenerator && method.key.type === "Identifier" && !method.computed && this.isClassProperty()) {
classBody.body.push(this.parseClassProperty(method))
@@ -499,25 +506,41 @@ pp.parseClass = function(node, isStatement) {
isAsync = true
this.parsePropertyName(method)
}
let isGetSet = false
method.kind = "method"
if (!method.computed && !isGenerator) {
if (method.key.type === "Identifier") {
if (this.type !== tt.parenL && (method.key.name === "get" || method.key.name === "set")) {
method.kind = method.key.name
this.parsePropertyName(method)
} else if (!method['static'] && method.key.name === "constructor") {
method.kind = "constructor"
}
} else if (!method['static'] && method.key.type === "Literal" && method.key.value === "constructor") {
if (!method.computed) {
let {key} = method
if (!isAsync && !isGenerator && key.type === "Identifier" && this.type !== tt.parenL && (key.name === "get" || key.name === "set")) {
isGetSet = true
method.kind = key.name
key = this.parsePropertyName(method)
}
if (!method.static && (key.type === "Identifier" && key.name === "constructor" ||
key.type === "Literal" && key.value === "constructor")) {
if (hadConstructor) this.raise(key.start, "Duplicate constructor in the same class")
if (isGetSet) this.raise(key.start, "Constructor can't have get/set modifier")
if (isGenerator) this.raise(key.start, "Constructor can't be a generator")
if (isAsync) this.raise(key.start, "Constructor can't be an async function")
method.kind = "constructor"
hadConstructor = true
}
}
if (method.kind === "constructor" && method.decorators) {
this.raise(method.start, "You can't attach decorators to a class constructor")
}
this.parseClassMethod(classBody, method, isGenerator, isAsync)
if (isGetSet) {
let paramCount = method.kind === "get" ? 0 : 1
if (method.value.params.length !== paramCount) {
let start = method.value.start
if (method.kind === "get")
this.raise(start, "getter should have no params");
else
this.raise(start, "setter should have exactly one param")
}
}
}
if (this.decorators.length) {
if (decorators.length) {
this.raise(this.start, "You have trailing decorators with no method");
}
node.body = this.finishNode(classBody, "ClassBody")
@@ -570,7 +593,7 @@ pp.parseExport = function(node) {
this.parseExportFrom(node)
return this.finishNode(node, "ExportAllDeclaration")
}
} else if (this.isExportDefaultSpecifier()) {
} else if (this.options.features["es7.exportExtensions"] && this.isExportDefaultSpecifier()) {
let specifier = this.startNode()
specifier.exported = this.parseIdent(true)
node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]
@@ -687,7 +710,6 @@ pp.parseImport = function(node) {
if (this.type === tt.string) {
node.specifiers = empty
node.source = this.parseExprAtom()
node.kind = ""
} else {
node.specifiers = []
this.parseImportSpecifiers(node)

View File

@@ -25,6 +25,9 @@ export class Token {
const pp = Parser.prototype
// Are we running under Rhino?
const isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]"
// Move to the next token
pp.next = function() {
@@ -283,7 +286,7 @@ pp.readToken_lt_gt = function(code) { // '<>'
}
if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 &&
this.input.charCodeAt(this.pos + 3) == 45) {
if (this.inModule) unexpected()
if (this.inModule) this.unexpected()
// `<!--`, an XML-style comment that should be interpreted as a line comment
this.skipLineComment(4)
this.skipSpace()
@@ -320,7 +323,13 @@ pp.getTokenFromCode = function(code) {
case 93: ++this.pos; return this.finishToken(tt.bracketR)
case 123: ++this.pos; return this.finishToken(tt.braceL)
case 125: ++this.pos; return this.finishToken(tt.braceR)
case 58: ++this.pos; return this.finishToken(tt.colon)
case 58:
if (this.options.features["es7.functionBind"] && this.input.charCodeAt(this.pos + 1) === 58)
return this.finishOp(tt.doubleColon, 2)
++this.pos
return this.finishToken(tt.colon)
case 63: ++this.pos; return this.finishToken(tt.question)
case 64: ++this.pos; return this.finishToken(tt.at)
@@ -424,23 +433,30 @@ pp.readRegexp = function() {
// negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
// perfectly valid pattern that is equivalent to `[a-b]`, but it would
// be replaced by `[x-b]` which throws an error.
tmp = tmp.replace(/\\u([a-fA-F0-9]{4})|\\u\{([0-9a-fA-F]+)\}|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x")
tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, (match, code, offset) => {
code = Number("0x" + code)
if (code > 0x10FFFF) this.raise(start + offset + 3, "Code point out of bounds")
return "x"
});
tmp = tmp.replace(/\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x")
}
}
// Detect invalid regular expressions.
try {
new RegExp(tmp)
} catch (e) {
if (e instanceof SyntaxError) this.raise(start, "Error parsing regular expression: " + e.message)
this.raise(e)
}
// Get a regular expression object for this pattern-flag pair, or `null` in
// case the current environment doesn't support the flags it uses.
let value
try {
value = new RegExp(content, mods)
} catch (err) {
value = null
let value = null
// Rhino's regular expression parser is flaky and throws uncatchable exceptions,
// so don't do detection if we are running under Rhino
if (!isRhino) {
try {
new RegExp(tmp)
} catch (e) {
if (e instanceof SyntaxError) this.raise(start, "Error parsing regular expression: " + e.message)
this.raise(e)
}
// Get a regular expression object for this pattern-flag pair, or `null` in
// case the current environment doesn't support the flags it uses.
try {
value = new RegExp(content, mods)
} catch (err) {}
}
return this.finishToken(tt.regexp, {pattern: content, flags: mods, value: value})
}
@@ -508,10 +524,10 @@ pp.readCodePoint = function() {
if (ch === 123) {
if (this.options.ecmaVersion < 6) this.unexpected()
++this.pos
let codePos = ++this.pos
code = this.readHexChar(this.input.indexOf('}', this.pos) - this.pos)
++this.pos
if (code > 0x10FFFF) this.unexpected()
if (code > 0x10FFFF) this.raise(codePos, "Code point out of bounds")
} else {
code = this.readHexChar(4)
}
@@ -533,7 +549,7 @@ pp.readString = function(quote) {
if (ch === quote) break
if (ch === 92) { // '\'
out += this.input.slice(chunkStart, this.pos)
out += this.readEscapedChar()
out += this.readEscapedChar(false)
chunkStart = this.pos
} else {
if (isNewLine(ch)) this.raise(this.start, "Unterminated string constant")
@@ -566,16 +582,20 @@ pp.readTmplToken = function() {
}
if (ch === 92) { // '\'
out += this.input.slice(chunkStart, this.pos)
out += this.readEscapedChar()
out += this.readEscapedChar(true)
chunkStart = this.pos
} else if (isNewLine(ch)) {
out += this.input.slice(chunkStart, this.pos)
++this.pos
if (ch === 13 && this.input.charCodeAt(this.pos) === 10) {
++this.pos
out += "\n"
} else {
out += String.fromCharCode(ch)
switch (ch) {
case 13:
if (this.input.charCodeAt(this.pos) === 10) ++this.pos;
case 10:
out += "\n";
break;
default:
out += String.fromCharCode(ch);
break;
}
if (this.options.locations) {
++this.curLine
@@ -590,42 +610,46 @@ pp.readTmplToken = function() {
// Used to read escaped characters
pp.readEscapedChar = function() {
pp.readEscapedChar = function(inTemplate) {
let ch = this.input.charCodeAt(++this.pos)
let octal = /^[0-7]+/.exec(this.input.slice(this.pos, this.pos + 3))
if (octal) octal = octal[0]
while (octal && parseInt(octal, 8) > 255) octal = octal.slice(0, -1)
if (octal === "0") octal = null
++this.pos
if (octal) {
if (this.strict) this.raise(this.pos - 2, "Octal literal in strict mode")
this.pos += octal.length - 1
return String.fromCharCode(parseInt(octal, 8))
} else {
switch (ch) {
case 110: return "\n"; // 'n' -> '\n'
case 114: return "\r"; // 'r' -> '\r'
case 120: return String.fromCharCode(this.readHexChar(2)); // 'x'
case 117: return codePointToString(this.readCodePoint()); // 'u'
case 116: return "\t"; // 't' -> '\t'
case 98: return "\b"; // 'b' -> '\b'
case 118: return "\u000b"; // 'v' -> '\u000b'
case 102: return "\f"; // 'f' -> '\f'
case 48: return "\0"; // 0 -> '\0'
case 13: if (this.input.charCodeAt(this.pos) === 10) ++this.pos; // '\r\n'
case 10: // ' \n'
if (this.options.locations) { this.lineStart = this.pos; ++this.curLine }
return ""
default: return String.fromCharCode(ch)
switch (ch) {
case 110: return "\n"; // 'n' -> '\n'
case 114: return "\r"; // 'r' -> '\r'
case 120: return String.fromCharCode(this.readHexChar(2)); // 'x'
case 117: return codePointToString(this.readCodePoint()); // 'u'
case 116: return "\t"; // 't' -> '\t'
case 98: return "\b"; // 'b' -> '\b'
case 118: return "\u000b"; // 'v' -> '\u000b'
case 102: return "\f"; // 'f' -> '\f'
case 13: if (this.input.charCodeAt(this.pos) === 10) ++this.pos; // '\r\n'
case 10: // ' \n'
if (this.options.locations) { this.lineStart = this.pos; ++this.curLine }
return ""
default:
if (ch >= 48 && ch <= 55) {
let octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0]
let octal = parseInt(octalStr, 8)
if (octal > 255) {
octalStr = octalStr.slice(0, -1)
octal = parseInt(octalStr, 8)
}
if (octal > 0 && (this.strict || inTemplate)) {
this.raise(this.pos - 2, "Octal literal in strict mode")
}
this.pos += octalStr.length - 1
return String.fromCharCode(octal)
}
return String.fromCharCode(ch)
}
}
// Used to read character escape sequences ('\x', '\u', '\U').
pp.readHexChar = function(len) {
let codePos = this.pos
let n = this.readInt(16, len)
if (n === null) this.raise(this.start, "Bad character escape sequence")
if (n === null) this.raise(codePos, "Bad character escape sequence")
return n
}

View File

@@ -54,6 +54,7 @@ export const types = {
comma: new TokenType(",", beforeExpr),
semi: new TokenType(";", beforeExpr),
colon: new TokenType(":", beforeExpr),
doubleColon: new TokenType("::", beforeExpr),
dot: new TokenType("."),
question: new TokenType("?", beforeExpr),
arrow: new TokenType("=>", beforeExpr),
@@ -111,12 +112,12 @@ kw("case", beforeExpr)
kw("catch")
kw("continue")
kw("debugger")
kw("default")
kw("default", beforeExpr)
kw("do", {isLoop: true})
kw("else", beforeExpr)
kw("finally")
kw("for", {isLoop: true})
kw("function")
kw("function", startsExpr)
kw("if")
kw("return", beforeExpr)
kw("switch")

View File

@@ -1,7 +1,3 @@
export function isArray(obj) {
return Object.prototype.toString.call(obj) === "[object Array]"
}
// Checks if an object has a property.
export function has(obj, propName) {

4
src/babel/README.md Normal file
View File

@@ -0,0 +1,4 @@
## Diving into Babel
If you look around in the various directories in here you'll find some details
about the organization of the Babel codebase.

18
src/babel/api/README.md Normal file
View File

@@ -0,0 +1,18 @@
## API
In this directory you'll find all the public interfaces to using Babel for both
node and the browser.
### Node
There are two ways people use Babel within Node, they either are manipulating
strings of code with `babel.transform` or `babel.parse`, they also might be
running their code through Babel before execution via `register` or `polyfill`.
### Browser
Usage of Babel in the browser is extremely uncommon and in most cases
considered A Bad Idea™. However it works by loading `<script>`'s with XHR,
transforming them and then executing them. These `<script>`'s need to have a
`type` of "text/ecmascript-6", "text/babel", or "module" ("text/6to5" exists as
well for legacy reasons).

View File

@@ -1,22 +1,45 @@
/* eslint no-new-func: 0 */
require("./node");
var transform = module.exports = require("../transformation");
/**
* Add `options` and `version` to `babel` global.
*/
transform.options = require("../transformation/file/options");
transform.version = require("../../../package").version;
/**
* Add `transform` api to `babel` global.
*/
transform.transform = transform;
/**
* Tranform and execute script, adding in inline sourcemaps.
*/
transform.run = function (code, opts = {}) {
opts.sourceMaps = "inline";
return new Function(transform(code, opts).code)();
};
/**
* Load scripts via xhr, and `transform` when complete (optional).
*/
transform.load = function (url, callback, opts = {}, hold) {
opts.filename ||= url;
opts.filename = opts.filename || url;
var xhr = global.ActiveXObject ? new global.ActiveXObject("Microsoft.XMLHTTP") : new global.XMLHttpRequest();
xhr.open("GET", url, true);
if ("overrideMimeType" in xhr) xhr.overrideMimeType("text/plain");
/**
* When successfully loaded, transform (optional), and call `callback`.
*/
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return;
@@ -33,11 +56,22 @@ transform.load = function (url, callback, opts = {}, hold) {
xhr.send(null);
};
/**
* Load and transform all scripts of `types`.
*
* @example
* <script type="module"></script>
*/
var runScripts = function () {
var scripts = [];
var types = ["text/ecmascript-6", "text/6to5", "text/babel", "module"];
var index = 0;
/**
* Transform and execute script. Ensures correct load order.
*/
var exec = function () {
var param = scripts[index];
if (param instanceof Array) {
@@ -47,6 +81,10 @@ var runScripts = function () {
}
};
/**
* Load, transform, and execute all scripts.
*/
var run = function (script, i) {
var opts = {};
@@ -61,7 +99,9 @@ var runScripts = function () {
}
};
var _scripts = global.document .getElementsByTagName("script");
// Collect scripts with Babel `types`.
var _scripts = global.document.getElementsByTagName("script");
for (var i = 0; i < _scripts.length; ++i) {
var _script = _scripts[i];
@@ -75,6 +115,10 @@ var runScripts = function () {
exec();
};
/**
* Register load event to transform and execute scripts.
*/
if (global.addEventListener) {
global.addEventListener("DOMContentLoaded", runScripts, false);
} else if (global.attachEvent) {

View File

@@ -4,12 +4,14 @@ import * as acorn from "../../acorn";
import * as util from "../util";
import fs from "fs";
export { util, acorn };
export { util, acorn, transform };
export { pipeline } from "../transformation";
export { canCompile } from "../util";
export { default as options } from "../transformation/file/options";
export { default as options } from "../transformation/file/options/config";
export { default as Plugin } from "../transformation/plugin";
export { default as Transformer } from "../transformation/transformer";
export { default as transform } from "../transformation";
export { default as Pipeline } from "../transformation/pipeline";
export { default as traverse } from "../traversal";
export { default as buildExternalHelpers } from "../tools/build-external-helpers";
export { version } from "../../../package";
@@ -17,16 +19,28 @@ export { version } from "../../../package";
import * as t from "../types";
export { t as types };
/**
* Register Babel and polyfill globally.
*/
export function register(opts?: Object) {
var callback = require("./register/node");
var callback = require("./register/node-polyfill");
if (opts != null) callback(opts);
return callback;
}
/**
* Register polyfill globally.
*/
export function polyfill() {
require("../polyfill");
}
/**
* Asynchronously transform `filename` with optional `opts`, calls `callback` when complete.
*/
export function transformFile(filename: string, opts?: Object, callback: Function) {
if (isFunction(opts)) {
callback = opts;
@@ -50,7 +64,32 @@ export function transformFile(filename: string, opts?: Object, callback: Functio
});
}
/**
* Synchronous form of `transformFile`.
*/
export function transformFileSync(filename: string, opts?: Object = {}) {
opts.filename = filename;
return transform(fs.readFileSync(filename), opts);
return transform(fs.readFileSync(filename, "utf8"), opts);
}
/**
* Parse script with Babel's parser.
*/
export function parse(code, opts = {}) {
opts.allowHashBang = true;
opts.sourceType = "module";
opts.ecmaVersion = Infinity;
opts.plugins = {
jsx: true,
flow: true
};
opts.features = {};
for (var key in transform.pipeline.transformers) {
opts.features[key] = true;
}
return acorn.parse(code, opts);
}

View File

@@ -1,5 +1,5 @@
// required to safely use babel/register within a browserify codebase
export default function () {};
export default function () {}
import "../../polyfill";

View File

@@ -1,22 +1,30 @@
import path from "path";
import os from "os";
import fs from "fs";
import userHome from "user-home";
import homeOrTmp from "home-or-tmp";
import pathExists from "path-exists";
const FILENAME = process.env.BABEL_CACHE_PATH || path.join(userHome || os.tmpdir(), ".babel.json");
const FILENAME = process.env.BABEL_CACHE_PATH || path.join(homeOrTmp, ".babel.json");
var data = {};
/**
* Write stringified cache to disk.
*/
export function save() {
fs.writeFileSync(FILENAME, JSON.stringify(data, null, " "));
}
/**
* Load cache from disk and parse.
*/
export function load() {
if (process.env.BABEL_DISABLE_CACHE) return;
process.on("exit", save);
process.nextTick(save);
if (!fs.existsSync(FILENAME)) return;
if (!pathExists.sync(FILENAME)) return;
try {
data = JSON.parse(fs.readFileSync(FILENAME));
@@ -25,6 +33,10 @@ export function load() {
}
}
/**
* Retrieve data from cache.
*/
export function get() {
return data;
}

View File

@@ -0,0 +1,2 @@
import "../../polyfill";
export { default } from "./node";

View File

@@ -1,12 +1,16 @@
import "../../polyfill";
import sourceMapSupport from "source-map-support";
import * as registerCache from "./cache";
import resolveRc from "../../tools/resolve-rc";
import OptionManager from "../../transformation/file/options/option-manager";
import extend from "lodash/object/extend";
import * as babel from "../node";
import each from "lodash/collection/each";
import * as util from "../../util";
import fs from "fs";
import path from "path";
/**
* Install sourcemaps into node.
*/
sourceMapSupport.install({
handleUncaughtExceptions: false,
@@ -23,34 +27,59 @@ sourceMapSupport.install({
}
});
//
/**
* Load and setup cache.
*/
registerCache.load();
var cache = registerCache.get();
//
/**
* Store options.
*/
var transformOpts = {};
var ignoreRegex = /node_modules/;
var onlyRegex;
var ignore;
var only;
var oldHandlers = {};
var maps = {};
var cwd = process.cwd();
/**
* Get path from `filename` relative to the current working directory.
*/
var getRelativePath = function (filename){
return path.relative(cwd, filename);
};
/**
* Get last modified time for a `filename`.
*/
var mtime = function (filename) {
return +fs.statSync(filename).mtime;
};
var compile = function (filename) {
/**
* Compile a `filename` with optional `opts`.
*/
var compile = function (filename, opts = {}) {
var result;
var opts = extend({}, transformOpts);
// this will be done when the file is transformed anyway but we need all
// the options so we can generate the cache key
resolveRc(filename, opts);
var optsManager = new OptionManager;
optsManager.mergeOptions(transformOpts);
opts = optsManager.init(opts);
var cacheKey = `${filename}:${JSON.stringify(opts)}:${babel.version}`;
var env = process.env.BABEL_ENV || process.env.NODE_ENV;
if (env) cacheKey += `:${env}`;
if (cache) {
var cached = cache[cacheKey];
if (cached && cached.mtime === mtime(filename)) {
@@ -75,13 +104,25 @@ var compile = function (filename) {
return result.code;
};
/**
* Test if a `filename` should be ignored by Babel.
*/
var shouldIgnore = function (filename) {
return (ignoreRegex && ignoreRegex.test(filename)) || (onlyRegex && !onlyRegex.test(filename));
if (!ignore && !only) {
return getRelativePath(filename).split(path.sep).indexOf("node_modules") >= 0;
} else {
return util.shouldIgnore(filename, ignore || [], only);
}
};
/**
* Monkey patch istanbul if it is running so that it works properly.
*/
var istanbulMonkey = {};
if (process.env.running_under_istanbul) { // jshint ignore:line
if (process.env.running_under_istanbul) {
// we need to monkey patch fs.readFileSync so we can hook into
// what istanbul gets, it's extremely dirty but it's the only way
var _readFileSync = fs.readFileSync;
@@ -89,7 +130,9 @@ if (process.env.running_under_istanbul) { // jshint ignore:line
fs.readFileSync = function (filename) {
if (istanbulMonkey[filename]) {
delete istanbulMonkey[filename];
var code = compile(filename);
var code = compile(filename, {
auxiliaryCommentBefore: "istanbul ignore next"
});
istanbulMonkey[filename] = true;
return code;
} else {
@@ -98,20 +141,32 @@ if (process.env.running_under_istanbul) { // jshint ignore:line
};
}
/**
* Replacement for the loader for istanbul.
*/
var istanbulLoader = function (m, filename, old) {
istanbulMonkey[filename] = true;
old(m, filename);
};
/**
* Default loader.
*/
var normalLoader = function (m, filename) {
m._compile(compile(filename), filename);
};
/**
* Register a loader for an extension.
*/
var registerExtension = function (ext) {
var old = oldHandlers[ext] || oldHandlers[".js"];
var old = oldHandlers[ext] || oldHandlers[".js"] || require.extensions[".js"];
var loader = normalLoader;
if (process.env.running_under_istanbul) loader = istanbulLoader; // jshint ignore:line
if (process.env.running_under_istanbul) loader = istanbulLoader;
require.extensions[ext] = function (m, filename) {
if (shouldIgnore(filename)) {
@@ -122,6 +177,10 @@ var registerExtension = function (ext) {
};
};
/**
* Register loader for given extensions.
*/
var hookExtensions = function (_exts) {
each(oldHandlers, function (old, ext) {
if (old === undefined) {
@@ -139,11 +198,19 @@ var hookExtensions = function (_exts) {
});
};
/**
* Register loader for default extensions.
*/
hookExtensions(util.canCompile.EXTENSIONS);
/**
* Update options at runtime.
*/
export default function (opts = {}) {
if (opts.only != null) onlyRegex = util.regexify(opts.only);
if (opts.ignore != null) ignoreRegex = util.regexify(opts.ignore);
if (opts.only != null) only = util.arrayify(opts.only, util.regexify);
if (opts.ignore != null) ignore = util.arrayify(opts.ignore, util.regexify);
if (opts.extensions) hookExtensions(util.arrayify(opts.extensions));
@@ -155,17 +222,4 @@ export default function (opts = {}) {
delete opts.only;
extend(transformOpts, opts);
};
//
try {
var runtimePackage = require("babel-runtime/package");
var version = require("../../../../package").version;
if (runtimePackage.version !== version) {
throw new ReferenceError(`The verison of babel-runtime of ${runtimePackage.runtime} that you have installed does not match the babel verison of ${version}`);
}
} catch (err) {
if (err.code !== "MODULE_NOT_FOUND") throw err;
}

View File

@@ -0,0 +1,16 @@
## Generation
Here is Babel's code generator, here you'll find all of the code to turn an AST
back into a string of code.
[TBD: To Be Documented:]
- Code Generator
- Buffer
- Source Maps
- Position
- Printer
- Code Style
- Whitespace
- Parenthesis
- Generators

View File

@@ -4,6 +4,10 @@ import isBoolean from "lodash/lang/isBoolean";
import includes from "lodash/collection/includes";
import isNumber from "lodash/lang/isNumber";
/**
* Buffer for collecting generated output.
*/
export default class Buffer {
constructor(position, format) {
this.position = position;
@@ -12,10 +16,18 @@ export default class Buffer {
this.buf = "";
}
/**
* Get the current trimmed buffer.
*/
get() {
return trimRight(this.buf);
}
/**
* Get the current indent.
*/
getIndent() {
if (this.format.compact || this.format.concise) {
return "";
@@ -24,43 +36,80 @@ export default class Buffer {
}
}
/**
* Get the current indent size.
*/
indentSize() {
return this.getIndent().length;
}
/**
* Increment indent size.
*/
indent() {
this._indent++;
}
/**
* Decrement indent size.
*/
dedent() {
this._indent--;
}
/**
* Add a semicolon to the buffer.
*/
semicolon() {
this.push(";");
}
/**
* Ensure last character is a semicolon.
*/
ensureSemicolon() {
if (!this.isLast(";")) this.semicolon();
}
/**
* Add a right brace to the buffer.
*/
rightBrace() {
this.newline(true);
this.push("}");
}
/**
* Add a keyword to the buffer.
*/
keyword(name) {
this.push(name);
this.space();
}
space() {
if (this.format.compact) return;
if (this.buf && !this.isLast(" ") && !this.isLast("\n")) {
/**
* Add a space to the buffer unless it is compact (override with force).
*/
space(force?) {
if (!force && this.format.compact) return;
if (force || this.buf && !this.isLast(" ") && !this.isLast("\n")) {
this.push(" ");
}
}
/**
* Remove the last character.
*/
removeLast(cha) {
if (this.format.compact) return;
if (!this.isLast(cha)) return;
@@ -69,15 +118,20 @@ export default class Buffer {
this.position.unshift(cha);
}
/**
* Add a newline (or many newlines), maintaining formatting.
* Strips multiple newlines if removeLast is true.
*/
newline(i, removeLast) {
if (this.format.compact) return;
if (this.format.compact || this.format.retainLines) return;
if (this.format.concise) {
this.space();
return;
}
removeLast ||= false;
removeLast = removeLast || false;
if (isNumber(i)) {
i = Math.min(2, i);
@@ -99,6 +153,10 @@ export default class Buffer {
this._newline(removeLast);
}
/**
* Adds a newline unless there is already two previous newlines.
*/
_newline(removeLast) {
// never allow more than two lines
if (this.endsWith("\n\n")) return;
@@ -117,8 +175,9 @@ export default class Buffer {
_removeSpacesAfterLastNewline() {
var lastNewlineIndex = this.buf.lastIndexOf("\n");
if (lastNewlineIndex === -1)
if (lastNewlineIndex === -1) {
return;
}
var index = this.buf.length - 1;
while (index > lastNewlineIndex) {
@@ -134,6 +193,10 @@ export default class Buffer {
}
}
/**
* Push a string to the buffer, maintaining indentation and newlines.
*/
push(str, noIndent) {
if (!this.format.compact && this._indent && !noIndent && str !== "\n") {
// we have an indent level and we aren't pushing a newline
@@ -149,15 +212,31 @@ export default class Buffer {
this._push(str);
}
/**
* Push a string to the buffer.
*/
_push(str) {
this.position.push(str);
this.buf += str;
}
endsWith(str) {
return this.buf.slice(-str.length) === str;
/**
* Test if the buffer ends with a string.
*/
endsWith(str, buf = this.buf) {
if (str.length === 1) {
return buf[buf.length - 1] === str;
} else {
return buf.slice(-str.length) === str;
}
}
/**
* Test if a character is last in the buffer.
*/
isLast(cha) {
if (this.format.compact) return false;

View File

@@ -0,0 +1,10 @@
## Generators
Code generation in Babel is broken down into generators by node type, they all
live in this directory.
[TBD: To Be Documented:]
- How generators work
- How to print a node
- How generators related to one another

View File

@@ -1,11 +1,23 @@
/**
* Print File.program
*/
export function File(node, print) {
print(node.program);
print.plain(node.program);
}
/**
* Print all nodes in a Program.body.
*/
export function Program(node, print) {
print.sequence(node.body);
}
/**
* Print BlockStatement, collapses empty blocks, prints body.
*/
export function BlockStatement(node, print) {
if (node.body.length === 0) {
this.push("{}");
@@ -13,7 +25,18 @@ export function BlockStatement(node, print) {
this.push("{");
this.newline();
print.sequence(node.body, { indent: true });
this.removeLast("\n");
if (!this.format.retainLines) this.removeLast("\n");
this.rightBrace();
}
}
/**
* What is my purpose?
* Why am I here?
* Why are any of us here?
* Does any of this really matter?
*/
export function Noop() {
}

View File

@@ -1,18 +1,22 @@
/**
* Print ClassDeclaration, prints decorators, typeParameters, extends, implements, and body.
*/
export function ClassDeclaration(node, print) {
print.list(node.decorators);
print.list(node.decorators, { separator: "" });
this.push("class");
if (node.id) {
this.space();
print(node.id);
this.push(" ");
print.plain(node.id);
}
print(node.typeParameters);
print.plain(node.typeParameters);
if (node.superClass) {
this.push(" extends ");
print(node.superClass);
print(node.superTypeParameters);
print.plain(node.superClass);
print.plain(node.superTypeParameters);
}
if (node.implements) {
@@ -21,11 +25,19 @@ export function ClassDeclaration(node, print) {
}
this.space();
print(node.body);
print.plain(node.body);
}
/**
* Alias ClassDeclaration printer as ClassExpression.
*/
export { ClassDeclaration as ClassExpression };
/**
* Print ClassBody, collapses empty blocks, prints body.
*/
export function ClassBody(node, print) {
if (node.body.length === 0) {
this.push("{}");
@@ -41,24 +53,32 @@ export function ClassBody(node, print) {
}
}
/**
* Print ClassProperty, prints decorators, static, key, typeAnnotation, and value.
* Also: semicolons, deal with it.
*/
export function ClassProperty(node, print) {
print.list(node.decorators);
print.list(node.decorators, { separator: "" });
if (node.static) this.push("static ");
print(node.key);
print(node.typeAnnotation);
print.plain(node.key);
print.plain(node.typeAnnotation);
if (node.value) {
this.space();
this.push("=");
this.space();
print(node.value);
print.plain(node.value);
}
this.semicolon();
}
/**
* Print MethodDefinition, prints decorations, static, and method.
*/
export function MethodDefinition(node, print) {
print.list(node.decorators);
print.list(node.decorators, { separator: "" });
if (node.static) {
this.push("static ");

View File

@@ -1,12 +1,20 @@
/**
* Prints ComprehensionBlock, prints left and right.
*/
export function ComprehensionBlock(node, print) {
this.keyword("for");
this.push("(");
print(node.left);
print.plain(node.left);
this.push(" of ");
print(node.right);
print.plain(node.right);
this.push(")");
}
/**
* Prints ComprehensionExpression, prints blocks, filter, and body. Handles generators.
*/
export function ComprehensionExpression(node, print) {
this.push(node.generator ? "(" : "[");
@@ -16,12 +24,12 @@ export function ComprehensionExpression(node, print) {
if (node.filter) {
this.keyword("if");
this.push("(");
print(node.filter);
print.plain(node.filter);
this.push(")");
this.space();
}
print(node.body);
print.plain(node.body);
this.push(node.generator ? ")" : "]");
}

View File

@@ -1,95 +1,144 @@
import isInteger from "is-integer";
import isNumber from "lodash/lang/isNumber";
import * as t from "../../types";
/**
* Prints UnaryExpression, prints operator and argument.
*/
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(" ");
print(node.argument);
if (needsSpace) this.push(" ");
print.plain(node.argument);
}
/**
* Prints DoExpression, prints body.
*/
export function DoExpression(node, print) {
this.push("do");
this.space();
print(node.body);
print.plain(node.body);
}
/**
* Prints ParenthesizedExpression, prints expression.
*/
export function ParenthesizedExpression(node, print) {
this.push("(");
print.plain(node.expression);
this.push(")");
}
/**
* Prints UpdateExpression, prints operator and argument.
*/
export function UpdateExpression(node, print) {
if (node.prefix) {
this.push(node.operator);
print(node.argument);
print.plain(node.argument);
} else {
print(node.argument);
print.plain(node.argument);
this.push(node.operator);
}
}
/**
* Prints ConditionalExpression, prints test, consequent, and alternate.
*/
export function ConditionalExpression(node, print) {
print(node.test);
print.plain(node.test);
this.space();
this.push("?");
this.space();
print(node.consequent);
print.plain(node.consequent);
this.space();
this.push(":");
this.space();
print(node.alternate);
print.plain(node.alternate);
}
/**
* Prints NewExpression, prints callee and arguments.
*/
export function NewExpression(node, print) {
this.push("new ");
print(node.callee);
print.plain(node.callee);
this.push("(");
print.list(node.arguments);
this.push(")");
}
/**
* Prints SequenceExpression.expressions.
*/
export function SequenceExpression(node, print) {
print.list(node.expressions);
}
/**
* Prints ThisExpression.
*/
export function ThisExpression() {
this.push("this");
}
/**
* Prints Super.
*/
export function Super() {
this.push("super");
}
/**
* Prints Decorator, prints expression.
*/
export function Decorator(node, print) {
this.push("@");
print(node.expression);
print.plain(node.expression);
this.newline();
}
/**
* Prints CallExpression, prints callee and arguments.
*/
export function CallExpression(node, print) {
print(node.callee);
print.plain(node.callee);
this.push("(");
var separator = ",";
var isPrettyCall = node._prettyCall && !this.format.retainLines && !this.format.compact;
if (node._prettyCall) {
separator += "\n";
var separator;
if (isPrettyCall) {
separator = ",\n";
this.newline();
this.indent();
} else {
separator += " ";
}
print.list(node.arguments, { separator: separator });
print.list(node.arguments, { separator });
if (node._prettyCall) {
if (isPrettyCall) {
this.newline();
this.dedent();
}
@@ -97,6 +146,11 @@ export function CallExpression(node, print) {
this.push(")");
}
/**
* Builds yield or await expression printer.
* Prints delegate, all, and argument.
*/
var buildYieldAwait = function (keyword) {
return function (node, print) {
this.push(keyword);
@@ -106,44 +160,100 @@ var buildYieldAwait = function (keyword) {
}
if (node.argument) {
this.space();
print(node.argument);
this.push(" ");
print.plain(node.argument);
}
};
};
/**
* Create YieldExpression and AwaitExpression printers.
*/
export var YieldExpression = buildYieldAwait("yield");
export var AwaitExpression = buildYieldAwait("await");
/**
* Prints EmptyStatement.
*/
export function EmptyStatement() {
this.semicolon();
}
/**
* Prints ExpressionStatement, prints expression.
*/
export function ExpressionStatement(node, print) {
print(node.expression);
print.plain(node.expression);
this.semicolon();
}
/**
* Prints AssignmentPattern, prints left and right.
*/
export function AssignmentPattern(node, print) {
print.plain(node.left);
this.push(" = ");
print.plain(node.right);
}
/**
* Prints AssignmentExpression, prints left, operator, and right.
*/
export function AssignmentExpression(node, print) {
// todo: add cases where the spaces can be dropped when in compact mode
print(node.left);
this.push(" ");
print.plain(node.left);
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(" ");
print(node.right);
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);
}
/**
* Prints BindExpression, prints object and callee.
*/
export function BindExpression(node, print) {
print.plain(node.object);
this.push("::");
print.plain(node.callee);
}
/**
* Alias ClassDeclaration printer as ClassExpression,
* and AssignmentExpression printer as LogicalExpression.
*/
export {
AssignmentExpression as BinaryExpression,
AssignmentExpression as LogicalExpression,
AssignmentExpression as AssignmentPattern
AssignmentExpression as LogicalExpression
};
var SCIENTIFIC_NOTATION = /e/i;
/**
* Print MemberExpression, prints object, property, and value. Handles computed.
*/
export function MemberExpression(node, print) {
var obj = node.object;
print(obj);
print.plain(obj);
if (!node.computed && t.isMemberExpression(node.property)) {
throw new TypeError("Got a MemberExpression for MemberExpression property");
@@ -156,21 +266,20 @@ export function MemberExpression(node, print) {
if (computed) {
this.push("[");
print(node.property);
print.plain(node.property);
this.push("]");
} else {
// 5..toFixed(2);
if (t.isLiteral(obj) && isInteger(obj.value) && !SCIENTIFIC_NOTATION.test(obj.value.toString())) {
this.push(".");
}
this.push(".");
print(node.property);
print.plain(node.property);
}
}
/**
* Print MetaProperty, prints meta and property.
*/
export function MetaProperty(node, print) {
print(node.meta);
print.plain(node.meta);
this.push(".");
print(node.property);
print.plain(node.property);
}

View File

@@ -1,47 +1,79 @@
import * as t from "../../types";
/**
* Prints AnyTypeAnnotation.
*/
export function AnyTypeAnnotation() {
this.push("any");
}
/**
* Prints ArrayTypeAnnotation, prints elementType.
*/
export function ArrayTypeAnnotation(node, print) {
print(node.elementType);
print.plain(node.elementType);
this.push("[");
this.push("]");
}
/**
* Prints BooleanTypeAnnotation.
*/
export function BooleanTypeAnnotation(node) {
this.push("bool");
}
/**
* Prints DeclareClass, prints node.
*/
export function DeclareClass(node, print) {
this.push("declare class ");
this._interfaceish(node, print);
}
/**
* Prints DeclareFunction, prints id and id.typeAnnotation.
*/
export function DeclareFunction(node, print) {
this.push("declare function ");
print(node.id);
print(node.id.typeAnnotation.typeAnnotation);
print.plain(node.id);
print.plain(node.id.typeAnnotation.typeAnnotation);
this.semicolon();
}
/**
* Prints DeclareModule, prints id and body.
*/
export function DeclareModule(node, print) {
this.push("declare module ");
print(node.id);
print.plain(node.id);
this.space();
print(node.body);
print.plain(node.body);
}
/**
* Prints DeclareVariable, prints id and id.typeAnnotation.
*/
export function DeclareVariable(node, print) {
this.push("declare var ");
print(node.id);
print(node.id.typeAnnotation);
print.plain(node.id);
print.plain(node.id.typeAnnotation);
this.semicolon();
}
/**
* Prints FunctionTypeAnnotation, prints typeParameters, params, and rest.
*/
export function FunctionTypeAnnotation(node, print, parent) {
print(node.typeParameters);
print.plain(node.typeParameters);
this.push("(");
print.list(node.params);
@@ -51,7 +83,7 @@ export function FunctionTypeAnnotation(node, print, parent) {
this.space();
}
this.push("...");
print(node.rest);
print.plain(node.rest);
}
this.push(")");
@@ -65,98 +97,175 @@ export function FunctionTypeAnnotation(node, print, parent) {
}
this.space();
print(node.returnType);
print.plain(node.returnType);
}
/**
* Prints FunctionTypeParam, prints name and typeAnnotation, handles optional.
*/
export function FunctionTypeParam(node, print) {
print(node.name);
print.plain(node.name);
if (node.optional) this.push("?");
this.push(":");
this.space();
print(node.typeAnnotation);
print.plain(node.typeAnnotation);
}
/**
* Prints InterfaceExtends, prints id and typeParameters.
*/
export function InterfaceExtends(node, print) {
print(node.id);
print(node.typeParameters);
print.plain(node.id);
print.plain(node.typeParameters);
}
/**
* Alias InterfaceExtends printer as ClassImplements,
* and InterfaceExtends printer as GenericTypeAnnotation.
*/
export { InterfaceExtends as ClassImplements, InterfaceExtends as GenericTypeAnnotation };
/**
* Prints interface-like node, prints id, typeParameters, extends, and body.
*/
export function _interfaceish(node, print) {
print(node.id);
print(node.typeParameters);
print.plain(node.id);
print.plain(node.typeParameters);
if (node.extends.length) {
this.push(" extends ");
print.join(node.extends, { separator: ", " });
}
this.space();
print(node.body);
print.plain(node.body);
}
/**
* Prints InterfaceDeclaration, prints node.
*/
export function InterfaceDeclaration(node, print) {
this.push("interface ");
this._interfaceish(node, print);
}
/**
* Prints IntersectionTypeAnnotation, prints types.
*/
export function IntersectionTypeAnnotation(node, print) {
print.join(node.types, { separator: " & " });
}
/**
* Prints MixedTypeAnnotation.
*/
export function MixedTypeAnnotation() {
this.push("mixed");
}
/**
* Prints NullableTypeAnnotation, prints typeAnnotation.
*/
export function NullableTypeAnnotation(node, print) {
this.push("?");
print(node.typeAnnotation);
print.plain(node.typeAnnotation);
}
/**
* Prints NumberTypeAnnotation.
*/
export function NumberTypeAnnotation() {
this.push("number");
}
/**
* Prints StringLiteralTypeAnnotation, prints value.
*/
export function StringLiteralTypeAnnotation(node) {
this._stringLiteral(node.value);
}
/**
* Prints StringTypeAnnotation.
*/
export function StringTypeAnnotation() {
this.push("string");
}
/**
* Prints TupleTypeAnnotation, prints types.
*/
export function TupleTypeAnnotation(node, print) {
this.push("[");
print.join(node.types, { separator: ", " });
this.push("]");
}
/**
* Prints TypeofTypeAnnotation, prints argument.
*/
export function TypeofTypeAnnotation(node, print) {
this.push("typeof ");
print(node.argument);
print.plain(node.argument);
}
/**
* Prints TypeAlias, prints id, typeParameters, and right.
*/
export function TypeAlias(node, print) {
this.push("type ");
print(node.id);
print(node.typeParameters);
print.plain(node.id);
print.plain(node.typeParameters);
this.space();
this.push("=");
this.space();
print(node.right);
print.plain(node.right);
this.semicolon();
}
/**
* Prints TypeAnnotation, prints typeAnnotation, handles optional.
*/
export function TypeAnnotation(node, print) {
this.push(":");
this.space();
if (node.optional) this.push("?");
print(node.typeAnnotation);
print.plain(node.typeAnnotation);
}
/**
* Prints TypeParameterInstantiation, prints params.
*/
export function TypeParameterInstantiation(node, print) {
this.push("<");
print.join(node.params, { separator: ", " });
this.push(">");
}
/**
* Alias TypeParameterInstantiation printer as TypeParameterDeclaration
*/
export { TypeParameterInstantiation as TypeParameterDeclaration };
/**
* Prints ObjectTypeAnnotation, prints properties, callProperties, and indexers.
*/
export function ObjectTypeAnnotation(node, print) {
this.push("{");
var props = node.properties.concat(node.callProperties, node.indexers);
@@ -181,52 +290,80 @@ export function ObjectTypeAnnotation(node, print) {
this.push("}");
}
/**
* Prints ObjectTypeCallProperty, prints value, handles static.
*/
export function ObjectTypeCallProperty(node, print) {
if (node.static) this.push("static ");
print(node.value);
print.plain(node.value);
}
/**
* Prints ObjectTypeIndexer, prints id, key, and value, handles static.
*/
export function ObjectTypeIndexer(node, print) {
if (node.static) this.push("static ");
this.push("[");
print(node.id);
print.plain(node.id);
this.push(":");
this.space();
print(node.key);
print.plain(node.key);
this.push("]");
this.push(":");
this.space();
print(node.value);
print.plain(node.value);
}
/**
* Prints ObjectTypeProperty, prints static, key, and value.
*/
export function ObjectTypeProperty(node, print) {
if (node.static) this.push("static ");
print(node.key);
print.plain(node.key);
if (node.optional) this.push("?");
if (!t.isFunctionTypeAnnotation(node.value)) {
this.push(":");
this.space();
}
print(node.value);
print.plain(node.value);
}
/**
* Prints QualifiedTypeIdentifier, prints qualification and id.
*/
export function QualifiedTypeIdentifier(node, print) {
print(node.qualification);
print.plain(node.qualification);
this.push(".");
print(node.id);
print.plain(node.id);
}
/**
* Prints UnionTypeAnnotation, prints types.
*/
export function UnionTypeAnnotation(node, print) {
print.join(node.types, { separator: " | " });
}
/**
* Prints TypeCastExpression, prints expression and typeAnnotation.
*/
export function TypeCastExpression(node, print) {
this.push("(");
print(node.expression);
print(node.typeAnnotation);
print.plain(node.expression);
print.plain(node.typeAnnotation);
this.push(")");
}
/**
* Prints VoidTypeAnnotation.
*/
export function VoidTypeAnnotation(node) {
this.push("void");
}

View File

@@ -1,63 +1,94 @@
import each from "lodash/collection/each";
import * as t from "../../types";
/**
* Prints JSXAttribute, prints name and value.
*/
export function JSXAttribute(node, print) {
print(node.name);
print.plain(node.name);
if (node.value) {
this.push("=");
print(node.value);
print.plain(node.value);
}
}
/**
* Prints JSXIdentifier, prints name.
*/
export function JSXIdentifier(node) {
this.push(node.name);
}
/**
* Prints JSXNamespacedName, prints namespace and name.
*/
export function JSXNamespacedName(node, print) {
print(node.namespace);
print.plain(node.namespace);
this.push(":");
print(node.name);
print.plain(node.name);
}
/**
* Prints JSXMemberExpression, prints object and property.
*/
export function JSXMemberExpression(node, print) {
print(node.object);
print.plain(node.object);
this.push(".");
print(node.property);
print.plain(node.property);
}
/**
* Prints JSXSpreadAttribute, prints argument.
*/
export function JSXSpreadAttribute(node, print) {
this.push("{...");
print(node.argument);
print.plain(node.argument);
this.push("}");
}
/**
* Prints JSXExpressionContainer, prints expression.
*/
export function JSXExpressionContainer(node, print) {
this.push("{");
print(node.expression);
print.plain(node.expression);
this.push("}");
}
/**
* Prints JSXElement, prints openingElement, children, and closingElement.
*/
export function JSXElement(node, print) {
var open = node.openingElement;
print(open);
print.plain(open);
if (open.selfClosing) return;
this.indent();
each(node.children, (child) => {
for (var child of (node.children: Array)) {
if (t.isLiteral(child)) {
this.push(child.value);
this.push(child.value, true);
} else {
print(child);
print.plain(child);
}
});
}
this.dedent();
print(node.closingElement);
print.plain(node.closingElement);
}
/**
* Prints JSXOpeningElement, prints name and attributes, handles selfClosing.
*/
export function JSXOpeningElement(node, print) {
this.push("<");
print(node.name);
print.plain(node.name);
if (node.attributes.length > 0) {
this.push(" ");
print.join(node.attributes, { separator: " " });
@@ -65,10 +96,18 @@ export function JSXOpeningElement(node, print) {
this.push(node.selfClosing ? " />" : ">");
}
/**
* Prints JSXClosingElement, prints name.
*/
export function JSXClosingElement(node, print) {
this.push("</");
print(node.name);
print.plain(node.name);
this.push(">");
}
/**
* Prints JSXEmptyExpression.
*/
export function JSXEmptyExpression() {}

View File

@@ -1,21 +1,29 @@
import * as t from "../../types";
/**
* Prints nodes with params, prints typeParameters, params, and returnType, handles optional params.
*/
export function _params(node, print) {
print(node.typeParameters);
print.plain(node.typeParameters);
this.push("(");
print.list(node.params, {
iterator: (node) =>{
if (node.optional) this.push("?");
print(node.typeAnnotation);
print.plain(node.typeAnnotation);
}
});
this.push(")");
if (node.returnType) {
print(node.returnType);
print.plain(node.returnType);
}
}
/**
* Prints method-like nodes, prints key, value, and body, handles async, generator, computed, and get or set.
*/
export function _method(node, print) {
var value = node.value;
var kind = node.kind;
@@ -35,17 +43,21 @@ export function _method(node, print) {
if (node.computed) {
this.push("[");
print(key);
print.plain(key);
this.push("]");
} else {
print(key);
print.plain(key);
}
this._params(value, print);
this.push(" ");
print(value.body);
this.space();
print.plain(value.body);
}
/**
* Prints FunctionExpression, prints id and body, handles async and generator.
*/
export function FunctionExpression(node, print) {
if (node.async) this.push("async ");
this.push("function");
@@ -53,23 +65,32 @@ export function FunctionExpression(node, print) {
if (node.id) {
this.push(" ");
print(node.id);
print.plain(node.id);
} else {
this.space();
}
this._params(node, print);
this.space();
print(node.body);
print.plain(node.body);
}
/**
* Alias FunctionExpression printer as FunctionDeclaration.
*/
export { FunctionExpression as FunctionDeclaration };
/**
* Prints ArrowFunctionExpression, prints params and body, handles async.
* Leaves out parentheses when single param.
*/
export function ArrowFunctionExpression(node, print) {
if (node.async) this.push("async ");
if (node.params.length === 1 && t.isIdentifier(node.params[0])) {
print(node.params[0]);
print.plain(node.params[0]);
} else {
this._params(node, print);
}
@@ -82,7 +103,7 @@ export function ArrowFunctionExpression(node, print) {
this.push("(");
}
print(node.body);
print.plain(node.body);
if (bodyNeedsParens) {
this.push(")");

View File

@@ -1,69 +1,104 @@
import each from "lodash/collection/each";
import * as t from "../../types";
/**
* Prints ImportSpecifier, prints imported and local.
*/
export function ImportSpecifier(node, print) {
print(node.imported);
if (node.local && node.local !== node.imported) {
print.plain(node.imported);
if (node.local && node.local.name !== node.imported.name) {
this.push(" as ");
print(node.local);
print.plain(node.local);
}
}
/**
* Prints ImportDefaultSpecifier, prints local.
*/
export function ImportDefaultSpecifier(node, print) {
print(node.local);
print.plain(node.local);
}
/**
* Prints ExportDefaultSpecifier, prints exported.
*/
export function ExportDefaultSpecifier(node, print) {
print(node.exported);
print.plain(node.exported);
}
/**
* Prints ExportSpecifier, prints local and exported.
*/
export function ExportSpecifier(node, print) {
print(node.local);
if (node.exported && node.local !== node.exported) {
print.plain(node.local);
if (node.exported && node.local.name !== node.exported.name) {
this.push(" as ");
print(node.exported);
print.plain(node.exported);
}
}
/**
* Prints ExportNamespaceSpecifier, prints exported.
*/
export function ExportNamespaceSpecifier(node, print) {
this.push("* as ");
print(node.exported);
print.plain(node.exported);
}
/**
* Prints ExportAllDeclaration, prints exported and source.
*/
export function ExportAllDeclaration(node, print) {
this.push("export *");
if (node.exported) {
this.push(" as ");
print(node.exported);
print.plain(node.exported);
}
this.push(" from ");
print(node.source);
print.plain(node.source);
this.semicolon();
}
/**
* Prints ExportNamedDeclaration, delegates to ExportDeclaration.
*/
export function ExportNamedDeclaration(node, print) {
this.push("export ");
ExportDeclaration.call(this, node, print);
}
/**
* Prints ExportDefaultDeclaration, delegates to ExportDeclaration.
*/
export function ExportDefaultDeclaration(node, print) {
this.push("export default ");
ExportDeclaration.call(this, node, print);
}
/**
* Prints ExportDeclaration, prints specifiers, declration, and source.
*/
function ExportDeclaration(node, print) {
var specifiers = node.specifiers;
if (node.declaration) {
var declar = node.declaration;
print(declar);
print.plain(declar);
if (t.isStatement(declar) || t.isFunction(declar) || t.isClass(declar)) return;
} else {
var first = specifiers[0];
var hasSpecial = false;
if (t.isExportDefaultSpecifier(first) || t.isExportNamespaceSpecifier(first)) {
hasSpecial = true;
print(specifiers.shift());
print.plain(specifiers.shift());
if (specifiers.length) {
this.push(", ");
}
@@ -81,25 +116,29 @@ function ExportDeclaration(node, print) {
if (node.source) {
this.push(" from ");
print(node.source);
print.plain(node.source);
}
}
this.ensureSemicolon();
}
/**
* Prints ImportDeclaration, prints specifiers and source, handles isType.
*/
export function ImportDeclaration(node, print) {
this.push("import ");
if (node.isType) {
this.push("type ");
if (node.importKind === "type" || node.importKind === "typeof") {
this.push(node.importKind + " ");
}
var specfiers = node.specifiers;
if (specfiers && specfiers.length) {
var first = node.specifiers[0];
if (t.isImportDefaultSpecifier(first) || t.isImportNamespaceSpecifier(first)) {
print(node.specifiers.shift());
print.plain(node.specifiers.shift());
if (node.specifiers.length) {
this.push(", ");
}
@@ -107,20 +146,24 @@ export function ImportDeclaration(node, print) {
if (node.specifiers.length) {
this.push("{");
this.space()
this.space();
print.join(node.specifiers, { separator: ", " });
this.space()
this.space();
this.push("}");
}
this.push(" from ");
}
print(node.source);
print.plain(node.source);
this.semicolon();
}
/**
* Prints ImportNamespaceSpecifier, prints local.
*/
export function ImportNamespaceSpecifier(node, print) {
this.push("* as ");
print(node.local);
print.plain(node.local);
}

View File

@@ -1,18 +1,26 @@
import repeating from "repeating";
import * as t from "../../types";
/**
* Prints WithStatement, prints object and body.
*/
export function WithStatement(node, print) {
this.keyword("with");
this.push("(");
print(node.object);
print.plain(node.object);
this.push(")");
print.block(node.body);
}
/**
* Prints IfStatement, prints test, consequent, and alternate.
*/
export function IfStatement(node, print) {
this.keyword("if");
this.push("(");
print(node.test);
print.plain(node.test);
this.push(")");
this.space();
@@ -25,61 +33,87 @@ export function IfStatement(node, print) {
}
}
/**
* Prints ForStatement, prints init, test, update, and body.
*/
export function ForStatement(node, print) {
this.keyword("for");
this.push("(");
print(node.init);
print.plain(node.init);
this.push(";");
if (node.test) {
this.push(" ");
print(node.test);
this.space();
print.plain(node.test);
}
this.push(";");
if (node.update) {
this.push(" ");
print(node.update);
this.space();
print.plain(node.update);
}
this.push(")");
print.block(node.body);
}
/**
* Prints WhileStatement, prints test and body.
*/
export function WhileStatement(node, print) {
this.keyword("while");
this.push("(");
print(node.test);
print.plain(node.test);
this.push(")");
print.block(node.body);
}
/**
* Builds ForIn or ForOf statement printers.
* Prints left, right, and body.
*/
var buildForXStatement = function (op) {
return function (node, print) {
this.keyword("for");
this.push("(");
print(node.left);
print.plain(node.left);
this.push(` ${op} `);
print(node.right);
print.plain(node.right);
this.push(")");
print.block(node.body);
};
};
/**
* Create ForInStatement and ForOfStatement printers.
*/
export var ForInStatement = buildForXStatement("in");
export var ForOfStatement = buildForXStatement("of");
/**
* Prints DoWhileStatement, prints body and test.
*/
export function DoWhileStatement(node, print) {
this.keyword("do");
print(node.body);
this.push("do ");
print.plain(node.body);
this.space();
this.keyword("while");
this.push("(");
print(node.test);
print.plain(node.test);
this.push(");");
}
/**
* Builds continue, return, or break statement printers.
* Prints label (or key).
*/
var buildLabelStatement = function (prefix, key) {
return function (node, print) {
this.push(prefix);
@@ -87,62 +121,86 @@ var buildLabelStatement = function (prefix, key) {
var label = node[key || "label"];
if (label) {
this.push(" ");
print(label);
print.plain(label);
}
this.semicolon();
};
};
/**
* Create ContinueStatement, ReturnStatement, and BreakStatement printers.
*/
export var ContinueStatement = buildLabelStatement("continue");
export var ReturnStatement = buildLabelStatement("return", "argument");
export var BreakStatement = buildLabelStatement("break");
/**
* Prints LabeledStatement, prints label and body.
*/
export function LabeledStatement(node, print) {
print(node.label);
print.plain(node.label);
this.push(": ");
print(node.body);
print.plain(node.body);
}
/**
* Prints TryStatement, prints block, handlers, and finalizer.
*/
export function TryStatement(node, print) {
this.keyword("try");
print(node.block);
print.plain(node.block);
this.space();
// Esprima bug puts the catch clause in a `handlers` array.
// see https://code.google.com/p/esprima/issues/detail?id=433
// We run into this from regenerator generated ast.
if (node.handlers) {
print(node.handlers[0]);
print.plain(node.handlers[0]);
} else {
print(node.handler);
print.plain(node.handler);
}
if (node.finalizer) {
this.space();
this.push("finally ");
print(node.finalizer);
print.plain(node.finalizer);
}
}
/**
* Prints CatchClause, prints param and body.
*/
export function CatchClause(node, print) {
this.keyword("catch");
this.push("(");
print(node.param);
print.plain(node.param);
this.push(") ");
print(node.body);
print.plain(node.body);
}
/**
* Prints ThrowStatement, prints argument.
*/
export function ThrowStatement(node, print) {
this.push("throw ");
print(node.argument);
print.plain(node.argument);
this.semicolon();
}
/**
* Prints SwitchStatement, prints discriminant and cases.
*/
export function SwitchStatement(node, print) {
this.keyword("switch");
this.push("(");
print(node.discriminant);
print.plain(node.discriminant);
this.push(")");
this.space();
this.push("{");
@@ -157,10 +215,14 @@ export function SwitchStatement(node, print) {
this.push("}");
}
/**
* Prints SwitchCase, prints test and consequent.
*/
export function SwitchCase(node, print) {
if (node.test) {
this.push("case ");
print(node.test);
print.plain(node.test);
this.push(":");
} else {
this.push("default:");
@@ -172,47 +234,72 @@ export function SwitchCase(node, print) {
}
}
/**
* Prints DebuggerStatement.
*/
export function DebuggerStatement() {
this.push("debugger;");
}
/**
* Prints VariableDeclaration, prints declarations, handles kind and format.
*/
export function VariableDeclaration(node, print, parent) {
this.push(node.kind + " ");
var hasInits = false;
// don't add whitespace to loop heads
if (!t.isFor(parent)) {
for (var i = 0; i < node.declarations.length; i++) {
if (node.declarations[i].init) {
for (var declar of (node.declarations: Array)) {
if (declar.init) {
// has an init so let's split it up over multiple lines
hasInits = true;
}
}
}
var sep = ",";
if (!this.format.compact && hasInits) {
sep += `\n${repeating(" ", node.kind.length + 1)}`;
} else {
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)}`;
}
//
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;
}
this.semicolon();
}
/**
* Prints VariableDeclarator, handles id, id.typeAnnotation, and init.
*/
export function VariableDeclarator(node, print) {
print(node.id);
print(node.id.typeAnnotation);
print.plain(node.id);
print.plain(node.id.typeAnnotation);
if (node.init) {
this.space();
this.push("=");
this.space();
print(node.init);
print.plain(node.init);
}
}

View File

@@ -1,29 +1,39 @@
import each from "lodash/collection/each";
/**
* Prints TaggedTemplateExpression, prints tag and quasi.
*/
export function TaggedTemplateExpression(node, print) {
print(node.tag);
print(node.quasi);
print.plain(node.tag);
print.plain(node.quasi);
}
/**
* Prints TemplateElement, prints value.
*/
export function TemplateElement(node) {
this._push(node.value.raw);
}
/**
* Prints TemplateLiteral, prints quasis, and expressions.
*/
export function TemplateLiteral(node, print) {
this.push("`");
var quasis = node.quasis;
var len = quasis.length;
each(quasis, (quasi, i) => {
print(quasi);
for (var i = 0; i < len; i++) {
print.plain(quasis[i]);
if (i + 1 < len) {
this.push("${ ");
print(node.expressions[i]);
print.plain(node.expressions[i]);
this.push(" }");
}
});
}
this._push("`");
}

View File

@@ -1,16 +1,36 @@
import each from "lodash/collection/each";
/* eslint quotes: 0 */
import isInteger from "is-integer";
import * as t from "../../types";
/**
* Prints Identifier, prints name.
*/
export function Identifier(node) {
this.push(node.name);
}
/**
* Prints RestElement, prints argument.
*/
export function RestElement(node, print) {
this.push("...");
print(node.argument);
print.plain(node.argument);
}
/**
* Alias RestElement printer as SpreadElement,
* and RestElement printer as SpreadProperty.
*/
export { RestElement as SpreadElement, RestElement as SpreadProperty };
/**
* Prints ObjectExpression, prints properties.
*/
export function ObjectExpression(node, print) {
var props = node.properties;
@@ -27,34 +47,62 @@ export function ObjectExpression(node, print) {
}
}
/**
* Alias ObjectExpression printer as ObjectPattern.
*/
export { ObjectExpression as ObjectPattern };
/**
* Prints Property, prints decorators, key, and value, handles kind, computed, and shorthand.
*/
export function Property(node, print) {
print.list(node.decorators, { separator: "" });
if (node.method || node.kind === "get" || node.kind === "set") {
this._method(node, print);
} else {
if (node.computed) {
this.push("[");
print(node.key);
print.plain(node.key);
this.push("]");
} else {
print(node.key);
if (node.shorthand) return;
// print `({ foo: foo = 5 } = {})` as `({ foo = 5 } = {});`
if (t.isAssignmentPattern(node.value) && t.isIdentifier(node.key) && node.key.name === node.value.left.name) {
print.plain(node.value);
return;
}
print.plain(node.key);
// shorthand!
if (node.shorthand &&
(t.isIdentifier(node.key) &&
t.isIdentifier(node.value) &&
node.key.name === node.value.name)) {
return;
}
}
this.push(":");
this.space();
print(node.value);
print.plain(node.value);
}
}
/**
* Prints ArrayExpression, prints elements.
*/
export function ArrayExpression(node, print) {
var elems = node.elements;
var len = elems.length;
this.push("[");
each(elems, (elem, i) => {
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
if (!elem) {
// If the array expression ends with a hole, that hole
// will be ignored by the interpreter, but if it ends with
@@ -63,25 +111,52 @@ export function ArrayExpression(node, print) {
// both (all) of the holes.
this.push(",");
} else {
if (i > 0) this.push(" ");
print(elem);
if (i > 0) this.space();
print.plain(elem);
if (i < len - 1) this.push(",");
}
});
}
this.push("]");
}
/**
* Alias ArrayExpression printer as ArrayPattern.
*/
export { ArrayExpression as ArrayPattern };
export function Literal(node) {
/**
* RegExp for testing scientific notation in literals.
*/
const SCIENTIFIC_NOTATION = /e/i;
/**
* Prints Literal, prints value, regex, raw, handles val type.
*/
export function Literal(node, print, parent) {
var val = node.value;
var type = typeof val;
if (type === "string") {
this._stringLiteral(val);
} else if (type === "number") {
this.push(val + "");
// check to see if this is the same number as the raw one in the original source as asm.js uses
// numbers in the form 5.0 for type hinting
var raw = node.raw;
if (val === +raw && raw[raw.length - 1] !== "." && !/^0[bo]/i.test(raw)) {
val = raw;
}
val = val + "";
if (isInteger(+val) && t.isMemberExpression(parent, { object: node }) && !SCIENTIFIC_NOTATION.test(val)) {
val += ".";
}
this.push(val);
} else if (type === "boolean") {
this.push(val ? "true" : "false");
} else if (node.regex) {
@@ -91,6 +166,10 @@ export function Literal(node) {
}
}
/**
* Prints string literals, handles format.
*/
export function _stringLiteral(val) {
val = JSON.stringify(val);
@@ -100,9 +179,16 @@ export function _stringLiteral(val) {
});
if (this.format.quotes === "single") {
// remove double quotes
val = val.slice(1, -1);
// unescape double quotes
val = val.replace(/\\"/g, '"');
// escape single quotes
val = val.replace(/'/g, "\\'");
// add single quotes
val = `'${val}'`;
}

View File

@@ -1,5 +1,6 @@
import detectIndent from "detect-indent";
import Whitespace from "./whitespace";
import NodePrinter from "./node/printer";
import repeating from "repeating";
import SourceMap from "./source-map";
import Position from "./position";
@@ -10,9 +11,14 @@ import each from "lodash/collection/each";
import n from "./node";
import * as t from "../types";
/**
* Babel's code generator, turns an ast into code, maintaining sourcemaps,
* user preferences, and valid output.
*/
class CodeGenerator {
constructor(ast, opts, code) {
opts ||= {};
opts = opts || {};
this.comments = ast.comments || [];
this.tokens = ast.tokens || [];
@@ -20,12 +26,19 @@ class CodeGenerator {
this.opts = opts;
this.ast = ast;
this.whitespace = new Whitespace(this.tokens, this.comments, this.format);
this.whitespace = new Whitespace(this.tokens);
this.position = new Position;
this.map = new SourceMap(this.position, opts, code);
this.buffer = new Buffer(this.position, this.format);
}
/**
* Normalize generator options, setting defaults.
*
* - Detects code indentation.
* - If `opts.compact = "auto"` and the code is over 100KB, `compact` will be set to `true`.
*/
static normalizeOptions(code, opts, tokens) {
var style = " ";
if (code) {
@@ -34,9 +47,10 @@ class CodeGenerator {
}
var format = {
retainLines: opts.retainLines,
comments: opts.comments == null || opts.comments,
compact: opts.compact,
quotes: CodeGenerator.findCommonStringDelimeter(code, tokens),
quotes: CodeGenerator.findCommonStringDelimiter(code, tokens),
indent: {
adjustMultilineComment: true,
style: style,
@@ -48,14 +62,17 @@ class CodeGenerator {
format.compact = code.length > 100000; // 100KB
if (format.compact) {
console.error(messages.get("codeGeneratorDeopt", opts.filename, "100KB"));
console.error("[BABEL] " + messages.get("codeGeneratorDeopt", opts.filename, "100KB"));
}
}
return format;
}
static findCommonStringDelimeter(code, tokens) {
/**
* Determine if input code uses more single or double quotes.
*/
static findCommonStringDelimiter(code, tokens) {
var occurences = {
single: 0,
double: 0
@@ -66,7 +83,6 @@ class CodeGenerator {
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (token.type.label !== "string") continue;
if (checked >= 3) continue;
var raw = code.slice(token.start, token.end);
if (raw[0] === "'") {
@@ -76,8 +92,8 @@ class CodeGenerator {
}
checked++;
if (checked >= 3) break;
}
if (occurences.single > occurences.double) {
return "single";
} else {
@@ -85,6 +101,10 @@ class CodeGenerator {
}
}
/**
* All node generators.
*/
static generators = {
templateLiterals: require("./generators/template-literals"),
comprehensions: require("./generators/comprehensions"),
@@ -99,16 +119,24 @@ class CodeGenerator {
jsx: require("./generators/jsx")
};
/**
* Generate code and sourcemap from ast.
*
* Appends comments that weren't attached to any node to the end of the generated output.
*/
generate() {
var ast = this.ast;
this.print(ast);
var comments = [];
each(ast.comments, function (comment) {
if (!comment._displayed) comments.push(comment);
});
this._printComments(comments);
if (ast.comments) {
var comments = [];
for (var comment of (ast.comments: Array)) {
if (!comment._displayed) comments.push(comment);
}
this._printComments(comments);
}
return {
map: this.map.get(),
@@ -116,36 +144,72 @@ class CodeGenerator {
};
}
/**
* Build NodePrinter.
*/
buildPrint(parent) {
var print = (node, opts) => {
return this.print(node, parent, opts);
};
print.sequence = (nodes, opts = {}) => {
opts.statement = true;
return this.printJoin(print, nodes, opts);
};
print.join = (nodes, opts) => {
return this.printJoin(print, nodes, opts);
};
print.list = function (items, opts = {}) {
if (opts.separator == null) opts.separator = ", ";
print.join(items, opts);
};
print.block = (node) => {
return this.printBlock(print, node);
};
print.indentOnComments = (node) => {
return this.printAndIndentOnComments(print, node);
};
return print;
return new NodePrinter(this, parent);
}
/**
* [Please add a description.]
*/
catchUp(node, parent, leftParenPrinted) {
// 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)) {
needsParens = true;
this._push("(");
}
while (this.position.line < node.loc.start.line) {
this._push("\n");
}
return needsParens;
}
return false;
}
/**
* [Please add a description.]
*/
_printNewline(leading, node, parent, opts) {
if (!opts.statement && !n.isUserWhitespacable(node, parent)) {
return;
}
var lines = 0;
if (node.start != null && !node._ignoreUserWhitespace) {
// user node
if (leading) {
lines = this.whitespace.getNewlinesBefore(node);
} else {
lines = this.whitespace.getNewlinesAfter(node);
}
} else {
// generated node
if (!leading) lines++; // always include at least a single line after
if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0;
var needs = n.needsWhitespaceAfter;
if (leading) needs = n.needsWhitespaceBefore;
if (needs(node, parent)) lines++;
// generated nodes can't add starting file whitespace
if (!this.buffer.buf) lines = 0;
}
this.newline(lines);
}
/**
* [Please add a description.]
*/
print(node, parent, opts = {}) {
if (!node) return;
@@ -158,36 +222,6 @@ class CodeGenerator {
this.format.concise = true;
}
var newline = (leading) => {
if (!opts.statement && !n.isUserWhitespacable(node, parent)) {
return;
}
var lines = 0;
if (node.start != null && !node._ignoreUserWhitespace) {
// user node
if (leading) {
lines = this.whitespace.getNewlinesBefore(node);
} else {
lines = this.whitespace.getNewlinesAfter(node);
}
} else {
// generated node
if (!leading) lines++; // always include at least a single line after
if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0;
var needs = n.needsWhitespaceAfter;
if (leading) needs = n.needsWhitespaceBefore;
if (needs(node, parent)) lines++;
// generated nodes can't add starting file whitespace
if (!this.buffer.buf) lines = 0;
}
this.newline(lines);
};
if (this[node.type]) {
var needsNoLineTermParens = n.needsParensNoLineTerminator(node, parent);
var needsParens = needsNoLineTermParens || n.needsParens(node, parent);
@@ -197,7 +231,9 @@ class CodeGenerator {
this.printLeadingComments(node, parent);
newline(true);
var needsParensFromCatchup = this.catchUp(node, parent, needsParens);
this._printNewline(true, node, parent, opts);
if (opts.before) opts.before();
this.map.mark(node, "start");
@@ -208,21 +244,25 @@ class CodeGenerator {
this.newline();
this.dedent();
}
if (needsParens) this.push(")");
if (needsParens || needsParensFromCatchup) this.push(")");
this.map.mark(node, "end");
if (opts.after) opts.after();
newline(false);
this.format.concise = oldConcise;
this._printNewline(false, node, parent, opts);
this.printTrailingComments(node, parent);
} else {
throw new ReferenceError(`unknown node of type ${JSON.stringify(node.type)} with constructor ${JSON.stringify(node && node.constructor.name)}`);
}
this.format.concise = oldConcise;
}
/**
* [Please add a description.]
*/
printJoin(print, nodes, opts = {}) {
if (!nodes || !nodes.length) return;
@@ -230,44 +270,59 @@ class CodeGenerator {
if (opts.indent) this.indent();
each(nodes, (node, i) => {
print(node, {
statement: opts.statement,
addNewlines: opts.addNewlines,
after: () => {
if (opts.iterator) {
opts.iterator(node, i);
}
if (opts.separator && i < len - 1) {
this.push(opts.separator);
}
var printOpts = {
statement: opts.statement,
addNewlines: opts.addNewlines,
after: () => {
if (opts.iterator) {
opts.iterator(node, i);
}
});
});
if (opts.separator && i < len - 1) {
this.push(opts.separator);
}
}
};
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
print.plain(node, printOpts);
}
if (opts.indent) this.dedent();
}
/**
* [Please add a description.]
*/
printAndIndentOnComments(print, node) {
var indent = !!node.leadingComments;
if (indent) this.indent();
print(node);
print.plain(node);
if (indent) this.dedent();
}
/**
* [Please add a description.]
*/
printBlock(print, node) {
if (t.isEmptyStatement(node)) {
this.semicolon();
} else {
this.push(" ");
print(node);
print.plain(node);
}
}
/**
* [Please add a description.]
*/
generateComment(comment) {
var val = comment.value;
if (comment.type === "Line") {
if (comment.type === "CommentLine") {
val = `//${val}`;
} else {
val = `/*${val}*/`;
@@ -275,14 +330,26 @@ class CodeGenerator {
return val;
}
/**
* [Please add a description.]
*/
printTrailingComments(node, parent) {
this._printComments(this.getComments("trailingComments", node, parent));
}
/**
* [Please add a description.]
*/
printLeadingComments(node, parent) {
this._printComments(this.getComments("leadingComments", node, parent));
}
/**
* [Please add a description.]
*/
getComments(key, node, parent) {
if (t.isExpressionStatement(parent)) {
return [];
@@ -295,39 +362,50 @@ class CodeGenerator {
nodes.push(node.argument);
}
each(nodes, (node) => {
for (let node of (nodes: Array)) {
comments = comments.concat(this._getComments(key, node));
});
}
return comments;
}
/**
* [Please add a description.]
*/
_getComments(key, node) {
return (node && node[key]) || [];
}
/**
* [Please add a description.]
*/
_printComments(comments) {
if (this.format.compact) return;
if (!this.format.comments) return;
if (!comments || !comments.length) return;
each(comments, (comment) => {
for (var comment of (comments: Array)) {
var skip = false;
// find the original comment in the ast and set it as displayed
each(this.ast.comments, function (origComment) {
if (origComment.start === comment.start) {
// comment has already been output
if (origComment._displayed) skip = true;
if (this.ast.comments) {
// find the original comment in the ast and set it as displayed
for (var origComment of (this.ast.comments: Array)) {
if (origComment.start === comment.start) {
// comment has already been output
if (origComment._displayed) skip = true;
origComment._displayed = true;
return false;
origComment._displayed = true;
break;
}
}
});
}
if (skip) return;
this.catchUp(comment);
// whitespace before
this.newline(this.whitespace.getNewlinesBefore(comment));
@@ -340,9 +418,8 @@ class CodeGenerator {
}
//
if (comment.type === "Block" && this.format.indent.adjustMultilineComment) {
var offset = comment.loc.start.column;
if (comment.type === "CommentBlock" && this.format.indent.adjustMultilineComment) {
var offset = comment.loc && comment.loc.start.column;
if (offset) {
var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
val = val.replace(newlineRegex, "\n");
@@ -356,26 +433,43 @@ class CodeGenerator {
val = this.getIndent() + val;
}
//
// force a newline for line comments when retainLines is set in case the next printed node
// doesn't catch up
if (this.format.retainLines && comment.type === "CommentLine") {
val += "\n";
}
//
this._push(val);
// whitespace after
this.newline(this.whitespace.getNewlinesAfter(comment));
});
}
}
}
/**
* [Please add a description.]
*/
each(Buffer.prototype, function (fn, key) {
CodeGenerator.prototype[key] = function () {
return fn.apply(this.buffer, arguments);
};
});
/**
* [Please add a description.]
*/
each(CodeGenerator.generators, function (generator) {
extend(CodeGenerator.prototype, generator);
});
/**
* [Please add a description.]
*/
module.exports = function (ast, opts, code) {
var gen = new CodeGenerator(ast, opts, code);
return gen.generate();

View File

@@ -4,6 +4,16 @@ import each from "lodash/collection/each";
import some from "lodash/collection/some";
import * as t from "../../types";
/**
* Test if node matches a set of type-matcher pairs.
* @example
* find({
* VariableDeclaration(node, parent) {
* return true;
* }
* }, node, parent);
*/
var find = function (obj, node, parent) {
if (!obj) return;
var result;
@@ -22,16 +32,28 @@ var find = function (obj, node, parent) {
return result;
};
/**
* Whitespace and Parenthesis related methods for nodes.
*/
export default class Node {
constructor(node, parent) {
this.parent = parent;
this.node = node;
}
/**
* Test if `node` can have whitespace set by the user.
*/
static isUserWhitespacable(node) {
return t.isUserWhitespacable(node);
}
/**
* Test if a `node` requires whitespace.
*/
static needsWhitespace(node, parent, type) {
if (!node) return 0;
@@ -54,14 +76,26 @@ export default class Node {
return (linesInfo && linesInfo[type]) || 0;
}
/**
* Test if a `node` requires whitespace before it.
*/
static needsWhitespaceBefore(node, parent) {
return Node.needsWhitespace(node, parent, "before");
}
/**
* Test if a `note` requires whitespace after it.
*/
static needsWhitespaceAfter(node, parent) {
return Node.needsWhitespace(node, parent, "after");
}
/**
* Test if a `node` needs parentheses around it.
*/
static needsParens(node, parent) {
if (!parent) return false;
@@ -77,6 +111,10 @@ export default class Node {
return find(parens, node, parent);
}
/**
* [Please add a description.]
*/
static needsParensNoLineTerminator(node, parent) {
if (!parent) return false;
@@ -85,19 +123,14 @@ export default class Node {
return false;
}
if (t.isYieldExpression(parent) || t.isAwaitExpression(parent)) {
return true;
}
if (t.isContinueStatement(parent) || t.isBreakStatement(parent) ||
t.isReturnStatement(parent) || t.isThrowStatement(parent)) {
return true;
}
return false;
return t.isTerminatorless(parent);
}
}
/**
* Add all static methods from `Node` to `Node.prototype`.
*/
each(Node, function (fn, key) {
Node.prototype[key] = function () {
// Avoid leaking arguments to prevent deoptimization

View File

@@ -1,6 +1,12 @@
import each from "lodash/collection/each";
import * as t from "../../types";
/**
* Create a mapping of operators to precendence.
*
* @example
* { "==": 6, "+": 9 }
*/
const PRECEDENCE = {};
each([
@@ -21,12 +27,24 @@ each([
});
});
/**
* Test if NullableTypeAnnotation needs parentheses.
*/
export function NullableTypeAnnotation(node, parent) {
return t.isArrayTypeAnnotation(parent);
}
/**
* Alias NullableTypeAnnotation test as FunctionTypeAnnotation.
*/
export { NullableTypeAnnotation as FunctionTypeAnnotation };
/**
* Test if UpdateExpression needs parentheses.
*/
export function UpdateExpression(node, parent) {
if (t.isMemberExpression(parent) && parent.object === node) {
// (foo++).test()
@@ -34,6 +52,10 @@ export function UpdateExpression(node, parent) {
}
}
/**
* Test if ObjectExpression needs parentheses.
*/
export function ObjectExpression(node, parent) {
if (t.isExpressionStatement(parent)) {
// ({ foo: "bar" });
@@ -48,6 +70,10 @@ export function ObjectExpression(node, parent) {
return false;
}
/**
* Test if Binary needs parentheses.
*/
export function Binary(node, parent) {
if ((t.isCallExpression(parent) || t.isNewExpression(parent)) && parent.callee === node) {
return true;
@@ -78,6 +104,10 @@ export function Binary(node, parent) {
}
}
/**
* Test if BinaryExpression needs parentheses.
*/
export function BinaryExpression(node, parent) {
if (node.operator === "in") {
// var i = (1 in []);
@@ -92,6 +122,10 @@ export function BinaryExpression(node, parent) {
}
}
/**
* Test if SequenceExpression needs parentheses.
*/
export function SequenceExpression(node, parent) {
if (t.isForStatement(parent)) {
// Although parentheses wouldn't hurt around sequence
@@ -110,6 +144,10 @@ export function SequenceExpression(node, parent) {
return true;
}
/**
* Test if YieldExpression needs parentheses.
*/
export function YieldExpression(node, parent) {
return t.isBinary(parent) ||
t.isUnaryLike(parent) ||
@@ -120,14 +158,26 @@ export function YieldExpression(node, parent) {
t.isYieldExpression(parent);
}
/**
* Test if ClassExpression needs parentheses.
*/
export function ClassExpression(node, parent) {
return t.isExpressionStatement(parent);
}
/**
* Test if UnaryLike needs parentheses.
*/
export function UnaryLike(node, parent) {
return t.isMemberExpression(parent) && parent.object === node;
}
/**
* Test if FunctionExpression needs parentheses.
*/
export function FunctionExpression(node, parent) {
// function () {};
if (t.isExpressionStatement(parent)) {
@@ -145,6 +195,10 @@ export function FunctionExpression(node, parent) {
}
}
/**
* Test if ConditionalExpression needs parentheses.
*/
export function ConditionalExpression(node, parent) {
if (t.isUnaryLike(parent)) {
return true;
@@ -171,4 +225,14 @@ export function ConditionalExpression(node, parent) {
return false;
}
export { ConditionalExpression as AssignmentExpression };
/**
* Test if AssignmentExpression needs parentheses.
*/
export function AssignmentExpression(node) {
if (t.isObjectPattern(node.left)) {
return true;
} else {
return ConditionalExpression(...arguments);
}
}

View File

@@ -0,0 +1,64 @@
/**
* Printer for nodes, needs a `generator` and a `parent`.
*/
export default class NodePrinter {
constructor(generator, parent) {
this.generator = generator;
this.parent = parent;
}
/**
* Print a plain node.
*/
plain(node, opts) {
return this.generator.print(node, this.parent, opts);
}
/**
* Print a sequence of nodes as statements.
*/
sequence(nodes, opts = {}) {
opts.statement = true;
return this.generator.printJoin(this, nodes, opts);
}
/**
* Print a sequence of nodes as expressions.
*/
join(nodes, opts) {
return this.generator.printJoin(this, nodes, opts);
}
/**
* Print a list of nodes, with a customizable separator (defaults to ",").
*/
list(items, opts = {}) {
if (opts.separator == null) {
opts.separator = ",";
if (!this.generator.format.compact) opts.separator += " ";
}
return this.join(items, opts);
}
/**
* Print a block-like node.
*/
block(node) {
return this.generator.printBlock(this, node);
}
/**
* Print node and indent comments.
*/
indentOnComments(node) {
return this.generator.printAndIndentOnComments(this, node);
}
}

View File

@@ -3,6 +3,14 @@ import each from "lodash/collection/each";
import map from "lodash/collection/map";
import * as t from "../../types";
/**
* Crawl a node to test if it contains a CallExpression, a Function, or a Helper.
*
* @example
* crawl(node)
* // { hasCall: false, hasFunction: true, hasHelper: false }
*/
function crawl(node, state = {}) {
if (t.isMemberExpression(node)) {
crawl(node.object, state);
@@ -16,12 +24,16 @@ function crawl(node, state = {}) {
} else if (t.isFunction(node)) {
state.hasFunction = true;
} else if (t.isIdentifier(node)) {
state.hasHelper ||= isHelper(node.callee);
state.hasHelper = state.hasHelper || isHelper(node.callee);
}
return state;
}
/**
* Test if a node is or has a helper.
*/
function isHelper(node) {
if (t.isMemberExpression(node)) {
return isHelper(node.object) || isHelper(node.property);
@@ -36,12 +48,25 @@ function isHelper(node) {
}
}
/**
* [Please add a description.]
*/
function isType(node) {
return t.isLiteral(node) || t.isObjectExpression(node) || t.isArrayExpression(node) ||
t.isIdentifier(node) || t.isMemberExpression(node);
}
/**
* Tests for node types that need whitespace.
*/
exports.nodes = {
/**
* Test if AssignmentExpression needs whitespace.
*/
AssignmentExpression(node) {
var state = crawl(node.right);
if ((state.hasCall && state.hasHelper) || state.hasFunction) {
@@ -52,12 +77,20 @@ exports.nodes = {
}
},
/**
* Test if SwitchCase needs whitespace.
*/
SwitchCase(node, parent) {
return {
before: node.consequent.length || parent.cases[0] === node
};
},
/**
* Test if LogicalExpression needs whitespace.
*/
LogicalExpression(node) {
if (t.isFunction(node.left) || t.isFunction(node.right)) {
return {
@@ -66,6 +99,10 @@ exports.nodes = {
}
},
/**
* Test if Literal needs whitespace.
*/
Literal(node) {
if (node.value === "use strict") {
return {
@@ -74,6 +111,10 @@ exports.nodes = {
}
},
/**
* Test if CallExpression needs whitespace.
*/
CallExpression(node) {
if (t.isFunction(node.callee) || isHelper(node)) {
return {
@@ -83,6 +124,10 @@ exports.nodes = {
}
},
/**
* Test if VariableDeclaration needs whitespace.
*/
VariableDeclaration(node) {
for (var i = 0; i < node.declarations.length; i++) {
var declar = node.declarations[i];
@@ -102,6 +147,10 @@ exports.nodes = {
}
},
/**
* Test if IfStatement needs whitespace.
*/
IfStatement(node) {
if (t.isBlockStatement(node.consequent)) {
return {
@@ -112,6 +161,10 @@ exports.nodes = {
}
};
/**
* Test if Property or SpreadProperty needs whitespace.
*/
exports.nodes.Property =
exports.nodes.SpreadProperty = function (node, parent) {
if (parent.properties[0] === node) {
@@ -121,20 +174,41 @@ exports.nodes.SpreadProperty = function (node, parent) {
}
};
/**
* Returns lists from node types that need whitespace.
*/
exports.list = {
/**
* Return VariableDeclaration declarations init properties.
*/
VariableDeclaration(node) {
return map(node.declarations, "init");
},
/**
* Return VariableDeclaration elements.
*/
ArrayExpression(node) {
return node.elements;
},
/**
* Return VariableDeclaration properties.
*/
ObjectExpression(node) {
return node.properties;
}
};
/**
* Add whitespace tests for nodes and their aliases.
*/
each({
Function: true,
Class: true,

View File

@@ -1,9 +1,17 @@
/**
* Track current position in code generation.
*/
export default class Position {
constructor() {
this.line = 1;
this.column = 0;
}
/**
* Push a string to the current position, mantaining the current line and column.
*/
push(str) {
for (var i = 0; i < str.length; i++) {
if (str[i] === "\n") {
@@ -15,6 +23,10 @@ export default class Position {
}
}
/**
* Unshift a string from the current position, mantaining the current line and column.
*/
unshift(str) {
for (var i = 0; i < str.length; i++) {
if (str[i] === "\n") {

View File

@@ -1,6 +1,10 @@
import sourceMap from "source-map";
import * as t from "../types";
/**
* Build a sourcemap.
*/
export default class SourceMap {
constructor(position, opts, code) {
this.position = position;
@@ -8,7 +12,7 @@ export default class SourceMap {
if (opts.sourceMaps) {
this.map = new sourceMap.SourceMapGenerator({
file: opts.sourceMapName,
file: opts.sourceMapTarget,
sourceRoot: opts.sourceRoot
});
@@ -18,6 +22,10 @@ export default class SourceMap {
}
}
/**
* Get the sourcemap.
*/
get() {
var map = this.map;
if (map) {
@@ -27,6 +35,10 @@ export default class SourceMap {
}
}
/**
* Mark a node's generated position, and add it to the sourcemap.
*/
mark(node, type) {
var loc = node.loc;
if (!loc) return; // no location info

View File

@@ -1,5 +1,3 @@
import sortBy from "lodash/collection/sortBy";
/**
* Returns `i`th number from `base`, continuing from 0 when `max` is reached.
* Useful for shifting `for` loop by a fixed number but going over all items.
@@ -20,9 +18,13 @@ function getLookupIndex(i, base, max) {
return i;
}
/**
* Get whitespace around tokens.
*/
export default class Whitespace {
constructor(tokens, comments) {
this.tokens = sortBy(tokens.concat(comments), "start");
constructor(tokens) {
this.tokens = tokens;
this.used = {};
// Profiling this code shows that while generator passes over it, indexes
@@ -36,16 +38,19 @@ export default class Whitespace {
this._lastFoundIndex = 0;
}
/**
* Count all the newlines before a node.
*/
getNewlinesBefore(node) {
var startToken;
var endToken;
var tokens = this.tokens;
var token;
for (var j = 0; j < tokens.length; j++) {
// optimize for forward traversal by shifting for loop index
var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length);
token = tokens[i];
var token = tokens[i];
// this is the token this node starts with
if (node.start === token.start) {
@@ -60,21 +65,25 @@ export default class Whitespace {
return this.getNewlinesBetween(startToken, endToken);
}
/**
* Count all the newlines after a node.
*/
getNewlinesAfter(node) {
var startToken;
var endToken;
var tokens = this.tokens;
var token;
for (var j = 0; j < tokens.length; j++) {
// optimize for forward traversal by shifting for loop index
var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length);
token = tokens[i];
var token = tokens[i];
// this is the token this node ends with
if (node.end === token.end) {
startToken = token;
endToken = tokens[i + 1];
if (endToken.type.label === ",") endToken = tokens[i + 2];
this._lastFoundIndex = i;
break;
@@ -85,7 +94,7 @@ export default class Whitespace {
return 1;
} else {
var lines = this.getNewlinesBetween(startToken, endToken);
if (node.type === "Line" && !lines) {
if (node.type === "CommentLine" && !lines) {
// line comment
return 1;
} else {
@@ -94,6 +103,10 @@ export default class Whitespace {
}
}
/**
* Count all the newlines between two tokens.
*/
getNewlinesBetween(startToken, endToken) {
if (!endToken || !endToken.loc) return 0;

View File

@@ -0,0 +1,4 @@
## Helpers
Utilities for Babel, which is just another way to say "helpers", but I wrote it
anyways, so deal with it.

View File

@@ -4,6 +4,10 @@ import jsTokens from "js-tokens";
import esutils from "esutils";
import chalk from "chalk";
/**
* Chalk styles for token types.
*/
var defs = {
string: chalk.red,
punctuator: chalk.bold,
@@ -17,8 +21,16 @@ var defs = {
invalid: chalk.inverse
};
/**
* RegExp to test for newlines in terminal.
*/
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
/**
* Get the type of token, specifying punctuator type.
*/
function getTokenType(match) {
var token = jsTokens.matchToToken(match);
if (token.type === "name" && esutils.keyword.isReservedWordES6(token.value)) {
@@ -42,6 +54,10 @@ function getTokenType(match) {
return token.type;
}
/**
* Highlight `text`.
*/
function highlight(text) {
return text.replace(jsTokens, function (...args) {
var type = getTokenType(args);
@@ -54,6 +70,10 @@ function highlight(text) {
});
}
/**
* Create a code frame, adding line numbers, code highlighting, and pointing to a given position.
*/
export default function (lines: number, lineNumber: number, colNumber: number, opts = {}): string {
colNumber = Math.max(colNumber, 0);
@@ -79,10 +99,12 @@ export default function (lines: number, lineNumber: number, colNumber: number, o
if (params.number !== lineNumber) {
return;
}
if (colNumber) {
params.line += `\n${params.before}${repeating(" ", params.width)}${params.after}${repeating(" ", colNumber - 1)}^`;
}
params.before = params.before.replace(/^./, ">");
}
}).join("\n");
};
}

View File

@@ -0,0 +1,21 @@
import merge from "lodash/object/merge";
/**
* Merge options.
*/
export default function (dest, src) {
if (!dest || !src) return;
return merge(dest, src, function (a, b) {
if (b && Array.isArray(a)) {
var c = a.slice(0);
for (var v of b) {
if (a.indexOf(v) < 0) {
c.push(v);
}
}
return c;
}
});
}

View File

@@ -1,9 +1,15 @@
import * as t from "../types";
/**
* Normalize an AST.
*
* - Wrap `Program` node with a `File` node.
*/
export default function (ast, comments, tokens) {
if (ast && ast.type === "Program") {
return t.file(ast, comments || [], tokens || []);
} else {
throw new Error("Not a valid ast?");
}
};
}

View File

@@ -1,3 +1,7 @@
/**
* Create an object with a `null` prototype.
*/
export default function () {
return Object.create(null);
};
}

View File

@@ -1,65 +1,62 @@
import normalizeAst from "./normalize-ast";
import estraverse from "estraverse";
import codeFrame from "./code-frame";
import * as acorn from "../../acorn";
export default function (opts, code, callback) {
try {
var comments = [];
var tokens = [];
/**
* Parse `code` with normalized options, collecting tokens and comments.
*/
var parseOpts = {
allowImportExportEverywhere: opts.looseModules,
allowReturnOutsideFunction: opts.looseModules,
ecmaVersion: 6,
strictMode: opts.strictMode,
sourceType: opts.sourceType,
onComment: comments,
locations: true,
features: opts.features || {},
plugins: opts.plugins || {},
onToken: tokens,
ranges: true
export default function (code, opts = {}) {
var commentsAndTokens = [];
var comments = [];
var tokens = [];
var parseOpts = {
allowImportExportEverywhere: opts.looseModules,
allowReturnOutsideFunction: opts.looseModules,
allowHashBang: true,
ecmaVersion: 6,
strictMode: opts.strictMode,
sourceType: opts.sourceType,
locations: true,
features: opts.features || {},
plugins: opts.plugins || {},
onToken: tokens,
ranges: true
};
/**
* Collect all tokens.
*/
parseOpts.onToken = function (token) {
tokens.push(token);
commentsAndTokens.push(token);
};
/**
* Collection all comments.
*/
parseOpts.onComment = function (block, text, start, end, startLoc, endLoc) {
var comment = {
type: block ? "CommentBlock" : "CommentLine",
value: text,
start: start,
end: end,
loc: new acorn.SourceLocation(this, startLoc, endLoc),
range: [start, end]
};
if (opts.nonStandard) {
parseOpts.plugins.jsx = true;
parseOpts.plugins.flow = true;
}
commentsAndTokens.push(comment);
comments.push(comment);
};
var ast = acorn.parse(code, parseOpts);
estraverse.attachComments(ast, comments, tokens);
ast = normalizeAst(ast, comments, tokens);
if (callback) {
return callback(ast);
} else {
return ast;
}
} catch (err) {
if (!err._babel) {
err._babel = true;
var message = err.message = `${opts.filename}: ${err.message}`;
var loc = err.loc;
if (loc) {
err.codeFrame = codeFrame(code, loc.line, loc.column + 1, opts);
message += "\n" + err.codeFrame;
}
if (err.stack) {
var newStack = err.stack.replace(err.message, message);
try {
err.stack = newStack;
} catch (e) {
// `err.stack` may be a readonly property in some environments
}
}
}
throw err;
if (opts.nonStandard) {
parseOpts.plugins.jsx = true;
parseOpts.plugins.flow = true;
}
};
var ast = acorn.parse(code, parseOpts);
estraverse.attachComments(ast, comments, tokens);
ast = normalizeAst(ast, comments, commentsAndTokens);
return ast;
}

View File

@@ -1,42 +1,82 @@
import * as util from "util";
/**
* Mapping of messages to be used in Babel.
* Messages can include $0-style placeholders.
*/
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",
classesIllegalConstructorKind: "Illegal kind for constructor method",
scopeDuplicateDeclaration: "Duplicate declaration $1",
undeclaredVariable: "Reference to undeclared variable $1",
undeclaredVariableSuggestion: "Reference to undeclared variable $1 - did you mean $2?",
settersInvalidParamLength: "Setters must have exactly one parameter",
settersNoRest: "Setters aren't allowed to have a rest",
noAssignmentsInForHead: "No assignments allowed in for-in/of head",
expectedMemberExpressionOrIdentifier: "Expected type MemeberExpression or Identifier",
expectedMemberExpressionOrIdentifier: "Expected type MemberExpression or Identifier",
invalidParentForThisNode: "We don't know how to handle this node within the current parent - please open an issue",
readOnly: "$1 is read-only",
modulesIllegalExportName: "Illegal export $1",
unknownForHead: "Unknown node type $1 in ForStatement",
didYouMean: "Did you mean $1?",
evalInStrictMode: "eval is not allowed in strict mode",
codeGeneratorDeopt: "Note: The code generator has deoptimised the styling of $1 as it exceeds the max of $2.",
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"
illegalMethodName: "Illegal method name $1",
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",
undeclaredVariable: "Reference to undeclared variable $1",
undeclaredVariableType: "Referencing a type alias outside of a type annotation",
undeclaredVariableSuggestion: "Reference to undeclared variable $1 - did you mean $2?",
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",
pluginIllegalKind: "Illegal kind $1 for plugin $2",
pluginIllegalPosition: "Illegal position $1 for plugin $2",
pluginKeyCollision: "The plugin $1 collides with another of the same name",
pluginNotTransformer: "The plugin $1 didn't export a Plugin instance",
pluginUnknown: "Unknown plugin $1",
pluginNotFile: "Plugin $1 is resolving to a different Babel version than what is performing the transformation.",
pluginInvalidProperty: "Plugin $1 provided an invalid property of $2.",
pluginInvalidPropertyVisitor: `Define your visitor methods inside a \`visitor\` property like so:
new Plugin("foobar", {
visitor: {
// define your visitor methods here!
}
});
`
};
export function get(key: String, ...args) {
/**
* Get a message with $0 placeholders replaced by arguments.
*/
export function get(key: string, ...args): string {
var msg = MESSAGES[key];
if (!msg) throw new ReferenceError(`Unknown message ${JSON.stringify(key)}`);
// stringify args
args = parseArgs(args);
// replace $0 placeholders with args
return msg.replace(/\$(\d+)/g, function (str, i) {
return args[--i];
});
}
export function parseArgs(args: Array<any>) {
/**
* Stingify arguments to be used inside messages.
*/
export function parseArgs(args: Array<any>): Array<string> {
return args.map(function (val) {
if (val != null && val.inspect) {
return val.inspect();

View File

@@ -1,58 +1,7 @@
import estraverse from "estraverse";
import extend from "lodash/object/extend";
import types from "ast-types";
import * as t from "./types";
// estraverse
extend(estraverse.VisitorKeys, t.VISITOR_KEYS);
// regenerator/ast-types
var def = types.Type.def;
var or = types.Type.or;
//def("File")
// .bases("Node")
// .build("program")
// .field("program", def("Program"));
def("AssignmentPattern")
.bases("Pattern")
.build("left", "right")
.field("left", def("Pattern"))
.field("right", def("Expression"));
def("RestElement")
.bases("Pattern")
.build("argument")
.field("argument", def("expression"));
def("DoExpression")
.bases("Expression")
.build("body")
.field("body", [def("Statement")]);
def("ExportDefaultDeclaration")
.bases("Declaration")
.build("declaration")
.field("declaration", or(
def("Declaration"),
def("Expression"),
null
));
def("ExportNamedDeclaration")
.bases("Declaration")
.build("declaration")
.field("declaration", or(
def("Declaration"),
def("Expression"),
null
))
.field("specifiers", [or(
def("ExportSpecifier")
)])
.field("source", or(def("ModuleSpecifier"), null));
types.finalize();

15
src/babel/tools/README.md Normal file
View File

@@ -0,0 +1,15 @@
## Tools
> This directory is best browsed while listening to
> https://www.youtube.com/watch?v=hglVqACd1C8.
### Protect Babel
The protect script seen here is to throw errors if someone ever tries to
include internal babel files in their script. If you need something to be
exposed, you should ask for it, not try to hack your way into getting it.
### External Helpers
You'll also find the script for building the external helpers file, this is
the Babel "runtime" where all helper functions go instead of the top of a file.

View File

@@ -5,6 +5,10 @@ import File from "../transformation/file";
import each from "lodash/collection/each";
import * as t from "../types";
/**
* [Please add a description.]
*/
function buildGlobal(namespace, builder) {
var body = [];
var container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body));
@@ -22,6 +26,10 @@ function buildGlobal(namespace, builder) {
return tree;
}
/**
* [Please add a description.]
*/
function buildUmd(namespace, builder) {
var body = [];
body.push(t.variableDeclaration("var", [
@@ -41,6 +49,10 @@ function buildUmd(namespace, builder) {
return t.program([container]);
}
/**
* [Please add a description.]
*/
function buildVar(namespace, builder) {
var body = [];
body.push(t.variableDeclaration("var", [
@@ -50,6 +62,10 @@ function buildVar(namespace, builder) {
return t.program(body);
}
/**
* [Please add a description.]
*/
function buildHelpers(body, namespace, whitelist) {
each(File.helpers, function (name) {
if (whitelist && whitelist.indexOf(name) === -1) return;
@@ -61,6 +77,10 @@ function buildHelpers(body, namespace, whitelist) {
});
}
/**
* [Please add a description.]
*/
export default function (whitelist, outputType = "global") {
var namespace = t.identifier("babelHelpers");
@@ -83,4 +103,4 @@ export default function (whitelist, outputType = "global") {
}
return generator(tree).code;
};
}

View File

@@ -0,0 +1,14 @@
import path from "path";
var root = path.resolve(__dirname, "../../../");
/**
* Protect Babel internals from being hotlinked by other tools.
* Sorry, not sorry.
*/
export default function (module) {
if (module.parent && module.parent.filename.indexOf(root) !== 0) {
throw new Error("Don't hotlink internal Babel files.");
}
}

View File

@@ -1,54 +0,0 @@
import stripJsonComments from "strip-json-comments";
import merge from "lodash/object/merge";
import path from "path";
import fs from "fs";
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);
}
export default function (loc, opts = {}) {
var rel = ".babelrc";
function find(start, rel) {
var file = path.join(start, rel);
if (exists(file)) {
var content = fs.readFileSync(file, "utf8");
var json;
try {
json = jsons[content] ||= JSON.parse(stripJsonComments(content));
} catch (err) {
err.message = `${file}: ${err.message}`;
throw err;
}
if (json.breakConfig) return;
merge(opts, json, function(a, b) {
if (Array.isArray(a)) {
return a.concat(b);
}
});
}
var up = path.dirname(start);
if (up !== start) { // root
find(up, rel);
}
}
if (opts.breakConfig !== true) {
find(loc, rel);
}
return opts;
};

View File

@@ -0,0 +1,3 @@
## Transformation
This is the Transformation directory.

View File

@@ -0,0 +1,3 @@
## File Transformation
This is the File Transformation directory.

View File

@@ -1,67 +1,74 @@
import convertSourceMap from "convert-source-map";
import * as optionParsers from "./option-parsers";
import moduleFormatters from "../modules";
import OptionManager from "./options/option-manager";
import PluginManager from "./plugin-manager";
import shebangRegex from "shebang-regex";
import TraversalPath from "../../traversal/path";
import NodePath from "../../traversal/path";
import isFunction from "lodash/lang/isFunction";
import isAbsolute from "path-is-absolute";
import resolveRc from "../../tools/resolve-rc";
import sourceMap from "source-map";
import transform from "./../index";
import generate from "../../generation";
import codeFrame from "../../helpers/code-frame";
import defaults from "lodash/object/defaults";
import includes from "lodash/collection/includes";
import traverse from "../../traversal";
import assign from "lodash/object/assign";
import Logger from "./logger";
import Plugin from "../plugin";
import parse from "../../helpers/parse";
import Scope from "../../traversal/scope";
import slash from "slash";
import Hub from "../../traversal/hub";
import * as util from "../../util";
import path from "path";
import each from "lodash/collection/each";
import * as t from "../../types";
var checkTransformerVisitor = {
enter(node, parent, scope, state) {
checkNode(state.stack, node, scope);
}
};
function checkNode(stack, node, scope) {
each(stack, function (pass) {
if (pass.shouldRun || pass.ran) return;
pass.checkNode(node, scope);
});
}
/**
* [Please add a description.]
*/
export default class File {
constructor(opts = {}) {
this.dynamicImportAbsoluteDefaults = [];
this.dynamicImportIds = {};
this.dynamicImports = [];
constructor(opts = {}, pipeline) {
this.transformerDependencies = {};
this.usedHelpers = {};
this.dynamicData = {};
this.data = {};
this.uids = {};
this.dynamicImportTypes = {};
this.dynamicImportIds = {};
this.dynamicImports = [];
this.lastStatements = [];
this.log = new Logger(this, opts.filename || "unknown");
this.opts = this.normalizeOptions(opts);
this.ast = {};
this.declarations = {};
this.usedHelpers = {};
this.dynamicData = {};
this.data = {};
this.metadata = {
modules: {
imports: [],
exports: {
exported: [],
specifiers: []
}
}
};
this.pipeline = pipeline;
this.log = new Logger(this, opts.filename || "unknown");
this.opts = this.initOptions(opts);
this.ast = {};
this.buildTransformers();
this.hub = new Hub(this);
}
/**
* [Please add a description.]
*/
static helpers = [
"inherits",
"defaults",
"create-class",
"create-decorated-class",
"create-decorated-object",
"define-decorated-property-descriptor",
"tagged-template-literal",
"tagged-template-literal-loose",
"interop-require",
"to-array",
"to-consumable-array",
"sliced-to-array",
@@ -73,6 +80,7 @@ export default class File {
"define-property",
"async-to-generator",
"interop-require-wildcard",
"interop-require-default",
"typeof",
"extends",
"get",
@@ -82,63 +90,31 @@ export default class File {
"temporal-undefined",
"temporal-assert-defined",
"self-global",
"default-props"
"default-props",
"instanceof",
// legacy
"interop-require"
];
/**
* [Please add a description.]
*/
static soloHelpers = [];
static options = require("./options");
normalizeOptions(opts: Object) {
opts = assign({}, opts);
/**
* [Please add a description.]
*/
if (opts.filename) {
var rcFilename = opts.filename;
if (!isAbsolute(rcFilename)) rcFilename = path.join(process.cwd(), rcFilename);
opts = resolveRc(rcFilename, opts);
}
//
for (let key in opts) {
if (key[0] === "_") continue;
let option = File.options[key];
if (!option) this.log.error(`Unknown option: ${key}`, ReferenceError);
}
for (let key in File.options) {
let option = File.options[key];
var val = opts[key];
if (!val && option.optional) continue;
if (val && option.deprecated) {
throw new Error("Deprecated option " + key + ": " + option.deprecated);
}
if (val == null) val = option.default || val;
var optionParser = optionParsers[option.type];
if (optionParser) val = optionParser(key, val);
if (option.alias) {
opts[option.alias] ||= val;
} else {
opts[key] = val;
}
}
initOptions(opts) {
opts = new OptionManager(this.log, this.pipeline).init(opts);
if (opts.inputSourceMap) {
opts.sourceMaps = true;
}
// normalize windows path separators to unix
opts.filename = slash(opts.filename);
if (opts.sourceRoot) {
opts.sourceRoot = slash(opts.sourceRoot);
}
if (opts.moduleId) {
opts.moduleIds = true;
}
@@ -146,7 +122,8 @@ export default class File {
opts.basename = path.basename(opts.filename, path.extname(opts.filename));
opts.ignore = util.arrayify(opts.ignore, util.regexify);
opts.only = util.arrayify(opts.only, util.regexify);
if (opts.only) opts.only = util.arrayify(opts.only, util.regexify);
defaults(opts, {
moduleRoot: opts.sourceRoot
@@ -162,7 +139,7 @@ export default class File {
defaults(opts, {
sourceFileName: opts.filenameRelative,
sourceMapName: opts.filenameRelative
sourceMapTarget: opts.filenameRelative
});
//
@@ -172,12 +149,20 @@ export default class File {
}
return opts;
};
}
/**
* [Please add a description.]
*/
isLoose(key: string) {
return includes(this.opts.loose, key);
}
/**
* [Please add a description.]
*/
buildTransformers() {
var file = this;
@@ -187,8 +172,9 @@ export default class File {
var stack = [];
// build internal transformers
each(transform.transformers, function (transformer, key) {
var pass = transformers[key] = transformer.buildPass(file);
for (var key in this.pipeline.transformers) {
var transformer = this.pipeline.transformers[key];
let pass = transformers[key] = transformer.buildPass(file);
if (pass.canTransform()) {
stack.push(pass);
@@ -201,121 +187,96 @@ export default class File {
transformer.manipulateOptions(file.opts, file);
}
}
});
}
// init plugins!
var beforePlugins = [];
var afterPlugins = [];
var pluginManager = new PluginManager({
file: this,
transformers: this.transformers,
before: beforePlugins,
after: afterPlugins
});
for (var i = 0; i < file.opts.plugins.length; i++) {
this.addPlugin(file.opts.plugins[i], beforePlugins, afterPlugins);
pluginManager.add(file.opts.plugins[i]);
}
stack = beforePlugins.concat(stack, afterPlugins);
// register
this.transformerStack = stack.concat(secondaryStack);
}
// build transformer stack
this.uncollapsedTransformerStack = stack = stack.concat(secondaryStack);
getModuleFormatter(type: string) {
var ModuleFormatter = isFunction(type) ? type : transform.moduleFormatters[type];
if (!ModuleFormatter) {
var loc = util.resolveRelative(type);
if (loc) ModuleFormatter = require(loc);
// build dependency graph
for (let pass of (stack: Array)) {
for (var dep of (pass.plugin.dependencies: Array)) {
this.transformerDependencies[dep] = pass.key;
}
}
if (!ModuleFormatter) {
throw new ReferenceError(`Unknown module formatter type ${JSON.stringify(type)}`);
}
return new ModuleFormatter(this);
// collapse stack categories
this.transformerStack = this.collapseStack(stack);
}
addPlugin(name, before, after) {
var position = "before";
var plugin;
/**
* [Please add a description.]
*/
if (name) {
if (typeof name === "string") {
// this is a plugin in the form of "foobar" or "foobar:after"
// where the optional colon is the delimiter for plugin position in the transformer stack
collapseStack(_stack) {
var stack = [];
var ignore = [];
[name, position = "before"] = name.split(":");
for (let pass of (_stack: Array)) {
// been merged
if (ignore.indexOf(pass) >= 0) continue;
var loc = util.resolveRelative(name) || util.resolveRelative(`babel-plugin-${name}`);
if (loc) {
plugin = require(loc)
} else {
throw new ReferenceError(`Unknown plugin ${JSON.stringify(name)}`);
var group = pass.plugin.metadata.group;
// can't merge
if (!pass.canTransform() || !group) {
stack.push(pass);
continue;
}
var mergeStack = [];
for (let pass of (_stack: Array)) {
if (pass.plugin.metadata.group === group) {
mergeStack.push(pass);
ignore.push(pass);
}
} else {
// not a string so we'll just assume that it's a direct Transformer instance, if not then
// the checks later on will complain
plugin = name;
}
} else {
throw new TypeError(`Ilegal kind ${typeof name} for plugin name ${JSON.stringify(name)}`);
}
// validate position
if (position !== "before" && position !== "after") {
throw new TypeError(`Plugin ${JSON.stringify(name)} has an illegal position of ${JSON.stringify(position)}`);
}
// validate transformer key
var key = plugin.key;
if (this.transformers[key]) {
throw new ReferenceError(`The key for plugin ${JSON.stringify(name)} of ${key} collides with an existing plugin`);
}
// validate Transformer instance
if (!plugin.buildPass || plugin.constructor.name !== "Transformer") {
throw new TypeError(`Plugin ${JSON.stringify(name)} didn't export a default Transformer instance`);
}
// build!
var pass = this.transformers[key] = plugin.buildPass(this);
if (pass.canTransform()) {
var stack = before;
if (position === "after") stack = after;
stack.push(pass);
}
}
parseInputSourceMap(code: string) {
var opts = this.opts;
if (opts.inputSourceMap !== false) {
var inputMap = convertSourceMap.fromSource(code);
if (inputMap) {
opts.inputSourceMap = inputMap.toObject();
code = convertSourceMap.removeComments(code);
var visitors = [];
for (let pass of (mergeStack: Array)) {
visitors.push(pass.plugin.visitor);
}
var visitor = traverse.visitors.merge(visitors);
var mergePlugin = new Plugin(group, { visitor });
stack.push(mergePlugin.buildPass(this));
}
return code;
return stack;
}
parseShebang(code: string) {
var shebangMatch = shebangRegex.exec(code);
if (shebangMatch) {
this.shebang = shebangMatch[0];
// remove shebang
code = code.replace(shebangRegex, "");
}
return code;
}
/**
* [Please add a description.]
*/
set(key: string, val): any {
return this.data[key] = val;
};
}
/**
* [Please add a description.]
*/
setDynamic(key: string, fn: Function) {
this.dynamicData[key] = fn;
}
/**
* [Please add a description.]
*/
get(key: string): any {
var data = this.data[key];
if (data) {
@@ -328,14 +289,22 @@ export default class File {
}
}
/**
* [Please add a description.]
*/
resolveModuleSource(source: string): string {
var resolveModuleSource = this.opts.resolveModuleSource;
if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename);
return source;
}
addImport(source: string, name?: string, absoluteDefault?: boolean): Object {
name ||= source;
/**
* [Please add a description.]
*/
addImport(source: string, name?: string, type?: string): Object {
name = name || source;
var id = this.dynamicImportIds[name];
if (!id) {
@@ -345,10 +314,14 @@ export default class File {
var specifiers = [t.importDefaultSpecifier(id)];
var declar = t.importDeclaration(specifiers, t.literal(source));
declar._blockHoist = 3;
if (absoluteDefault) this.dynamicImportAbsoluteDefaults.push(declar);
if (type) {
var modules = this.dynamicImportTypes[type] = this.dynamicImportTypes[type] || [];
modules.push(declar);
}
if (this.transformers["es6.modules"].canTransform()) {
this.moduleFormatter.importSpecifier(specifiers[0], declar, this.dynamicImports);
this.moduleFormatter.importSpecifier(specifiers[0], declar, this.dynamicImports, this.scope);
this.moduleFormatter.hasLocalImports = true;
} else {
this.dynamicImports.push(declar);
@@ -358,22 +331,36 @@ export default class File {
return id;
}
isConsequenceExpressionStatement(node: Object): boolean {
return t.isExpressionStatement(node) && this.lastStatements.indexOf(node) >= 0;
}
/**
* [Please add a description.]
*/
attachAuxiliaryComment(node: Object): Object {
var comment = this.opts.auxiliaryComment;
if (comment) {
node.leadingComments ||= [];
var beforeComment = this.opts.auxiliaryCommentBefore;
if (beforeComment) {
node.leadingComments = node.leadingComments || [];
node.leadingComments.push({
type: "Line",
value: " " + comment
type: "CommentLine",
value: " " + beforeComment
});
}
var afterComment = this.opts.auxiliaryCommentAfter;
if (afterComment) {
node.trailingComments = node.trailingComments || [];
node.trailingComments.push({
type: "CommentLine",
value: " " + afterComment
});
}
return node;
}
/**
* [Please add a description.]
*/
addHelper(name: string): Object {
var isSolo = includes(File.soloHelpers, name);
@@ -381,10 +368,8 @@ export default class File {
throw new ReferenceError(`Unknown helper ${name}`);
}
var program = this.ast.program;
var declar = program._declarations && program._declarations[name];
if (declar) return declar.id;
var declar = this.declarations[name];
if (declar) return declar;
this.usedHelpers[name] = true;
@@ -400,47 +385,99 @@ export default class File {
}
var ref = util.template("helper-" + name);
ref._compact = true;
var uid = this.scope.generateUidIdentifier(name);
this.scope.push({
key: name,
id: uid,
init: ref
});
var uid = this.declarations[name] = this.scope.generateUidIdentifier(name);
if (t.isFunctionExpression(ref) && !ref.id) {
ref.body._compact = true;
ref._generated = true;
ref.id = uid;
ref.type = "FunctionDeclaration";
this.attachAuxiliaryComment(ref);
this.path.unshiftContainer("body", ref);
} else {
ref._compact = true;
this.scope.push({
id: uid,
init: ref,
unique: true
});
}
return uid;
}
/**
* [Please add a description.]
*/
errorWithNode(node, msg, Error = SyntaxError) {
var loc = node.loc.start;
var err = new Error(`Line ${loc.line}: ${msg}`);
err.loc = loc;
var err;
if (node && node.loc) {
var loc = node.loc.start;
err = new Error(`Line ${loc.line}: ${msg}`);
err.loc = loc;
} else {
// todo: find errors with nodes inside to at least point to something
err = new Error("There's been an error on a dynamic node. This is almost certainly an internal error. Please report it.");
}
return err;
}
addCode(code: string) {
code = (code || "") + "";
code = this.parseInputSourceMap(code);
this.code = code;
return this.parseShebang(code);
}
/**
* [Please add a description.]
*/
shouldIgnore() {
mergeSourceMap(map: Object) {
var opts = this.opts;
return util.shouldIgnore(opts.filename, opts.ignore, opts.only);
}
parse(code: string) {
if (this.shouldIgnore()) {
return {
metadata: {},
code: code,
map: null,
ast: null
};
var inputMap = opts.inputSourceMap;
if (inputMap) {
map.sources[0] = inputMap.file;
var inputMapConsumer = new sourceMap.SourceMapConsumer(inputMap);
var outputMapConsumer = new sourceMap.SourceMapConsumer(map);
var outputMapGenerator = sourceMap.SourceMapGenerator.fromSourceMap(outputMapConsumer);
outputMapGenerator.applySourceMap(inputMapConsumer);
var mergedMap = outputMapGenerator.toJSON();
mergedMap.sources = inputMap.sources;
mergedMap.file = inputMap.file;
return mergedMap;
}
code = this.addCode(code);
return map;
}
/**
* [Please add a description.]
*/
getModuleFormatter(type: string) {
if (isFunction(type) || !moduleFormatters[type]) {
this.log.deprecate("Custom module formatters are deprecated and will be removed in the next major. Please use Babel plugins instead.");
}
var ModuleFormatter = isFunction(type) ? type : moduleFormatters[type];
if (!ModuleFormatter) {
var loc = util.resolveRelative(type);
if (loc) ModuleFormatter = require(loc);
}
if (!ModuleFormatter) {
throw new ReferenceError(`Unknown module formatter type ${JSON.stringify(type)}`);
}
return new ModuleFormatter(this);
}
/**
* [Please add a description.]
*/
parse(code: string) {
var opts = this.opts;
//
@@ -462,129 +499,217 @@ export default class File {
parseOpts.strictMode = features.strict;
parseOpts.sourceType = "module";
//
return parse(parseOpts, code, (tree) => {
this.transform(tree);
return this.generate();
});
this.log.debug("Parse start");
var tree = parse(code, parseOpts);
this.log.debug("Parse stop");
return tree;
}
setAst(ast) {
this.path = TraversalPath.get(null, null, ast, ast, "program", this);
/**
* [Please add a description.]
*/
_addAst(ast) {
this.path = NodePath.get({
hub: this.hub,
parentPath: null,
parent: ast,
container: ast,
key: "program"
}).setContext();
this.scope = this.path.scope;
this.ast = ast;
this.path.traverse({
enter(node, parent, scope) {
if (this.isScope()) {
for (var key in scope.bindings) {
scope.bindings[key].setTypeAnnotation();
}
}
}
});
}
transform(ast) {
this.log.debug();
/**
* [Please add a description.]
*/
this.setAst(ast);
this.lastStatements = t.getLastStatements(ast.program);
addAst(ast) {
this.log.debug("Start set AST");
this._addAst(ast);
this.log.debug("End set AST");
this.log.debug("Start module formatter init");
var modFormatter = this.moduleFormatter = this.getModuleFormatter(this.opts.modules);
if (modFormatter.init && this.transformers["es6.modules"].canTransform()) {
modFormatter.init();
}
this.checkNode(ast);
this.call("pre");
each(this.transformerStack, function (pass) {
pass.transform();
});
this.call("post");
this.log.debug("End module formatter init");
}
/**
* [Please add a description.]
*/
transform() {
this.call("pre");
for (var pass of (this.transformerStack: Array)) {
pass.transform();
}
this.call("post");
return this.generate();
}
/**
* [Please add a description.]
*/
wrap(code, callback) {
code = code + "";
try {
if (this.shouldIgnore()) {
return this.makeResult({ code, ignored: true });
} else {
return callback();
}
} catch (err) {
if (err._babel) {
throw err;
} else {
err._babel = true;
}
var message = err.message = `${this.opts.filename}: ${err.message}`;
var loc = err.loc;
if (loc) {
err.codeFrame = codeFrame(code, loc.line, loc.column + 1, this.opts);
message += "\n" + err.codeFrame;
}
if (err.stack) {
var newStack = err.stack.replace(err.message, message);
try {
err.stack = newStack;
} catch (e) {
// `err.stack` may be a readonly property in some environments
}
}
throw err;
}
}
/**
* [Please add a description.]
*/
addCode(code: string) {
code = (code || "") + "";
code = this.parseInputSourceMap(code);
this.code = code;
}
/**
* [Please add a description.]
*/
parseCode() {
this.parseShebang();
this.addAst(this.parse(this.code));
}
/**
* [Please add a description.]
*/
shouldIgnore() {
var opts = this.opts;
return util.shouldIgnore(opts.filename, opts.ignore, opts.only);
}
/**
* [Please add a description.]
*/
call(key: string) {
var stack = this.transformerStack;
for (var i = 0; i < stack.length; i++) {
var transformer = stack[i].transformer;
var fn = transformer[key];
for (var pass of (this.uncollapsedTransformerStack: Array)) {
var fn = pass.plugin[key];
if (fn) fn(this);
}
}
checkNode(node, scope) {
if (Array.isArray(node)) {
for (var i = 0; i < node.length; i++) {
this.checkNode(node[i], scope);
/**
* [Please add a description.]
*/
parseInputSourceMap(code: string) {
var opts = this.opts;
if (opts.inputSourceMap !== false) {
var inputMap = convertSourceMap.fromSource(code);
if (inputMap) {
opts.inputSourceMap = inputMap.toObject();
code = convertSourceMap.removeComments(code);
}
return;
}
var stack = this.transformerStack;
scope ||= this.scope;
checkNode(stack, node, scope);
scope.traverse(node, checkTransformerVisitor, {
stack: stack
});
return code;
}
mergeSourceMap(map: Object) {
var opts = this.opts;
/**
* [Please add a description.]
*/
var inputMap = opts.inputSourceMap;
if (inputMap) {
map.sources[0] = inputMap.file;
var inputMapConsumer = new sourceMap.SourceMapConsumer(inputMap);
var outputMapConsumer = new sourceMap.SourceMapConsumer(map);
var outputMapGenerator = sourceMap.SourceMapGenerator.fromSourceMap(outputMapConsumer);
outputMapGenerator.applySourceMap(inputMapConsumer);
var mergedMap = outputMapGenerator.toJSON();
mergedMap.sources = inputMap.sources
mergedMap.file = inputMap.file;
return mergedMap;
parseShebang() {
var shebangMatch = shebangRegex.exec(this.code);
if (shebangMatch) {
this.shebang = shebangMatch[0];
this.code = this.code.replace(shebangRegex, "");
}
return map;
}
generate(): {
usedHelpers?: Array<string>;
code: string;
map?: Object;
ast?: Object;
} {
var opts = this.opts;
var ast = this.ast;
/**
* [Please add a description.]
*/
makeResult({ code, map = null, ast, ignored }) {
var result = {
metadata: {},
code: "",
map: null,
ast: null
metadata: null,
ignored: !!ignored,
code: null,
ast: null,
map: map
};
if (this.opts.metadataUsedHelpers) {
if (this.opts.code) {
result.code = code;
}
if (this.opts.ast) {
result.ast = ast;
}
if (this.opts.metadata) {
result.metadata = this.metadata;
result.metadata.usedHelpers = Object.keys(this.usedHelpers);
}
if (opts.ast) result.ast = ast;
if (!opts.code) return result;
return result;
}
/**
* [Please add a description.]
*/
generate() {
var opts = this.opts;
var ast = this.ast;
var result = { ast };
if (!opts.code) return this.makeResult(result);
this.log.debug("Generation start");
var _result = generate(ast, opts, this.code);
result.code = _result.code;
result.map = _result.map;
this.log.debug("Generation end");
if (this.shebang) {
// add back shebang
result.code = `${this.shebang}\n${result.code}`;
@@ -602,6 +727,6 @@ export default class File {
result.map = null;
}
return result;
return this.makeResult(result);
}
}

View File

@@ -1,4 +1,14 @@
import * as util from "../../util";
import type File from "./index";
import buildDebug from "debug/node";
var verboseDebug = buildDebug("babel:verbose");
var generalDebug = buildDebug("babel");
var seenDeprecatedMessages = [];
/**
* [Please add a description.]
*/
export default class Logger {
constructor(file: File, filename: string) {
@@ -6,27 +16,71 @@ export default class Logger {
this.file = file;
}
/**
* [Please add a description.]
*/
_buildMessage(msg: string): string {
var parts = this.filename;
var parts = `[BABEL] ${this.filename}`;
if (msg) parts += `: ${msg}`;
return parts;
}
/**
* [Please add a description.]
*/
warn(msg) {
console.warn(this._buildMessage(msg));
}
/**
* [Please add a description.]
*/
error(msg: string, Constructor = Error) {
throw new Constructor(this._buildMessage(msg));
}
/**
* [Please add a description.]
*/
deprecate(msg) {
if (!this.file.opts.suppressDeprecationMessages) {
console.error(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);
}
/**
* [Please add a description.]
*/
verbose(msg: string) {
if (verboseDebug.enabled) verboseDebug(this._buildMessage(msg));
}
/**
* [Please add a description.]
*/
debug(msg: string) {
util.debug(this._buildMessage(msg));
if (generalDebug.enabled) generalDebug(this._buildMessage(msg));
}
/**
* [Please add a description.]
*/
deopt(node: Object, msg: string) {
util.debug(this._buildMessage(msg));
this.debug(msg);
}
}

View File

@@ -1,28 +0,0 @@
import transform from "./../index";
import * as util from "../../util";
export function transformerList(key, val) {
val = util.arrayify(val);
if (val.indexOf("all") >= 0 || val.indexOf(true) >= 0) {
val = Object.keys(transform.transformers);
}
return transform._ensureTransformerNames(key, val);
}
export function number(key, val) {
return +val;
}
export function boolean(key, val) {
return !!val;
}
export function booleanString(key, val) {
return util.booleanify(val);
}
export function list(key, val) {
return util.list(val);
}

View File

@@ -0,0 +1,3 @@
## File Options
This is the File Options directory.

View File

@@ -1,6 +1,6 @@
{
"filename": {
"type": "string",
"type": "filename",
"description": "filename to use when reading from stdin - this will be used in source-maps, errors etc",
"default": "unknown",
"shorthand": "f"
@@ -15,23 +15,45 @@
"hidden": true
},
"extra": {
"hidden": true,
"default": {}
},
"env": {
"hidden": true,
"default": {}
},
"moduleId": {
"description": "specify a custom name for module ids",
"type": "string"
},
"getModuleId": {
"hidden": true
},
"retainLines": {
"type": "boolean",
"default": false,
"description": "retain line numbers - will result in really ugly code"
},
"nonStandard": {
"type": "boolean",
"default": true,
"description": "enable support for JSX and Flow"
"description": "enable/disable support for JSX and Flow (on by default)"
},
"experimental": {
"deprecated": "use `--stage 0`/`{ stage: 0 }` instead"
"type": "boolean",
"description": "allow use of experimental transformers",
"default": false
},
"highlightCode": {
"description": "ANSI syntax highlight code frames",
"description": "enable/disable ANSI syntax highlighting of code frames (on by default)",
"type": "boolean",
"default": true
},
@@ -56,7 +78,8 @@
"blacklist": {
"type": "transformerList",
"description": "blacklist of transformers to NOT use",
"shorthand": "b"
"shorthand": "b",
"default": []
},
"whitelist": {
@@ -68,7 +91,8 @@
"optional": {
"type": "transformerList",
"description": "list of optional transformers to enable"
"description": "list of optional transformers to enable",
"default": []
},
"modules": {
@@ -100,12 +124,14 @@
"plugins": {
"type": "list",
"description": ""
"description": "",
"default": []
},
"ignore": {
"type": "list",
"description": "list of glob paths to **not** compile"
"description": "list of glob paths to **not** compile",
"default": []
},
"only": {
@@ -119,6 +145,12 @@
"type": "boolean"
},
"metadata": {
"hidden": true,
"default": true,
"type": "boolean"
},
"ast": {
"hidden": true,
"default": true,
@@ -128,7 +160,7 @@
"comments": {
"type": "boolean",
"default": true,
"description": "output comments in generated output"
"description": "strip/output comments in generated output (on by default)"
},
"compact": {
@@ -145,20 +177,32 @@
},
"auxiliaryComment": {
"deprecated": "renamed to auxiliaryCommentBefore",
"shorthand": "a",
"alias": "auxiliaryCommentBefore"
},
"auxiliaryCommentBefore": {
"type": "string",
"default": "",
"shorthand": "a",
"description": "attach a comment before all helper declarations and auxiliary code"
},
"externalHelpers": {
"auxiliaryCommentAfter": {
"type": "string",
"default": "",
"description": "attach a comment after all helper declarations and auxiliary code"
},
"externalHelpers": {
"type": "boolean",
"default": false,
"shorthand": "r",
"description": "uses a reference to `babelHelpers` instead of placing helpers at the top of your code."
},
"metadataUsedHelpers": {
"deprecated": "Not required anymore as this is enabled by default",
"type": "boolean",
"default": false,
"hidden": true
@@ -177,6 +221,11 @@
},
"sourceMapName": {
"alias": "sourceMapTarget",
"description": "DEPRECATED - Please use sourceMapTarget"
},
"sourceMapTarget": {
"type": "string",
"description": "set `file` on returned source map"
},
@@ -187,12 +236,12 @@
},
"sourceRoot": {
"type": "string",
"type": "filename",
"description": "the root from which all sources are relative"
},
"moduleRoot": {
"type": "string",
"type": "filename",
"description": "optional prefix for the AMD module formatter that will be prepend to the filename on module definitions"
},
@@ -201,6 +250,10 @@
"default": false,
"hidden": true,
"description": "stop trying to load .babelrc files"
}
},
"babelrc": {
"description": "Specify a custom list of babelrc files to use",
"type": "list"
}
}

View File

@@ -0,0 +1,39 @@
import * as parsers from "./parsers";
import config from "./config";
export { config };
/**
* Validate an option.
*/
export function validateOption(key, val, pipeline) {
var opt = config[key];
var parser = opt && parsers[opt.type];
if (parser && parser.validate) {
return parser.validate(key, val, pipeline);
} else {
return val;
}
}
/**
* Normalize all options.
*/
export function normaliseOptions(options = {}) {
for (var key in options) {
var val = options[key];
if (val == null) continue;
var opt = config[key];
if (!opt) continue;
var parser = parsers[opt.type];
if (parser) val = parser(val);
options[key] = val;
}
return options;
}

View File

@@ -0,0 +1,170 @@
import { validateOption, normaliseOptions } from "./index";
import stripJsonComments from "strip-json-comments";
import isAbsolute from "path-is-absolute";
import pathExists from "path-exists";
import clone from "lodash/lang/clone";
import merge from "../../../helpers/merge";
import config from "./config";
import path from "path";
import fs from "fs";
var existsCache = {};
var jsonCache = {};
const CONFIG_FILENAME = ".babelrc";
function exists(filename) {
var cached = existsCache[filename];
if (cached != null) {
return cached;
} else {
return existsCache[filename] = pathExists.sync(filename);
}
}
export default class OptionManager {
constructor(log, pipeline) {
this.resolvedConfigs = [];
this.options = OptionManager.createBareOptions();
this.pipeline = pipeline;
this.log = log;
}
/**
* [Please add a description.]
*/
static createBareOptions() {
var opts = {};
for (var key in config) {
var opt = config[key];
opts[key] = clone(opt.default);
}
return opts;
}
/**
* [Please add a description.]
*/
addConfig(loc) {
if (this.resolvedConfigs.indexOf(loc) >= 0) return;
var content = fs.readFileSync(loc, "utf8");
var opts;
try {
opts = jsonCache[content] = jsonCache[content] || JSON.parse(stripJsonComments(content));
} catch (err) {
err.message = `${loc}: ${err.message}`;
throw err;
}
this.mergeOptions(opts, loc);
this.resolvedConfigs.push(loc);
}
/**
* [Please add a description.]
*/
mergeOptions(opts, alias = "foreign") {
if (!opts) return;
for (let key in opts) {
if (key[0] === "_") continue;
let option = config[key];
// check for an unknown option
if (!option) this.log.error(`Unknown option: ${alias}.${key}`, ReferenceError);
}
// normalise options
normaliseOptions(opts);
// merge them into this current files options
merge(this.options, opts);
}
/**
* [Please add a description.]
*/
findConfigs(loc) {
if (!loc) return;
if (!isAbsolute(loc)) {
loc = path.join(process.cwd(), loc);
}
while (loc !== (loc = path.dirname(loc))) {
if (this.options.breakConfig) return;
var configLoc = path.join(loc, CONFIG_FILENAME);
if (exists(configLoc)) this.addConfig(configLoc);
}
}
/**
* [Please add a description.]
*/
normaliseOptions() {
var opts = this.options;
for (let key in config) {
var option = config[key];
var val = opts[key];
// optional
if (!val && option.optional) continue;
// deprecated
if (this.log && val && option.deprecated) {
this.log.deprecate(`Deprecated option ${key}: ${option.deprecated}`);
}
// validate
if (this.pipeline && val) {
val = validateOption(key, val, this.pipeline);
}
// aaliases
if (option.alias) {
opts[option.alias] = opts[option.alias] || val;
} else {
opts[key] = val;
}
}
}
/**
* [Please add a description.]
*/
init(opts) {
this.mergeOptions(opts, "direct");
// babelrc option
if (opts.babelrc) {
for (var loc of (opts.babelrc: Array)) this.addConfig(loc);
}
// resolve all .babelrc files
this.findConfigs(opts.filename);
// merge in env
var envKey = process.env.BABEL_ENV || process.env.NODE_ENV || "development";
if (this.options.env) {
this.mergeOptions(this.options.env[envKey], `direct.env.${envKey}`);
}
// normalise
this.normaliseOptions(opts);
return this.options;
}
}

View File

@@ -0,0 +1,60 @@
import slash from "slash";
import * as util from "../../../util";
/**
* Get a transformer list from a value.
*/
export function transformerList(val) {
return util.arrayify(val);
}
/**
* Validate transformer list. Maps "all" to all transformer names.
*/
transformerList.validate = function (key, val, pipeline) {
if (val.indexOf("all") >= 0 || val.indexOf(true) >= 0) {
val = Object.keys(pipeline.transformers);
}
return pipeline._ensureTransformerNames(key, val);
};
/**
* Cast a value to a number.
*/
export function number(val) {
return +val;
}
/**
* Cast a value to a boolean.
*/
export var filename = slash;
/**
* [Please add a description.]
*/
export function boolean(val) {
return !!val;
}
/**
* Cast a boolean-like string to a boolean.
*/
export function booleanString(val) {
return util.booleanify(val);
}
/**
* Cast a value to an array, splitting strings by ",".
*/
export function list(val) {
return util.list(val);
}

View File

@@ -0,0 +1,160 @@
import Transformer from "../transformer";
import Plugin from "../plugin";
import * as types from "../../types";
import * as messages from "../../messages";
import traverse from "../../traversal";
import parse from "../../helpers/parse";
/**
* [Please add a description.]
*/
var context = {
messages,
Transformer,
Plugin,
types,
parse,
traverse
};
import * as util from "../../util";
/**
* [Please add a description.]
*/
export default class PluginManager {
/**
* [Please add a description.]
*/
static memoisedPlugins = [];
/**
* [Please add a description.]
*/
static memoisePluginContainer(fn) {
for (var i = 0; i < PluginManager.memoisedPlugins.length; i++) {
var plugin = PluginManager.memoisedPlugins[i];
if (plugin.container === fn) return plugin.transformer;
}
var transformer = fn(context);
PluginManager.memoisedPlugins.push({
container: fn,
transformer: transformer
});
return transformer;
}
/**
* [Please add a description.]
*/
static positions = ["before", "after"];
/**
* [Please add a description.]
*/
constructor({ file, transformers, before, after } = { transformers: {}, before: [], after: [] }) {
this.transformers = transformers;
this.file = file;
this.before = before;
this.after = after;
}
/**
* [Please add a description.]
*/
subnormaliseString(name, position) {
// this is a plugin in the form of "foobar" or "foobar:after"
// where the optional colon is the delimiter for plugin position in the transformer stack
var match = name.match(/^(.*?):(after|before)$/);
if (match) [, name, position] = match;
var loc = util.resolveRelative(`babel-plugin-${name}`) || util.resolveRelative(name);
if (loc) {
var plugin = require(loc);
return {
position: position,
plugin: plugin.default || plugin
};
} else {
throw new ReferenceError(messages.get("pluginUnknown", name));
}
}
/**
* [Please add a description.]
*/
validate(name, plugin) {
// validate transformer key
var key = plugin.key;
if (this.transformers[key]) {
throw new ReferenceError(messages.get("pluginKeyCollision", key));
}
// validate Transformer instance
if (!plugin.buildPass || plugin.constructor.name !== "Plugin") {
throw new TypeError(messages.get("pluginNotTransformer", name));
}
// register as a plugin
plugin.metadata.plugin = true;
}
/**
* [Please add a description.]
*/
add(name) {
var position;
var plugin;
if (name) {
if (typeof name === "object" && name.transformer) {
({ transformer: plugin, position } = name);
} else if (typeof name !== "string") {
// not a string so we'll just assume that it's a direct Transformer instance, if not then
// the checks later on will complain
plugin = name;
}
if (typeof name === "string") {
({ plugin, position } = this.subnormaliseString(name, position));
}
} else {
throw new TypeError(messages.get("pluginIllegalKind", typeof name, name));
}
// default position
position = position || "before";
// validate position
if (PluginManager.positions.indexOf(position) < 0) {
throw new TypeError(messages.get("pluginIllegalPosition", position, name));
}
// allow plugin containers to be specified so they don't have to manually require
if (typeof plugin === "function") {
plugin = PluginManager.memoisePluginContainer(plugin);
}
//
this.validate(name, plugin);
// build!
var pass = this.transformers[plugin.key] = plugin.buildPass(this.file);
if (pass.canTransform()) {
var stack = position === "before" ? this.before : this.after;
stack.push(pass);
}
}
}

View File

@@ -0,0 +1,3 @@
## Transformation Helpers
This is the Transformation Helpers directory.

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