GithubHelp home page GithubHelp logo

babel / babylon Goto Github PK

View Code? Open in Web Editor NEW
1.7K 52.0 257.0 9.87 MB

PSA: moved into babel/babel as @babel/parser -->

Home Page: https://github.com/babel/babel/tree/master/packages/babel-parser

License: MIT License

JavaScript 99.59% Makefile 0.41%
ast babylon parser babel estree es6 javascript

babylon's Introduction

Babylon has been moved into the main Babel mono-repo as @babel/parser.

The move makes it much easier to release and develop in sync with the rest of Babel!

This repo will be made read-only, as all of the issues/labels have been moved over as well. Please report any bugs and open pull requests over on the main mono-repo.

Check out the 6.x README here

babylon's People

Contributors

abraidwood avatar amasad avatar aparajita avatar azz avatar bakkot avatar danez avatar danharper avatar drewml avatar existentialism avatar greenkeeper[bot] avatar greenkeeperio-bot avatar haileys avatar hzoo avatar jmm avatar jridgewell avatar kaicataldo avatar loganfsmyth avatar marijnh avatar mathiasbynens avatar motiz88 avatar nicolo-ribaudo avatar oleksandr-kuzmenko avatar peey avatar qantas94heavy avatar rattrayalex avatar rreverser avatar rwaldron avatar samwgoldman avatar sebmck avatar xtuc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

babylon's Issues

Significant but hard-to-find bug in parsing arrow functions

