Generate TypeScript typings, and improve generated Flow typings (#7101)

* 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
This commit is contained in:
Boris Cherny 2018-01-17 07:31:46 -08:00 committed by Henry Zhu
parent 667f5815c1
commit c3654d83c8
18 changed files with 423 additions and 1980 deletions

View File

@ -13,7 +13,7 @@ codemods/*/src
[libs]
lib/file.js
lib/parser.js
lib/types.js
lib/packages/babel-types/lib/index.js.flow
lib/third-party-libs.js.flow
[options]

View File

@ -19,6 +19,11 @@ build: clean
node ./packages/babel-types/scripts/generateTypeHelpers.js
# call build again as the generated files might need to be compiled again.
./node_modules/.bin/gulp build
# generate flow and typescript typings
node scripts/generators/flow.js > ./packages/babel-types/lib/index.js.flow
node scripts/generators/typescript.js > ./packages/babel-types/lib/index.d.ts
# generate docs
node scripts/generators/docs.js > ./packages/babel-types/README.md
ifneq ("$(BABEL_ENV)", "cov")
make build-standalone
make build-preset-env-standalone

File diff suppressed because it is too large Load Diff

View File

@ -475,6 +475,14 @@ export function TypeCastExpression(node: Object) {
this.token(")");
}
export function Variance(node: Object) {
if (node.kind === "plus") {
this.token("+");
} else {
this.token("-");
}
}
export function VoidTypeAnnotation() {
this.word("void");
}

View File

@ -0,0 +1,5 @@
type A = {
+a: number,
-b: string,
c: boolean,
};

View File

@ -0,0 +1,5 @@
type A = {
+a: number,
-b: string,
c: boolean,
};

View File

@ -9,9 +9,6 @@ npm install --save-dev @babel/types
```
## API
<!-- begin generated section -->
### anyTypeAnnotation
```javascript
t.anyTypeAnnotation()
@ -137,7 +134,7 @@ See also `t.isBinaryExpression(node, opts)` and `t.assertBinaryExpression(node,
Aliases: `Binary`, `Expression`
- `operator`: `'+' | '-' | '/' | '%' | '*' | '**' | '&' | '|' | '>>' | '>>>' | '<<' | '^' | '==' | '===' | '!=' | '!==' | 'in' | 'instanceof' | '>' | '<' | '>=' | '<='` (required)
- `operator`: `"+" | "-" | "/" | "%" | "*" | "**" | "&" | "|" | ">>" | ">>>" | "<<" | "^" | "==" | "===" | "!=" | "!==" | "in" | "instanceof" | ">" | "<" | ">=" | "<="` (required)
- `left`: `Expression` (required)
- `right`: `Expression` (required)
@ -278,7 +275,7 @@ Aliases: `Scopable`, `Class`, `Statement`, `Declaration`, `Pureish`
- `decorators`: `Array<Decorator>` (default: `null`)
- `abstract`: `boolean` (default: `null`)
- `declare`: `boolean` (default: `null`)
- `implements`: `Array<TSExpressionWithTypeArguments | FlowClassImplements>` (default: `null`)
- `implements`: `Array<TSExpressionWithTypeArguments | ClassImplements>` (default: `null`)
- `mixins` (default: `null`)
- `superTypeParameters`: `TypeParameterInstantiation | TSTypeParameterInstantiation` (default: `null`)
- `typeParameters`: `TypeParameterDeclaration | TSTypeParameterDeclaration | Noop` (default: `null`)
@ -298,7 +295,7 @@ Aliases: `Scopable`, `Class`, `Expression`, `Pureish`
- `superClass`: `Expression` (default: `null`)
- `body`: `ClassBody` (required)
- `decorators`: `Array<Decorator>` (default: `null`)
- `implements`: `Array<TSExpressionWithTypeArguments | FlowClassImplements>` (default: `null`)
- `implements`: `Array<TSExpressionWithTypeArguments | ClassImplements>` (default: `null`)
- `mixins` (default: `null`)
- `superTypeParameters`: `TypeParameterInstantiation | TSTypeParameterInstantiation` (default: `null`)
- `typeParameters`: `TypeParameterDeclaration | TSTypeParameterDeclaration | Noop` (default: `null`)
@ -355,7 +352,7 @@ See also `t.isClassProperty(node, opts)` and `t.assertClassProperty(node, opts)`
Aliases: `Property`
- `key` (required)
- `key`: `Identifier | StringLiteral | NumericLiteral | Expression` (required)
- `value`: `Expression` (default: `null`)
- `typeAnnotation`: `TypeAnnotation | TSTypeAnnotation | Noop` (default: `null`)
- `decorators`: `Array<Decorator>` (default: `null`)
@ -435,7 +432,7 @@ See also `t.isDeclareExportAllDeclaration(node, opts)` and `t.assertDeclareExpor
Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration`
- `source`: `StringLiteral` (required)
- `exportKind`: `[ 'type', 'value' ]` (default: `null`)
- `exportKind`: `["type","value"]` (default: `null`)
---
@ -497,7 +494,7 @@ Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration`
- `id`: `Identifier | StringLiteral` (required)
- `body`: `BlockStatement` (required)
- `kind`: `'CommonJS' | 'ES'` (default: `null`)
- `kind`: `"CommonJS" | "ES"` (default: `null`)
---
@ -998,7 +995,7 @@ Aliases: `ModuleSpecifier`
- `local`: `Identifier` (required)
- `imported`: `Identifier` (required)
- `importKind`: `null | 'type' | 'typeof'` (default: `null`)
- `importKind`: `null | "type" | "typeof"` (default: `null`)
---
@ -1060,7 +1057,7 @@ Aliases: `Flow`, `FlowType`
### jSXAttribute
```javascript
t.jSXAttribute(name, value)
t.jsxAttribute(name, value)
```
See also `t.isJSXAttribute(node, opts)` and `t.assertJSXAttribute(node, opts)`.
@ -1074,7 +1071,7 @@ Aliases: `JSX`, `Immutable`
### jSXClosingElement
```javascript
t.jSXClosingElement(name)
t.jsxClosingElement(name)
```
See also `t.isJSXClosingElement(node, opts)` and `t.assertJSXClosingElement(node, opts)`.
@ -1087,7 +1084,7 @@ Aliases: `JSX`, `Immutable`
### jSXClosingFragment
```javascript
t.jSXClosingFragment()
t.jsxClosingFragment()
```
See also `t.isJSXClosingFragment(node, opts)` and `t.assertJSXClosingFragment(node, opts)`.
@ -1099,7 +1096,7 @@ Aliases: `JSX`, `Immutable`
### jSXElement
```javascript
t.jSXElement(openingElement, closingElement, children, selfClosing)
t.jsxElement(openingElement, closingElement, children, selfClosing)
```
See also `t.isJSXElement(node, opts)` and `t.assertJSXElement(node, opts)`.
@ -1115,7 +1112,7 @@ Aliases: `JSX`, `Immutable`, `Expression`
### jSXEmptyExpression
```javascript
t.jSXEmptyExpression()
t.jsxEmptyExpression()
```
See also `t.isJSXEmptyExpression(node, opts)` and `t.assertJSXEmptyExpression(node, opts)`.
@ -1127,7 +1124,7 @@ Aliases: `JSX`
### jSXExpressionContainer
```javascript
t.jSXExpressionContainer(expression)
t.jsxExpressionContainer(expression)
```
See also `t.isJSXExpressionContainer(node, opts)` and `t.assertJSXExpressionContainer(node, opts)`.
@ -1140,7 +1137,7 @@ Aliases: `JSX`, `Immutable`
### jSXFragment
```javascript
t.jSXFragment(openingFragment, closingFragment, children)
t.jsxFragment(openingFragment, closingFragment, children)
```
See also `t.isJSXFragment(node, opts)` and `t.assertJSXFragment(node, opts)`.
@ -1155,7 +1152,7 @@ Aliases: `JSX`, `Immutable`, `Expression`
### jSXIdentifier
```javascript
t.jSXIdentifier(name)
t.jsxIdentifier(name)
```
See also `t.isJSXIdentifier(node, opts)` and `t.assertJSXIdentifier(node, opts)`.
@ -1168,7 +1165,7 @@ Aliases: `JSX`
### jSXMemberExpression
```javascript
t.jSXMemberExpression(object, property)
t.jsxMemberExpression(object, property)
```
See also `t.isJSXMemberExpression(node, opts)` and `t.assertJSXMemberExpression(node, opts)`.
@ -1182,7 +1179,7 @@ Aliases: `JSX`
### jSXNamespacedName
```javascript
t.jSXNamespacedName(namespace, name)
t.jsxNamespacedName(namespace, name)
```
See also `t.isJSXNamespacedName(node, opts)` and `t.assertJSXNamespacedName(node, opts)`.
@ -1196,7 +1193,7 @@ Aliases: `JSX`
### jSXOpeningElement
```javascript
t.jSXOpeningElement(name, attributes, selfClosing)
t.jsxOpeningElement(name, attributes, selfClosing)
```
See also `t.isJSXOpeningElement(node, opts)` and `t.assertJSXOpeningElement(node, opts)`.
@ -1211,7 +1208,7 @@ Aliases: `JSX`, `Immutable`
### jSXOpeningFragment
```javascript
t.jSXOpeningFragment()
t.jsxOpeningFragment()
```
See also `t.isJSXOpeningFragment(node, opts)` and `t.assertJSXOpeningFragment(node, opts)`.
@ -1223,7 +1220,7 @@ Aliases: `JSX`, `Immutable`
### jSXSpreadAttribute
```javascript
t.jSXSpreadAttribute(argument)
t.jsxSpreadAttribute(argument)
```
See also `t.isJSXSpreadAttribute(node, opts)` and `t.assertJSXSpreadAttribute(node, opts)`.
@ -1236,7 +1233,7 @@ Aliases: `JSX`
### jSXSpreadChild
```javascript
t.jSXSpreadChild(expression)
t.jsxSpreadChild(expression)
```
See also `t.isJSXSpreadChild(node, opts)` and `t.assertJSXSpreadChild(node, opts)`.
@ -1249,7 +1246,7 @@ Aliases: `JSX`, `Immutable`
### jSXText
```javascript
t.jSXText(value)
t.jsxText(value)
```
See also `t.isJSXText(node, opts)` and `t.assertJSXText(node, opts)`.
@ -1283,7 +1280,7 @@ See also `t.isLogicalExpression(node, opts)` and `t.assertLogicalExpression(node
Aliases: `Binary`, `Expression`
- `operator`: `'||' | '&&' | '??'` (required)
- `operator`: `"||" | "&&" | "??"` (required)
- `left`: `Expression` (required)
- `right`: `Expression` (required)
@ -1558,7 +1555,7 @@ Aliases: `Flow`, `UserWhitespacable`
- `key`: `Identifier` (required)
- `value`: `FlowType` (required)
- `variance`: `Variance` (default: `null`)
- `kind`: `'init' | 'get' | 'set'` (default: `null`)
- `kind`: `"init" | "get" | "set"` (default: `null`)
- `optional`: `boolean` (default: `null`)
- `static`: `boolean` (default: `null`)
@ -1617,7 +1614,7 @@ Aliases: `Scopable`, `BlockParent`, `Block`
- `body`: `Array<Statement>` (required)
- `directives`: `Array<Directive>` (default: `[]`)
- `sourceType`: `'script' | 'module'` (default: `'script'`)
- `sourceType`: `"script" | "module"` (default: `'script'`)
- `sourceFile`: `string` (default: `null`)
---
@ -1782,7 +1779,7 @@ Aliases: `Statement`, `BlockParent`, `Scopable`
### tSAnyKeyword
```javascript
t.tSAnyKeyword()
t.tsAnyKeyword()
```
See also `t.isTSAnyKeyword(node, opts)` and `t.assertTSAnyKeyword(node, opts)`.
@ -1794,7 +1791,7 @@ Aliases: `TSType`
### tSArrayType
```javascript
t.tSArrayType(elementType)
t.tsArrayType(elementType)
```
See also `t.isTSArrayType(node, opts)` and `t.assertTSArrayType(node, opts)`.
@ -1807,7 +1804,7 @@ Aliases: `TSType`
### tSAsExpression
```javascript
t.tSAsExpression(expression, typeAnnotation)
t.tsAsExpression(expression, typeAnnotation)
```
See also `t.isTSAsExpression(node, opts)` and `t.assertTSAsExpression(node, opts)`.
@ -1821,7 +1818,7 @@ Aliases: `Expression`
### tSBooleanKeyword
```javascript
t.tSBooleanKeyword()
t.tsBooleanKeyword()
```
See also `t.isTSBooleanKeyword(node, opts)` and `t.assertTSBooleanKeyword(node, opts)`.
@ -1833,7 +1830,7 @@ Aliases: `TSType`
### tSCallSignatureDeclaration
```javascript
t.tSCallSignatureDeclaration(typeParameters, parameters, typeAnnotation)
t.tsCallSignatureDeclaration(typeParameters, parameters, typeAnnotation)
```
See also `t.isTSCallSignatureDeclaration(node, opts)` and `t.assertTSCallSignatureDeclaration(node, opts)`.
@ -1848,7 +1845,7 @@ Aliases: `TSTypeElement`
### tSConstructSignatureDeclaration
```javascript
t.tSConstructSignatureDeclaration(typeParameters, parameters, typeAnnotation)
t.tsConstructSignatureDeclaration(typeParameters, parameters, typeAnnotation)
```
See also `t.isTSConstructSignatureDeclaration(node, opts)` and `t.assertTSConstructSignatureDeclaration(node, opts)`.
@ -1863,7 +1860,7 @@ Aliases: `TSTypeElement`
### tSConstructorType
```javascript
t.tSConstructorType(typeParameters, typeAnnotation)
t.tsConstructorType(typeParameters, typeAnnotation)
```
See also `t.isTSConstructorType(node, opts)` and `t.assertTSConstructorType(node, opts)`.
@ -1878,7 +1875,7 @@ Aliases: `TSType`
### tSDeclareFunction
```javascript
t.tSDeclareFunction(id, typeParameters, params, returnType)
t.tsDeclareFunction(id, typeParameters, params, returnType)
```
See also `t.isTSDeclareFunction(node, opts)` and `t.assertTSDeclareFunction(node, opts)`.
@ -1897,13 +1894,13 @@ Aliases: `Statement`, `Declaration`
### tSDeclareMethod
```javascript
t.tSDeclareMethod(decorators, key, typeParameters, params, returnType)
t.tsDeclareMethod(decorators, key, typeParameters, params, returnType)
```
See also `t.isTSDeclareMethod(node, opts)` and `t.assertTSDeclareMethod(node, opts)`.
- `decorators`: `Array<Decorator>` (default: `null`)
- `key` (required)
- `key`: `Identifier | StringLiteral | NumericLiteral | Expression` (required)
- `typeParameters`: `TSTypeParameterDeclaration | Noop` (default: `null`)
- `params`: `Array<LVal>` (required)
- `returnType`: `TSTypeAnnotation | Noop` (default: `null`)
@ -1921,7 +1918,7 @@ See also `t.isTSDeclareMethod(node, opts)` and `t.assertTSDeclareMethod(node, op
### tSEnumDeclaration
```javascript
t.tSEnumDeclaration(id, members)
t.tsEnumDeclaration(id, members)
```
See also `t.isTSEnumDeclaration(node, opts)` and `t.assertTSEnumDeclaration(node, opts)`.
@ -1938,7 +1935,7 @@ Aliases: `Statement`, `Declaration`
### tSEnumMember
```javascript
t.tSEnumMember(id, initializer)
t.tsEnumMember(id, initializer)
```
See also `t.isTSEnumMember(node, opts)` and `t.assertTSEnumMember(node, opts)`.
@ -1950,7 +1947,7 @@ See also `t.isTSEnumMember(node, opts)` and `t.assertTSEnumMember(node, opts)`.
### tSExportAssignment
```javascript
t.tSExportAssignment(expression)
t.tsExportAssignment(expression)
```
See also `t.isTSExportAssignment(node, opts)` and `t.assertTSExportAssignment(node, opts)`.
@ -1963,7 +1960,7 @@ Aliases: `Statement`
### tSExpressionWithTypeArguments
```javascript
t.tSExpressionWithTypeArguments(expression, typeParameters)
t.tsExpressionWithTypeArguments(expression, typeParameters)
```
See also `t.isTSExpressionWithTypeArguments(node, opts)` and `t.assertTSExpressionWithTypeArguments(node, opts)`.
@ -1977,7 +1974,7 @@ Aliases: `TSType`
### tSExternalModuleReference
```javascript
t.tSExternalModuleReference(expression)
t.tsExternalModuleReference(expression)
```
See also `t.isTSExternalModuleReference(node, opts)` and `t.assertTSExternalModuleReference(node, opts)`.
@ -1988,7 +1985,7 @@ See also `t.isTSExternalModuleReference(node, opts)` and `t.assertTSExternalModu
### tSFunctionType
```javascript
t.tSFunctionType(typeParameters, typeAnnotation)
t.tsFunctionType(typeParameters, typeAnnotation)
```
See also `t.isTSFunctionType(node, opts)` and `t.assertTSFunctionType(node, opts)`.
@ -2003,7 +2000,7 @@ Aliases: `TSType`
### tSImportEqualsDeclaration
```javascript
t.tSImportEqualsDeclaration(id, moduleReference)
t.tsImportEqualsDeclaration(id, moduleReference)
```
See also `t.isTSImportEqualsDeclaration(node, opts)` and `t.assertTSImportEqualsDeclaration(node, opts)`.
@ -2018,7 +2015,7 @@ Aliases: `Statement`
### tSIndexSignature
```javascript
t.tSIndexSignature(parameters, typeAnnotation)
t.tsIndexSignature(parameters, typeAnnotation)
```
See also `t.isTSIndexSignature(node, opts)` and `t.assertTSIndexSignature(node, opts)`.
@ -2033,7 +2030,7 @@ Aliases: `TSTypeElement`
### tSIndexedAccessType
```javascript
t.tSIndexedAccessType(objectType, indexType)
t.tsIndexedAccessType(objectType, indexType)
```
See also `t.isTSIndexedAccessType(node, opts)` and `t.assertTSIndexedAccessType(node, opts)`.
@ -2047,7 +2044,7 @@ Aliases: `TSType`
### tSInterfaceBody
```javascript
t.tSInterfaceBody(body)
t.tsInterfaceBody(body)
```
See also `t.isTSInterfaceBody(node, opts)` and `t.assertTSInterfaceBody(node, opts)`.
@ -2058,7 +2055,7 @@ See also `t.isTSInterfaceBody(node, opts)` and `t.assertTSInterfaceBody(node, op
### tSInterfaceDeclaration
```javascript
t.tSInterfaceDeclaration(id, typeParameters, extends, body)
t.tsInterfaceDeclaration(id, typeParameters, extends, body)
```
See also `t.isTSInterfaceDeclaration(node, opts)` and `t.assertTSInterfaceDeclaration(node, opts)`.
@ -2075,7 +2072,7 @@ Aliases: `Statement`, `Declaration`
### tSIntersectionType
```javascript
t.tSIntersectionType(types)
t.tsIntersectionType(types)
```
See also `t.isTSIntersectionType(node, opts)` and `t.assertTSIntersectionType(node, opts)`.
@ -2088,7 +2085,7 @@ Aliases: `TSType`
### tSLiteralType
```javascript
t.tSLiteralType(literal)
t.tsLiteralType(literal)
```
See also `t.isTSLiteralType(node, opts)` and `t.assertTSLiteralType(node, opts)`.
@ -2101,7 +2098,7 @@ Aliases: `TSType`
### tSMappedType
```javascript
t.tSMappedType(typeParameter, typeAnnotation)
t.tsMappedType(typeParameter, typeAnnotation)
```
See also `t.isTSMappedType(node, opts)` and `t.assertTSMappedType(node, opts)`.
@ -2117,7 +2114,7 @@ Aliases: `TSType`
### tSMethodSignature
```javascript
t.tSMethodSignature(key, typeParameters, parameters, typeAnnotation)
t.tsMethodSignature(key, typeParameters, parameters, typeAnnotation)
```
See also `t.isTSMethodSignature(node, opts)` and `t.assertTSMethodSignature(node, opts)`.
@ -2135,7 +2132,7 @@ Aliases: `TSTypeElement`
### tSModuleBlock
```javascript
t.tSModuleBlock(body)
t.tsModuleBlock(body)
```
See also `t.isTSModuleBlock(node, opts)` and `t.assertTSModuleBlock(node, opts)`.
@ -2146,7 +2143,7 @@ See also `t.isTSModuleBlock(node, opts)` and `t.assertTSModuleBlock(node, opts)`
### tSModuleDeclaration
```javascript
t.tSModuleDeclaration(id, body)
t.tsModuleDeclaration(id, body)
```
See also `t.isTSModuleDeclaration(node, opts)` and `t.assertTSModuleDeclaration(node, opts)`.
@ -2162,7 +2159,7 @@ Aliases: `Statement`, `Declaration`
### tSNamespaceExportDeclaration
```javascript
t.tSNamespaceExportDeclaration(id)
t.tsNamespaceExportDeclaration(id)
```
See also `t.isTSNamespaceExportDeclaration(node, opts)` and `t.assertTSNamespaceExportDeclaration(node, opts)`.
@ -2175,7 +2172,7 @@ Aliases: `Statement`
### tSNeverKeyword
```javascript
t.tSNeverKeyword()
t.tsNeverKeyword()
```
See also `t.isTSNeverKeyword(node, opts)` and `t.assertTSNeverKeyword(node, opts)`.
@ -2187,7 +2184,7 @@ Aliases: `TSType`
### tSNonNullExpression
```javascript
t.tSNonNullExpression(expression)
t.tsNonNullExpression(expression)
```
See also `t.isTSNonNullExpression(node, opts)` and `t.assertTSNonNullExpression(node, opts)`.
@ -2200,7 +2197,7 @@ Aliases: `Expression`
### tSNullKeyword
```javascript
t.tSNullKeyword()
t.tsNullKeyword()
```
See also `t.isTSNullKeyword(node, opts)` and `t.assertTSNullKeyword(node, opts)`.
@ -2212,7 +2209,7 @@ Aliases: `TSType`
### tSNumberKeyword
```javascript
t.tSNumberKeyword()
t.tsNumberKeyword()
```
See also `t.isTSNumberKeyword(node, opts)` and `t.assertTSNumberKeyword(node, opts)`.
@ -2224,7 +2221,7 @@ Aliases: `TSType`
### tSObjectKeyword
```javascript
t.tSObjectKeyword()
t.tsObjectKeyword()
```
See also `t.isTSObjectKeyword(node, opts)` and `t.assertTSObjectKeyword(node, opts)`.
@ -2236,7 +2233,7 @@ Aliases: `TSType`
### tSParameterProperty
```javascript
t.tSParameterProperty(parameter)
t.tsParameterProperty(parameter)
```
See also `t.isTSParameterProperty(node, opts)` and `t.assertTSParameterProperty(node, opts)`.
@ -2244,14 +2241,14 @@ See also `t.isTSParameterProperty(node, opts)` and `t.assertTSParameterProperty(
Aliases: `LVal`
- `parameter`: `Identifier | AssignmentPattern` (required)
- `accessibility`: `'public' | 'private' | 'protected'` (default: `null`)
- `accessibility`: `"public" | "private" | "protected"` (default: `null`)
- `readonly`: `boolean` (default: `null`)
---
### tSParenthesizedType
```javascript
t.tSParenthesizedType(typeAnnotation)
t.tsParenthesizedType(typeAnnotation)
```
See also `t.isTSParenthesizedType(node, opts)` and `t.assertTSParenthesizedType(node, opts)`.
@ -2264,7 +2261,7 @@ Aliases: `TSType`
### tSPropertySignature
```javascript
t.tSPropertySignature(key, typeAnnotation, initializer)
t.tsPropertySignature(key, typeAnnotation, initializer)
```
See also `t.isTSPropertySignature(node, opts)` and `t.assertTSPropertySignature(node, opts)`.
@ -2282,7 +2279,7 @@ Aliases: `TSTypeElement`
### tSQualifiedName
```javascript
t.tSQualifiedName(left, right)
t.tsQualifiedName(left, right)
```
See also `t.isTSQualifiedName(node, opts)` and `t.assertTSQualifiedName(node, opts)`.
@ -2296,7 +2293,7 @@ Aliases: `TSEntityName`
### tSStringKeyword
```javascript
t.tSStringKeyword()
t.tsStringKeyword()
```
See also `t.isTSStringKeyword(node, opts)` and `t.assertTSStringKeyword(node, opts)`.
@ -2308,7 +2305,7 @@ Aliases: `TSType`
### tSSymbolKeyword
```javascript
t.tSSymbolKeyword()
t.tsSymbolKeyword()
```
See also `t.isTSSymbolKeyword(node, opts)` and `t.assertTSSymbolKeyword(node, opts)`.
@ -2320,7 +2317,7 @@ Aliases: `TSType`
### tSThisType
```javascript
t.tSThisType()
t.tsThisType()
```
See also `t.isTSThisType(node, opts)` and `t.assertTSThisType(node, opts)`.
@ -2332,7 +2329,7 @@ Aliases: `TSType`
### tSTupleType
```javascript
t.tSTupleType(elementTypes)
t.tsTupleType(elementTypes)
```
See also `t.isTSTupleType(node, opts)` and `t.assertTSTupleType(node, opts)`.
@ -2345,7 +2342,7 @@ Aliases: `TSType`
### tSTypeAliasDeclaration
```javascript
t.tSTypeAliasDeclaration(id, typeParameters, typeAnnotation)
t.tsTypeAliasDeclaration(id, typeParameters, typeAnnotation)
```
See also `t.isTSTypeAliasDeclaration(node, opts)` and `t.assertTSTypeAliasDeclaration(node, opts)`.
@ -2361,7 +2358,7 @@ Aliases: `Statement`, `Declaration`
### tSTypeAnnotation
```javascript
t.tSTypeAnnotation(typeAnnotation)
t.tsTypeAnnotation(typeAnnotation)
```
See also `t.isTSTypeAnnotation(node, opts)` and `t.assertTSTypeAnnotation(node, opts)`.
@ -2372,7 +2369,7 @@ See also `t.isTSTypeAnnotation(node, opts)` and `t.assertTSTypeAnnotation(node,
### tSTypeAssertion
```javascript
t.tSTypeAssertion(typeAnnotation, expression)
t.tsTypeAssertion(typeAnnotation, expression)
```
See also `t.isTSTypeAssertion(node, opts)` and `t.assertTSTypeAssertion(node, opts)`.
@ -2386,7 +2383,7 @@ Aliases: `Expression`
### tSTypeLiteral
```javascript
t.tSTypeLiteral(members)
t.tsTypeLiteral(members)
```
See also `t.isTSTypeLiteral(node, opts)` and `t.assertTSTypeLiteral(node, opts)`.
@ -2399,7 +2396,7 @@ Aliases: `TSType`
### tSTypeOperator
```javascript
t.tSTypeOperator(typeAnnotation)
t.tsTypeOperator(typeAnnotation)
```
See also `t.isTSTypeOperator(node, opts)` and `t.assertTSTypeOperator(node, opts)`.
@ -2413,7 +2410,7 @@ Aliases: `TSType`
### tSTypeParameter
```javascript
t.tSTypeParameter(constraint, default)
t.tsTypeParameter(constraint, default)
```
See also `t.isTSTypeParameter(node, opts)` and `t.assertTSTypeParameter(node, opts)`.
@ -2426,7 +2423,7 @@ See also `t.isTSTypeParameter(node, opts)` and `t.assertTSTypeParameter(node, op
### tSTypeParameterDeclaration
```javascript
t.tSTypeParameterDeclaration(params)
t.tsTypeParameterDeclaration(params)
```
See also `t.isTSTypeParameterDeclaration(node, opts)` and `t.assertTSTypeParameterDeclaration(node, opts)`.
@ -2437,7 +2434,7 @@ See also `t.isTSTypeParameterDeclaration(node, opts)` and `t.assertTSTypeParamet
### tSTypeParameterInstantiation
```javascript
t.tSTypeParameterInstantiation(params)
t.tsTypeParameterInstantiation(params)
```
See also `t.isTSTypeParameterInstantiation(node, opts)` and `t.assertTSTypeParameterInstantiation(node, opts)`.
@ -2448,7 +2445,7 @@ See also `t.isTSTypeParameterInstantiation(node, opts)` and `t.assertTSTypeParam
### tSTypePredicate
```javascript
t.tSTypePredicate(parameterName, typeAnnotation)
t.tsTypePredicate(parameterName, typeAnnotation)
```
See also `t.isTSTypePredicate(node, opts)` and `t.assertTSTypePredicate(node, opts)`.
@ -2462,7 +2459,7 @@ Aliases: `TSType`
### tSTypeQuery
```javascript
t.tSTypeQuery(exprName)
t.tsTypeQuery(exprName)
```
See also `t.isTSTypeQuery(node, opts)` and `t.assertTSTypeQuery(node, opts)`.
@ -2475,7 +2472,7 @@ Aliases: `TSType`
### tSTypeReference
```javascript
t.tSTypeReference(typeName, typeParameters)
t.tsTypeReference(typeName, typeParameters)
```
See also `t.isTSTypeReference(node, opts)` and `t.assertTSTypeReference(node, opts)`.
@ -2489,7 +2486,7 @@ Aliases: `TSType`
### tSUndefinedKeyword
```javascript
t.tSUndefinedKeyword()
t.tsUndefinedKeyword()
```
See also `t.isTSUndefinedKeyword(node, opts)` and `t.assertTSUndefinedKeyword(node, opts)`.
@ -2501,7 +2498,7 @@ Aliases: `TSType`
### tSUnionType
```javascript
t.tSUnionType(types)
t.tsUnionType(types)
```
See also `t.isTSUnionType(node, opts)` and `t.assertTSUnionType(node, opts)`.
@ -2514,7 +2511,7 @@ Aliases: `TSType`
### tSVoidKeyword
```javascript
t.tSVoidKeyword()
t.tsVoidKeyword()
```
See also `t.isTSVoidKeyword(node, opts)` and `t.assertTSVoidKeyword(node, opts)`.
@ -2735,7 +2732,7 @@ See also `t.isUnaryExpression(node, opts)` and `t.assertUnaryExpression(node, op
Aliases: `UnaryLike`, `Expression`
- `operator`: `'void' | 'throw' | 'delete' | '!' | '+' | '-' | '~' | 'typeof'` (required)
- `operator`: `"void" | "throw" | "delete" | "!" | "+" | "-" | "~" | "typeof"` (required)
- `argument`: `Expression` (required)
- `prefix`: `boolean` (default: `true`)
@ -2763,7 +2760,7 @@ See also `t.isUpdateExpression(node, opts)` and `t.assertUpdateExpression(node,
Aliases: `Expression`
- `operator`: `'++' | '--'` (required)
- `operator`: `"++" | "--"` (required)
- `argument`: `Expression` (required)
- `prefix`: `boolean` (default: `false`)
@ -2796,6 +2793,19 @@ See also `t.isVariableDeclarator(node, opts)` and `t.assertVariableDeclarator(no
---
### variance
```javascript
t.variance(kind)
```
See also `t.isVariance(node, opts)` and `t.assertVariance(node, opts)`.
Aliases: `Flow`
- `kind`: `"minus" | "plus"` (required)
---
### voidTypeAnnotation
```javascript
t.voidTypeAnnotation()
@ -2849,7 +2859,3 @@ Aliases: `Expression`, `Terminatorless`
- `delegate`: `boolean` (default: `false`)
---
<!-- end generated section -->

View File

@ -7,6 +7,7 @@
"license": "MIT",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-types",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"dependencies": {
"esutils": "^2.0.2",
"lodash": "^4.2.0",

View File

@ -552,6 +552,9 @@ export function assertUnionTypeAnnotation(
): void {
assert("UnionTypeAnnotation", node, opts);
}
export function assertVariance(node: Object, opts?: Object = {}): void {
assert("Variance", node, opts);
}
export function assertVoidTypeAnnotation(
node: Object,
opts?: Object = {},

View File

@ -493,6 +493,10 @@ export function UnionTypeAnnotation(...args: Array<any>): Object {
return builder("UnionTypeAnnotation", ...args);
}
export { UnionTypeAnnotation as unionTypeAnnotation };
export function Variance(...args: Array<any>): Object {
return builder("Variance", ...args);
}
export { Variance as variance };
export function VoidTypeAnnotation(...args: Array<any>): Object {
return builder("VoidTypeAnnotation", ...args);
}

View File

@ -383,11 +383,11 @@ defineType("Identifier", {
fields: {
...patternLikeCommon,
name: {
validate(node, key, val) {
validate: chain(function(node, key, val) {
if (!isValidIdentifier(val)) {
// throw new TypeError(`"${val}" is not a valid identifer name`);
}
},
}, assertValueType("string")),
},
optional: {
validate: assertValueType("boolean"),

View File

@ -124,7 +124,7 @@ const classCommon = {
validate: chain(
assertValueType("array"),
assertEach(
assertNodeType("TSExpressionWithTypeArguments", "FlowClassImplements"),
assertNodeType("TSExpressionWithTypeArguments", "ClassImplements"),
),
),
optional: true,
@ -399,7 +399,8 @@ export const classMethodOrPropertyCommon = {
optional: true,
},
key: {
validate: (function() {
validate: chain(
(function() {
const normal = assertNodeType(
"Identifier",
"StringLiteral",
@ -412,6 +413,13 @@ export const classMethodOrPropertyCommon = {
validator(node, key, val);
};
})(),
assertNodeType(
"Identifier",
"StringLiteral",
"NumericLiteral",
"Expression",
),
),
},
};

View File

@ -417,6 +417,14 @@ defineType("UnionTypeAnnotation", {
},
});
defineType("Variance", {
aliases: ["Flow"],
builder: ["kind"],
fields: {
kind: validate(assertOneOf("minus", "plus")),
},
});
defineType("VoidTypeAnnotation", {
aliases: ["Flow", "FlowType", "FlowBaseAnnotation"],
});

View File

@ -416,6 +416,9 @@ export function isTypeParameterInstantiation(
export function isUnionTypeAnnotation(node: Object, opts?: Object): boolean {
return is("UnionTypeAnnotation", node, opts);
}
export function isVariance(node: Object, opts?: Object): boolean {
return is("Variance", node, opts);
}
export function isVoidTypeAnnotation(node: Object, opts?: Object): boolean {
return is("VoidTypeAnnotation", node, opts);
}

View File

@ -1,24 +1,22 @@
"use strict";
const util = require("util");
const path = require("path");
const fs = require("fs");
const utils = require("./utils");
const types = require("../packages/babel-types");
const types = require("../../packages/babel-types");
const readmePath = path.join(
__dirname,
"..",
"packages",
"babel-types",
"README.md"
);
const readmeSrc = fs.readFileSync(readmePath, "utf8");
const readme = [
readmeSrc.split("<!-- begin generated section -->")[0].trim(),
"",
"<!-- begin generated section -->",
"",
`# @babel/types
> This module contains methods for building ASTs manually and for checking the types of AST nodes.
## Install
\`\`\`sh
npm install --save-dev @babel/types
\`\`\`
## API`,
];
const customTypes = {
@ -38,40 +36,6 @@ const customTypes = {
key: "if computed then `Expression` else `Identifier | Literal`",
},
};
function getType(validator) {
if (validator.type) {
return validator.type;
} else if (validator.oneOfNodeTypes) {
return validator.oneOfNodeTypes.join(" | ");
} else if (validator.oneOfNodeOrValueTypes) {
return validator.oneOfNodeOrValueTypes.join(" | ");
} else if (validator.oneOf) {
return validator.oneOf.map(val => util.inspect(val)).join(" | ");
} else if (validator.chainOf) {
if (
validator.chainOf.length === 2 &&
validator.chainOf[0].type === "array" &&
validator.chainOf[1].each
) {
return "Array<" + getType(validator.chainOf[1].each) + ">";
}
if (
validator.chainOf.length === 2 &&
validator.chainOf[0].type === "string" &&
validator.chainOf[1].oneOf
) {
return validator.chainOf[1].oneOf
.map(function(val) {
return JSON.stringify(val);
})
.join(" | ");
}
}
const err = new Error("Unrecognised validator type");
err.code = "UNEXPECTED_VALIDATOR_TYPE";
err.validator = validator;
throw err;
}
Object.keys(types.BUILDER_KEYS)
.sort()
.forEach(function(key) {
@ -79,8 +43,7 @@ Object.keys(types.BUILDER_KEYS)
readme.push("```javascript");
readme.push(
"t." +
key[0].toLowerCase() +
key.substr(1) +
utils.toFunctionName(key) +
"(" +
types.BUILDER_KEYS[key].join(", ") +
")"
@ -123,7 +86,9 @@ Object.keys(types.BUILDER_KEYS)
fieldDescription.push(`: ${customTypes[key][field]}`);
} else if (validator) {
try {
fieldDescription.push(": `" + getType(validator) + "`");
fieldDescription.push(
": `" + utils.stringifyValidator(validator, "") + "`"
);
} catch (ex) {
if (ex.code === "UNEXPECTED_VALIDATOR_TYPE") {
console.log(
@ -148,12 +113,4 @@ Object.keys(types.BUILDER_KEYS)
readme.push("");
});
readme.push(
"",
"<!-- end generated section -->",
"",
readmeSrc.split("<!-- end generated section -->")[1].trim()
);
fs.writeFileSync(readmePath, readme.join("\n"));
// console.log(readme.join('\n'));
process.stdout.write(readme.join("\n"));

View File

@ -1,12 +1,12 @@
"use strict";
const fs = require("fs");
const t = require("../packages/babel-types");
const t = require("../../packages/babel-types");
const utils = require("./utils");
const NODE_PREFIX = "BabelNode";
let code = `// NOTE: This file is autogenerated. Do not modify.
// See scripts/generate-interfaces.js for script used.
// See scripts/generators/flow.js for script used.
declare class ${NODE_PREFIX}Comment {
value: string;
@ -73,29 +73,7 @@ for (const type in t.NODE_FIELDS) {
const validate = field.validate;
if (validate) {
if (validate.oneOf) {
typeAnnotation = validate.oneOf
.map(function(val) {
return JSON.stringify(val);
})
.join(" | ");
}
if (validate.type) {
typeAnnotation = validate.type;
if (typeAnnotation === "array") {
typeAnnotation = "Array<any>";
}
}
if (validate.oneOfNodeTypes) {
const types = validate.oneOfNodeTypes.map(
type => `${NODE_PREFIX}${type}`
);
typeAnnotation = types.join(" | ");
if (suffix === "?") typeAnnotation = "?" + typeAnnotation;
}
typeAnnotation = utils.stringifyValidator(validate, NODE_PREFIX);
}
if (typeAnnotation) {
@ -116,7 +94,7 @@ for (const type in t.NODE_FIELDS) {
// Flow chokes on super() and import() :/
if (type !== "Super" && type !== "Import") {
lines.push(
`declare function ${type[0].toLowerCase() + type.slice(1)}(${args.join(
`declare function ${utils.toFunctionName(type)}(${args.join(
", "
)}): ${NODE_PREFIX}${type};`
);
@ -171,4 +149,4 @@ code += `\ndeclare module "@babel/types" {
//
fs.writeFileSync(__dirname + "/../lib/types.js", code);
process.stdout.write(code);

View File

@ -0,0 +1,188 @@
"use strict";
const t = require("../../packages/babel-types");
const utils = require("./utils");
let code = `// NOTE: This file is autogenerated. Do not modify.
// See scripts/generators/typescript.js for script used.
interface BaseComment {
value: string;
start: number;
end: number;
loc: SourceLocation;
type: "BlockComment" | "LineComment";
}
export interface BlockComment extends BaseComment {
type: "BlockComment";
}
export interface LineComment extends BaseComment {
type: "LineComment";
}
export type Comment = BlockComment | LineComment;
export interface SourceLocation {
start: {
line: number;
column: number;
};
end: {
line: number;
column: number;
};
}
interface BaseNode {
leadingComments: ReadonlyArray<Comment> | null;
innerComments: ReadonlyArray<Comment> | null;
trailingComments: ReadonlyArray<Comment> | null;
start: number | null;
end: number | null;
loc: SourceLocation | null;
type: Node["type"];
}
export type Node = ${t.TYPES.sort().join(" | ")};\n\n`;
//
const lines = [];
for (const type in t.NODE_FIELDS) {
const fields = t.NODE_FIELDS[type];
const fieldNames = sortFieldNames(Object.keys(t.NODE_FIELDS[type]), type);
const struct = ['type: "' + type + '";'];
const args = [];
fieldNames.forEach(fieldName => {
const field = fields[fieldName];
let typeAnnotation = utils.stringifyValidator(field.validate, "");
if (isNullable(field) && !hasDefault(field)) {
typeAnnotation += " | null";
}
if (areAllRemainingFieldsNullable(fieldName, fieldNames, fields)) {
args.push(
`${t.toBindingIdentifierName(fieldName)}${
isNullable(field) ? "?:" : ":"
} ${typeAnnotation}`
);
} else {
args.push(
`${t.toBindingIdentifierName(fieldName)}: ${typeAnnotation}${
isNullable(field) ? " | undefined" : ""
}`
);
}
if (t.isValidIdentifier(fieldName)) {
struct.push(`${fieldName}: ${typeAnnotation};`);
}
});
code += `export interface ${type} extends BaseNode {
${struct.join("\n ").trim()}
}\n\n`;
// super and import are reserved words in JavaScript
if (type !== "Super" && type !== "Import") {
lines.push(
`export function ${utils.toFunctionName(type)}(${args.join(
", "
)}): ${type};`
);
}
}
for (let i = 0; i < t.TYPES.length; i++) {
let decl = `export function is${
t.TYPES[i]
}(node: object, opts?: object | null): `;
if (t.NODE_FIELDS[t.TYPES[i]]) {
decl += `node is ${t.TYPES[i]};`;
} else {
decl += `boolean;`;
}
lines.push(decl);
}
lines.push(
`export function validate(n: Node, key: string, value: any): void;`,
`export function clone<T extends Node>(n: T): T;`,
`export function cloneDeep<T extends Node>(n: T): T;`,
`export function removeProperties(
n: Node,
opts?: { preserveComments: boolean } | null
): void;`,
`export function removePropertiesDeep<T extends Node>(
n: T,
opts?: { preserveComments: boolean } | null
): T;`,
`export type TraversalAncestors = ReadonlyArray<{
node: Node,
key: string,
index?: number,
}>;
export type TraversalHandler<T> = (node: Node, parent: TraversalAncestors, type: T) => void;
export type TraversalHandlers<T> = {
enter?: TraversalHandler<T>,
exit?: TraversalHandler<T>,
};`.replace(/(^|\n) {2}/g, "$1"),
// eslint-disable-next-line
`export function traverse<T>(n: Node, h: TraversalHandler<T> | TraversalHandlers<T>, state?: T): void;`
);
for (const type in t.DEPRECATED_KEYS) {
code += `/**
* @deprecated Use \`${t.DEPRECATED_KEYS[type]}\`
*/
export type ${type} = ${t.DEPRECATED_KEYS[type]};\n
`;
}
for (const type in t.FLIPPED_ALIAS_KEYS) {
const types = t.FLIPPED_ALIAS_KEYS[type];
code += `export type ${type} = ${types
.map(type => `${type}`)
.join(" | ")};\n`;
}
code += lines.join("\n") + "\n";
//
process.stdout.write(code);
//
function areAllRemainingFieldsNullable(fieldName, fieldNames, fields) {
const index = fieldNames.indexOf(fieldName);
return fieldNames.slice(index).every(_ => isNullable(fields[_]));
}
function hasDefault(field) {
return field.default != null;
}
function isNullable(field) {
return field.optional || hasDefault(field);
}
function sortFieldNames(fields, type) {
return fields.sort((fieldA, fieldB) => {
const indexA = t.BUILDER_KEYS[type].indexOf(fieldA);
const indexB = t.BUILDER_KEYS[type].indexOf(fieldB);
if (indexA === indexB) return fieldA < fieldB ? -1 : 1;
if (indexA === -1) return 1;
if (indexB === -1) return -1;
return indexA - indexB;
});
}

View File

@ -0,0 +1,51 @@
exports.stringifyValidator = function stringifyValidator(
validator,
nodePrefix
) {
if (validator === undefined) {
return "any";
}
if (validator.each) {
return `Array<${stringifyValidator(validator.each, nodePrefix)}>`;
}
if (validator.chainOf) {
return stringifyValidator(validator.chainOf[1], nodePrefix);
}
if (validator.oneOf) {
return validator.oneOf.map(JSON.stringify).join(" | ");
}
if (validator.oneOfNodeTypes) {
return validator.oneOfNodeTypes.map(_ => nodePrefix + _).join(" | ");
}
if (validator.oneOfNodeOrValueTypes) {
return validator.oneOfNodeOrValueTypes
.map(_ => {
return isValueType(_) ? _ : nodePrefix + _;
})
.join(" | ");
}
if (validator.type) {
return validator.type;
}
return ["any"];
};
exports.toFunctionName = function toFunctionName(typeName) {
const _ = typeName.replace(/^TS/, "ts").replace(/^JSX/, "jsx");
return _.slice(0, 1).toLowerCase() + _.slice(1);
};
/**
* Heuristic to decide whether or not the given type is a value type (eg. "null")
* or a Node type (eg. "Expression").
*/
function isValueType(type) {
return type.charAt(0).toLowerCase() === type.charAt(0);
}