* Add sourcemap examples for identifiers in code generator.
* Generate sourcemaps with exact mappings for identifiers, even if leading/trailing tokens also use that location.
* Save full descriptor instead of only value for private fields.
Decorators can make private fields non-writable, so we need to store this
information somewhere.
The descriptor can also be used to implement private accessors.
| Q | A
| ------------------------ | ---
| Fixed Issues? | #7747 (partly)
| Patch: Bug Fix? |
| Major: Breaking Change? |
| Minor: New Feature? | Yes
| Tests Added + Pass? | Yes
| Documentation PR |
| Any Dependency Changes? |
| License | MIT
@JamesHenry This changes the AST format. CC @DanielRosenwasser for review.
Supports parsing type arguments on tagged template calls.
Should wait on Microsoft/TypeScript#23430 to be merged so we're sure we have the final syntax.
Previously, if the optional `opts` parameter wasn't passed, the _intent_ was to move the function it held into the `callback` parameter and null out the `opts` param - but instead, it was nulling both.
Just default to pipeline "minimal" and true for decorators for ease of use. We are going to remove the stage presets next so it's fine since it will error when using the plugin individually later.
| Q | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues? | Fixes https://github.com/babel/babel-loader/issues/642
| Patch: Bug Fix? | Y
| Major: Breaking Change? | N
| Minor: New Feature? |
| Tests Added + Pass? | Yes
| Documentation PR Link | <!-- If only readme change, add `[skip ci]` to your commits -->
| Any Dependency Changes? |
| License | MIT
Since these were getting left in, things that loaded the config, and then passed in back to Babel would get `test` and such _twice_, which could lead to either bad configuration merging, or no configuration at all if the patterns were relative to different directories, as was the case in https://github.com/babel/babel-loader/issues/642.
Original PR: https://github.com/babel/babel/pull/8038
Ref Issue: https://github.com/babel/babel/issues/8184
Windows paths are broken so wanted to get a fix out since I don't see us fixing it correctly soon enough? I think that's more important than fixing the security warnings that don't apply to us until we can actually handle the change, otherwise need a version of the code that doesn't use the old dep but doesn't change the windows behavior or just remove the matching which will take some time.
Fixes#8163
The `isNodesEquivalent()` algorithm incorrectly assumes that any object properties must themselves be AST nodes, which is not the case here, causing the error.
| Q | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues? | Fixes#8272 <!-- remove the (`) quotes to link the issues -->
| Patch: Bug Fix? | Yes
| Major: Breaking Change? |
| Minor: New Feature? |
| Tests Added + Pass? | Yes
| Documentation PR | <!-- If so, add `[skip ci]` to your commit message to skip CI -->
| Any Dependency Changes? |
| License | MIT
The visitor for `typeArguments` in function calls wasn't set in the definition, so type annotations added there weren't visited.
This is required to fix https://github.com/babel/babel-eslint/issues/644
This is going to be required so we can add support for other proposals,
as well as later set the accepted proposal as the default.
Update stage-0 and stage-1 presets with `pipelineProposal` to thread down to
the plugin.
* babel/parser: test helpers: when test fails with an exception and both reference output file and options.json file do not exist, write a simple options.json with the error message to expect when such a file doesn't exist yet. This completes the `jest -u` capability for new tests which are expected to *fail*.
| Q | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues? | None
| Patch: Bug Fix? | No
| Major: Breaking Change? | No
| Minor: New Feature? | No
| Tests Added + Pass? | Existing tests pass
| Documentation PR | No
| Any Dependency Changes? | `regenerator-transform` in `@babel/plugin-transform-regenerator`
| License | MIT
I recently updated `regenerator`, `regenerator-transform`, and `regenerator-preset` to fix a number of vulnerabilities surfaced by `npm audit`. There was no need to update `regenerator-runtime`, as it does not have any dependencies of its own. I'm happy to report the latest versions of these packages have zero vulnerability warnings according to `npm audit`.
While I was at it, I also updated all dependencies of these packages to their Babel 7 equivalents, so there should hopefully be fewer legacy package dependencies installed because of Regenerator.
<!--
Before making a PR please make sure to read our contributing guidelines
https://github.com/babel/babel/blob/master/CONTRIBUTING.md
For issue references: Add a comma-separated list of a [closing word](https://help.github.com/articles/closing-issues-via-commit-messages/) followed by the ticket number fixed by the PR. It should be underlined in the preview if done correctly.
-->
| Q | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues? | --
| Patch: Bug Fix? |
| Major: Breaking Change? |
| Minor: New Feature? |
| Tests Added + Pass? | Yes
| Documentation PR | <!-- If so, add `[skip ci]` to your commit message to skip CI -->
| Any Dependency Changes? |
| License | MIT
Good ol' plugin ordering 🙃
Ref: https://github.com/babel/babel/pull/7065#issuecomment-395959112
Fix a ReferenceError caused by a typo (`_construct` instead of
`construct`) in the external `wrapNativeSuper` helper. (The typo
doesn't usually cause an error in inline helpers because `_construct`
happens to be the default name given to the `construct` helper
function.)
The extra field parenthesizedArgument was never set to true. It was
always set to false and the code that read this was incorrectly
checking if extra was present.
Fixes#7957
Given the following
```js
a = <F new/>
```
We used to generate:
```js
a = React.createElement(F, {"new": true})
```
but now we generate
```js
a = React.createElement(F, {new: true})
```
If you need to quote these (ie for ES3 you can use
transform-property-literals)
<!--
Before making a PR please make sure to read our contributing guidelines
https://github.com/babel/babel/blob/master/CONTRIBUTING.md
For issue references: Add a comma-separated list of a [closing word](https://help.github.com/articles/closing-issues-via-commit-messages/) followed by the ticket number fixed by the PR. It should be underlined in the preview if done correctly.
-->
| Q | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues? | <!-- remove the (`) quotes to link the issues -->
| Patch: Bug Fix? |
| Major: Breaking Change? | No
| Minor: New Feature? | Yes
| Tests Added + Pass? | Yes
| Documentation PR | <!-- If so, add `[skip ci]` to your commit message to skip CI -->
| Any Dependency Changes? |
| License | MIT
See eb815be907 for more information about this feature.
The proto modifier indicates that a property declared using `x: T` syntax is actually present on the prototype object of the class, rather than an own property.
The proto and static modifiers are mutually exclusive, as class declarations don't simultaneously define the static prototype object, as they do the instance prototype.
This syntax is only supported on declared classes, not object types, interfaces, or runtime class declarations, and as such should only appear in library definitions.
Fixes gh-8041
<!--
Before making a PR please make sure to read our contributing guidelines
https://github.com/babel/babel/blob/master/CONTRIBUTING.md
For issue references: Add a comma-separated list of a [closing word](https://help.github.com/articles/closing-issues-via-commit-messages/) followed by the ticket number fixed by the PR. It should be underlined in the preview if done correctly.
-->
| Q | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues? | #8041
| Patch: Bug Fix? |👍
| Major: Breaking Change? |
| Minor: New Feature? |
| Tests Added + Pass? | Yes
| Documentation PR | <!-- If so, add `[skip ci]` to your commit message to skip CI -->
| Any Dependency Changes? |
| License | MIT
<!-- Describe your changes below in as much detail as possible -->
| Q | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues? |
| Patch: Bug Fix? |
| Major: Breaking Change? |
| Minor: New Feature? |
| Tests Added + Pass? | Yes
| Documentation PR | <!-- If so, add `[skip ci]` to your commit message to skip CI -->
| Any Dependency Changes? |
| License | MIT
The `all` option landed in https://github.com/babel/babel/pull/7934/files#diff-3a8233bcd2766d2c7d87f23f944f7726R3 but it is only exposed from the plugin, not the preset, so this exposes it there too since the flow preset is what we want people to use.
* Revert "Move subclass inheritance to end (#7772)"
This reverts commit f8ab9466d3.
* Only use getPrototypeOf if setPrototypeOf is implemented
* Update fixtures
* Helpers updates
* Update fixtures
* Fall back to getPrototypeOf
* Update fixtures
<!--
Before making a PR please make sure to read our contributing guidelines
https://github.com/babel/babel/blob/master/CONTRIBUTING.md
For any issue references: Add a comma-separated list of a [closing word](https://help.github.com/articles/closing-issues-via-commit-messages/) followed by the ticket number fixed by the PR
-->
| Q | A <!--(yes/no) -->
| ------------------------ | ---
| Patch: Bug Fix? |
| Major: Breaking Change? |
| Minor: New Feature? | y
| Deprecations? |
| Spec Compliancy? |
| Tests Added/Pass? | y/y
| Fixed Tickets | #5616
| License | MIT
| Doc PR | <!-- if yes, add `[skip ci]` to your commit message to skip CI builds -->
| Dependency Changes |
<!-- Describe your changes below in as much detail as possible -->
Once merged I will make the corresponding documentation changes on the website (in a 7 branch)
| Q | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues? | Fixes#8001
| Patch: Bug Fix? | Y
| Major: Breaking Change? | Not unless things were relying on a very specific AST structure as output
| Minor: New Feature? |
| Tests Added + Pass? | Yes
| Documentation PR | <!-- If so, add `[skip ci]` to your commit message to skip CI -->
| Any Dependency Changes? |
| License | MIT
The filed bug was for `-0`, but I also realize that `numericLiteral` also shouldn't be getting `-Infinity`/`Infinity` or `NaN` since those just get stringified with the JS-standard stringification logic which means we get a reference to `NaN` or `Infinity` identifiers, which could have been shadowed in a local scope and thus not be the right value. I've avoided that by generating `NaN` as `0/0` and the infinity values as `1/0` and `-1/0`.
| Q | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues? |
| Patch: Bug Fix? | Y
| Major: Breaking Change? | N
| Minor: New Feature? |
| Tests Added + Pass? | Yes
| Documentation PR | <!-- If so, add `[skip ci]` to your commit message to skip CI -->
| Any Dependency Changes? |
| License | MIT
Currently the `opts.filename` value exposed to plugins is just whatever the user passed. While it _could_ be relative to the working directory, if Babel was passed an absolute URL, it'll be absolute.
This PR explicitly ensures the filename is a relative path based on the working directory. This also exposes an officially endorsed API for reading the working directory path.
* Update member-expression-to-functions
1. Babel using British spellings, so `memoise`
2. Provide a helper `AssignmentMemoiser` class, which will assign the memo'd value with the `n`th access.
* Private properties!
* Fixes
* Tests
* Update helper name
* Fix privates that reference other privates
* Don't extend a builtin
* Rebase
Follow-up to https://github.com/babel/babel/pull/7404
There is no TypeParameter type in the Babylon TypeScript AST hierarchy.
Flow does have a TypeParameter type, but it should not be confused with
the TypeScript TSTypeParameter, since Flow !== TypeScript, and the types
have totally different fields. Instead, the .typeParameter.type of a
Babylon-parsed TSInferType node should be TSTypeParameter.
It would probably be fine to leave the declared type of the TSInferType
.typeParameter field as TSType instead of TSTypeParameter, but the more
specific TSTypeParameter type should be safe/correct, since the TypeScript
parseInferType function always uses SyntaxKind.TypeParameter:
66d6e5e6e0/src/compiler/parser.ts (L3006)
I noticed this typo because it has been causing ast-types test failures
lately, e.g. https://travis-ci.org/benjamn/ast-types/jobs/369634972
* Add all option to babel-plugin-syntax-flow
The Flow parser has some conditional logic based on whether types should
be parsed or not, which is based on either (a) the @flow pragma in the
docblock of the file of (b) the `all` configuration, provided via
command line or .flowconfig.
This commit adds the ability to provide the `all` configuration to
Babel as well, via the syntax-flow plugin. This should be set to `true`
if the project uses all=true.
* Parse @flow pragma
The Flow parser has some conditional logic based on whether types should
be parsed or not, which is based on either (a) the @flow pragma in the
docblock of the file of (b) the `all` configuration, provided via
command line or .flowconfig.
This commit parses the @flow (or @noflow) pragma from the first comment
in the source file. Directives are allowed to appear before the comment.
* WIP: add tests for explicit type arguments
This commit includes tests which have unexpected output, but will change
to the expected output as later commits add parsing support for various
features.
* Parse type arguments in new expressions
* Parse type arguments in call expressions
* Parse optional call expressions with explicit type args
* Add explicit type arguments to babel-types
Flow calls these typeArguments instead of typeParameters, which clearly
separates formal/actual parameters, and mirrors the existing arguments
key.
The existing definitions to support TypeScript also included Flow's
TypeParameterInstantiation node type, which I've moved to the the new
field.
* Add support for explicit type arguments to babel-generator
* Add test for explicit type args to transform-flow-strip-types plugin
* Oops. Forgot to regenerate the babel-types README.
* Fix Flow parser shouldParseTypes() function
I was looking at `options.all`, but the correct property ws
`options.flowAll`. Oops!
* Remove typeapp_call from whitelist of expected failures
Now that Babylon parses this syntax extension, we can remove the
typeapp_call tests from the list of expected differences.
Note that I am using the `flowAll` option, mirroring the behavior of the
Flow tests, which assume types without requiring the `@flow` pragma.
* Use Babylon plugin options instead of parser options
* Parse optional call expressions type arguments unambiguously
* Remove second wrapper from _wrapNativeSuper
* Fix tests on node 4
I DON'T KNOW WHY IT WORKS.
* Update fixtures
* Use Reflect.construct
* Parens
* Fix things
* Fix things
* Undo changes
* Fix with sham
* Typo
* Support internalSlots to babel-types and babel-generator
* Parsing support for internal slot properties
* Print internal slots in babel-generator
* Add whitespace before first internal slot property
* Add support for plugin options in Babylon
They work similarly to how they work in Babel. e.g.
babylon.parse({
options: [
"plugin1",
["plugin2", { option: true }]
]
});
The inernal api to get an option is
this.getPluginOption("pluginName", "option")
If the plugin isn't defined, it returns undefined.
* Add Babylon option decorators.secoratorsBeforeExport
* Nit
Fixes#7631
Before, if a JSX pragma was imported, the import was removed because
it did not think it was used as a value. This changes it so it knows
that the import is being used as a JSX pragma
* Lazy load tagged template literal strings
* Update snapshots to reflect lazy loading
* Use pure annotation and remove unnecessary parenthesized expression
* Update snapshots
* Optimize lazy loading by doing assignment within logical expression
* Update snapshots to reflect optimization
* Use re-define function pattern to avoid hitting function size deopts
* Update snapshots to reflect the usage of the redefining function pattern
* Fix default sourceFileName.
This deals with a problem mentioned in [babel/babelify#255][0]. I'm not
super sure about the implications, but it seems this may have been a
regression from Babel 6.
In babel@6, the default `sourceFileName` was the basename of the input
file:
```js
require('babel-core').transform('var a = 10', {
filename: __filename,
sourceMaps: true
}).map
// { version: 3,
// sources: [ 'index.js' ],
// names: [ 'a' ],
// mappings: 'AAAA,IAAIA,IAAI,EAAR',
// file: 'index.js',
// sourcesContent: [ 'var a = 10' ] } }
```
Currently however, the full file path is used:
```js
require('@babel/core').transformSync('var a = 10', {
filename: __filename,
sourceMaps: true
}).map
// { version: 3,
// sources: [ '/home/goto-bus-stop/Code/babel/repro-babelify-255/index.js' ],
// names: [ 'a' ],
// mappings: 'AAAA,IAAIA,IAAI,EAAR',
// file: '/home/goto-bus-stop/Code/babel/repro-babelify-255/index.js',
// sourcesContent: [ 'var a = 10' ] } }
```
This patch adds the `path.basename()` call that [Babel 6 used][1] to
@babel/core's default options, so it's the same as back then.
```js
require('../babel/packages/babel-core').transform('var a = 10', {
filename: __filename,
sourceMaps: true
}).map
// { version: 3,
// sources: [ 'index.js' ],
// names: [ 'a' ],
// mappings: 'AAAA,IAAIA,IAAI,EAAR',
// sourcesContent: [ 'var a = 10' ] }
```
This is the desired behaviour for browserify at least, as it expects
relative paths in the source maps and rebases them to a root directory
when generating the final source map.
[0]: https://github.com/babel/babelify/pull/255
[1]: 6689d2d23c/packages/babel-core/src/transformation/file/index.js (L163-L172)
* Use cwd-relative path for sourceFileName.
* Revert sourceMap `file` property change.
* fixup! Revert sourceMap `file` property change.
* Fix whitespace change from merge conflict
* Revert to using basename in source map outputs.
This undoes the property call folding from #6656.
It complicates the private property transforms, since they boil down to `map.set(this, vlaue)` and we definitely don't want the next call define a property on the map.
/cc @Andarist
Yes, the output is uglier. But, this is necessary for me to refactor
`replaceSupers` for #7733, which is necessary for both #7555 and
https://github.com/babel/babel/pull/7553#issuecomment-381434519.
I'm still in the middle of cleaning up all this code. Don't expect
`transformClass` to survive much longer as it's written currently.
We were using `Object.create` to setup the prototype chain at the start of the class definition, which lead to #7771.
I was a bit worried about a speed hit, but it seems everyone optimizes the two patterns the same way.
https://jsbench.github.io/#f9fca52407643d96458a35763b201215Fixes#7771.
* Implement MemberExpressionToFunctions helper
Fixes#7733.
This will also be used to simplify the Private Fields transform, which had [almost the same code](ccd941057a/packages/babel-plugin-proposal-class-properties/src/index.js (L114-L217)) hand written.
* Cleanup
* Little more comment cleanup
* Use unary plus
This can't be redefined, unlike the `Number` identifier.
* Review comments
* Remove unused deps
* drop support for Node.js v4; closes#7753
- remove version 4 from Travis build matrix
- update environment support doc
- update `CONTRIBUTING.md`
- update `engines` field of root `package.json`
Signed-off-by: Christopher Hiller <boneskull@boneskull.com>
* update engines for babylon
Signed-off-by: Christopher Hiller <boneskull@boneskull.com>
* Improve asyncIterator error
When an object is has neither asyncIterator or iterator defined, throw the "not an async iterable" error
* Correct logic
* reduce access
* Update helpers.js
* Update decorators parsing
This commit introduces three changes:
1) Class properties can be decorated
2) Decorators can contain arbitrary expressions, using @(...)
3) The Decorator node type has a new property, "arguments". This
makes it possible do distinguish @dec() and @(dec()), which have
different behaviors because @(dec()) is equivalent to @(dec())().
* Rename Decorator#expression to Decorator#callee
* Add test for @dec()()
* Fix class properties after nested class' bare super
Fixes#7371.
* Fix node 4 test
* This damn node 4 test
* All of the ClassBody, but not the methods or field inits
* tmp
* tmp
* Use common class environment visitor
* Tests
* Use skipKey to avoid recursive traversal
* Remove old state
* Use jest expect
* Properly traverse nested class for supers
* Add object nested in class cases
* Add object nested object cases
* Test class properties
* Undo changes to lerna.json
* Add tests arournd prefix/postfix super increment
* tmp
* Use sets
* Improve get/set helper
* fixtures
* Edge cases
* Add loose edge cases
* Spec compliant
* Add issue case
* Even more edge cases!
* Final updates
* Fix name
* Use Reflect.{get, set} when available
* Avoid block scoping in loose
* Remove semicolon
* Do not redefine a non-enumerable
* Get strictness from call site, not helpers
* Add called assertions
* Classes are always strict
* Update test fixture
* #7349
- Add "use strict" directive to transformed class bodies
* Update tests (#7349)
* Add test for program with use strict directive (#7349)
* Update tests (#7349)
* Update source mapping (#7349)
* Add test for parent blockStatement with use strict directive (#7349)
* Update tests (#7349)
* Update tests (#7349)
* Update tests (#7349)
* Add test for constructor-only class (#7349)
* Constructor only classes are strict, too
But constructor only that use non-simple parameters must use a strict function wrapper.
* Fix test
* Wrapper not needed if class is already strict
* Revert change to lerna.json
Added the value argument to the visitors of flow literal type
annotations.
Literal type annotations need a value since they work very much like
primitive literals in normal JavaScript.
Fixes#7697
* Fix name computation for literal values
* Add more computed literal test cases
* Always return a string in getNameFromLiteralId
- Also concatenate quasis id for regex literal
* Add a test clarifying function name for template literals
* Remove useless else ifs
It was needed to avoid collision of identifiers used in fields
initializers with variables declared in the constructor, but it
broke `this` handling.
This commit removes that behavior and instead renames the
colliding variables.
* Add support for RegExp includes/excludes
* Keep the plugin order
* Detect invalid modules in regexp
* Add more tests for regexp
* Cover builtins, and unnormalized in the RegExp tests
* Remove babel-plugin- in all positions
* Change babel-plugin- prefix to string
* Add a test for the same module in include/exclude
* Handle partial matches explicitly
* Remove extra valid regexp check
* Optimise validation of plugins
* Optimise selecting the plugins
* Fix undefined include/exclude option
* Update documentation to reflect the new include matching
* Fix typo
* Apply reviews
Use regexp.test instead of string.match (slower)
Define flatten helper
Do not normalize babel-plugin anywhere in the string
These files appear to have been missed in the update of test file naming from actual/expected.js to input/output.js. As a result, they were silently not being run. I've confirmed that they were not running, updated the names, then confirmed that they are running now.
The boolean expressions returns false in environments where Map is missing.
This change explicitly sets _cache to undefined in such cases, to ensure the cache methods will be ignored.
* docs(babel-standalone): remove bower mention
Since the package won't be downloadable as `@babel/standalone` it's best to just remove it, since it's pretty much deprecated as is. I left the other mention of babel-standalone-bower since I guess that's just the name and still useful in other cases
cc @daniel15
reported in https://github.com/babel/babel/pull/6495#pullrequestreview-70980926
* Update README.md
* Update test262 and whitelist
* Use test262-stream
* Check escapes in contextual keywords
* Check escapes when parsing new.target
* Check escapes for getters/setters
* Check escapes for static class methods
* Check escapes on async arrow and functions
* .prettierrc: full configuration for Prettier
This way, contributors using different-from-default settings will still
use the correct prettier settings
* Makefile: also lint .babelrc.js
* Makefile: also prettify .json files
* Exclude package.json files and correct build dir
* Add more default options to prettierrc and load it in cli
This avoids prettier looking up the config for each file
* Format json
* Update prettier and eslint and reformat codebase
* Remove obsolete file
* Add comment
* Fix reseting modules in jest and config
we have lib folders inside the source folders which should not be ignored.
* Add codemods lib folder
* Support mjs
* improve ignore pattern
for-await was transformed in @babel/helper-remap-async-to-generator, which was
called by @babel/plugin-transform-async-to-generator and
@babel/plugin-proposal-async-generator-functions. This prevented for-await
statements in async functions to be transpiled if the
transform-async-to-generator plugin was't enabled.
* feat(babel-cli): add a brief summary to build output
* address feedback
* further adjustments
* Use quiet output as default, add --verbose
* fix tests
* remove verbose alias
Prior to this change, we'd conduct an open-ended traversal on the 'id'
of any VariableDeclarator to find a RestElement. The 'id' of
a VariableDeclarator can contain an AssignmentPattern (to supply
a default value), and if the right-hand side of the AssignmentPattern
contained a RestElement, we'd transform it.
The problem here is that the right-hand side of an AssignmentPattern can
be *any* Expression. If the right-hand side is a function body, we'd
traverse the entire function body, and if a RestElement occurred
anywhere in that function body, we'd transform it and emit the
transformations wherever we began the traversal (at least one scope
outside its usage).
The fix is to stop the inner traversal if we encounter an
AssignmentPattern. The outer traversal will still visit the
AssignmentPattern, so RestElements within the right-hand side of an
AssignmentPattern will be properly transformed at that time.
This creates a new package called @babel/highlight which syntax highlights
JavaScript code for terminal output. This functionality was already
present in @babel/code-frame, but exposing it as a separate package lets
other projects leverage it. @babel/code-frame has been refactored
slightly so that it uses @babel/highlight to do its syntax highlighting.
* Added optionalExpression types to babylon and babel-types
* OptionalChain transforms bug fix
* Added OptionalExpressions to babel-generator. Fixed OptionalChain Bugs
* Removed 'optionalChain' from newExpression and added test cases
* Added test cases for optionalChain
* Update index.js
This failing test case demonstrates a regression between 7.0.0-beta.38 and
7.0.0-beta.39 in the @babel/plugin-proposal-object-rest-spread package.
I distilled this test case from a larger configuration of plugins in my
application, one of which calls api.traverse.cache.clearScope(). Although
calling clearScope() is an uncommon thing for a plugin to do, it was a
reliable way to reproduce the problem. If I can find other reliable
reproductions, I'll push some additional failing tests to this PR.
Regardless of how common it is, clearing the scope cache should be a safe
operation that only slows down the transform (because scopes have to be
recreated and re-crawled). Crashing due to a spurious duplicate
declaration seems like a bug worth fixing.
My hunch is that [these two lines](eb38ea2b10/packages/babel-plugin-proposal-object-rest-spread/src/index.js (L75-L76))
(which were changed in `7.0.0-beta.39`) are not actually removing the
original rest element as a binding from the enclosing `Scope`, in certain
circumstances, so the new variable declaration ends up colliding with the
old (removed) binding.
Possibly related: #7304 (reported by @julien-f)
* generate typescript types
* improve type generator output
* move generator scripts to scripts/generators
* use new stringifier for generating flow types too
* export summary types
* add support for oneOfNodeOrValueTypes to improve type generation
* export typescript types from top level, and remove module declaration
* generate typescript/flow types and copy typescript types to babel-types/lib as part of make build
* copy flow types to babel-types/lib as part of make build (fix#6839)
* improve typing: Identifier->name should be a string, not any
* avoid destructuring, to support node 4
* update doc generator to share more code, regenerate babel-types readme, pipe all generator output to stdout
* regenerate babel-types readme as part of make build
* improve typing: ClassProperty->key should be Identifier | StringLiteral | NumericLiteral | Expression, not any
* improve typing: optional node properties are nullable, not undefinedable
* improve docs: FlowClassImplements should be ClassImplements
* make ts usage more friendly: when using babel-types api, make optional params | undefined, and when reading nodes keep optional params | null
* rm lib/types.d.ts and lib/types.js in favor of packages/babel-types/lib
* add missing variance node type, address review comments
* add tests for flow variance
* Comment should be a disjoint union of tagged types
* update .flowconfig
Keeping the shape of an object constant is a performance improvement for modern javascript engines. At the point of the code change it is certain that the `children` property will be set later, so the property can already be set to `undefined`.
* use the async version of transform in babel-cli
* Modify compile to use async version of transformFile
* Babel-CLI: transform files sequentially
* Remove useless res in callback
* Add test case for simple reference in tdz
* Add more examples from old issues as test cases
* Fix two testcases by excluding function declarations from being tdz checked
* Document the option for block-scoping
* Add test cases with destructuring assignments
* Remove failing test cases
* [skip ci] Include type and default value for options
* Bail out on JSX fragments instead of throwing
The `transform-react-inline-elements` plugin doesn't handle JSX fragments. It throws an exception because `node.openingElement` is undefined.
* Add a comment explaining `node.openingElement`
* Update line endings in test fixtures to match current output
* Fix incorrectly set up static-property-tdz fixtures
It seems the fixture runner does not look into subfolders.
* Remove expected file that should not exist
* Reenable disable optimisation test
* Reenable disabled nbsp tests
* Reenable comments between props test
The comments adjacent to children test is still broken so it stays off.
* Avoid adding #__PURE__ annotation to .bind(this)() expressions
Fixes the #__PURE__ annotation getting added to (async () => {})() IIFEs when the arrow function transform is running with spec: true.
* Return false instead of undefined
* Fix indentation in json files
* Add one more case to the async-iife fixtures
* Better error messages when Babel fails to parse import = and export = syntax from typescript when using babel-plugin-transform-typescript
* Fixing Test cases
* Ran make fix and broken looong sentence into smaller
* Slight changes to Messages after review with Nicolo & existentialism
* Removed trailing space
* Handling babylon parsing errors in a better way
* Better error messages + Helpful URLs
* Replaced message from babylon completely
* Add importMeta plugin to the map
Currently, Babel is treating JSXIdentifier, JSXMemberExpression, and JSXEmptyExpression as expressions as well, which means Babel will for example incorrectly allow you to place these anywhere an expression is wanted.
Closes#6851.
`this.blockPath.get("body")` constructs an array of paths corresponding to each node in `blocks.body` so takes O(n) time if n is that length. We were re-constructing that array on each iteration, so the entire loop was O(n^2).
On files with many statements in a single block (such as Rollup-generated bundles), this takes a large portion of time. In particular, this makes transforming react-dom.development.js about 40% faster. Not that you should be transforming our bundle with Babel.
Test Plan:
Make an HTML file with these three lines and watch it in the Chrome Performance tab to see timings (on my machine: 2.9s before, 1.6s after):
```
<!DOCTYPE html>
<script src="https://unpkg.com/babel-standalone@7.0.0-beta.3/babel.js"></script>
<script type="text/babel" src="https://unpkg.com/react-dom@16.2.0/umd/react-dom.development.js"></script>
```
This commit introduces 4 changes:
1) Function declarations are wrapped using function declarations.
This has two advantages:
- We can rely on native hoisting, instead of using _blockHoist
- The function isn't wrapped until it is called. This avoids
problems where `regeneratorRuntime.wrap` was called before
that `babel-polyfill` was imported.
Example:
function fn() {}
// becomes
function fn() { return _fn.apply(this, arguments); }
function _fn() {
_fn = _wrapper(/* Original function ... */);
return _fn.apply(this, arguments);
}
2) Use a single template for both named and anonymous function
expressions. They already had the same behavior, but the one
used for named functions was a bit longer.
3) Use normal functions instead of arrow functions to wrap
function expressions.
4) Generate a name based on the original one for wrapped
functions (e.g. `foo` becomes `_foo` instead of `_ref`).
* Split exportExtensions into two plugins in babylon
* rename proposal-export-default to proposal-export-default-from
* rename proposal-export-namespace to proposal-export-namespace-from
* Consider reexports for bindingKindLookup.
* Update test cases according to reexports change
* Fix order for assign reexports.
* void 0 assignation to module keys only for loose mode.
* Create buildReexportsFromMeta helper.
* Update umd/amd fixtures.
* Refactor reexports build.
* Hoist template for reexports.
* Use map as a second argument of Array.from.
* Remove unnecessary export.
* First implementation sketch and testcase
* Use helper instead of inline IIFE's
* minNodeVersion 6.0.0
* Hoisted visitor for subtraversal and fixed edgest case
* Resolve merge conflicts in helpers
* Remove duplicated helper from messing up Git
Flow bindings have been deprecated for a while.
The reason behind this change is that `declare var foo`
doesn't introduce a new local binding, but it represents
a global one.
* Install sourceMapSupport only when sourceMaps are requested
* Add tests for sourceMapSupport
* Fix sourceMap position for tests
* Fix gen_error file
* fix the test descriptions
* Refactor install sourceMap support
* Run sourceMapSupport only once
* Handle cases where sourceMaps is undefined
* No unneeded empty arrays in transform spread
Since Array.prototype.concat creates a new array from inputs, there's
no need to call it from a new empty array ([].concat()).
* [fixup] simplify detection of new array
* Fix transform-arrow-functions in { spec: true } shadowing
The function name matching the variable declaration name could
shadow the actual function object inside the generated function,
leading to invalid behavior due to holding a reference to the
original unbound function.
* Combine it with transform-function-name just to be sure in spec: false
* Revert "Fix transform-arrow-functions in { spec: true } shadowing"
This reverts commit 1cafe2561d0b0ddd181b956a85eb074621da12e8.
* Much simpler version of the above fix
* Missing fixture updates
* Avoid using rest/spread to make the tests pass on node 4
* ...actually update _all_ the fixtures
* Unify eslint/prettier config
Use a prettier config file and correctly configure trailing commas
Enable curly in babylon as in all other packages.
* Add experimental and codemods
* Properly guard for..in loops with Object#hasOwnProperty.
I noticed that babylon spends a lot of time in what we call *slow mode*
`for..in` when running in Node (on V8), and the reason for that is that
the version distributed on npm is build with *loose mode*, which turns
methods on the prototype into enumerable properties. Let's look at a
simplified example of the `State` class from `src/tokenizer/state.js`:
```js
class State {
constructor() { this.x = 1; }
clone() {
var state = new State();
for (var key in this) {
var val = this[key];
state[key] = val;
}
return state;
}
}
```
According to the specification the `State.prototype.clone` method is
non-enumerable. However when transpiling this with loose mode, we get
the following output:
```js
var State = (function() {
function State() { this.x = 1; }
State.prototype.clone = function clone() {
var state = new State();
for (var key in this) {
var val = this[key];
state[key] = val;
}
return state;
}
return State;
})();
```
So all of a sudden the `State.prototype.clone` method is enumerable.
This means that the `for..in` loop inside of that method enumerates
`x` and `clone` for `key`, whereas originally it was supposed to only
enumerate `x`. This in turn means that the shape of the result of a
call to `clone` will be different than the shape of a state that is
created via the `State` constructor. You can check this in `d8` using
the `--allow-natives-syntax` flag and this simple test driver:
```js
const s = new State;
%DebugPrint(s);
%DebugPrint(s.clone());
```
Using either the class version or the transpiled version we see:
```
$ out/Release/d8 --allow-natives-syntax state-original.js
0x2a9d7970d329 <State map = 0x2a9d40b0c751>
0x2a9d7970d3c1 <State map = 0x2a9d40b0c751>
$ out/Release/d8 --allow-natives-syntax state-loose.js
0x3729ee30d1b9 <State map = 0x3729af90c701>
0x3729ee30d251 <State map = 0x3729af90c7a1>
```
So as you can see, the transpiled version (using *loose mode*) produces
a different shape for the result of `clone`, whereas the original
version is fine. This pollutes all sites which use either a state
created from the `State` constructor or returned from the `clone`
method. The original one has only the `x` property in either case,
whereas in the transpiled version the result of `clone` has properties
`x` and `clone` on the instance.
To mitigate this effect, it's best to guard the `for..in` loops with
`Object.prototype.hasOwnProperty` calls, such that the actual body of
the loop only deals with own properties and not with properties from the
prototype chain. This change does exactly that for the two affected
`clone` functions.
In addition to the performance hit because of the unnecessary
polymorphism, there's also the performance hit because of the *slow
mode* `for..in` itself, which has to collect the properties from the
instance plus the prototype. Ideally the prototype properties shouldn't
be enumerable to avoid this whole set of problems. I see a couple of
possible solutions:
1. Distribute the original ES2015 version via npm.
2. Don't use loose mode, so that `Object.defineProperty` is used
instead, correctly passing `enumerable:false`.
3. Globally change loose mode in Babel to generate the correct and
fast `Object.defineProperty` instead.
I'd personally prefer a combination of 1. and 3. here, but I'm aware
that distributing the ES2015 code might not be an option yet. So the
mitigation of properly guarding the `for..in` here should already help.
But it'd be nice to have a discussion on using `Object.defineProperty`
in general, as I imagine that this could easily bite other applications
as well and this performance cliff is completely unobvious to
developers.
* Switch to Object.keys and Array.prototype.forEach.
- This is because with scoped packages the `latest` package was the first publish we did
- This happens to be beta.4..
- So in this case we should publish whatever version as latest anyway
* Consider instance type for polyfills.
* Add test cases for evaluated objects.
* preset-env fixtures: babel-polyfill -> @babel/polyfill
* Split up fixtures with evaluated variables.
* Add JSX Fragments to babel-types
* Support JSX fragments in the transform-react-jsx plugin
* Add tests JSX fragments
* Update helper-builder and transform plugin documentations for jsx fragment
* Add generator for jsx fragments
* Add test for jsx fragment generator
* Split jsx transform example into normal and fragment examples
* Remove unnecessary fields from ElementState in babel-helper-builder-react-jsx
* inline [skip ci]
* Use parseFunctionParams to parse method parameters
* [funct] Set this.state.inGenerator before parsing the function name/params
This allows "yield" inside generator parameters to be actually
parsed as a yield expression
* [funct] Disallow yield in function parameters
* [arrow] "yield" can start an arrow function (e.g. "yield => {}")
* [arrow] Disallow YieldExpressions inside arrow parameters.
* [err msg] Disallow yield as fn name in strict mode using checkReservedWord.
So Babylon throws "yield is a reserved word" instead of
a custom "Binding yield in strict mode"
* [err msg] "X is reserved in strict mode" should have precedence over "X is reserved", since it is more specific.
This was observable if "checkKeywords" is true and the word is both a keyword and a reserved
word in strict mode
* Disallow "yield" as an identifier inside generators
* [tests] Add tests, update wrong esprima tests and enable disabled esprima tests
* [tests] Move uncategorized tests to es2015/yield
* [tests] Update test262 whitelist
* Fix regression introduced by 8c77073
* [tests] Update flow whitelist
* Fix flow errors
- adds `get` and `set` kind in addition to `method` to the list of allowed class members for having a decorator,
- adds tests for this two cases (decorator + set and decorator + get)
* Fix OOB string character access in Printer#_maybeAddParen.
The `_maybeAddParen` method of the `Printer` class does
```js
const chaPost = str[i + 1]
```
without checking that `i + 1` is still within the bounds of `str`. It
seems like this triggers fairly often that the `str[i + 1]` access is
out of bounds. The first out of bounds access will turn the KeyedLoadIC
(in case of V8) into *MEGAMORPHIC* state, which is significantly slower
for strings (there's a fix in flight for V8 to mitigate the cost a bit
in that case). Even worse than that, the out of bounds access also
pollutes the later comparisons, namely
```js
chaPost === "/"
```
and
```js
chaPost === "*"
```
which are now no longer monomorphic on strings, since `chaPost` was
sometimes `undefined`.
This is a non-breaking performance fix, which improves babel execution
on the [web-tooling-benchmark](github.com/v8/web-tooling-benchmark)
workload by around 6-9%.
* Restructure and optimize the code a bit.
* Added tests for ifThrowNamespace flag
* JSX transformator could work with XMLNamespaces (ifThrowNamespace flag)
* Use template literal instead
* Attempt to reword the message
* Added docs
* Reworded docs
* Reworded docs
* Fixed missing space in error message
The code
```js
linesInfo && linesInfo[type]
```
performs a lot of dynamic lookups on the `Boolean.prototype`, as the
*ToBoolean* operation let's `true` pass for `linesInfo` (which might
itself be concerning that this can be a boolean). Instead of the
coercion, the code should properly check for valid objects via `typeof`
and strict equality with `null` comparison.
This is a non-breaking performance fix.
Similar to the fixes in https://github.com/babel/babel/pull/6580 and
https://github.com/babel/babel/pull/6581, accesses of the form
```js
nodesOut[nodesOut.length - 1]
```
where `nodesOut` can be an empty array, are bad for performance in Node.
In this particular case it's easy to restructure the code a bit to not
require the array access at all, but just track the current `tail` as we
go.
This is a non-breaking performance fix.
* Fix path.popContext() to not try to load "-1" from contexts array.
The current implement of popContext does
```js
this.setContext(this.contexts[this.contexts.length - 1]);
```
even if `this.contexts` can be empty, which causes it to lookup the
property `"-1"`, which is not found on the array itself and obviously
also not in the `Object.prototype` and the `Array.prototype`. However
since `"-1"` is not a valid array index, but has a valid integer
representation, this is a very expensive lookup in V8 (and probably
other engines too, but that is probably less relevant, since Babel
most often runs on Node nowadays).
* Make zero check explicit (for readability).
Similar in spirit to https://github.com/babel/babel/pull/6580, the
current implementation did
```js
node.params[node.params.length - 1]
```
where `node.params` can also be empty, which causes it to lookup the
property `"-1"`, which is not found on the array itself and obviously
also not in the `Object.prototype` and the `Array.prototype`. However
since `"-1"` is not a valid array index, but has a valid integer
representation, this is a very expensive lookup in V8 (and probably
other engines too, but that is probably less relevant, since Babel
most often runs on Node nowadays). In V8 this causes a call to
the `%SetProperty` runtime function for each of these `"-1"`
property lookups, and in addition sends the whole `KeyedLoadIC`
to `MEGAMORPHIC` state, which also penalizes other accesses
on this line.
This is a small non-breaking performance fix.
Similar to the fixes in https://github.com/babel/babel/pull/6580 and
https://github.com/babel/babel/pull/6581, accesses of the form
```js
stack[stack.length - 1];
```
when `stack` can be an empty array are pretty bad for performance.
In this case it also breaks the type safety, since the function
`last<T>` is declared to only return values of type `T`, but
occasionally also returns `undefined` now, since the `stack` parameters
passed to it never contain a property `"-1"` and neither do the
`Object.prototype` or the `Array.prototype`.
This is a non-breaking performance fix, which adds proper checking
to ensure that `last` is only invoked on non-empty arrays.
* Initial version
* Replace .includes with .indexOf and better node set to visit
* Alphabetically sort es3 reserved words and make difference helper for readability
* Fix second Array.include error that was not polyfilled
* Move es3 keywords into separate babel-types helper and use in all es3 transforms
* Reference local plugin build directly for tests
* Try relative import for babel-types
* Update to scoped package name and beta 3
* Fix unscoped package import
* Replace local plugin reference with proper plugin name
* Removed index.js stub from packages/babel-core
Added "main":"./lib/index.js" entry to package.json to replace index.js in packages/babel-core
* Fix indentation of new main.
Previously, computed class properties would be evaluated every time a
new instance of the class was created. This means the property name
may have changed between different instances, as well as potential side
effects.
This commit fixes this by storing the computed value in a separate
variable.
* centralize plugin options
* Centralize plugins options
- move more options to the top
- move validations that depend on options to the top
* use isLoose option
* Move more validations to the top
* Move ref parameter for rewriteModuleStatementsAndPrepareHeader() to the top
* fix eslint errors
* remove unused parameter
* set default systemGlobal value
* Revert "Move ref parameter for rewriteModuleStatementsAndPrepareHeader() to the top"
This reverts commit b3855302d17fa19d8acb4c8accab3680c8d2710e.
* Revert "Move more validations to the top"
This reverts commit e5861d8a034ff8f553391f55654f753bcf428a5d.
* fix allowMutablePropsOnTags option usage
* improve naming
* change Contructor definition for sake of consistency
* move allowMutablePropsOnTags validation to the top
* add missing !
Supports:
```js
// these all should produce "code;" when generated
template`code;`();
template`${0}`(t.identifier('code'));
template`${'code'}`({ code: t.identifier('code') });
template`${t.identifier('code')}`()
template({})`code`();
```
Amusingly the pipeline OP "breaks" the readme formatting because Markdown likes the `|` character a bit too much. Escaping the `|` fixes this and makes the readme display properly
This prevents a requeued path from inheriting a totally wrong scope later on. I can't find exactly where this is happening, but either way a path should only inherit scope from it's ancestors.
* Add support for helpers dependencies.
They are used like this:
helpers.main = defineHelper(`
import dep from "dependency";
export default function main() { return dependency; }
`);
helpers.dependency = defineHelper(`ì
export default function dep() { return 0; }
`);
* Clone import references
* Don't make test helpers name depend on the order the tests are run
* Path#ensureBlock keeps path context
This ensures that if you're inside an ArrowFunction with an expression body (say, you're on the BooleanLiteral in `() => true`), you don't suddenly lose your path context after inserting a variable.
This is because of 82d8aded8e (diff-9e0668ad44535be897b934e7077ecea5R14). Basically, an innocent `Scope#push` caused my visitor to suddenly stop working. Now, we mutate the Path so it's still in the tree.
* Tests
* Use helper-builder-react-jsx inside plugin-transform-react-inline-elements.
This avoids duplicating the logic for converting jsx elements to plain JavaScript.
* Add a comment which explains the _jsx signature, [skip ci]
so it is a little bit easier to understand what all those .splice() calls do
* Re-name uncatagorised 1 and 2
* Move to es2015
* Add expected.json to parenthesized lhs object
* Orginize into parenthesized-lhs-array and parenthesized-lhs-object
* Remove uncategorised/33 because it was repeditive decorators/class-decorator
* Move uncatagorised/34 to decorators/class-decorator-assignment
* Move uncategorised/35 to decorators/method-decorator
* Move uncategorised/36 to decorators/class-decorator-setter
* Move uncategorised/37 to decorators/class-decorator-getter
* Move uncategorised/38 to decorators/class-decorators-multiple
* Clean up syntax
* Move uncategorised/39 to decorators/object-decorator
* Remove syntax in order to pass tests
* Re-add uncategorisd/33 as decorators/class-decorator-new-line
* Move class-decorator-new-line to class-decorator-same-line
* Remove babel-node from babel-cli
* Use new Array instead of Array for V8 optimization
* Remove extraneous use strict clauses
* Require babel-node in babel-cli
* Remove babel-node from babel-cli
* Require babel-node in babel-cli
* Remove babel-node executable from babel-cli
* Clean up babel-node from package.json
* outline of plugin to remove unused catch binding, test not passing
* plugin to remove unused catch binding
* Edit README.md and package.json
* tests for try catch finally
* Add test to handle case when binding is referenced and given new TypeError (not passing)
* Fix visitor to not remove catch clause param when binding being assigned a new value
* Improve naming of tests and explanations
* add test case for catch param not present and fix test for duplicate variable declaration
* Remove binding.constantViolations filter in visitor as superfluous
* Remove duplicate check that catch clause param present
* Alter visitor so returns out when catch binding is not an Identifier
* Created failing tests for ObjectPattern params and rewrote visitor so now passing
Took out the pass in visitor when param not an Identifier, wrote case to handle when param isObjectPattern, and wrote failing tests for when param isArrayPattern
* Handle case when param isArrayPattern, tests passing
* Update package.json to v7.0.0-alpha.20
* Revert visitor to only consider transform if param is Identifier
This separates `classPrivateMethods`'s dependency on
`classPrivateProperties`. It also starts a `PrivateName` at the hash
symbol, not the `Identifier`.
* Add --keep-module-extension option to babel-cli
* Rename keep-module-extension option to keep-file-extension; Change option to preserve all file extensions
* Return inserted/replaced paths
This gives `Path`’s replacement and insertion methods a consistent
return value: the inserted/replaced paths.
Before, they could return `undefined`, a `node`, or a the current path
inside an array. It was kinda pointless. But now they always return an
array of paths, which is useful for solving
https://github.com/babel/babel/pull/4935#discussion_r96151368.
* Return inserted nodes and not BlockStatement
Addded test for bug #4363
* Cleanups
- `#replaceWith` will now return the current path if it's the same node
- `#insertAfter` and `#insertBefore` use public Path APIs now
- Makes container insertion faster (single splice call)
- Use public APIs in container insertion
- Replacing a statement with an expression returns the expression's path
- Replacing an expression with multiple statements returns the inserted
closure's body's paths.
* Add failing test case for object rest after array rest.
Discovered while upgrading https://github.com/meteor/babel to Babel 7.
The error is:
1) babel-plugin-transform-object-rest-spread/object rest with array rest:
TypeError: /Users/ben/dev/babel/packages/babel-plugin-transform-object-rest-spread/test/fixtures/object-rest/with-array-rest/actual.js: Property id of VariableDeclarator expected node to be of a type ["LVal"] but instead got null
at Object.validate (packages/babel-types/lib/definitions/index.js:73:13)
at validate (packages/babel-types/lib/index.js:460:9)
at Object.builder (packages/babel-types/lib/index.js:428:7)
at Object.RestElement (packages/babel-plugin-transform-object-rest-spread/lib/index.js:157:41)
at NodePath._call (packages/babel-traverse/lib/path/context.js:53:20)
at NodePath.call (packages/babel-traverse/lib/path/context.js:40:17)
at NodePath.visit (packages/babel-traverse/lib/path/context.js:84:12)
...
* Fix object rest following array rest. (#6213)
* Avoid treating array ...rest elements as object ...rest properties.
* Also avoid treating ...rest parameters as object ...rest properties.
Returning early if the parent was an ArrayPattern was not quite enough,
since a RestElement can appear as a parameter in a Function as well.
* Move RestElement parent check earlier in visitor method.
* Fix output directory if filename is given
* Add test for relative output path
* Add option to define output dir relative to input
* Add tests for --copy-files
* Test error handling for wrong arguments
* Redeclaring a variable counts as a modification.
Fixes#6217.
* Remove "existing" logic from Binding.
Was added in #5745, but no longer triggered since 6536e605a.
* Add support for class private methods
This commit adds parser support for the TC39 Stage 2 Private Methods
proposal.
This commit also changes "key" in ClassPrivateProperty from an
Identifier to a PrivateName, as well as disallowing #constructor as a
valid private field name.
* Add tests for string literal get/set/async
These should be treated as regular methods and not special get/set/async
behaviour.
* Add tests for class private methods
This also removes a test from the Test262 whitelist that failed before
the changes for private methods support and now passes.
* Modify class private prop tests for PrivateName
* Add class private prop tests for #constructor
* Fix existing ASI test case failure
* Removed the deprecated jsx pragma detection code and the concerned tests that included jsx-pragma
* Removed extra tests
* Restored packages/babel-plugin-transform-react-jsx/test/fixtures/react/honor-custom-jsx-pragma-option/
* Added JSX_ANNOTATION_REGEX
* Reverted the tests for jsx-pragma-options and removed those which throw deprecated message
* Fix bad Scope#parent caching
Now, we traverse the path until we find a parent scope.
Fixes#6057.
* Fix bad merge
* Remove cached data
* I need to stop using Github editor
* Fix infinite loops due to scopable paths being moved up
This reverts the former fix done in #5743 and always requeues
BlockStatements when they get created.
This also fixes a bug in babel-generator which would indent code
even though no comments are present.
* Allow NodeJS v8.4 experimental HTTP2
Native NodeJS HTTP/2 support experimental though, so might not be worth merging this
* Linter picked up on a line with only spaces
Removed the spaces
* added --delete-dir-on-start option
added --delete-dir-on-start-option to delete dir on start of compilation to remove deleted files from the orignial files from the --out-dir
* added option --delete-dir-on-start
added --delete-dir-on-start that option will delete the --out-dir before the compilation of code to remove the deleted files from the source from the out directory
* added --delete-dir-on-start option
added --delete-dir-on-start-option to delete dir on start of compilation to remove deleted files from the orignial files from the --out-dir
* bug removed deleting the correct dir
in the previous code, the source dir was deleted each time rather than deleting the out dir
* Remove shorthand
* Prevent babel-cli option from reaching babel-core
* Lint
I can never remember the syntax and end up coming here to copy/paste this snippet all the time.
I assume other people want to as well, or at least make it clear for newbs that this can be used with Node without them having to scroll.
* for-of: IteratorClose spec compatibility.
See #3:
https://tc39.github.io/ecma262/#sec-iteratorclose
* Update spec fixtures for for-of.
* Fix IteratorClose case for remap-async-to-generator.
* Fix IteratorClose case for async-generator-function test output.
* Modify few tests according to iteratorClose fix.
* Fix iteratorClose for helpers.slicedToArray also.
* Update iteratorClose fixture for commonjs.
* Don't merge test options.
Particularly, I don't want `lodash/merge` to merge my specific plugins
with the general test plugins. It led to odd behavior where I could
enable a loose transform in my specific test, just to have it overridden
by the test fixture's general options.
* Need options
Given that it refers to an identifier, it's somewhat confusing to have
to use .name.name to get the actual string. The type declared within
types.js is also incorrect, which this commit fixes.
The for-in loop in helpers.defineEnumerableProperties doesn't iterate over Symbols.
If Object.getOwnPropertySymbols exists, include the discovered values when defining properties.
* Changed updateExpression to report itself as violation instead of its argument
* Update getBindingIdentifiers to work with forXStatement and return proper node as violation
* Updated unaryExpression violation to be consistent with changes.
* Removed the deprecated jsx pragma detection code and the concerned tests that included jsx-pragma
* Removed extra tests
* Restored packages/babel-plugin-transform-react-jsx/test/fixtures/react/honor-custom-jsx-pragma-option/
* Allow nightly Yarn builds to be used
Fixes:
```
C:\src\babel (fix-it-fix-it-fix-it-fix-it) (babel)
λ yarn
yarn install v1.0.0-20170811.1240
[1/5] Validating package.json...
error babel@: The engine "yarn" is incompatible with this module. Expected version ">=0.27.5".
error Found incompatible module
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
```
* Use Yarn 0.28.4 to fix build
This change has two reasons:
- The object was actually used as a map
- Using an object leads some problems with the
private_class_fields/constructor.js test, since
`tests[test_name] || {}` returned the Obejct
constructor instead of an empty object.
So, I was reading the new Flow type strictness and noticed
https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/
Specifically, I wondered whether the `sum_all` example would copy the
arguments into an array, then loop over. Sadly, it does.
```js
function sum_all(...rest) {
let ret = 0;
for (let i = 0; i < rest.length; i++) { ret += rest[i]; }
return ret;
}
// output
function sum_all() {
var ret = 0;
for (var _len = arguments.length, rest = Array(_len), _key = 0; _key < _len; _key++) {
rest[_key] = arguments[_key];
}
for (var i = 0; i < rest.length; i++) { ret += rest[i]; }
return ret;
}
```
But then I noticed if I changed `let i = 0` to `let i: number = 0`, it
worked directly on `arguments`. That lead me down a rabbit hole to
`Path#_guessExecutionStatusRelativeTo`. When tracing through, the last
comparison made no sense to me. It was trying to find the index of
`"init"` in a list of `["declarations"]` and `"body"` in `["directives",
"body"]`. Red flags and such.
But it makes sense when you're trying to compare the visitor order of
the common ancestor path. Then we're trying to find `"init"` in a list
of `["init", "test", "update", "body"]`. Oh, and there's `"body"` in
there too! And now we know the `ForStatement`'s `init` is executed
before the `body`.
Arrow functions can't be entrly skipped while traversing because this
references inside of them needs to be transformed, so I added a check
which prevents return statements inside arrow functions from being
saved for the transformation.
Fixes#5817 (regression)
* Move babel-standalone into main Babel repo
* Don't try to gather coverage data for babel-standalone test
* Fix JSX test
* Always use npm v4 on Travis
* Include pull request number as part of version number
* Cherry-picking 5721b2e43e
Remove deprecated packages to prevent Babel v6 files from being pulled in
* Use RootMostResolvePlugin to dedupe packages
* Avoid destructuring so the build works on archaic Node.js versions
* - Fix version number
- Remove Babili packages (they should be in separate babili-standalone)
- Remove deprecated syntax-class-constructor-call
* - Remove more Babili packages
- Remove `babel-plugin-inline-replace-variables` for now as it pulls in Babel 6 stuff
* Actually remove reference to babel-plugin-undeclared-variables-check
* Add Babylon to root package.json so we hoist the right version. This fixes the tests.
* add transform-class-properties to stage 3, set spec mode to default
* update readme with examples; use `buildUndefinedNode()`; change behavior to always define both static and nonstatic class properties regardless of spec/loose mode; update tests
* Add babel-plugin-syntax-typescript and babel-plugin-transform-typescript
* Add babel-preset-typescript
* Remove unnecessary handler for JSXOpeningElement
* Use `t.isFoo(node)` instead of `node.type === "Foo"`
* Clean up parameter property assignment generation
* Don't use function for `isSuperCall`
* slice -> shift
* Calculate sourceFileHasJsx only if necessary
* Remove `export =` support
* remove some syntax readme newlines [skip ci]
* Integrate Test262
Introduce a GNU Make target for retrieving TC-39's Test262 suite and
validating parsing of the files it contains. Interpret each file as a
parser test in accordance with that project's `INTERPRETING.md`
document. Allow for the specification of allowed failures via a
"whitelist" file so that the test suite may help prevent regressions in
this project in situations where this project has known bugs. Initialize
the "whitelist" file with a listing of all tests that are currently
failing. Extend the continuous integration environment's configuration
to automatically run these tests.
* use graceful-fs and latest yarn on travis
* update lerna and lerna-changelog
* Lerna: enable yarn, yarn workspaces [skip ci]
* use older version of Babel since it matches on semver (cannot be the same version)
* install yarn version
* revert node engine change
* update flow
* circle ci on 8
* update lock
* Arrow fns can't be used as the left side of a binary or ternary expression
Fixes#536
* Add test for logical expression with arrow function
* Fix eslint
* babel-generator: Add TypeScript support
* Remove type declarations; not published from babylon
* Remove TODOs
* Consistently use `this.word` for tokens that are words
* allow PluginPass.file.addImport to create empty import statements; fixes#6021
omitting addImport's second argument creates an import statement with an
empty `specifiers` array i.e. an empty import statement:
plugin:
Program (path, { file }) {
file.addImport('foo-bar/register')
}
output:
import "foo-bar/register";
* babel-types: Add TypeScript definitions
* Add missing builders
* Allow arrow function to have "generator"
* Replace link to resolved issue with comment
* Re-add 'generator' to functionCommon
* Create "babel-helper-wrap-function"
It contains the logic to wrap a function inside a call expression.
It was part of the "babel-helper-remap-async-to-generator" package, but
it is needed to transpile "function.sent"
* Create "babel-transform-function-sent"
It transforms the "function.sent" meta property by replacing it with
"yield" and making the generator ignore the first ".next()" call.
* "function.sent" is the last value passed to .next(), not the first one
* Disable exec tests on old node
* Fix flow error
* Add "transform-function-sent" to "stage-2" preset
* Do every trasformation in one traversal
* Test for "yield function.sent"
* [skip ci]
* Fix some typos [skip ci]
* Use first binding for multiple var declarations
Since var declarations after initial binding have no effect, use the
first declaration. Fixes#2378
* Include hoisted function bindings
* Missing newline in expected.js
* Simplify constantViolations in new Binding on existing
* clarify comment language
* Add optionality to catch bindings (plus tests)
* Update ast/spec, README, set param to null if no param with plugin optionalCatchBinding
* Fix: wrap param = null in else case
* Fix tests for optional catch binding; add tests which include finally clause
* Figuring out where to place throw statement
* Restored path argument destructuring
* New approach using comma expressions for assignments
* Moved throwNode into body of forXstatements
* Refactored with helper function and ensureBlock, additional tests for update exprs
* Added exec tests for all violations
* Hoisted helper function for comma expression outside of visitor
* Remove parens around break and continue
Fixes#5742
* Fix space in doc comment
* Add some tests
* Remove newlines within CommentBlock
* Prevent newline before/after label
* Remove reference to node
* Check for label within startTerminatorless
* Print block instead of single line comment
* Clean up
* Add new.target transform
* Catch new.target under only an arrow function
* More unsupported reflect.construct cases
* Fix node 4 test
* Do not transform Methods
* More tests
* Properly setup function inheritance test
* Tests tests tests
* Fix ES6 class's new.target
* Remove expected output thats supposed to throw.
* Remove whitespace generation and rely on default printing
Changes to printing:
* Add newline after last empty SwitchCase
* Add newlines around block comments if they are non-flow comments or contain newlines
* Fix a few more fixtures
* Fix destructured exports
- adds a failing test based on description in #5768
- handles ObjectPattern and ArrayPattern
* use export assignment template
* Distinguish between ternary's : and arrow fn's return type
* Correctly parse nested arrow functions inside conditional expressions
Defer the conversion of arrow function parameters to assignable nodes so that
it is possible to use the (invalid) ast to get the exact position of the (wrong)
arrow functions.
* Check params of arrow fns w/ type params or w/o return type
* Fix also async functions
* Add test from prettier
https://github.com/prettier/prettier/issues/2194
* Don't check arrow params if they are valid at the first attemp
* Use state instead of relying on the "noArrowParamsConversion" parameter
* Remove noArrowParamsConversion
The parsing of private fields checks whether or not it is within a
class to determine if it is valid or not. However, the state.inClass
property is incorrect as it marks it as outside a class when the inner
class is closed.
This commit fixes this problem by replacing the state.inClass property
with a class nesting counter.
Given that private fields can only be used within classes, any code
using them must be in a strict mode context. As private fields cannot
be deleted, throw an early SyntaxError.
* Remove node 7 and introduce node 8 in travis config
Progress on #5804
* Run yarn install with node 8
Progress on #5804
* Remove expose_debug_as from tests; replace with expose_gc_as
Fixes#5804
* Remove dashed options since they aren't listed
* Revert "Remove dashed options since they aren't listed"
This reverts commit f826167e320ee85331e09ac63b5674401cac6236.
This way, it quickly returns from the conditions. The first nil will
now exit, instead of checking every nil.
This also allows conditionalChaining inside a container to still
operate the container.
* Wrap an arrow function in parentheses if it the test of a conditional expression
Fixes#5819
* Use ConditionalExpresion to check if () => {} should be wrapped
* Move `t.isTaggedTemplateExpression()` from ArrowFunctionExpression to
ConditionalExpresion
* [test] `await (() => {})` needs the parentheses
* [test] (a ? b : c)`` needs the parentheses
* Spec compatibility for template literals.
* Update preset-es2015 `spec` expected case.
* Prevent array mutability by replacing `shift`.
* Fix condition for single item.
* Group concats to ensure toPrimitive sequence.
* Update function test case.
* Add semi for function test case.
* Simplify concat call expressions creating.
* Fix some cases with multiple idengifiers.
* Add test case with different literals.
* Add test case for `Symbol()` and toPrimitive order
* Add actual literal case.
* Add minNodeVersion to template literals order.
* Flip the logical expression.
* Update README for template literals spec option.
* docs [skip ci]
* Add plugin for import.meta proposal
Fixes https://github.com/babel/babylon/issues/539
* Tests for assignment/mutation of import.meta
* Use correct identifier in failure message
* Simpler & more consistent script errors for import.meta
The arguments of a function would be unnecessarily copied if there was
a nested function that had a parameter with the same identifier as the
rest parameter for the outer function. This checks the scope of the
parameter is correct before deoptimising.
Fixes: https://github.com/babel/babel/issues/5656
Refs: https://github.com/babel/babel/issues/2091
* Add support for declare export
* Do not allow declare module inside declare module
* Reallow module exports outside module
* Add handling of `declare export default`
Add check for multiple module.export declarations
* Disallow export let/const/type
Refactor parsing object properties to share more code and add support
for getters and setters
* Rename tests
* Update test fixtures
* Optimize for performance
* disallow declare export interface outside of module
* Refactor code to be more readable and less lookahead
* Add comments
* Add test for export star as
* Test for number literal getter/setter
* Add more tests
* Fix tests
* Allow union types and correctly eat semi after type
* Use non computed keys
* Fix tests
* Add support for flow type spread (#418)
* Add support for flow type spread
* Broaden spreadable types from primary to all, more tests
* Eliminate variance sigil for type spreads, better errors, fix tests
# Conflicts:
# src/plugins/flow.js
* Fix tests
* Add support for flow type spread
* Broaden spreadable types from primary to all, more tests
* Eliminate variance sigil for type spreads, better errors, fix tests
* Test runner: Detect extra property in 'actual' but not in 'expected'.
Also update all expected.json where this would result in errors.
* Include rmExpected.js script in case it is needed again
* master:
Upgrade flow to 0.41
Throw error if new.target is used outside of a function (#402)
Fix watch command (#403)
Update yarn lock
Fix parsing of class properties (#351)
# Conflicts:
# src/parser/statement.js
# test/fixtures/experimental/class-constructor-call/illegal-key/options.json
* Fix negative number literal typeannotations
Also use parseLiteral() to parser string and number literal typeannotations
so that future changes (estree) to literals are also reflected to flow.
* Instead of invalid fallthrough throw immediately
* Increase coverage and better error mesage
* Initial estree support for ClassMethod
* Handle literals for estree
* Fix regex
* correct output of regexp and regenerate test
* Add tests for validation stuff with estree plugin
* Parse Properties correctly
This also refactors how babylon parses obj properties in general
so that this logic can be more easily extended.
* Run all throws-tests a second time with estree plugin
* Fix all throw tests
* Remove rebase conflict
* Correctly set kind
This ensures state.inMethod gets propagated correctly
* Add computed: false to methods with ident async
* Implement directive field on Directives
* Test invalid directives
* more tests
* [Flow] Function predicate declaration
The accepted syntax for function declarations is extended to allow
the following predicate declaration:
FunctionReturnType :=
Type
Predicate
Type Predicate
Predicate :=
%checks
%checks ( ConditionalExpression )
* [Flow] Minor tweaks and more examples to function predicates
* [Flow] Clean-up and better message for function predicates
* [Flow] Adding abstract function predicate example
* [Flow] Rearranging the `predicate` field to ease babel generator.
* Replace manual electron-to-chromium list and function with external library
* test fixtures for electron: Switch to electron 1.4, with known chrome version and update expected output
* update tests: electron 1.0 used chrome 49, not 50
* import only the relevant function from electron-to-chromium
* electron fixtures: Use number instead of string
* If both chrome and electron are defined, choose the lower version to preserve
* Add to test cases to verify correct handling of chrome number
* refactor(tokenizer): use class for keywork tokens
* refactor(tokenizer): re-use constacts in types
* refactor(tokenizer): binop token type
* feat(tokenizer): use beforeAndStartExpr for shortcut
* fix(tokenizer): typo in keywordTokenType
* refactor(tokenizer): don't use spread operator
* refactor(tokenizer): constant for isLoop, isAssign, prefix, postfix
* fix(tokenizer): remove constant beforeAndStartExpr
* style(tokenizer): space after comma
Adding the line `this.state = this.state.clone();` in a parser plugin
(specifically, in my case `parseExprAtom`)
would break decorators.
This change fixes that.
* Use fromCodePoint to convert high value unicode entities
* Include polyfill for String.fromCodePoint
* copy and adapt fromCodePoint into String.fromcodepoint
In order to avoid modifying String as the polyfill does, I've copied
the source from the polyfill and adapted it return the polyfill
function if the native version does not exist. Once support for node
versions that lack fromCodePoint is dropped, this polyfill can be
removed.
* move license notice to top of file
* Rename ios_saf in browserslist data to ios, ignore unknown browsers
browserslist queries, especially ones with percentages, often bring in mobile browsers that _probably_ have the similar support level as desktop ones, but since there's no support for them in the data, including them here would just lead to all plugins being enabled always.
It's also easy to get crazy things like `op_mini` or `and_uc` in the results.
Browserslist also reports iOS Safari as `ios_saf`, while the data uses `ios`, so it needs to be renamed.
* Fix lint
* Run tests of flow with babylon
* Fix travis
* Fix typo
* Again...
* Brtter hint
* proper exit code
* Fix some flase-positives and better reporting
* Enable some plugins, that flow supports by default
* Parse flow nested array type annotations like number[][]
Fixes#217.
* Do not parse a newline separated array statement into a flow type annotation
* Get rid of lineBreak dependency in flow.js in favor of higher level method
browserslist queries, especially ones with percentages, often bring in mobile browsers that _probably_ have the similar support level as desktop ones, but since there's no support for them in the data, including them here would just lead to all plugins being enabled always.
It's also easy to get crazy things like `op_mini` or `and_uc` in the results.
Browserslist also reports iOS Safari as `ios_saf`, while the data uses `ios`, so it needs to be renamed.
* Add code coverage from Babel tests
* Configure nyc correctly for Babel test coverage
* Guard against nyc config conflicts if Babel switches to nyc in the future
* Move .nyc_output from Babel build dir to root
* Use .gitattributes to ignore files with weird newlines
* [Flow] Make parameter names in function types optional
* [Flow] Anonymous function types with single params can omit parens
* [Flow] Optional names for object indexer keys
* Add noAnonFunctionType explicitly to state
* Adjust gitattributes as files have been fixed
* Increase test coverage
* Test for error when binding `this` in destructuring pattern
* Ignore coverage of inAsync check in parseAwait - already checked externally
* Ignore coverage of default case in checkPropClash
* Remove unused parameter isAsync from parseParenAndDistinguishExpression
* Ignore coverage of an `else` branch in flowParseTypeParameterDeclaration
* Flow: remove unused parameters to flowParseTypeAnnotatableIdentifier
* Flow: ignore coverage of pass-through throw statement in parseConditional
* Flow: Add test for error on property with type param
* Flow: ignore coverage of pass-through throw statements in parseMaybeAssign, parseArrow
* Add test for error on XML-style comment in module code
* Update test for error on method in object pattern
* Test for error: "Only '=' operator can be used for specifying default value"
* Property variance type annotations for Flow plugin
Non-method properties and indexers of object types, declare class, and
interfaces can be "positive" or "negative." Class fields, but again not
methods, can also have variance.
This PR generalizes the variance annotations for type parameters into a
new node type, and reuses that node for those properties.
The code for object types is reused for interfaces and declare classes.
The changes there are straightfoward.
The code for class fields is reused for object literals, which do not
support variance annotations (currently). This code is a bit sketchy,
because we always parse variance annotations in the `parsePropertyName`
extension, then error in a the subsequent parse phase for object
literals (`parseObjPropValue`) or class methods (`parseClassMethod`).
* Remove bogus unreachable code, clarify variance parsing conditional
* Don't use a new node type for variance annotations
Adding a new node type, specifically changing the TypeParameter node's
variance property to be node-valued, is a breaking change. We might
choose to make this breaking change in a later version.
* s/start/variancePos
Expanding on #150, this allows `unexpected()` to accept the expected token type instead of a message string.
This overload is then used in a couple more places (that independently implement a logic similar to `expect()`'s) to construct an `Unexpected token, expected FOO` message.
I also noticed that there was missing test coverage for builtin types,
so I added a test for that, which includes the newly added type as well
as the other existing types.
* Use browserslist to parse browsers from query.
* Update README.
* Use int values.
* Allow `isPluginRequired` use browserslist queries.
* Fix conflicts during different versions merging.
* Add tests for browserslist queries.
* Early return for getTargets.
* Update README: Describe `browsers` option.
* fix doc [skip ci]
* Move to dependencies [skip ci]
* Remove unused const.
* Use doublequotes for strings.
* Add Caveat section to Readme.md
The Caveat section details some known issues and workaround when targeting specific environments and using specific plugins.
* fixes [skip ci]
Use the data from https://github.com/kangax/compat-table to build the
browser data.
Each Babel plugin is mapped to a list of features in the compatibility
table (in `data/pluginFeatures.js`), and the minimum supporting
version looked up from the compatibility test data. The script builds
the final browser data file in `data/plugins.json`.
* Fix parsing object rest
This makes object-rest-spread behave according to spec and only
allow one rest operator and enforces it to be the last
param in the object.
Also move all object-rest-spread tests to a own folder.
* Show nicer error messages
* Rephrase "assigning/binding to rvalue" error messages with context (#119)
* Fix code style in parser/lval.js
* istanbul ignore some unused branches in parser/lval.js
* Fix code style again in parser/lval.js
* Slightly simplify logic
* Implement ES2016 check for simple parameter list in strict mode
See e.g. ECMA-262 7.0 14.1.2:
> It is a Syntax Error if ContainsUseStrict of FunctionBody is true and
> IsSimpleParameterList of FormalParameters is false.
Similar clauses cover arrow functions, generator functions, methods, and
generator methods, as well as async functions and async arrow functions.
* exact object type annotations for Flow plugin
* Couple tweaks per suggestions
* s/==/===/
* add test for unexpected token in flowObjectType Semicolon
This makes declare class extends behave the same way as in flow
The ast-token after the extends keyword, might be either Identifier or
QualifiedTypeIdentifier
To do that this commits splits the parseGenericType into two functions,
one for parsing genericType and on for qualifiedTypeIdentifier
Flow's "toAssignable" override wasn't calling the inner function,
resulting in the destructuring in an AssignmentPattern not having the
node type changed from ObjectExpression to ObjectPattern, resulting in
"Binding rvalue" thrown from "checkLVal()"
* This removes the exponentiationOperator as it is now in es2016
* Remove from tests
* Remove asyncFunctions and restructure test dirs
* Remove trailingFunctionCommas
We do not clone arrays in lookahead() but comments were added
to leading/trailing arrays during lookahead, leading to leak to the next next() call.
Also extracted parsing of JSXSpreadChild to own parse function.
This commit e6c11a0 (#19) made a big performance regression.
The reason was that parseConditional was always cloning the current state
even if no question mark (potential conditional or flow-optional
token) was at the current position.
Simply checking if questionmark matches the current token solves the problem.
Fixes#62
The cloning caused comments that where added to the original node to be persisted into
the cloned node.
Espree/Acorn does not have any cloning, that's why it is working there.
This change omits comments when cloning, as removing the cloning
causes tests in babel to fail.
The primary goal of this commit is to add the ability to parse type parameter
declarations with defaults, like `type Foo<T = string> = T`. While I was in the
code, I fixed a few small things, like
* Type parameter declarations need 1 or more type parameters.
* The existential type `*` is not a valid type parameter.
* The existential type `*` is a primary type
* The param list for type parameter declarations now consists of
`TypeParameter` nodes
This fixes an issue that comments were added as leading comments
to expressions, which are not immediately folowing the comment.
This was also reported and fixed in espree, and is basically a port to
babylon. eslint/espree#256
this also fixes an issue in babel-eslint with certain rules babel/babel-eslint#289
The fix includes creating a new method on the parser called `parseArrow`.
This new function by default only checks if current position matches an
arrow. If it does returns the `node` otherwise `undefined`.
The flow plugin can then extend this function and correctly parse the typeAnnotation
and add it to the node.
With this change, in the flow plugin there is no need anymore to extend
`parseParenAndDistinguishExpression` and the arrow handling in `parseParenItem`
could also be removed, because it is all handled now in `parseArrow`.
Some existing tests were failing, because `extra->parentesized` is now missing,
but this is correct as it is now inline with parsing without flow annotation. No extra
is added for arrow function without type annotations.
In the expression-parser `this.next()` was replaced by a more specific
`this.expect(tt.parenL)`.
This syntax allows you to specify whether a type variable can appear in
a covariant or contravariant position, and is super useful for, say,
Promise.
Right now this is hacked in jankily, but in the next major release we
should stop using Identifier nodes for type parameters.
An interface export is just like a type export. In fact, it's a syntax affordance which makes the following equivalent:
```javascript
interface I_ { ... }
export type I = I_;
```
```javascript
export interface I { ... }
```
See facebook/flow#1145
This has been a feature in Flow for a long time (couldn't easily find a
specific commit adding this). Interfaces are basically undocumented, though, so
it's easy to see how this was missed.
For example:
var foo = function () {
"use strict";
"use strict";
// there is inside of strict mode,
// so `0123` (octal number) occurs a syntax error.
};
// there is outside of strict mode,
0123; // so left is valid syntax.
// however:
// SyntaxError: Invalid number (8:0)
I fixed it and add the test case.
Removed `@flow` annotation from files that don't actually pass Flow check at the moment. These will be added back file by file once the files are properly converted to use Flow.
Closes#3064
I'm extremely stupid and didn't commit as I go. To anyone reading this
I'm extremely sorry. A lot of these changes are very broad and I plan on
releasing Babel 6.0.0 today live on stage at Ember Camp London so I'm
afraid I couldn't wait. If you're ever in London I'll buy you a beer
(or assorted beverage!) to make up for it, also I'll kiss your feet and
give you a back massage, maybe.
- The visitor keys for `ObjectTypeAnnotation`s were incorrect so those nodes weren't being traversed so comments weren't attached for them.
- The type parser wasn't eating the semicolons for the nodes so the `end` location of each of the type properties wasn't accurate which threw off the code generation newline algorithm.
- Type properties hadn't been given the `UserWhitespacable` alias.
This completely changes the interface, and removes most of the complexity
in the old tokenizer interface (jump-to-position was removed, since it is
all kinds of unreliable given the new tokenizer context system).
Makes almost everything in acorn.js a method of this object.
Performance is not significantly affected on a modern V8. Makes the
code reentrant and allows us to more easily expose more methods
externally in the future.
On the other hand, the proliferation of `this.` is unfortunate.
Now identifiers and strings even with escaped chars are read
in optimized way by reading entire chunks delimited by escape
chars (and not bailing to deopt mode on first one).
Avoid need for:
* extra `templates` array in favor of new `tokContext`;
* special location handling for first & last template elements;
* separate `_templateContinued` token in favor of same `_template`.
Adds:
* token types for backQuote and dollarBraceL instead of skipping them
so they can be handled (i.e. highlighted differently).
* Parsing assignables without extra transform step when possible (speed-up).
* Added support for shorthand defaults in such certain contexts (issue #181).
Conflicts:
acorn.js
acorn_loose.js
* Parsing assignables without extra transform step when possible (speed-up).
* Added support for shorthand defaults in such certain contexts (issue #181).
Define Program node extent to be the whole program, make
both parser and the tests conform to this.
Fix a bunch of bugs in the loose parser's handling of corner
cases.
Issue #151
* Added support for acorn_loose and grouped log to web-driver.
* Removed unused copy-pasted `parseTemplate` from loose parser.
* Throw non-SyntaxError errors immediately (as those are generic).
* Tokens are now instances of single exported constructor Token.
* Token objects are compatible with Esprima (only `type` format is different).
* Added token.loc in format of node.loc (Mozilla).
* Deprecated token.startLoc & token.endLoc.
* Updated comment generation example.
Also added ability to pass arrays in `onToken`/`onComment` where
tokens/comments will be collected in Esprima's format so you can
simply pass those arrays to `escodegen.attachComments`.
Updated docs and comment attachment example.
* Fixed `onToken` & `tokenize` to return `startLoc` & `endLoc`
in token object only when `options.locations` is `true`.
* Fixed `onToken` tests.
* Added example for generating comments with escodegen.
Possible dev relic.
readToken_slash currently does not have any arguments and does not appear to look at arguments. All existing tests pass after removal of extraneous argument while calling readToken_slash.
http://wiki.ecmascript.org/doku.php?id=harmony:rest_parameters
The final parameter to a function is a rest parameter if it is
prefixed by "...". FunctionExpression and FunctionDeclaration
nodes have a new "rest" property that is null if there is no
rest parameter, or contains an Identifer for the parameter.
https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API#Functions
Implemented by adding a new token, `_ellipsis`, which consists of
three dots. Modified the body of parseFunction to allow a single
rest parameter at the end of an argument list. Both the token and
the rest parameter require `options.ecmaVersion` >= 6, otherwise
three dots are tokenized as three dots.
Before this the ast produced by parse_dammit crashed in the following
code, as Uglify correctly noticed that f."" is invalid.
sample = 'f."';
loose = require('acorn/acorn_loose');
uglify = require('uglify-js');
out = new uglify.OutputStream();
ast = loose.parse_dammit(sample);
ast = uglify.AST_Node.from_mozilla_ast(ast);
ast.print(out);
// TypeError: Cannot call method 'toString' of undefined
// member_exp.computed = false && member_exp.property == ""
console.log(out.toString());
After this the round-tripped AST looks like: `t.✖;"";`, which is
consistent with how `foo.{` is parsed.
I also considered making it parse as t[""], but as this only turns up in
the wild when people try to use multiline strings, I felt it was better
to be obviously wrong.
Both readString and skipLineComment considered 8232/8233 as eol, but skipSpace itself would not increment the line counters if they were found.
Previously 8232/8233 were listed in nonASCIIwhitespace, but since that is only used within skipSpace and those values are checked separately, they could be removed from nonASCIIwhitespace.
Just being consistent.
In every other place where a between comparison is done, the lower limit is on the left. It's a whole lot easier to see it's a between comparison when the limits are in order.
When the continued expression sat on column 1 after a non-whitespace char,
the heuristic would consider it the start of the line, even though it wasn't.
Issue marijnh/tern#141
Dedented tokens should only end an expression if they are actually the first
token on the line.
This to prevent code like this from going wrong:
x = (function(..) {
blah();
})(); // <-- indented same as start of expression
My initial idea, that client code would constantly need to access the individual
walker functions directly, isn't actually the case. This prevents unnecessary copying
of other interface functions into walkers.
When setting the .prototype.source the sourceFile variable is undefined, and
setting the sourceFile option doesn't change the .source property on the
prototype anymore.
By setting the .source property inside the node_loc_t constructor, the correct
sourceFile is set in the loc object.
In the generated ast, "null"/"true"/"false" are "Literal" nodes.
As every "Literal" node has a 'raw' property,
When i am doing something with the ast using python,
the 3 "Literal"s caused some problem.
make the 3 "Literal"s have 'raw' property.
This way, composite expressions that they are part of won't get bogus
unsyntactic substrings as their range (i.e. in '(1)+1', the binop expression
would span '1)+1').
Closes#14
- if `program` is given, it'll be used as the toplevel node, instead of
creating a new node, and statements will be added to its body
- if `sourceFile` is given and `locations` is ON, it'll set the `source`
property in every node's `loc`.
Checking for `\r\n?` is redundant with the `|[\n\r\u2028\u2029]`, better straighten the regexp and check for `\r\n|[\n\r\u2028\u2029]`. This might even be a itsy bitsty bit faster.
* Allow `inputSourceMap` to be set to `false` to skip the source map inference.
* Infer computed literal property names.
* **Bug Fix**
* Fix nested labeled for-ofs.
* Fix block scoping `break` colliding with the parent switch case.
* **Internal**
* Upgrade `acorn-babel`.
## 4.7.8
* **Bug Fix**
* Fix computed classes not properly setting symbols.
## 4.7.7
* **Bug Fix**
* Fix `types` API exposure.
## 4.7.6
* **Bug Fix**
* Fix non-Identifier/Literal computed class methods.
* **Polish**
* Add a fallback if `stack` on an error is unconfigurable.
* Hoist `esModule` module declarations to the top of the file to handle circular dependencies better.
## 4.7.5
* **Bug Fix**
* Don't remap` break`s to call the iterator return.
* **Polish**
* Use a different helper for computed classes for much nicer output. Also fixes a bug in symbols being non-enumerable so they wouldn't be set on the class.
## 4.7.4
* **Bug Fix**
* Rewrite named function expressions in optional async function transformers.
* Hoist directives.
* Remove `Number` from the list of valid `runtime` constructors.
* **Internal**
*`spec.typeofSymbol` transformer has been renamed to `es6.symbols`.
## 4.7.2
* **New Feature**
*`"both"` option for `sourceMap`.
* Add output types to external helpers. Thanks [@neVERberleRfellerER](https://github.com/neVERberleRfellerER)!
* **Bug Fix**
* Fix node duplication sometimes resulting in a recursion error.
* Ignore `break`s within cases inside `for...of`.
* **Polish**
* Split up variable declarations and export declarations to allow easier transformation.
## 4.7.0
* **Bug Fix**
* Add `alternate` to list of `STATEMENT_OR_BLOCK` keys.
* Add support for module specifiers to `t.isReferenced`.
* **New Feature**
* Add `inputSourceMap` option.
* **Polish**
* Throw an error on different `babel` and `babel-runtime` versions.
* Replicate module environment for `babel-node` eval.
* Clean up classes output.
* **Spec Compliancy**
* Make it illegal to use a rest parameter on a setter.
## 4.6.6
* **Bug Fix**
* Fix incorrect method call in `utility.deadCodeElimination` transformer.
*`useStrict` transformer has been renamed to `strict`.
## 4.6.4
* **Bug Fix**
* Fix `ForOfStatement` not proplery inheriting labels.
* When in closure mode in block scoping transformer, properly check for variable shadowing.
* **New Feature**
* New `utility.inlineEnvironmentVariables` and `utility.inlineExpression` transformers.
## 4.6.3
* **Bug Fix**
* Fix `arguments` being incorrectly aliased in arrow function rest parameter optimisation.
* Make deoptimisation trigger safer.
* **New Feature**
* Flow types are now retained when blacklisting the `flow` transformer.
## 4.6.1
* **Bug Fix**
* Fix generators in template directory being transformed.
* Fix exposure of `util` for plugins.
## 4.6.0
* **New Feature**
* Desugar sticky regexes to a new constructor expression so it can be handled by a polyfill.
* **Spec Compliancy**
*`for...of` now outputs in a lengthy `try...catch` this is to ensure spec compliancy in regards to iterator returns and abrupt completions. See [google/traceur-compiler#1773](https://github.com/google/traceur-compiler/issues/1773) and [babel/babel/#838](https://github.com/babel/babel/issues/838) for more information.
* **Polish**
* Rest parameters that are only refered to via number properties on member expressions are desugared into a direct `arguments` reference. Thanks [@neVERberleRfellerER](https://github.com/neVERberleRfellerER)!
*`$ babel` no longer exits on syntax errors.
* **Internal**
* Upgrade `browserify`.
* Upgrade `source-map`.
* Publicly expose more internals.
## 4.5.5
* **Polish**
* Delete old extensions when overriding them in `babel/register`.
## 4.5.3
* **Bug Fix**
* Fix whitelisting logic for helper build script.
## 4.5.2
* **New Feature**
*`returnUsedHelpers` option and add whitelist to `buildHelpers`.
* **Bug Fix**
* Fix function arity on self referencing inferred named functions.
* Republish to get fix for runtime `typeof-react-element` helper.
## 5.8.25
* **Internal**
* Rename `define` method to avoid webpack assuming those files are AMD.
## 5.8.24
* **Spec Compliancy**
* Updated `optimisation.react.inlineElements` transformer to React 0.14 output. Thanks [@spicyj](https://github.com/spicyj)!
* **Polish**
* Add support for evaluating more static nodes. Thanks [@hzoo](https://github.com/hzoo)!
## 5.8.23
* **Bug Fix**
* Fix a bug where pushed scope bindings weren't properly being registered.
## 5.8.22
* **Bug Fix**
* Fix bug causing regexes to cause a syntax error after a block.
* **Internal**
* Expose `File`.
## 5.8.21
* **New Feature**
* Add support for Flow export types.
* **Bug Fix**
* Fix flow type annotations on object properties being lost.
* Fix bug effecting nested arrow functions.
* Check valid `export default``function`/`class` token when parsing export default before converting to a declaration to avoid turning expressions into declarations.
* **Polish**
* Add an exception to non-existent bindings when checking if we need to wrap block scoping blocks in a closure.
* Make comment retainment for multiple replacement nodes more predictable.
* **Internal**
* Remove `operator` property from `AssignmentPattern` nodes.
* Update `es7.asyncFunctions` and `es7.objectRestSpread` to stage 2.
## 5.8.13-5.8.20
**The CHANGELOG was broken for these releases. Git tags were not pushed in the correct order and are therefore incorrect. It's recommended you NOT use any versions within this range.**
* **New Feature**
* Add `es6.spec.modules` transformer.
* **Bug Fix**
* Don't register export declarations as a module binding.
* Register import bindings to the specifier instead of the declaration.
*`export *` should not export `default`.
* Clear `rawValue from JSX attribute values to avoid outputting the raw source verbatim.
* Add support for boolean flow literals.
* Fix bug where files that babel can compile weren't being written when ignored with the `--copy-files` flag.
* Create new raw identifiers instead of cloning the original user one when exploding export specifiers to fix source map issues resulting in incorrect locations.
* Break on hitting a terminator paren triggering character to avoid pushing multiple starting parens.
* Consider comment starting character to be a terminatorless separator to avoid starting comments breaking terminatorless nodes.
* **Internal**
* Use `json5` for parsing `.babelrc` files and `JSON` for `package.json`.
* Update Regenerator dependency to `0.8.35`.
* Remove flow types from being scope tracked.
* **Polish**
* Only register export declarations in scope tracking if they're of a valid type.
* Only output code frame and message on syntax errors in CLI.
* Set decorated initialisers that have no `initialiser` to `undefined`.
* Optimise common `typeof` cases in `es6.spec.symbols` transformer.
## 5.8.12
* **Bug Fix**
* Fix bug in lookahead causing decorators to be cleared.
## 5.8.11
* **Bug Fix**
* Check if module options are nully instead of falsy to allow empty strings as `moduleRoot` etc.
* Fix bug where reassigning the rest parameter wouldn't result in a deoptimisation.
## 5.8.9
* **Bug Fix**
* Fix issue in parser where the flow plugin wasn't using state to refer to whether it as in a type or not causing lookaheads to cause breakages.
## 5.8.8
* **Bug Fix**
* Fix comments not being attached if they're touching the start of their node.
## 5.8.7
* Never published, environment issues, again.
## 5.8.6
* **Bug Fix**
* Remove `rawValue` for JSX inner text.
## 5.8.5
* **Polish**
* Rewrite parentheses insertion for terminatorless nodes such as `BreakStatement` to be much more stable and cleaner.
* Use `Object.setPrototypeOf` and fallback to `__proto__` in `inherits` helper.
## 5.8.2-5.8.4
Issues with publish process.
## 5.8.1
* **Bug Fix**
* Fix regression where async arrow functions couldn't have type annotation parameters.
* Output type annotations of type instantiation parameters.
* **Polish**
* Prepend to highest loop when performing rest parameter allocation optimisation.
* Add comment attachment to parser.
* Add support for retaining inner comments of empty blocks.
## 5.8.0
* Never released due to publish environment issues.
## 5.7.4
* **Bug Fix**
* Fix comments containg `@flow` being completely removed from output rather than just the specific directive.
## 5.7.3
* **Bug Fix**
* Add shim file for broken file path that old versions of the CLI would attempt to use.
## 5.7.2
* **Bug Fix**
* Fix performance issue in code generator when comment columns would attempt to match up in `compact` mode causing large amounts of whitespace.
* Fix single line comments not outputting a newline in `compact` mode.
* **Polish**
* Add support for flow return types for arrow functions.
## 5.7.1
* **Bug Fix**
* Add back mistakenly removed `replaceWithSourceString` method.
## 5.7.0
* **Bug Fix**
* Deopt on spread elements when performing array destructuring unpack optimisation.
* **New Feature**
* Add `shouldPrintComment` option to control comment output.
* Add `.babelignore` file to be consistent with other tools.
* Allow `.babelrc` configs to be specified via `package.json`.
* **Polish**
* Don't ignore comments when using `compact: true` option.
* Add support for Flow `import typeof`.
* Fix incorrect inheritance method position when using loose mode classes and constructor isn't the first item.
* **Internal**
* Completely fork Acorn with `babylon`.
* Rewrite build system to accommodate for multiple packages.
## 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`.
* 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.
* 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.
* 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.
* 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)!
* 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 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.
Babel has always been a community project, not really backed or owned by any single (or group) of companies. While some maintainers used to work at Facebook (and Henry at Adobe) no one was working on it full time and there certainly isn't a huge company or team anywhere doing all this work.
---
As a group of volunteers you can help us in a few ways
- Giving developer time on the project. (Message us on [Twitter](https://twitter.com/babeljs) or [Slack](https://slack.babeljs.io/) for guidance). Companies should be paying their employees to contribute back to the open source projects they use everyday.
- Giving funds by becoming one of our sponsors/donators!
If you'd like to sustain the future of the project as a whole, we have an [Open Collective](https://opencollective.com/babel) that you can donate to. This is a way for funds to be allocated to the core team.
You can also support [Henry](https://github.com/hzoo) directly since I [left my job to work on Babel and Open Source full time](https://twitter.com/left_pad/status/969793227862790144) at my [Patreon](https://www.patreon.com/henryzhu).
For any issue references: Add a comma-separated list of a [closing word](https://help.github.com/articles/closing-issues-via-commit-messages/) followed by the ticket number fixed by the PR
For issue references: Add a comma-separated list of a [closing word](https://help.github.com/articles/closing-issues-via-commit-messages/) followed by the ticket number fixed by the PR. (it should be underlined in the preview if done correctly)
If you are making a change that should have a docs update: submit another PR to https://github.com/babel/website
-->
| Q | A <!--(yes/no) -->
| Q | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Patch: Bug Fix? |
| Major: Breaking Change? |
| Minor: New Feature? |
| Deprecations? |
| Spec Compliancy? |
| Tests Added/Pass? |
| Fixed Tickets | `Fixes #1, Fixes #2` <!-- rm the quotes to link the issues -->
| Fixed Issues? | `Fixes #1, Fixes #2` <!-- remove the (`) quotes to link the issues -->
| Patch: Bug Fix? |
| Major: Breaking Change? |
| Minor: New Feature? |
| Tests Added + Pass? | Yes
| Documentation PR Link | <!-- If only readme change, add `[skip ci]` to your commits -->
| Any Dependency Changes? |
| License | MIT
| Doc PR | <!-- if yes, add `[skip ci]` to your commit message to skip CI builds -->
| Dependency Changes |
<!-- Describe your changes below in as much detail as possible -->
# NOTE: DO NOT OPEN ISSUES FOR QUESTIONS AND SUPPORT. SEE THE README FOR MORE INFO.
----
<p align="center" class="toc">
@@ -19,32 +17,33 @@
# Contributing
> Before contributing, please read our [code of conduct](https://github.com/babel/babel/blob/master/CODE_OF_CONDUCT.md).
Contributions are always welcome, no matter how large or small.
Contributions are always welcome, no matter how large or small. Before
contributing, please read the
[code of conduct](https://github.com/babel/babel/blob/master/CODE_OF_CONDUCT.md).
## Not sure where to start?
- If you aren't just making a documentation change, you'll probably want to learn a bit about a few topics.
- [ASTs](https://en.wikipedia.org/wiki/Abstract_syntax_tree) (Abstract Syntax Tree): The Babel AST [spec](https://github.com/babel/babylon/blob/master/ast/spec.md) is a bit different from [ESTree](https://github.com/estree/estree). The differences are listed [here](https://github.com/babel/babylon#output).
- [ASTs](https://en.wikipedia.org/wiki/Abstract_syntax_tree) (Abstract Syntax Tree): The Babel AST [spec](https://github.com/babel/babel/blob/master/packages/babel-parser/ast/spec.md) is a bit different from [ESTree](https://github.com/estree/estree). The differences are listed [here](https://github.com/babel/babel/tree/master/packages/babel-parser#output).
- Check out [`/doc`](https://github.com/babel/babel/tree/master/doc) for information about Babel's internals
- Check out [the Babel Plugin Handbook](https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-plugin-handbook) - core plugins are written the same way as any other plugin!
- Check out [AST Explorer](http://astexplorer.net/#/scUfOmVOG5) to learn more about ASTs or make your own plugin in the browser
- When you feel ready to jump into the Babel source code, a good place to start is to look for issues tagged with [help-wanted](https://github.com/babel/babel/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) and/or [beginner-friendly](https://github.com/babel/babel/issues?q=is%3Aissue+is%3Aopen+label%3A%22beginner-friendly%22).
- When you feel ready to jump into the Babel source code, a good place to start is to look for issues tagged with [helpwanted](https://github.com/babel/babel/labels/help%20wanted) and/or [good first issue](https://github.com/babel/babel/labels/good%20first%20issue).
- Follow along with what we are working on by joining our [Slack](https://babeljs.slack.com) (you can sign-up [here](https://slack.babeljs.io/)
for an invite), following our announcements on [Twitter](https://twitter.com/babeljs), and reading (or participating!) in our [meeting notes](https://github.com/babel/notes).
- Check out our [website](http://babeljs.io/) and the [repo](https://github.com/babel/website)
## Chat
Feel free to check out the `#discussion`/`#development` channels on our [Slack](https://slack.babeljs.io). Some of us are always online to chat!
Feel free to check out the `#discussion`/`#development` channels on our [Slack](https://slack.babeljs.io) (you can sign-up [here](https://slack.babeljs.io/) for an invite). Some of us are always online to chat!
## Developing
**Note:** Versions `< 5.1.10` can't be built.
Babel is built for Node.js 4 and up but we develop using Node.js 6. Make sure you are on npm 3.
Babel is built for Node 6 and up but we develop using Node 8 and yarn. You can check this with `node -v`.
You can check this with `node -v` and `npm -v`.
In addition, make sure that Yarn is installed.
Make sure that Yarn is installed with version >= `0.28.0`.
Installation instructions can be found here: https://yarnpkg.com/en/docs/install.
### Setup
@@ -114,12 +113,25 @@ To run tests for a specific package in [packages](https://github.com/babel/babel
$ TEST_ONLY=babel-cli make test
```
`TEST_ONLY` will also match substrings of the package name:
```sh
# Run tests for the @babel/plugin-transform-classes package.
$ TEST_ONLY=babel-plugin-transform-classes make test
```
Use the `TEST_GREP` variable to run a subset of tests by name:
```sh
$ TEST_GREP=transformation make test
```
Substitute spaces for hyphens and forward slashes when targeting specific test names:
```sh
$ TEST_GREP="arrow functions destructuring parameters" make test
```
To enable the Node.js debugger added in v6.3.0, set the `TEST_DEBUG` environment variable:
```sh
@@ -128,6 +140,12 @@ $ TEST_DEBUG=true make test
You can combine `TEST_DEBUG` with `TEST_GREP` or `TEST_ONLY` to debug a subset of tests. If you plan to stay long in the debugger (which you'll likely do!), you may increase the test timeout by editing [test/mocha.opts](https://github.com/babel/babel/blob/master/test/mocha.opts).
To overwrite any test fixtures when fixing a bug or anything, add the env variable `OVERWRITE=true`
```sh
$ OVERWRITE=trueTEST_ONLY=babel-plugin-transform-classes make test-only
```
To test the code coverage, use:
```sh
@@ -135,59 +153,58 @@ $ BABEL_ENV=cov make build
$ ./scripts/test-cov.sh
```
#### Troubleshooting Tests
In case you're not able to reproduce an error on CI locally, it may be due to
In case you're not able to reproduce an error on CI locally, it may be due to
- Node Version: Travis CI runs the tests against all major node versions. If your tests use JavaScript features unsupported by lower versions of node, then use [minNodeVersion option](#writing-tests) in options.json.
- Timeout: Check the CI log and if the only errors are timeout errors and you are sure that it's not related to the changes you made, ask someone in the slack channel to trigger rebuild on the CI build and it might be resolved
In case you're locally getting errors which are not on the CI, it may be due to
- Updates in Dependencies: Make sure you run `make bootstrap` before you run `make build` or `make watch` before you run the tests.
### Writing tests
Most packages in [`/packages`](https://github.com/babel/babel/tree/master/packages) have a `test` folder, however some tests might be in other packages or in [`/packages/babel-core`](https://github.com/babel/babel/tree/master/packages/babel-core/test/fixtures).
#### `babel-plugin-x`
#### `@babel/plugin-x`
All the Babel plugins (and other packages) that have a `/test/fixtures` are written in a similar way.
For example, in [`babel-plugin-transform-exponentiation-operator/test`](https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-exponentiation-operator/test):
For example, in [`@babel/plugin-transform-exponentiation-operator/test`](https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-exponentiation-operator/test):
- There is an `index.js` file. It imports our [test helper](https://github.com/babel/babel/tree/master/packages/babel-helper-plugin-test-runner). (You don't have to worry about this).
- There can be multiple folders under [`/fixtures`](https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures)
- There is an [`options.json`](https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures/exponentian-operator/options.json) file whose function is similar to a `.babelrc` file, allowing you to pass in the plugins and settings you need for your tests.
- For this test, we only need the relevant plugin, so it's just `{ "plugins": ["transform-exponentiation-operator"] }`.
- For this test, we only need the relevant plugin, so it's just `{ "plugins": ["@babel/plugin-transform-exponentiation-operator"] }`.
- If necessary, you can have an `options.json` with different options in each subfolder.
- In each subfolder, you can organize your directory structure by categories of tests. (Example: these folders can be named after the feature you are testing or can reference the issue number they fix)
- Generally, there are two kinds of tests for plugins
- The first is a simple test of the input and output produced by running Babel on some code. We do this by creating an [`actual.js`](https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures/exponentian-operator/binary/actual.js) file and an [`expected.js`](https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures/exponentian-operator/binary/expected.js) file.
- If you need to expect an error, you can ignore creating the `expected.js` file and pass a new `throws` key to the `options.json` that contains the error string that is created.
- The first is a simple test of the input and output produced by running Babel on some code. We do this by creating an [`input.js`](https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures/exponentian-operator/binary/input.js) file and an [`output.js`](https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures/exponentian-operator/binary/output.js) file. This kind of test only works in sub-subdirectories of `/fixtures`, i.e. `/fixtures/exponentian-operator/binary/input.js` and **not**`/fixtures/exponentian-operator/input.js`.
- If you need to expect an error, you can ignore creating the `output.js` file and pass a new `throws` key to the `options.json` that contains the error string that is created.
- The second and preferred type is a test that actually evaluates the produced code and asserts that certain properties are true or false. We do this by creating an [`exec.js`](https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures/exponentian-operator/comprehensive/exec.js) file.
In an actual/expected test, you simply write out the code you want transformed in `actual.js`.
In a fixture test, you simply write out the code you want transformed in `input.js`.
```js
// actual.js
// input.js
2**2;
```
and the expected output after transforming it with your `options.json` in `expected.js`.
and the expected output after transforming it with your `options.json` in `output.js`.
```js
// expected.js
// output.js
Math.pow(2,2);
```
In an `exec.js` test, we run or check that the code actually does what it's supposed to do rather than just check the static output.
```js
// exec.js
assert.equal(8,2**3);
assert.equal(24,3*2**3);
expect(2**3).toBe(8);
expect(3*2**3).toBe(24);
```
If you need to check for an error that is thrown you can add to the `options.json`
@@ -195,8 +212,8 @@ If you need to check for an error that is thrown you can add to the `options.jso
"throws":"@babel/plugin-proposal-object-rest-spread currently only accepts a boolean option for useBuiltIns (defaults to false)"
}
```
@@ -209,20 +226,45 @@ If the test requires a minimum Node version, you can add `minNodeVersion` (must
}
```
#### `@babel/parser` (babylon)
Writing tests for the babel parser is very
similar to the other packages.
Inside the `packages/babel-parser/test/fixtures` folder are categories/groupings of test fixtures (es2015, flow,
etc.). To add a test, create a folder under one of these groupings (or create a new one) with a
descriptive name, and add the following:
* Create an `input.js` file that contains the code you want the babel parser to parse.
* Add an `output.json` file with the expected parser output. For added convenience, if there is no `output.json` present, the test runner will generate one for you.
After writing tests for @babel/parser, just build it by running:
```sh
$ make build
```
Then, to run the tests, use:
```sh
$ TEST_ONLY=babel-parser make test-only
```
#### Bootstrapping expected output
For both `babel-plugin-x` and `babylon`, you can easily generate an `expected.js`/`expected.json` automatically by just providing `actual.js` and running the tests as you usually would.
For both `@babel/plugin-x` and `@babel/parser`, you can easily generate an `output.js`/`output.json` automatically by just providing `input.js` and running the tests as you usually would.
```
// Example
- babylon
- test
- fixtures
- comments
- basic
- block-trailing-comment
- actual.js
- expected.json (will be generated if not created)
- packages
- babel-parser
- test
- fixtures
- comments
- basic
- block-trailing-comment
- input.js
- output.json (will be generated if not created)
```
### Debugging code
@@ -244,7 +286,7 @@ To include the changes, we have to make sure to build Babel:
$ make build
```
Next, we need to execute `Generator.generate()`, which can be achieved by running a test case in the `babel-generator` package.
Next, we need to execute `Generator.generate()`, which can be achieved by running a test case in the `@babel/generator` package.
For example, we can run the test case that tests the generation of class declarations:
```bash
@@ -252,7 +294,6 @@ $ TEST_DEBUG=true TEST_GREP=ClassDeclaration make test-only
./scripts/test.sh
Debugger listening on port 9229.
Warning: This is an experimental feature and could change at any time.
To start debugging, open the following URL in Chrome:
@@ -261,10 +302,22 @@ To start the debugging in Chrome DevTools, open the given URL.
The debugger starts at the first executed line of code, which is Mocha's first line by default.
Click _Resume script execution_ <img src="https://i.imgur.com/TmYBn9d.png" alt="Resume script execution button." width="16"> to jump to the set breakpoint.
Note that the code shown in Chrome DevTools is compiled code and therefore differs.
- Create a new issue that describes the proposal (ex: [#538](https://github.com/babel/babylon/issues/538)). Include any relevant information like proposal repo/author, examples, parsing approaches, meeting notes, presentation slides, and more.
- The pull request should include:
- [ ] An update to the [plugins](https://github.com/babel/babel/tree/master/packages/babel-parser#plugins) part of the readme. Add a new entry to that list for the new plugin flag (and link to the proposal)
- [ ] If any new nodes or modifications need to be added to the AST, update [ast/spec.md](https://github.com/babel/babel/bloc/master/packages/babel-parser/ast/spec.md)
- [ ] Make sure you use the `this.hasPlugin("plugin-name-here")` check in the babel parser so that your new plugin code only runs when that flag is turned on (not default behavior)
- [ ] Add failing/passing tests according to spec behavior
- Compiler environment support ([doc/design/compiler-environment-support.md](https://github.com/babel/babel/blob/master/doc/design/compiler-environment-support.md))
Babel is a community-driven tool that helps you write code in the latest version of JavaScript.
Babel is a community-driven project used by many companies and projects, and is maintained by a group of [volunteers](https://babeljs.io/team). If you'd like to help support the future of the project, please consider:
When your supported environments don't support certain features natively, Babel will help you compile those features down to a supported version.
- Giving developer time on the project. (Message us on [Twitter](https://twitter.com/babeljs) or [Slack](https://slack.babeljs.io/) for guidance!)
- Giving funds by becoming a sponsor (see below)!
## Open Collective Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/babel#sponsor)]
Babel is a tool that helps you write code in the latest version of JavaScript. When your supported environments don't support certain features natively, Babel will help you compile those features down to a supported version.
**In**
@@ -41,242 +93,43 @@ When your supported environments don't support certain features natively, Babel
});
```
Try it out at our [REPL](https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=latest&code=%5B1%2C2%2C3%5D.map(n%20%3D%3E%20n%20%2B%201)%3B&experimental=true&loose=true&spec=false&playground=false&stage=0) and follow us at [@babeljs](https://twitter.com/babeljs).
Try it out at our [REPL](https://babeljs.io/repl/build/master#?code_lz=NoRgNATGDMC6B0BbAhgBwBQDsAEBeAfNjgNTYgCUA3EA&lineWrap=true&presets=es2015%2Ces2016%2Ces2017&version=7.0.0-beta.2).
- [FAQ](#faq)
- [Packages](#packages)
- [Core Packages](#core-packages)
- [Other](#other)
- [Presets](#presets)
- [Plugins](#plugins)
- [Transform Plugins](#transform-plugins)
- [Syntax Plugins](#syntax-plugins)
- [Misc Packages](#misc-packages)
- [Team](#team)
- [License](#license)
## FAQ
# FAQ
### Who maintains Babel?
## Docs?
Mostly a handful of volunteers! Please check out our [team page](https://babeljs.io/team)!
Check out our website: [babeljs.io](http://babeljs.io/)
### Looking for support?
## Looking for support?
For questions and support please visit join our [Slack Community](https://slack.babeljs.io/) (you can sign-up [here](https://slack.babeljs.io/) for an invite), ask a question on [Stack Overflow](https://stackoverflow.com/questions/tagged/babeljs), or ping us on [Twitter](https://twitter.com/babeljs).
For questions and support please visit our [discussion forum](https://discuss.babeljs.io/), sign up for our [Slack community](https://slack.babeljs.io/), or [StackOverflow](http://stackoverflow.com/questions/tagged/babeljs).
### Is there a Babel song?
## Want to report a bug or request a feature?
I'm so glad you asked: [Hallelujah —— In Praise of Babel](SONG.md) by [@angus-c](https://github.com/angus-c), [audio version](https://youtu.be/40abpedBKK8) by [@swyx](https://twitter.com/@swyx). Tweet us your recordings!
Bugs and feature requests can be posted at https://github.com/babel/babel/issues.
### Where are the docs?
> We've moved our issues from phabricator back to github issues!
Check out our website: [babeljs.io](https://babeljs.io/), and report issues/features at [babel/website](https://github.com/babel/website/issues).
Former phabricator issue URLs now automatically redirect to their corresponding Github issue:
### Want to report a bug orrequest a feature?
https://phabricator.babeljs.io/T2168 mostly corresponds to https://github.com/babel/babel/issues/2168.
Please read through our [CONTRIBUTING.md](CONTRIBUTING.md) and fill out the issue template at [babel/issues](https://github.com/babel/babel/issues)!
## Want to report an issue with [babeljs.io](https://babeljs.io) (the website)?
### Want to contribute to Babel?
For documentation and website issues please visit the [babel/babel.github.io](https://github.com/babel/babel.github.io) repo.
Check out our [CONTRIBUTING.md](CONTRIBUTING.md) to get started with setting up the repo.
## Want to contribute to Babel?
- If you have already joined Slack, join our [#development](https://babeljs.slack.com/messages/development) channel and say hi!
- Check out the issues with the [good first issue](https://github.com/babel/babel/labels/good%20first%20issue) and [help wanted](https://github.com/babel/babel/labels/help%20wanted) label. We suggest also looking at the closed ones to get a sense of the kinds of issues you can tackle.
- Our progress on TC39 proposals: [babel/proposals](https://github.com/babel/proposals)
Check out our [CONTRIBUTING.md](https://github.com/babel/babel/blob/master/CONTRIBUTING.md). If you have already joined Slack, join our [#development](https://babeljs.slack.com/messages/development) channel!
### How is the repo structured?
You can also start by checking out the issues with the [help-wanted](https://github.com/babel/babel/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) label.
[`babel-core`](/packages/babel-core) is the Babel compiler itself; it exposes the `babel.transform` method, where `transformedCode = transform(src).code`.
The compiler can be broken down into 3 parts:
- The parser: [`babylon`](https://github.com/babel/babylon) (moved to a separate repo and versioned independently)
- The transformer[s]: All the plugins/presets
- These all use [`babel-traverse`](/packages/babel-traverse) to traverse through the AST
- The generator: [`babel-generator`](/packages/babel-generator)
Check out the [`babel-handbook`](https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#introduction) for more information on this.
- [`babel-cli`](/packages/babel-cli) is the CLI tool that runs `babel-core` and helps with outputting to a directory, a file, stdout and more (also includes `babel-node`). Check out the [docs](https://babeljs.io/docs/usage/cli/).
- [`babel-types`](/packages/babel-types) is used to validate, build and change AST nodes.
- [`babel-polyfill`](/packages/babel-polyfill) is [literally a wrapper](https://github.com/babel/babel/blob/master/packages/babel-polyfill/src/index.js) around [`core-js`](https://github.com/zloirock/core-js) and [regenerator-runtime](https://github.com/facebook/regenerator/tree/master/packages/regenerator-runtime). Check out the [docs](https://babeljs.io/docs/usage/polyfill/).
- [`babel-runtime`](/packages/babel-runtime) is similar to the polyfill except that it doesn't modify the global scope and is to be used with [`babel-plugin-transform-runtime`](/packages/babel-plugin-transform-runtime) (usually in library/plugin code). Check out the [docs](https://babeljs.io/docs/plugins/transform-runtime/).
- [`babel-register`](/packages/babel-register) is a way to automatically compile files with Babel on the fly by binding to Node.js `require`. Check out the [docs](http://babeljs.io/docs/usage/require/).
- [`babel-template`](/packages/babel-template) is a helper function that allows constructing AST nodes from a string presentation of the code; this eliminates the tedium of using `babel-types` for building AST nodes.
- [`babel-helpers`](/packages/babel-helpers) is a set of pre-made `babel-template` functions that are used in some Babel plugins.
- [`babel-code-frame`](/packages/babel-code-frame) is a standalone package used to generate errors that print the source code and point to error locations.
After Babel 6, the default transforms were removed; if you don't specify any plugins/presets, Babel will just return the original source code.
The transformer[s] used in Babel are the independent pieces of code that transform specific things. For example: the [`es2015-arrow-functions`](/packages/babel-plugin-transform-es2015-arrow-functions) transform specifically changes arrow functions into regular functions. A preset is simply an array of plugins that make it easier to run a whole a set of transforms without specifying each one manually.
| Package | Version | Dependencies | Description |
|--------|-------|------------|---|
| [`babel-preset-env`](https://github.com/babel/babel-preset-env) | [](https://www.npmjs.com/package/babel-preset-env) | [](https://david-dm.org/babel/babel-preset-env) | automatically determines plugins and polyfills you need based on your supported environments |
> You can find community maintained presets on [npm](https://www.npmjs.com/search?q=babel-preset)
### [Plugins](http://babeljs.io/docs/plugins)
Plugins are the heart of Babel and what make it work.
> You can find community plugins on [npm](https://www.npmjs.com/search?q=babel-plugin).
#### Transform Plugins
There are many kinds of plugins: ones that convert ES6/ES2015 to ES5, transform to ES3, minification, JSX, flow, experimental features, and more. Check out our [website for more](http://babeljs.io/docs/plugins/#transform-plugins).
#### Syntax Plugins
These just enable the transform plugins to be able to parse certain features (the transform plugins already include the syntax plugins so you don't need both): `babel-plugin-syntax-x`. Check out our [website for more](http://babeljs.io/docs/plugins/#syntax-plugins).
### Helpers
These are mostly for internal use in various plugins: `babel-helper-x`.
The [AST specification](https://github.com/babel/babylon/blob/master/ast/spec.md) has been moved to the Babylon repo, `babel/babylon`.
The [AST specification](https://github.com/babel/babel/blob/master/packages/babel-parser/ast/spec.md) has been moved to the babel parser package, `packages/babel-parser`.
@@ -15,13 +15,13 @@ This is quite taboo but let's look at the pros and cons:
* Easy to coordinate changes across modules.
* Single place to report issues.
* Easier to setup a development environment.
* Tests across modules are ran together which finds bugs that touch multiple modules easier.
* Tests across modules are run together which finds bugs that touch multiple modules easier.
**Cons:**
* Codebase looks more intimidating.
* Repo is bigger in size.
*Lower ranking in [npms](https://npms.io/) results. At least until [npms-io/npms-analyzer#83](https://github.com/npms-io/npms-analyzer/issues/83) is fixed.
*[Can't `npm install` modules directly from GitHub](https://github.com/npm/npm/issues/2974)
[`@babel/core`](/packages/babel-core) is the Babel compiler itself; it exposes the `babel.transform` method, where `transformedCode = transform(src).code`.
The compiler can be broken down into 3 parts:
- The parser: [`@babel/parser`](/packages/babel-parser)
- The transformer[s]: All the plugins/presets
- These all use [`@babel/traverse`](/packages/babel-traverse) to traverse through the AST
- The generator: [`@babel/generator`](/packages/babel-generator)
Check out the [`babel-handbook`](https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#introduction) for more information on this.
- [`@babel/cli`](/packages/babel-cli) is the CLI tool that runs `@babel/core` and helps with outputting to a directory, a file, stdout and more (also includes `@babel/node` cli). Check out the [docs](https://babeljs.io/docs/usage/cli/).
- [`@babel/types`](/packages/babel-types) is used to validate, build and change AST nodes.
- [`@babel/polyfill`](/packages/babel-polyfill) is [literally a wrapper](/packages/babel-polyfill/src/index.js) around [`core-js`](https://github.com/zloirock/core-js) and [regenerator-runtime](https://github.com/facebook/regenerator/tree/master/packages/regenerator-runtime). Check out the [docs](https://babeljs.io/docs/usage/polyfill/).
- [`@babel/runtime`](/packages/babel-runtime) is similar to the polyfill except that it doesn't modify the global scope and is to be used with [`@babel/plugin-transform-runtime`](/packages/babel-plugin-transform-runtime) (usually in library/plugin code). Check out the [docs](https://babeljs.io/docs/plugins/transform-runtime/).
- [`@babel/register`](/packages/babel-register) is a way to automatically compile files with Babel on the fly by binding to Node.js `require`. Check out the [docs](http://babeljs.io/docs/usage/require/).
- [`@babel/template`](/packages/babel-template) is a helper function that allows constructing AST nodes from a string presentation of the code; this eliminates the tedium of using `@babel/types` for building AST nodes.
- [`@babel/helpers`](/packages/babel-helpers) is a set of pre-made `@babel/template` functions that are used in some Babel plugins.
- [`@babel/code-frame`](/packages/babel-code-frame) is a standalone package used to generate errors that print the source code and point to error locations.
After Babel 6, the default transforms were removed; if you don't specify any plugins/presets, Babel will just return the original source code.
The transformer[s] used in Babel are the independent pieces of code that transform specific things. For example: the [`es2015-arrow-functions`](/packages/babel-plugin-transform-arrow-functions) transform specifically changes arrow functions into regular functions. A preset is simply an array of plugins that make it easier to run a whole a set of transforms without specifying each one manually.
| Package | Version | Dependencies | Description |
|--------|-------|------------|---|
| [`@babel/preset-env`](/packages/babel-preset-env) | [](https://www.npmjs.com/package/@babel/preset-env) | [](https://david-dm.org/babel/babel?path=packages/babel-preset-env) | automatically determines plugins and polyfills you need based on your supported environments |
> You can find community maintained presets on [npm](https://www.npmjs.com/search?q=babel-preset)
### [Plugins](http://babeljs.io/docs/plugins)
Plugins are the heart of Babel and what make it work.
> You can find community plugins on [npm](https://www.npmjs.com/search?q=babel-plugin).
#### Transform Plugins
There are many kinds of plugins: ones that convert ES6/ES2015 to ES5, transform to ES3, minification, JSX, flow, experimental features, and more. Check out our [website for more](http://babeljs.io/docs/plugins/#transform-plugins).
#### Syntax Plugins
These just enable the transform plugins to be able to parse certain features (the transform plugins already include the syntax plugins so you don't need both): `@babel/plugin-syntax-x`. Check out our [website for more](http://babeljs.io/docs/plugins/#syntax-plugins).
### Helpers
These are mostly for internal use in various plugins: `@babel/helper-x`.
In addition, various entry point scripts live in the top-level package at `babel-cli/bin`.
There are some shell-executable utility scripts, `babel-external-helpers.js` and `babel-node.js`, and the main Babel cli script, `babel.js`.
See our website [@babel/cli](https://babeljs.io/docs/en/next/babel-cli.html) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20cli%22+is%3Aopen) associated with this package.
## Install
```sh
npm install --save-dev babel-cli
```
## Usage
Using npm:
```sh
babel script.js
npm install --save-dev @babel/cli
```
For more in depth documentation see: http://babeljs.io/docs/usage/cli/
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.