As of a recent release (Don't know when, exactly, but this issue broke code that was working fine around June 4), babylon's parsing of arrow functions has broken in a very peculiar way. When babylon encounters the following pattern:

<some expression> :
    <a parenthesized arrow expression> ?
    <an unparenthesized arrow expression>

It reports an error parsing the parenthesized arrow expression:

Module build failed: SyntaxError: <path to file>: Assigning to rvalue (23:3)

For example:

let x = foo() ?
    (value => true) :
    value => false

The contents of the condition don't seem to matter, nor does parenthesizing the entire conditional expression. However, if the parenthesis around the first arrow function are removed, or parenthesis are added to the second arrow function, or either arrow function is something other than an arrow function, it is parsed fine. This specific pattern is the only one that triggers the error.

For what it's worth, I'm running babylon via babel via webpack, but the stack trace I get is entirely from babylon.

This seems implausible, I know, so I've created a git repo which reproduces the error, available here:

https://github.com/Lucretiel/babylon-error

The specific file I'm trying to pack is index.js with no dependencies or requires. The raw output from webpack is in build_result.

Proposal for theme song

image

Friday night I'm going nowhere
All the lights are changing green to red
Turning over TV stations
Situations running through my head
Looking back through time
You know it's clear that I've been blind, I've been a fool
To open up my heart to all that jealousy,
That bitterness, that ridicule

Saturday I'm running wild
And all the lights are changing red to green
Moving through the crowds I'm pushing
Chemicals are rushing in my bloodstream

Only wish that you were here
You know I'm seeing it so clear
I've been afraid
To show you how I really feel
Admit to some of those bad mistakes I've made

And if you want it
Come and get it
Crying out loud
The love that I was
Giving you was
Never in doubt
Let go your heart
Let go your head
And feel it now
Let go your heart
Let go your head
And feel it now

Babylon, Babylon, Babylon

Sunday all the lights of London shining,
Sky is fading red to blue
Kicking through the autumn leaves
And wondering where it is you might be going to

Turning back for home
You know I'm feeling so alone
I can't believe
Climbing on the stair
I turn around to see you smiling there
In front of me

And if you want it
Come and get it
Crying out loud
The love that I was
Giving you was
Never in doubt

Let go your heart
Let go your head
And feel it now
Let go your heart
Let go your head
And feel it now

Let go your heart
Let go your head
And feel it now
Let go your heart
Let go your head
And feel it now

Babylon, Babylon, Babylon, Babylon
Make sure to CAPO 1ST FRET

intro:
     (D) (D)                                 (A)  (A)
e|--2---2-----------2-------2--------------------------------------
B|--3---3---------------3----------2----2------------2------3----
G|--2---2---0h2------------------2----2----------------2--------
D|-----------------------------------2----2----0h2----------------
A|---------------------------------------------------------------------
E|---------------------------------------------------------------------
     (Em) (Em)    
e|----------------------------------------------------------------------
B|-------------------------------------------------0-------------------
G|------------------------------------------------------2--------------
D|---2------2-----------0--------------------0------------0---------
A|---2------2-----0h2-----2--0---------2--------------------------
E|-----------------------------------2--0------------------------------
Verse:
e|----------------------------------------------------------------
B|-------2h3p2------------3--0--3--3-----------------------
G|-------2-------------------2---------2-----------------------
D|-------------------0------------------------------------------
A|----------------------------------------------------------------
E|---2-------------------3---------------------------------------
Chorus:
The chorus is different in that it doesn't have any individual picking, rather, a soft 
strum of these chords:

D, A, Em, A   (progression 1)
D, A, Em, G  (progression 2)

Progression 2 follows number 1 and continues in this patter until returning to the verse.

Duplicate named exports should be a syntax error

Babylon currently will parse multiple exports of the same name, though this should actually be a syntax error.

Here's the relevant portion of the spec and related Babel issue.

I'd love to take a look at and work on this! I currently have an open PR to the main Babel repo (where it was suggested that this change probably belongs in Babylon) with the modified tests. If/once this proposed change lands, I can update that PR to bump the Babylon version and fix the tests accordingly.

Does not support 'return + yield ....'

I wonder if such syntax should be supported by babylon. For me such a construction makes sense.

*chooseShowResultsInstantly() {
    return true === yield this.choose({choices: [true, false]})
}

Unable to decorate generator functions

With the latest [email protected] I am unable to decorate generator functions, i.e.

class Foo
{
    @deco
    * gen() {}
}

will result in an unexpected error.

Here, it will fail if isGenerator is true.

I am currently working on a patch for this and will report back.

RATIONALE

According to 14.3/14.4 of the ECMAScript specification, a GeneratorMethod (14.4) is a valid MethodDefinition (14.3). And in the decorator specification also states that it can be used with a MethodDefinition and makes no limitations whatsoever.

npm install error

The package reference to core-js is invalid .

$ npm install babylon --save-dev
npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Users\Gabi\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js" "install" "babylon" "--save-dev"
npm ERR! node v6.2.0
npm ERR! npm v3.8.8

npm ERR! No compatible version found: core-js@^2.4.0
npm ERR! Valid install targets:
npm ERR! 2.3.0, 2.2.2, 2.2.1, 2.2.0, 2.1.5, 2.1.4, 2.1.3, 2.1.2, 2.1.1, 2.1.0, 2.0.3, 2.0.2, 2.0.1, 2.0.0, 2.0.0-beta.2, 2.0.0-beta, 2.0.0-alpha, 1.2.6, 1.2.5, 1.2.4, 1.2.3, 1.2.2, 1.2.1, 1.2.0, 1.1.4, 1.1.3, 1.1.2, 1.1.1, 1.1.0, 1.0.1, 1.0.0, 0.9.18, 0.9.17, 0.9.16, 0.9.15, 0.9.14, 0.9.13, 0.9.12, 0.9.11, 0.9.10, 0.9.9, 0.9.8, 0.9.7, 0.9.6, 0.9.5, 0.9.4, 0.9.3, 0.9.2, 0.9.1, 0.9.0, 0.8.4, 0.8.3, 0.8.2, 0.8.1, 0.8.0, 0.7.2, 0.7.1, 0.7.0, 0.6.1, 0.6.0, 0.5.4, 0.5.3, 0.5.2, 0.5.1, 0.5.0, 0.4.10, 0.4.9, 0.4.8, 0.4.7, 0.4.6, 0.4.5, 0.4.4, 0.4.3, 0.4.2, 0.4.1, 0.4.0, 0.3.3, 0.3.2, 0.3.1, 0.3.0, 0.2.5, 0.2.4, 0.2.3, 0.2.2, 0.2.1, 0.2.0, 0.1.5, 0.1.4, 0.1.3, 0.1.2, 0.1.1, 0.0.9, 0.0.8, 0.0.7, 0.0.5, 0.0.4, 0.0.3
npm ERR!
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR! https://github.com/npm/npm/issues

npm ERR! Please include the following file with any support re

6.8.3 Changing checkbox input's checked attribute to null does not uncheck it

I am building a React project with webpack and noticed that after updating from 6.8.2 to 6.8.3 that setting a checkbox input's checked attribute from whatever is was before to null does not result in the checkbox unchecked. It seems that if it started checked, it will stay checked when set to null, but if it started null, it will appear unchecked until it is clicked.

I expected that setting an attribute to null would be the equivalent of removing that attribute. Is that not the case?

Also, it may be possible that this change was caused by something other than babylon updating, but not as far as I can tell.

Example of the React snippet I am referring to:
<input type="checkbox" checked={condition ? "checked" : null} />

Fails to parse Flow-annotated polymorphic methods which name is a keyword

I started using Flow recently, and was delighted to see that Babel (which I was already using) supported stripping Flow types by default already! I just found a funny issue though:

sebmck: It's being parsed as a JSX tag for some reason.
sebmck: Figured it out exprAllowed is being set to true on delete tokens so the < is being interpreted as the start of a JSX starting tag expression.
thejameskyle: @sebmck is this an easy one to tackle?

class Foo {
  delete<T>(item: T): T {
    return item;
  }
}

copied from https://phabricator.babeljs.io/T1737

flow + async + default params => Unexpected Token error (T7484)

Reported by @spudly

const testFunc = async (arg: string = '') => {};
export default testFunc;

The code above results in an Unexpected Token error.

If you remove 'async' or remove " = ''", it parses successfully.

http://babeljs.io/repl/#?evaluate=false&lineWrap=false&presets=es2015%2Creact%2Cstage-0&experimental=true&loose=true&spec=false&code=%2F%2F%20%40flow%0A%0Aconst%20testFunc%20%3D%20async%20(arg%3A%20string%20%3D%20'')%20%3D%3E%20%7B%7D%3B%0A%0Aexport%20default%20testFunc%3B%0A


Comment by @BLamy

This issue has nothing to do with flow. It's a combination of arrow functions, async-await and destructured default parameters.

const example5 = async function({bar = "bar"}) { // Works fine
    console.log(bar);
}

const example6 = async ({bar = "bar"}) => { // Syntax error
    console.log(bar);
}

How can I parse JSX with attributes?

Sorry for using this issue for asking questions.
But I don't understand how to parse JSX with attributes.

I wanted to write a babel plugin to transform JSX code.
I can get an AST with the following code:

var babylon = require('babylon');
var code = '\
    <Outer>\
      <Inter />\
    </Outer>\
';
var ast = babylon.parse(code, {
  sourceType: 'module',
  plugins: ['jsx']
});

However, an error occurs with the following code:

var code = '\
    <Outer>\
      <Inter value=0 />\
    </Outer>\
';

The error is:

SyntaxError: JSX value should be either an expression or a quoted JSX text

Any suggestions?

Incorrect "keyword" value for the key of object property which looks like an boolean

For the case like

({true: 1})

token for the key, will look like this -

{
  "type": {
    "label": "true",
    "keyword": "true",
    "beforeExpr": false,
    "startsExpr": true,
    "rightAssociative": false,
    "isLoop": false,
    "isAssign": false,
    "prefix": false,
    "postfix": false,
    "binop": null,
    "updateContext": null
  },
  "value": "true"
}

I believe "keyword": "true" bit should look like this - "keyword": undefined or "keyword": false

state.inMethod: wrong type checking

Reported by @virtyaluk

Continuing to exploring sources of babylon I've found another interesting moment out of the code.

Look at this and this lines of code:

this.inMethod = this.inFunction = this.inGenerator = this.inAsync = false;

and

inMethod: boolean;

inMethod is boolean, right?

But in this place the property compared as string:

if (this.match(tt.parenL) && this.state.inMethod !== "constructor" && !this.options.allowSuperOutsideMethod) {

There's no assigning string to the property in the whole project. So, I believe, there's no need to performing this check.

Inconsistency with semicolons closing decorator statements

I noticed that when I have decorated classes, a decorator closed with a semi-colon is a syntax error, while a semi-colon closing a method in a class is acceptable. Here is my .babelrc:

{
  "presets": [
    "es2015",
    "es2016",
    "es2017,
    "stage-2"
  ],
  "plugins": [
    "transform-decorators-legacy",
    "transform-class-properties",
    "transform-es2015-block-scoping",
    [
      "transform-es2015-classes",
      {
        "loose": true
      }
    ],
    "transform-proto-to-assign"
  ]
}

and an example of the issue to which I am referring:

@decorator('foo') // Semi-colon here throws a syntax error on compile
class Bar {
    @decorator('baz'); // Semi-colon here compiles properly
    qux() {}

    @decorator('baz'); // Semi-colon here compiles properly
    static quux() {}
}

Admittedly, I do not know enough about the class/property decorators proposal to determine whether or not this is the expected behavior or this is some inconsistency with the AST parser or the babel-plugin-transform-decorators-legacy plugin specifically. @loganfsmyth recommended I open an issue here.

Document deviations from ESTree spec

I tried using Babylon parser as a replacement for Esprima, discovering that the AST it produces doesn't quite correspond to the ESTree spec. Which is even more surprising because the README states that Babylon is based on acorn, which does conform to ESTree spec.

I found no documentation about this. So far I've discovered the following differences:

I'd like to evaluate whether it's feasible for me to switch the parser to Babylon... but I'm not really sure how big the AST differences turn out to be.

Dynamic props in class body

reported by imaxmaxmaximus in phabricator

The parse interprets this

class Cat {

  symbol = 10
  [symbol] = 10
}

as

class Cat {

  symbol = 10[symbol] = 10
}

With semicolon there is a parsing error:

class Cat {

  symbol = 10;
  [symbol] = 10;
}

Very slow parsing of large JSON file with flow plugin

With the flow plugin, #19 seems to have regressed parsing performance on really giant files.

Before #19 (e6c11a0), this finished in about 0.5 seconds. After, it takes hours:

curl -O https://raw.githubusercontent.com/mbostock/topojson/master/examples/world-50m.json
node -e 'require("/path/to/babylon").parse("(" + require("fs").readFileSync("world-50m.js", "utf-8") + ")", { plugins: [ "flow" ] })

There is no problem if the flow plugin is disabled. It looks like the this.state.clone() calls get slower and slower as it parses more of the file. Maybe the total runtime is O(n^3) in the size of the file? That would put us at about 470 hours to parse the file based on a bit of logging I did.

This is blocking me from updating us to use a newer Babylon. (Actually, the reason I want to upgrade is to get the fix from #19โ€ฆ)

Exponentiation operator error with negative base

Trying to parse ((-1) ** 2); fails with the following error, despite already being wrapped in parens:

Illegal expression. Wrap left hand side or entire exponentiation in parentheses. (1:3)
> 1 | ((-1) ** 2);
    |    ^

jsx elements in yield statement

I found that write jsx elements directly after yield statement would cause a syntax error (Unexpected token). But according to jsx spec (https://facebook.github.io/jsx/) and ECMAScript spec. JSXElement is a PrimaryExpression which can be used after yield statement.

Currently Error but should be OK:
yield <a></a>;

Currently OK:
yield (<a></a>);

Because I am writing a program heavily depends on generator functions. I want my code be more clear. So I forked this project and fix this problem in commit de56e12. There is just one line difference where I add { startsExpr: true } to jsxTagStart token.

Because I am not familiar with the internal representation in this project. I don't know if it is proper to do such a change. But at least there is no test failed after change.

Repeated identifier references in arrays and arguments not replaced.

Despite binding.referencePaths being replaced with path.replaceWith the resulting code is missing them.
You can see here they are all supposed to be _noop3.default and _range3.default but some are still _noop and _range instead:

myFunc(_range3.default, _noop3.default);
myFunc(_noop, _noop3.default);
myFunc(_range3.default, _noop, _noop3.default);
myFunc(_range, _noop, _range3.default, _noop3.default);
myFunc(_range, _noop, _range, _noop3.default, _range3.default);

Related to lodash/babel-plugin-lodash#91.

Flow declarations don't check for declare name

Currently declares inside declare module don't need to start with a declare name. For example this is valid code:

declare module A {
  placeanythinghere var a:number
}

Flow itself also parses it. I know flow tries not to fail in most situations, but do we also want to do that in babylon?
It could be easily changed and there is already a todo, but I'm not sure what the wanted way currently is.

@jeffmo, @kittens : What are your thoughts on this?

Including trailing delimiter in flow types

I believe the Babylon parser is incorrectly including the delimiter in .loc.end.column of ObjectTypePropertys:

var babylon = require('babylon');                                                 
var flow = require('flow-parser');                                                

var code = `                                                                      
type X = {                                                                        
  a: number,                                                                      
}                                                                                 
`;                                                                                

var endColumnOfPropertyBabylon =                                                  
  babylon.parse(code, {plugins: ['flow']})                                        
  .program.body[0].right.properties[0].loc.end.column;                            

var endColumnOfPropertyFlow =                                                     
  flow.parse(code, {})                                                            
  .body[0].right.properties[0].loc.end.column;                                                                                                                                                             

// outputs "12 11"
console.log(endColumnOfPropertyBabylon, endColumnOfPropertyFlow);

This bug causes recast to insert double delimiters in some cases: benjamn/recast#282

Cannot handle large js file

the babylon.js uses console.log(JSON.stringify(ast, null, " ")); to dump the ast output, which will run out of memory if the js file is roughly more than 1M (the AST text becomes close to 1G).
It would be nice to provide an option to babylon.js to strip the tokens from the output, as they take up most of the space and are often useless.

Duplicate definitions of variables should throw syntax error

According to the spec when defining multiple variables with the same name, the parser should throw and SyntaxError when using let or const:

let foo, foo;
or
let foo; let foo;

From 13.2.1.1:

It is a Syntax Error if the BoundNames of BindingList contains any duplicate entries.

V8 trows an error for let and const, but not vor var.

Improve parsing error message (T6710)

Issue originally made by @markelog

Ref babel/babel#3774

Input code

require("babylon").parse("2++");

Description

Will throw a error -

"SyntaxError: Assigning to rvalue (1:0)"

Which is pretty cryptic, parsers like esprima, or any other JS engine will show more meaningful message - "Invalid left-hand side expression in postfix operation"

asynchronous plugin?

export default myplugin = ({ type:t }) => {
       let visitor = {
            stringLiteral ( path ) {
                  asyncfn(path, result =>{
                      // do something async
                      // how can i get these async result into ast tree?
                  })
            }
       }
       return {
            visitor
       }
}

Wrong arguments passing order.

Reported by @virtyaluk

I'm exploring source code of babylon parser and saw next code under lval.js:

// Parses spread element.

pp.parseSpread = function (refShorthandDefaultPos) {
  let node = this.startNode();
  this.next();
  node.argument = this.parseMaybeAssign(refShorthandDefaultPos);
  return this.finishNode(node, "SpreadElement");
};

Pay attention to the line:

node.argument = this.parseMaybeAssign(refShorthandDefaultPos);

And have a look at parseMaybessign signature:

function (noIn, refShorthandDefaultPos, afterLeftParse)

Seems like argument passed in wrong order.
I believe, there's need to pass some bool argument first and only then pass refShorthandDefaultPos.
Am I wrong?

Duplicated nodes in object destructuring node

Consider this example -

({ test = 1 } = {})

Then relevant parts of generated AST would look like this -

"properties": [
  {
    "type": "ObjectProperty",
    "start": 3,
    "end": 11,
    "loc": {
      "start": {
        "line": 1,
        "column": 3
      },
      "end": {
        "line": 1,
        "column": 11
      }
    },
    "method": false,
    "shorthand": true,
    "computed": false,
    "key": {
      "type": "Identifier",
      "start": 3,
      "end": 7,
      "loc": {
        "start": {
          "line": 1,
          "column": 3
        },
        "end": {
          "line": 1,
          "column": 7
        }
      },
      "name": "test"
    },
    "value": {
      "type": "AssignmentPattern",
      "start": 3,
      "end": 11,
      "loc": {
        "start": {
          "line": 1,
          "column": 3
        },
        "end": {
          "line": 1,
          "column": 11
        }
      },
      "left": {
        "type": "Identifier",
        "start": 3,
        "end": 7,
        "loc": {
          "start": {
            "line": 1,
            "column": 3
          },
          "end": {
            "line": 1,
            "column": 7
          }
        },
        "name": "test"
      }

Notice duplication in ObjectProperty for key and in AssignmentPattern for left properties - Identifier node is used twice.

This creates weird issues for traversing and for code generation.

In arrow functions, the location for parameters with flow types don't cover the flow type

There is a bug in the AST, where in arrows functions, the loc's for params with flow types only cover the argument identifier (or rest element), and not the flow type. @zertosh

Ref babel/eslint-plugin-babel#64, https://github.com/babel/eslint-plugin-babel/pull/64/files#diff-7f0b9d9a07eb0ef5f9145411c7980679R235

{code: 'f = (a:T) => {}', output: 'f = (a:T,) => {}', options: ['always'], errors: MISSING_I},

and it is ok in FunctionDeclaration/FunctionExpression

Flow coercing yield result without extra parens fails to parse

Wrapping a UnaryExpression and an exponential base in parentheses gives error

Both expressions below produces the same error(using the babel online repl in various settings),
"Illegal expression. Wrap left hand side or entire exponentiation in parentheses."

(-2) ** 2;
((-2) ** 2);

According to this reference it should work,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Exponentiation

Looking briefly at the source,

if (node.operator === "**" && left.type === "UnaryExpression" && left.extra && !left.extra.parenthesizedArgument) {

My best guess is that it should also check if "left.extra.paranthesized" is false!

Cheers

class extends null error

Error: 'this' is not allowed before super()

class Class extends null {
    constructor(name) {
        this.name = name
    }
}

Babel must not be throw error if we access to this without super() if parent class is null.
Null parent class hasn't constructor, an obvious logical fallacy.

Temporary hack:

class NullClass extends null {

}

class Class extends NullClass {
    constructor(name) {
        super()
        this.name = name
    }
}

6.8.0 causes `Uncaught ReferenceError: require is not defined` errors

My project's babylon package upgraded to 6.8.0 today as a result of a devDependency of babel-core. As a result, some stuff broke.

Specifically in my app I do some dynamic babel parsing (ala. repl). So I import babel directly like this:

import preset_es2015 from 'babel-preset-es2015';
import preset_react from 'babel-preset-react';
import preset_stage0 from 'babel-preset-stage-0';
import {transform} from 'babel-core';

It seems this no longer works with 6.8.0 and results in the following error stack:

screen shot 2016-05-04 at 4 33 22 pm

The top-most item in the stack is babylon/lib/index.js failing on var _parser = require("./parser");

Rolling back to [email protected] makes the errors go away.

I looked through the 6.8.0 CHANGELOG for both babylon and babel-core and can't see any reason why this would be happening. Can you please advise?

Export Parser class from Babylon?

Can we export the Parser class from Babylon? We are already very close to doing so on this line.

Then Babel plugins would be able to override Parser methods like getTokenFromCode() to add support for new tokens. For example, adding support for a # token:

import * as babylon from "babylon";

babylon.tokTypes.hash = { label: "#", beforeExpr: true };

let {getTokenFromCode} = babylon.Parser.prototype;
babylon.Parser.prototype.getTokenFromCode = function(code) {
  if (code === 35) { // '#'
    ++this.state.pos;
    return this.finishToken(babylon.tokTypes.hash);
  }

  return getTokenFromCode.bind(this)(code);
};

At the very least, it would be nice to have some hooks into the different Parser methods.

Destructing function parameters with "set" property in it

Reported by @pavelkornev

Following snippet:

function A({set}) {
  set = "a"
}

compiles to:

"use strict";

function A(_ref) {
  var set = _ref.set;

  set = "foo";
}

https://babeljs.io/repl/#?experimental=false&evaluate=true&loose=false&spec=false&code=function%20A(%7Bset%7D)%20%7B%0A%20%20set%20%3D%20%22a%22%0A%7D

But when we try to assign default value to "set":

function A({set="bar"}) {
  set="foo"
}

it crashes with the following error:

repl: Unexpected token (1:15)
> 1 | function A({set="bar"}) {
    |                ^
  2 |   set="foo"
  3 | }

https://babeljs.io/repl/#?experimental=false&evaluate=true&loose=false&spec=false&code=function%20A(%7Bset%3D%22bar%22%7D)%20%7B%0A%20%20set%3D%22foo%22%0A%7D

On other hand if we assign alias to it:

function A({set:set_="bar"}) {
  set="foo"
}

It compiles just fine:

"use strict";

function A(_ref) {
  var _ref$set = _ref.set;
  var set_ = _ref$set === undefined ? "bar" : _ref$set;

  set = "foo";
}

https://babeljs.io/repl/#?experimental=false&evaluate=true&loose=false&spec=false&code=function%20A(%7Bset%7D)%20%7B%0A%20%20set%3D%22foo%22%0A%7D

If "set" reserved why does it work in first case? If it's not why second case doesn't work? I consider this as a bug of compiler, am i right?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.