babel / babel/babel

[breaking] Make Identifier an "atomic" node

Open
#9,545 11 comments 2 reactions 0 assignees View on GitHub
i: discussion
Dominant language
TypeScript
Stars
44k
Forks
6k
Avg merge
5d 15h
Merged PRs (30d)
23

Description

`Identifier`s can have different properties totally unrelated to their "Identifierness":
- `optional` (e.g. in `function f(a?) {}` with Flow)
- `typeAnnotation` (e.g. in `var a: string;` with Flow/TypeScript)
- `decorators` (e.g. in `function f(@dec a) {}` with TypeScript)

Every other "atom" (e.g. strings, numbers, ...) don't have child nodes. Additionally, it makes it impossible to get the actual identifier name start/end position, because in `foo: string` `foo` isn't represented by anything. Example: [AST Explorer](https://astexplorer.net/#/gist/8ab88f26fe8714059fdc05d3387d5810/3247ca3be02eed96c7b617d91661656d1376ef6f).

Also, these properties don't make sense in many places: what does it mean if I add `typeAnnotation` to `prop` in `obj.prop`? Or `optional` to `label` in `break label;`?

I propose creating a new node, `AnnotatedPattern` (name suggestions are welcome), like this:

```js
defineType("AnnotatedPattern", {
builder: ["pattern", "typeAnnotation", "optional", "decorators"],
visitor: ["pattern", "typeAnnotation", "decorators"],
aliases: ["PatternLike", "LVal"],
fields: {
pattern: {
validate: assertNodeType("PatternLike"),
},
typeAnnotation: {
validate: assertNodeType("TypeAnnotation", "TSTypeAnnotation"),
optional: true,
},
optional: {
validate: assertValueType("boolean"), // Only valid if pattern is an identifier
optional: true,
},
decorators: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Decorator")),
),
optional: true,
},
},
});
```

`AnnotatedPattern` would be accepted in function parameters and in variable declarations. `typeAnnotation` & co would then be removed from destructuring patterns.

Contributor guide

Open the contributing guide

Research direction

The issue names no repository files or tests. Start by locating Babel's AST node definitions and the handling of Identifier, patterns, function parameters, and variable declarations; compare the current child properties with the proposed AnnotatedPattern shape. Done means the AST structure and validations consistently make Identifier atomic without leaving the described properties on unrelated nodes.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
compilers
Issue type
Refactor
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.