Commit 762b95bc authored by Cholgrrr's avatar Cholgrrr
Browse files

Merge branch 'New_Structure' of https://gitlab.com/Cholgrrr/m4labplatform into New_Structure

parents 613a2f33 a2e8cafb
...@@ -5,12 +5,10 @@ Object.defineProperty(exports, "__esModule", { ...@@ -5,12 +5,10 @@ Object.defineProperty(exports, "__esModule", {
}); });
exports.default = isImmutable; exports.default = isImmutable;
var _isType = _interopRequireDefault(require("./isType")); var _isType = require("./isType");
var _generated = require("./generated"); var _generated = require("./generated");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isImmutable(node) { function isImmutable(node) {
if ((0, _isType.default)(node.type, "Immutable")) return true; if ((0, _isType.default)(node.type, "Immutable")) return true;
......
...@@ -48,7 +48,7 @@ function isNodesEquivalent(a, b) { ...@@ -48,7 +48,7 @@ function isNodesEquivalent(a, b) {
continue; continue;
} }
if (typeof a[field] === "object" && (!visitorKeys || !visitorKeys.includes(field))) { if (typeof a[field] === "object" && !(visitorKeys != null && visitorKeys.includes(field))) {
for (const key of Object.keys(a[field])) { for (const key of Object.keys(a[field])) {
if (a[field][key] !== b[field][key]) { if (a[field][key] !== b[field][key]) {
return false; return false;
......
...@@ -22,22 +22,19 @@ function isReferenced(node, parent, grandparent) { ...@@ -22,22 +22,19 @@ function isReferenced(node, parent, grandparent) {
case "ArrowFunctionExpression": case "ArrowFunctionExpression":
return parent.body === node; return parent.body === node;
case "ExportSpecifier":
if (parent.source) {
return false;
}
return parent.local === node;
case "PrivateName": case "PrivateName":
return false; return false;
case "ObjectProperty":
case "ClassProperty":
case "ClassPrivateProperty":
case "ClassMethod": case "ClassMethod":
case "ClassPrivateMethod": case "ClassPrivateMethod":
case "ObjectMethod": case "ObjectMethod":
if (parent.params.includes(node)) {
return false;
}
case "ObjectProperty":
case "ClassProperty":
case "ClassPrivateProperty":
if (parent.key === node) { if (parent.key === node) {
return !!parent.computed; return !!parent.computed;
} }
...@@ -79,6 +76,13 @@ function isReferenced(node, parent, grandparent) { ...@@ -79,6 +76,13 @@ function isReferenced(node, parent, grandparent) {
case "ExportDefaultSpecifier": case "ExportDefaultSpecifier":
return false; return false;
case "ExportSpecifier":
if (grandparent != null && grandparent.source) {
return false;
}
return parent.local === node;
case "ImportDefaultSpecifier": case "ImportDefaultSpecifier":
case "ImportNamespaceSpecifier": case "ImportNamespaceSpecifier":
case "ImportSpecifier": case "ImportSpecifier":
......
...@@ -8,16 +8,12 @@ exports.default = isScope; ...@@ -8,16 +8,12 @@ exports.default = isScope;
var _generated = require("./generated"); var _generated = require("./generated");
function isScope(node, parent) { function isScope(node, parent) {
if ((0, _generated.isBlockStatement)(node) && (0, _generated.isFunction)(parent, { if ((0, _generated.isBlockStatement)(node) && ((0, _generated.isFunction)(parent) || (0, _generated.isCatchClause)(parent))) {
body: node
})) {
return false; return false;
} }
if ((0, _generated.isBlockStatement)(node) && (0, _generated.isCatchClause)(parent, { if ((0, _generated.isPattern)(node) && ((0, _generated.isFunction)(parent) || (0, _generated.isCatchClause)(parent))) {
body: node return true;
})) {
return false;
} }
return (0, _generated.isScopable)(node); return (0, _generated.isScopable)(node);
......
...@@ -5,9 +5,7 @@ Object.defineProperty(exports, "__esModule", { ...@@ -5,9 +5,7 @@ Object.defineProperty(exports, "__esModule", {
}); });
exports.default = isValidES3Identifier; exports.default = isValidES3Identifier;
var _isValidIdentifier = _interopRequireDefault(require("./isValidIdentifier")); var _isValidIdentifier = require("./isValidIdentifier");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const RESERVED_WORDS_ES3_ONLY = new Set(["abstract", "boolean", "byte", "char", "double", "enum", "final", "float", "goto", "implements", "int", "interface", "long", "native", "package", "private", "protected", "public", "short", "static", "synchronized", "throws", "transient", "volatile"]); const RESERVED_WORDS_ES3_ONLY = new Set(["abstract", "boolean", "byte", "char", "double", "enum", "final", "float", "goto", "implements", "int", "interface", "long", "native", "package", "private", "protected", "public", "short", "static", "synchronized", "throws", "transient", "volatile"]);
......
...@@ -5,16 +5,16 @@ Object.defineProperty(exports, "__esModule", { ...@@ -5,16 +5,16 @@ Object.defineProperty(exports, "__esModule", {
}); });
exports.default = isValidIdentifier; exports.default = isValidIdentifier;
var _esutils = _interopRequireDefault(require("esutils")); var _helperValidatorIdentifier = require("@babel/helper-validator-identifier");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function isValidIdentifier(name, reserved = true) {
if (typeof name !== "string") return false;
function isValidIdentifier(name) { if (reserved) {
if (typeof name !== "string" || _esutils.default.keyword.isReservedWordES6(name, true)) { if ((0, _helperValidatorIdentifier.isKeyword)(name) || (0, _helperValidatorIdentifier.isStrictReservedWord)(name, true)) {
return false; return false;
} else if (name === "await") { }
return false;
} else {
return _esutils.default.keyword.isIdentifierNameES6(name);
} }
return (0, _helperValidatorIdentifier.isIdentifierName)(name);
} }
\ No newline at end of file
...@@ -29,6 +29,8 @@ function matchesPattern(member, match, allowPartial) { ...@@ -29,6 +29,8 @@ function matchesPattern(member, match, allowPartial) {
value = node.name; value = node.name;
} else if ((0, _generated.isStringLiteral)(node)) { } else if ((0, _generated.isStringLiteral)(node)) {
value = node.value; value = node.value;
} else if ((0, _generated.isThisExpression)(node)) {
value = "this";
} else { } else {
return false; return false;
} }
......
...@@ -5,9 +5,7 @@ Object.defineProperty(exports, "__esModule", { ...@@ -5,9 +5,7 @@ Object.defineProperty(exports, "__esModule", {
}); });
exports.default = void 0; exports.default = void 0;
var _buildMatchMemberExpression = _interopRequireDefault(require("../buildMatchMemberExpression")); var _buildMatchMemberExpression = require("../buildMatchMemberExpression");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const isReactComponent = (0, _buildMatchMemberExpression.default)("React.Component"); const isReactComponent = (0, _buildMatchMemberExpression.default)("React.Component");
var _default = isReactComponent; var _default = isReactComponent;
......
...@@ -5,6 +5,7 @@ Object.defineProperty(exports, "__esModule", { ...@@ -5,6 +5,7 @@ Object.defineProperty(exports, "__esModule", {
}); });
exports.default = validate; exports.default = validate;
exports.validateField = validateField; exports.validateField = validateField;
exports.validateChild = validateChild;
var _definitions = require("../definitions"); var _definitions = require("../definitions");
...@@ -14,10 +15,18 @@ function validate(node, key, val) { ...@@ -14,10 +15,18 @@ function validate(node, key, val) {
if (!fields) return; if (!fields) return;
const field = fields[key]; const field = fields[key];
validateField(node, key, val, field); validateField(node, key, val, field);
validateChild(node, key, val);
} }
function validateField(node, key, val, field) { function validateField(node, key, val, field) {
if (!field || !field.validate) return; if (!(field != null && field.validate)) return;
if (field.optional && val == null) return; if (field.optional && val == null) return;
field.validate(node, key, val); field.validate(node, key, val);
}
function validateChild(node, key, val) {
if (val == null) return;
const validate = _definitions.NODE_PARENT_VALIDATIONS[val.type];
if (!validate) return;
validate(node, key, val);
} }
\ No newline at end of file
{ {
"_from": "@babel/types@^7.7.2", "name": "@babel/types",
"_id": "@babel/types@7.7.2", "version": "7.14.5",
"_inBundle": false,
"_integrity": "sha512-YTf6PXoh3+eZgRCBzzP25Bugd2ngmpQVrk7kXX0i5N9BO7TFBtIgZYs7WtxtOGs8e6A4ZI7ECkbBCEHeXocvOA==",
"_location": "/@babel/types",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@babel/types@^7.7.2",
"name": "@babel/types",
"escapedName": "@babel%2ftypes",
"scope": "@babel",
"rawSpec": "^7.7.2",
"saveSpec": null,
"fetchSpec": "^7.7.2"
},
"_requiredBy": [
"/@babel/core",
"/@babel/generator",
"/@babel/helper-annotate-as-pure",
"/@babel/helper-builder-binary-assignment-operator-visitor",
"/@babel/helper-call-delegate",
"/@babel/helper-define-map",
"/@babel/helper-explode-assignable-expression",
"/@babel/helper-function-name",
"/@babel/helper-get-function-arity",
"/@babel/helper-hoist-variables",
"/@babel/helper-member-expression-to-functions",
"/@babel/helper-module-imports",
"/@babel/helper-module-transforms",
"/@babel/helper-optimise-call-expression",
"/@babel/helper-remap-async-to-generator",
"/@babel/helper-replace-supers",
"/@babel/helper-simple-access",
"/@babel/helper-split-export-declaration",
"/@babel/helper-wrap-function",
"/@babel/helpers",
"/@babel/template",
"/@babel/traverse"
],
"_resolved": "https://registry.npmjs.org/@babel/types/-/types-7.7.2.tgz",
"_shasum": "550b82e5571dcd174af576e23f0adba7ffc683f7",
"_spec": "@babel/types@^7.7.2",
"_where": "C:\\Work\\OneDrive - bwstaff\\M4_Lab\\TV3\\NewVersion01\\LAFJLBmf939XYm5gj\\dev\\node_modules\\@babel\\core",
"author": {
"name": "Sebastian McKenzie",
"email": "sebmck@gmail.com"
},
"bundleDependencies": false,
"dependencies": {
"esutils": "^2.0.2",
"lodash": "^4.17.13",
"to-fast-properties": "^2.0.0"
},
"deprecated": false,
"description": "Babel Types is a Lodash-esque utility library for AST nodes", "description": "Babel Types is a Lodash-esque utility library for AST nodes",
"devDependencies": { "author": "The Babel Team (https://babel.dev/team)",
"@babel/generator": "^7.7.2", "homepage": "https://babel.dev/docs/en/next/babel-types",
"@babel/parser": "^7.7.2" "bugs": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20types%22+is%3Aopen",
},
"gitHead": "35f4d1276310bac6fede4a6f86a5c76f951e179e",
"homepage": "https://babeljs.io/",
"license": "MIT", "license": "MIT",
"main": "lib/index.js",
"name": "@babel/types",
"publishConfig": { "publishConfig": {
"access": "public" "access": "public"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-types" "url": "https://github.com/babel/babel.git",
"directory": "packages/babel-types"
},
"main": "./lib/index.js",
"types": "./lib/index-legacy.d.ts",
"typesVersions": {
">=3.7": {
"lib/index-legacy.d.ts": [
"lib/index.d.ts"
]
}
},
"dependencies": {
"@babel/helper-validator-identifier": "^7.14.5",
"to-fast-properties": "^2.0.0"
},
"devDependencies": {
"@babel/generator": "7.14.5",
"@babel/parser": "7.14.5",
"chalk": "^4.1.0"
}, },
"types": "lib/index.d.ts", "engines": {
"version": "7.7.2" "node": ">=6.9.0"
} }
}
\ No newline at end of file
"use strict";
const path = require("path");
const chalk = require("chalk");
const generateBuilders = require("./generators/generateBuilders");
const generateValidators = require("./generators/generateValidators");
const generateAsserts = require("./generators/generateAsserts");
const generateConstants = require("./generators/generateConstants");
const format = require("../../../scripts/utils/formatCode");
const writeFile = require("../../../scripts/utils/writeFileAndMkDir");
const baseDir = path.join(__dirname, "../src");
console.log("Generating @babel/types dynamic functions");
const buildersFile = path.join(baseDir, "builders/generated/index.js");
writeFile(buildersFile, format(generateBuilders(), buildersFile));
console.log(` ${chalk.green("✔")} Generated builders`);
const validatorsFile = path.join(baseDir, "validators/generated/index.js");
writeFile(validatorsFile, format(generateValidators(), validatorsFile));
console.log(` ${chalk.green("✔")} Generated validators`);
const assertsFile = path.join(baseDir, "asserts/generated/index.js");
writeFile(assertsFile, format(generateAsserts(), assertsFile));
console.log(` ${chalk.green("✔")} Generated asserts`);
const constantsFile = path.join(baseDir, "constants/generated/index.js");
writeFile(constantsFile, format(generateConstants(), constantsFile));
console.log(` ${chalk.green("✔")} Generated constants`);
"use strict"; import util from "util";
import stringifyValidator from "../utils/stringifyValidator.js";
import toFunctionName from "../utils/toFunctionName.js";
const util = require("util"); import t from "../../lib/index.js";
const stringifyValidator = require("../utils/stringifyValidator");
const toFunctionName = require("../utils/toFunctionName");
const types = require("../../");
const readme = [ const readme = [
`# @babel/types `---
id: babel-types
title: @babel/types
---
<!-- Do not modify! This file is automatically generated by
github.com/babel/babel/babel-types/scripts/generators/docs.js !-->
> This module contains methods for building ASTs manually and for checking the types of AST nodes. > This module contains methods for building ASTs manually and for checking the types of AST nodes.
...@@ -36,53 +39,52 @@ const customTypes = { ...@@ -36,53 +39,52 @@ const customTypes = {
ObjectProperty: { ObjectProperty: {
key: "if computed then `Expression` else `Identifier | Literal`", key: "if computed then `Expression` else `Identifier | Literal`",
}, },
ClassPrivateMethod: {
computed: "'false'",
},
ClassPrivateProperty: {
computed: "'false'",
},
}; };
Object.keys(types.BUILDER_KEYS) const APIHistory = {
.sort() ClassProperty: [["v7.6.0", "Supports `static`"]],
.forEach(function(key) { };
readme.push("### " + key[0].toLowerCase() + key.substr(1)); function formatHistory(historyItems) {
readme.push("```javascript"); const lines = historyItems.map(
readme.push( item => "| `" + item[0] + "` | " + item[1] + " |"
"t." + );
toFunctionName(key) + return [
"(" + "<details>",
types.BUILDER_KEYS[key].join(", ") + " <summary>History</summary>",
")" "| Version | Changes |",
); "| --- | --- |",
readme.push("```"); ...lines,
"</details>",
];
}
function printAPIHistory(key, readme) {
if (APIHistory[key]) {
readme.push(""); readme.push("");
readme.push( readme.push(...formatHistory(APIHistory[key]));
"See also `t.is" + }
key + }
"(node, opts)` and `t.assert" + function printNodeFields(key, readme) {
key + if (Object.keys(t.NODE_FIELDS[key]).length > 0) {
"(node, opts)`."
);
readme.push(""); readme.push("");
if (types.ALIAS_KEYS[key] && types.ALIAS_KEYS[key].length) { readme.push("AST Node `" + key + "` shape:");
readme.push( Object.keys(t.NODE_FIELDS[key])
"Aliases: " + .sort(function (fieldA, fieldB) {
types.ALIAS_KEYS[key] const indexA = t.BUILDER_KEYS[key].indexOf(fieldA);
.map(function(key) { const indexB = t.BUILDER_KEYS[key].indexOf(fieldB);
return "`" + key + "`";
})
.join(", ")
);
readme.push("");
}
Object.keys(types.NODE_FIELDS[key])
.sort(function(fieldA, fieldB) {
const indexA = types.BUILDER_KEYS[key].indexOf(fieldA);
const indexB = types.BUILDER_KEYS[key].indexOf(fieldB);
if (indexA === indexB) return fieldA < fieldB ? -1 : 1; if (indexA === indexB) return fieldA < fieldB ? -1 : 1;
if (indexA === -1) return 1; if (indexA === -1) return 1;
if (indexB === -1) return -1; if (indexB === -1) return -1;
return indexA - indexB; return indexA - indexB;
}) })
.forEach(function(field) { .forEach(function (field) {
const defaultValue = types.NODE_FIELDS[key][field].default; const defaultValue = t.NODE_FIELDS[key][field].default;
const fieldDescription = ["`" + field + "`"]; const fieldDescription = ["`" + field + "`"];
const validator = types.NODE_FIELDS[key][field].validate; const validator = t.NODE_FIELDS[key][field].validate;
if (customTypes[key] && customTypes[key][field]) { if (customTypes[key] && customTypes[key][field]) {
fieldDescription.push(`: ${customTypes[key][field]}`); fieldDescription.push(`: ${customTypes[key][field]}`);
} else if (validator) { } else if (validator) {
...@@ -99,19 +101,177 @@ Object.keys(types.BUILDER_KEYS) ...@@ -99,19 +101,177 @@ Object.keys(types.BUILDER_KEYS)
} }
} }
} }
if (defaultValue !== null || types.NODE_FIELDS[key][field].optional) { if (defaultValue !== null || t.NODE_FIELDS[key][field].optional) {
fieldDescription.push( fieldDescription.push(
" (default: `" + util.inspect(defaultValue) + "`)" " (default: `" + util.inspect(defaultValue) + "`"
); );
if (t.BUILDER_KEYS[key].indexOf(field) < 0) {
fieldDescription.push(", excluded from builder function");
}
fieldDescription.push(")");
} else { } else {
fieldDescription.push(" (required)"); fieldDescription.push(" (required)");
} }
readme.push(" - " + fieldDescription.join("")); readme.push("- " + fieldDescription.join(""));
}); });
}
}
function printAliasKeys(key, readme) {
if (t.ALIAS_KEYS[key] && t.ALIAS_KEYS[key].length) {
readme.push("");
readme.push(
"Aliases: " +
t.ALIAS_KEYS[key]
.map(function (key) {
return "[`" + key + "`](#" + key.toLowerCase() + ")";
})
.join(", ")
);
}
}
readme.push("### Node Builders");
readme.push("");
Object.keys(t.BUILDER_KEYS)
.sort()
.forEach(function (key) {
readme.push("#### " + toFunctionName(key));
readme.push("");
readme.push("```javascript");
readme.push(
"t." + toFunctionName(key) + "(" + t.BUILDER_KEYS[key].join(", ") + ");"
);
readme.push("```");
printAPIHistory(key, readme);
readme.push("");
readme.push(
"See also `t.is" +
key +
"(node, opts)` and `t.assert" +
key +
"(node, opts)`."
);
printNodeFields(key, readme);
printAliasKeys(key, readme);
readme.push(""); readme.push("");
readme.push("---"); readme.push("---");
readme.push(""); readme.push("");
}); });
function generateMapAliasToNodeTypes() {
const result = new Map();
for (const nodeType of Object.keys(t.ALIAS_KEYS)) {
const aliases = t.ALIAS_KEYS[nodeType];
if (!aliases) continue;
for (const alias of aliases) {
if (!result.has(alias)) {
result.set(alias, []);
}
const nodeTypes = result.get(alias);
nodeTypes.push(nodeType);
}
}
return result;
}
const aliasDescriptions = {
Binary:
"A cover of BinaryExpression and LogicalExpression, which share the same AST shape.",
Block: "Deprecated. Will be removed in Babel 8.",
BlockParent:
"A cover of AST nodes that start an execution context with new [LexicalEnvironment](https://tc39.es/ecma262/#table-additional-state-components-for-ecmascript-code-execution-contexts). In other words, they define the scope of `let` and `const` declarations.",
Class:
"A cover of ClassExpression and ClassDeclaration, which share the same AST shape.",
CompletionStatement:
"A statement that indicates the [completion records](https://tc39.es/ecma262/#sec-completion-record-specification-type). In other words, they define the control flow of the program, such as when should a loop break or an action throws critical errors.",
Conditional:
"A cover of ConditionalExpression and IfStatement, which share the same AST shape.",
Declaration:
"A cover of any [Declaration](https://tc39.es/ecma262/#prod-Declaration)s.",
EnumBody: "A cover of Flow enum bodies.",
EnumMember: "A cover of Flow enum membors.",
ExportDeclaration:
"A cover of any [ExportDeclaration](https://tc39.es/ecma262/#prod-ExportDeclaration)s.",
Expression:
"A cover of any [Expression](https://tc39.es/ecma262/#sec-ecmascript-language-expressions)s.",
ExpressionWrapper:
"A wrapper of expression that does not have runtime semantics.",
Flow: "A cover of AST nodes defined for Flow.",
FlowBaseAnnotation: "A cover of primary Flow type annotations.",
FlowDeclaration: "A cover of Flow declarations.",
FlowPredicate: "A cover of Flow predicates.",
FlowType: "A cover of Flow type annotations.",
For: "A cover of [ForStatement](https://tc39.es/ecma262/#sec-for-statement)s and [ForXStatement](#forxstatement)s.",
ForXStatement:
"A cover of [ForInStatements and ForOfStatements](https://tc39.es/ecma262/#sec-for-in-and-for-of-statements).",
Function:
"A cover of functions and [method](#method)s, the must have `body` and `params`. Note: `Function` is different to `FunctionParent`.",
FunctionParent:
"A cover of AST nodes that start an execution context with new [VariableEnvironment](https://tc39.es/ecma262/#table-additional-state-components-for-ecmascript-code-execution-contexts). In other words, they define the scope of `var` declarations. FunctionParent did not include `Program` since Babel 7.",
Immutable:
"A cover of immutable objects and JSX elements. An object is [immutable](https://tc39.es/ecma262/#immutable-prototype-exotic-object) if no other properties can be defined once created.",
JSX: "A cover of AST nodes defined for [JSX](https://facebook.github.io/jsx/).",
LVal: "A cover of left hand side expressions used in the `left` of assignment expressions and [ForXStatement](#forxstatement)s. ",
Literal:
"A cover of [Literal](https://tc39.es/ecma262/#sec-primary-expression-literals)s, [Regular Expression Literal](https://tc39.es/ecma262/#sec-primary-expression-regular-expression-literals)s and [Template Literal](https://tc39.es/ecma262/#sec-template-literals)s.",
Loop: "A cover of loop statements.",
Method: "A cover of object methods and class methods.",
ModuleDeclaration:
"A cover of ImportDeclaration and [ExportDeclaration](#exportdeclaration)",
ModuleSpecifier:
"A cover of import and export specifiers. Note: It is _not_ the [ModuleSpecifier](https://tc39.es/ecma262/#prod-ModuleSpecifier) defined in the spec.",
ObjectMember:
"A cover of [members](https://tc39.es/ecma262/#prod-PropertyDefinitionList) in an object literal.",
Pattern:
"A cover of [BindingPattern](https://tc39.es/ecma262/#prod-BindingPattern) except Identifiers.",
PatternLike:
"A cover of [BindingPattern](https://tc39.es/ecma262/#prod-BindingPattern)s. ",
Private: "A cover of private class elements and private identifiers.",
Property: "A cover of object properties and class properties.",
Pureish:
"A cover of AST nodes which do not have side-effects. In other words, there is no observable behaviour changes if they are evaluated more than once.",
Scopable:
"A cover of [FunctionParent](#functionparent) and [BlockParent](#blockparent).",
Statement:
"A cover of any [Statement](https://tc39.es/ecma262/#prod-Statement)s.",
TSBaseType: "A cover of primary TypeScript type annotations.",
TSEntityName: "A cover of ts entities.",
TSType: "A cover of TypeScript type annotations.",
TSTypeElement: "A cover of TypeScript type declarations.",
Terminatorless:
"A cover of AST nodes whose semantic will change when a line terminator is inserted between the operator and the operand.",
UnaryLike: "A cover of UnaryExpression and SpreadElement.",
UserWhitespacable: "Deprecated. Will be removed in Babel 8.",
While:
"A cover of DoWhileStatement and WhileStatement, which share the same AST shape.",
};
const mapAliasToNodeTypes = generateMapAliasToNodeTypes();
readme.push("### Aliases");
readme.push("");
for (const alias of [...mapAliasToNodeTypes.keys()].sort()) {
const nodeTypes = mapAliasToNodeTypes.get(alias);
nodeTypes.sort();
if (!(alias in aliasDescriptions)) {
throw new Error(
'Missing alias descriptions of "' +
alias +
", which covers " +
nodeTypes.join(",")
);
}
readme.push("#### " + alias);
readme.push("");
readme.push(aliasDescriptions[alias]);
readme.push("```javascript");
readme.push("t.is" + alias + "(node);");
readme.push("```");
readme.push("");
readme.push("Covered nodes: ");
for (const nodeType of nodeTypes) {
readme.push("- [`" + nodeType + "`](#" + nodeType.toLowerCase() + ")");
}
readme.push("");
}
process.stdout.write(readme.join("\n")); process.stdout.write(readme.join("\n"));
"use strict"; import t from "../../lib/index.js";
import stringifyValidator from "../utils/stringifyValidator.js";
const t = require("../../"); import toFunctionName from "../utils/toFunctionName.js";
const stringifyValidator = require("../utils/stringifyValidator");
const toFunctionName = require("../utils/toFunctionName");
const NODE_PREFIX = "BabelNode"; const NODE_PREFIX = "BabelNode";
...@@ -43,6 +41,7 @@ declare class ${NODE_PREFIX} { ...@@ -43,6 +41,7 @@ declare class ${NODE_PREFIX} {
start: ?number; start: ?number;
end: ?number; end: ?number;
loc: ?${NODE_PREFIX}SourceLocation; loc: ?${NODE_PREFIX}SourceLocation;
extra?: { [string]: mixed };
}\n\n`; }\n\n`;
// //
...@@ -54,6 +53,7 @@ for (const type in t.NODE_FIELDS) { ...@@ -54,6 +53,7 @@ for (const type in t.NODE_FIELDS) {
const struct = ['type: "' + type + '";']; const struct = ['type: "' + type + '";'];
const args = []; const args = [];
const builderNames = t.BUILDER_KEYS[type];
Object.keys(t.NODE_FIELDS[type]) Object.keys(t.NODE_FIELDS[type])
.sort((fieldA, fieldB) => { .sort((fieldA, fieldB) => {
...@@ -80,8 +80,9 @@ for (const type in t.NODE_FIELDS) { ...@@ -80,8 +80,9 @@ for (const type in t.NODE_FIELDS) {
if (typeAnnotation) { if (typeAnnotation) {
suffix += ": " + typeAnnotation; suffix += ": " + typeAnnotation;
} }
if (builderNames.includes(fieldName)) {
args.push(t.toBindingIdentifierName(fieldName) + suffix); args.push(t.toBindingIdentifierName(fieldName) + suffix);
}
if (t.isValidIdentifier(fieldName)) { if (t.isValidIdentifier(fieldName)) {
struct.push(fieldName + suffix + ";"); struct.push(fieldName + suffix + ";");
...@@ -95,7 +96,7 @@ for (const type in t.NODE_FIELDS) { ...@@ -95,7 +96,7 @@ for (const type in t.NODE_FIELDS) {
// Flow chokes on super() and import() :/ // Flow chokes on super() and import() :/
if (type !== "Super" && type !== "Import") { if (type !== "Super" && type !== "Import") {
lines.push( lines.push(
`declare function ${toFunctionName(type)}(${args.join( `declare export function ${toFunctionName(type)}(${args.join(
", " ", "
)}): ${NODE_PREFIX}${type};` )}): ${NODE_PREFIX}${type};`
); );
...@@ -110,78 +111,94 @@ for (const type in t.NODE_FIELDS) { ...@@ -110,78 +111,94 @@ for (const type in t.NODE_FIELDS) {
} }
} }
for (let i = 0; i < t.TYPES.length; i++) { for (const typeName of t.TYPES) {
let decl = `declare function is${t.TYPES[i]}(node: ?Object, opts?: ?Object): boolean`; const isDeprecated = !!t.DEPRECATED_KEYS[typeName];
const realName = isDeprecated ? t.DEPRECATED_KEYS[typeName] : typeName;
if (t.NODE_FIELDS[t.TYPES[i]]) { let decl = `declare export function is${typeName}(node: ?Object, opts?: ?Object): boolean`;
decl += ` %checks (node instanceof ${NODE_PREFIX}${t.TYPES[i]})`; if (t.NODE_FIELDS[realName]) {
decl += ` %checks (node instanceof ${NODE_PREFIX}${realName})`;
} }
lines.push(decl); lines.push(decl);
lines.push(
`declare export function assert${typeName}(node: ?Object, opts?: ?Object): void`
);
} }
lines.push( lines.push(
`declare export var VISITOR_KEYS: { [type: string]: string[] }`,
// assert/
`declare export function assertNode(obj: any): void`,
// builders/ // builders/
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
`declare function createTypeAnnotationBasedOnTypeof(type: 'string' | 'number' | 'undefined' | 'boolean' | 'function' | 'object' | 'symbol'): ${NODE_PREFIX}TypeAnnotation`, `declare export function createTypeAnnotationBasedOnTypeof(type: 'string' | 'number' | 'undefined' | 'boolean' | 'function' | 'object' | 'symbol'): ${NODE_PREFIX}TypeAnnotation`,
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
`declare function createUnionTypeAnnotation(types: Array<${NODE_PREFIX}FlowType>): ${NODE_PREFIX}UnionTypeAnnotation`, `declare export function createUnionTypeAnnotation(types: Array<${NODE_PREFIX}FlowType>): ${NODE_PREFIX}UnionTypeAnnotation`,
// eslint-disable-next-line max-len
`declare export function createFlowUnionType(types: Array<${NODE_PREFIX}FlowType>): ${NODE_PREFIX}UnionTypeAnnotation`,
// this smells like "internal API" // this smells like "internal API"
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
`declare function buildChildren(node: { children: Array<${NODE_PREFIX}JSXText | ${NODE_PREFIX}JSXExpressionContainer | ${NODE_PREFIX}JSXSpreadChild | ${NODE_PREFIX}JSXElement | ${NODE_PREFIX}JSXFragment | ${NODE_PREFIX}JSXEmptyExpression> }): Array<${NODE_PREFIX}JSXText | ${NODE_PREFIX}JSXExpressionContainer | ${NODE_PREFIX}JSXSpreadChild | ${NODE_PREFIX}JSXElement | ${NODE_PREFIX}JSXFragment>`, `declare export function buildChildren(node: { children: Array<${NODE_PREFIX}JSXText | ${NODE_PREFIX}JSXExpressionContainer | ${NODE_PREFIX}JSXSpreadChild | ${NODE_PREFIX}JSXElement | ${NODE_PREFIX}JSXFragment | ${NODE_PREFIX}JSXEmptyExpression> }): Array<${NODE_PREFIX}JSXText | ${NODE_PREFIX}JSXExpressionContainer | ${NODE_PREFIX}JSXSpreadChild | ${NODE_PREFIX}JSXElement | ${NODE_PREFIX}JSXFragment>`,
// clone/ // clone/
`declare function clone<T>(n: T): T;`, `declare export function clone<T>(n: T): T;`,
`declare function cloneDeep<T>(n: T): T;`, `declare export function cloneDeep<T>(n: T): T;`,
`declare function cloneNode<T>(n: T, deep?: boolean): T;`, `declare export function cloneDeepWithoutLoc<T>(n: T): T;`,
`declare function cloneWithoutLoc<T>(n: T): T;`, `declare export function cloneNode<T>(n: T, deep?: boolean, withoutLoc?: boolean): T;`,
`declare export function cloneWithoutLoc<T>(n: T): T;`,
// comments/ // comments/
`declare type CommentTypeShorthand = 'leading' | 'inner' | 'trailing'`, `declare type CommentTypeShorthand = 'leading' | 'inner' | 'trailing'`,
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
`declare function addComment<T: Node>(node: T, type: CommentTypeShorthand, content: string, line?: boolean): T`, `declare export function addComment<T: BabelNode>(node: T, type: CommentTypeShorthand, content: string, line?: boolean): T`,
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
`declare function addComments<T: Node>(node: T, type: CommentTypeShorthand, comments: Array<Comment>): T`, `declare export function addComments<T: BabelNode>(node: T, type: CommentTypeShorthand, comments: Array<Comment>): T`,
`declare function inheritInnerComments(node: Node, parent: Node): void`, `declare export function inheritInnerComments(node: BabelNode, parent: BabelNode): void`,
`declare function inheritLeadingComments(node: Node, parent: Node): void`, `declare export function inheritLeadingComments(node: BabelNode, parent: BabelNode): void`,
`declare function inheritsComments<T: Node>(node: T, parent: Node): void`, `declare export function inheritsComments<T: BabelNode>(node: T, parent: BabelNode): void`,
`declare function inheritTrailingComments(node: Node, parent: Node): void`, `declare export function inheritTrailingComments(node: BabelNode, parent: BabelNode): void`,
`declare function removeComments<T: Node>(node: T): T`, `declare export function removeComments<T: BabelNode>(node: T): T`,
// converters/ // converters/
`declare function ensureBlock(node: ${NODE_PREFIX}, key: string): ${NODE_PREFIX}BlockStatement`, `declare export function ensureBlock(node: ${NODE_PREFIX}, key: string): ${NODE_PREFIX}BlockStatement`,
`declare function toBindingIdentifierName(name?: ?string): string`, `declare export function toBindingIdentifierName(name?: ?string): string`,
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
`declare function toBlock(node: ${NODE_PREFIX}Statement | ${NODE_PREFIX}Expression, parent?: ${NODE_PREFIX}Function | null): ${NODE_PREFIX}BlockStatement`, `declare export function toBlock(node: ${NODE_PREFIX}Statement | ${NODE_PREFIX}Expression, parent?: ${NODE_PREFIX}Function | null): ${NODE_PREFIX}BlockStatement`,
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
`declare function toComputedKey(node: ${NODE_PREFIX}Method | ${NODE_PREFIX}Property, key?: ${NODE_PREFIX}Expression | ${NODE_PREFIX}Identifier): ${NODE_PREFIX}Expression`, `declare export function toComputedKey(node: ${NODE_PREFIX}Method | ${NODE_PREFIX}Property, key?: ${NODE_PREFIX}Expression | ${NODE_PREFIX}Identifier): ${NODE_PREFIX}Expression`,
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
`declare function toExpression(node: ${NODE_PREFIX}ExpressionStatement | ${NODE_PREFIX}Expression | ${NODE_PREFIX}Class | ${NODE_PREFIX}Function): ${NODE_PREFIX}Expression`, `declare export function toExpression(node: ${NODE_PREFIX}ExpressionStatement | ${NODE_PREFIX}Expression | ${NODE_PREFIX}Class | ${NODE_PREFIX}Function): ${NODE_PREFIX}Expression`,
`declare function toIdentifier(name?: ?string): string`, `declare export function toIdentifier(name?: ?string): string`,
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
`declare function toKeyAlias(node: ${NODE_PREFIX}Method | ${NODE_PREFIX}Property, key?: ${NODE_PREFIX}): string`, `declare export function toKeyAlias(node: ${NODE_PREFIX}Method | ${NODE_PREFIX}Property, key?: ${NODE_PREFIX}): string`,
// toSequenceExpression relies on types that aren't declared in flow // toSequenceExpression relies on types that aren't declared in flow
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
`declare function toStatement(node: ${NODE_PREFIX}Statement | ${NODE_PREFIX}Class | ${NODE_PREFIX}Function | ${NODE_PREFIX}AssignmentExpression, ignore?: boolean): ${NODE_PREFIX}Statement | void`, `declare export function toStatement(node: ${NODE_PREFIX}Statement | ${NODE_PREFIX}Class | ${NODE_PREFIX}Function | ${NODE_PREFIX}AssignmentExpression, ignore?: boolean): ${NODE_PREFIX}Statement | void`,
`declare function valueToNode(value: any): ${NODE_PREFIX}Expression`, `declare export function valueToNode(value: any): ${NODE_PREFIX}Expression`,
// modifications/ // modifications/
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
`declare function removeTypeDuplicates(types: Array<${NODE_PREFIX}FlowType>): Array<${NODE_PREFIX}FlowType>`, `declare export function removeTypeDuplicates(types: Array<${NODE_PREFIX}FlowType>): Array<${NODE_PREFIX}FlowType>`,
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
`declare function appendToMemberExpression(member: ${NODE_PREFIX}MemberExpression, append: ${NODE_PREFIX}, computed?: boolean): ${NODE_PREFIX}MemberExpression`, `declare export function appendToMemberExpression(member: ${NODE_PREFIX}MemberExpression, append: ${NODE_PREFIX}, computed?: boolean): ${NODE_PREFIX}MemberExpression`,
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
`declare function inherits<T: Node>(child: T, parent: ${NODE_PREFIX} | null | void): T`, `declare export function inherits<T: BabelNode>(child: T, parent: ${NODE_PREFIX} | null | void): T`,
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
`declare function prependToMemberExpression(member: ${NODE_PREFIX}MemberExpression, prepend: ${NODE_PREFIX}Expression): ${NODE_PREFIX}MemberExpression`, `declare export function prependToMemberExpression(member: ${NODE_PREFIX}MemberExpression, prepend: ${NODE_PREFIX}Expression): ${NODE_PREFIX}MemberExpression`,
`declare function removeProperties<T>(n: T, opts: ?{}): void;`, `declare export function removeProperties<T>(n: T, opts: ?{}): void;`,
`declare function removePropertiesDeep<T>(n: T, opts: ?{}): T;`, `declare export function removePropertiesDeep<T>(n: T, opts: ?{}): T;`,
// retrievers/ // retrievers/
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
`declare function getBindingIdentifiers(node: ${NODE_PREFIX}, duplicates: boolean, outerOnly?: boolean): { [key: string]: ${NODE_PREFIX}Identifier | Array<${NODE_PREFIX}Identifier> }`, `declare export var getBindingIdentifiers: {
(node: ${NODE_PREFIX}, duplicates?: boolean, outerOnly?: boolean): { [key: string]: ${NODE_PREFIX}Identifier | Array<${NODE_PREFIX}Identifier> },
keys: { [type: string]: string[] }
}`,
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
`declare function getOuterBindingIdentifiers(node: Node, duplicates: boolean): { [key: string]: ${NODE_PREFIX}Identifier | Array<${NODE_PREFIX}Identifier> }`, `declare export function getOuterBindingIdentifiers(node: BabelNode, duplicates?: boolean): { [key: string]: ${NODE_PREFIX}Identifier | Array<${NODE_PREFIX}Identifier> }`,
// traverse/ // traverse/
`declare type TraversalAncestors = Array<{ `declare type TraversalAncestors = Array<{
...@@ -195,36 +212,36 @@ lines.push( ...@@ -195,36 +212,36 @@ lines.push(
exit?: TraversalHandler<T>, exit?: TraversalHandler<T>,
};`.replace(/(^|\n) {2}/g, "$1"), };`.replace(/(^|\n) {2}/g, "$1"),
// eslint-disable-next-line // eslint-disable-next-line
`declare function traverse<T>(n: BabelNode, TraversalHandler<T> | TraversalHandlers<T>, state?: T): void;`, `declare export function traverse<T>(n: BabelNode, TraversalHandler<T> | TraversalHandlers<T>, state?: T): void;`,
`declare function traverseFast<T>(n: Node, h: TraversalHandler<T>, state?: T): void;`, `declare export function traverseFast<T>(n: BabelNode, h: TraversalHandler<T>, state?: T): void;`,
// utils/ // utils/
// cleanJSXElementLiteralChild is not exported // cleanJSXElementLiteralChild is not exported
// inherit is not exported // inherit is not exported
`declare function shallowEqual(actual: Object, expected: Object): boolean`, `declare export function shallowEqual(actual: Object, expected: Object): boolean`,
// validators/ // validators/
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
`declare function buildMatchMemberExpression(match: string, allowPartial?: boolean): (?BabelNode) => boolean`, `declare export function buildMatchMemberExpression(match: string, allowPartial?: boolean): (?BabelNode) => boolean`,
`declare function is(type: string, n: BabelNode, opts: Object): boolean;`, `declare export function is(type: string, n: BabelNode, opts: Object): boolean;`,
`declare function isBinding(node: BabelNode, parent: BabelNode, grandparent?: BabelNode): boolean`, `declare export function isBinding(node: BabelNode, parent: BabelNode, grandparent?: BabelNode): boolean`,
`declare function isBlockScoped(node: BabelNode): boolean`, `declare export function isBlockScoped(node: BabelNode): boolean`,
`declare function isImmutable(node: BabelNode): boolean`, `declare export function isImmutable(node: BabelNode): boolean`,
`declare function isLet(node: BabelNode): boolean`, `declare export function isLet(node: BabelNode): boolean`,
`declare function isNode(node: ?Object): boolean`, `declare export function isNode(node: ?Object): boolean`,
`declare function isNodesEquivalent(a: any, b: any): boolean`, `declare export function isNodesEquivalent(a: any, b: any): boolean`,
`declare function isPlaceholderType(placeholderType: string, targetType: string): boolean`, `declare export function isPlaceholderType(placeholderType: string, targetType: string): boolean`,
`declare function isReferenced(node: BabelNode, parent: BabelNode, grandparent?: BabelNode): boolean`, `declare export function isReferenced(node: BabelNode, parent: BabelNode, grandparent?: BabelNode): boolean`,
`declare function isScope(node: BabelNode, parent: BabelNode): boolean`, `declare export function isScope(node: BabelNode, parent: BabelNode): boolean`,
`declare function isSpecifierDefault(specifier: BabelNodeModuleSpecifier): boolean`, `declare export function isSpecifierDefault(specifier: BabelNodeModuleSpecifier): boolean`,
`declare function isType(nodetype: ?string, targetType: string): boolean`, `declare export function isType(nodetype: ?string, targetType: string): boolean`,
`declare function isValidES3Identifier(name: string): boolean`, `declare export function isValidES3Identifier(name: string): boolean`,
`declare function isValidES3Identifier(name: string): boolean`, `declare export function isValidES3Identifier(name: string): boolean`,
`declare function isValidIdentifier(name: string): boolean`, `declare export function isValidIdentifier(name: string): boolean`,
`declare function isVar(node: BabelNode): boolean`, `declare export function isVar(node: BabelNode): boolean`,
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
`declare function matchesPattern(node: ?BabelNode, match: string | Array<string>, allowPartial?: boolean): boolean`, `declare export function matchesPattern(node: ?BabelNode, match: string | Array<string>, allowPartial?: boolean): boolean`,
`declare function validate(n: BabelNode, key: string, value: mixed): void;` `declare export function validate(n: BabelNode, key: string, value: mixed): void;`
); );
for (const type in t.FLIPPED_ALIAS_KEYS) { for (const type in t.FLIPPED_ALIAS_KEYS) {
...@@ -235,10 +252,7 @@ for (const type in t.FLIPPED_ALIAS_KEYS) { ...@@ -235,10 +252,7 @@ for (const type in t.FLIPPED_ALIAS_KEYS) {
} }
code += `\ndeclare module "@babel/types" { code += `\ndeclare module "@babel/types" {
${lines ${lines.join("\n").replace(/\n/g, "\n ").trim()}
.join("\n")
.replace(/\n/g, "\n ")
.trim()}
}\n`; }\n`;
// //
......
"use strict";
const definitions = require("../../lib/definitions");
function addAssertHelper(type) {
return `export function assert${type}(node: Object, opts?: Object = {}): void {
assert("${type}", node, opts) }
`;
}
module.exports = function generateAsserts() {
let output = `// @flow
/*
* This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build'
*/
import is from "../../validators/is";
function assert(type: string, node: Object, opts?: Object): void {
if (!is(type, node, opts)) {
throw new Error(
\`Expected type "\${type}" with option \${JSON.stringify((opts: any))}, \` +
\`but instead got "\${node.type}".\`,
);
}
}\n\n`;
Object.keys(definitions.VISITOR_KEYS).forEach(type => {
output += addAssertHelper(type);
});
Object.keys(definitions.FLIPPED_ALIAS_KEYS).forEach(type => {
output += addAssertHelper(type);
});
Object.keys(definitions.DEPRECATED_KEYS).forEach(type => {
const newType = definitions.DEPRECATED_KEYS[type];
output += `export function assert${type}(node: Object, opts: Object): void {
console.trace("The node type ${type} has been renamed to ${newType}");
assert("${type}", node, opts);
}\n`;
});
return output;
};
"use strict";
const definitions = require("../../lib/definitions");
const formatBuilderName = require("../utils/formatBuilderName");
const lowerFirst = require("../utils/lowerFirst");
module.exports = function generateBuilders() {
let output = `// @flow
/*
* This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build'
*/
import builder from "../builder";\n\n`;
Object.keys(definitions.BUILDER_KEYS).forEach(type => {
output += `export function ${type}(...args: Array<any>): Object { return builder("${type}", ...args); }
export { ${type} as ${formatBuilderName(type)} };\n`;
// This is needed for backwards compatibility.
// It should be removed in the next major version.
// JSXIdentifier -> jSXIdentifier
if (/^[A-Z]{2}/.test(type)) {
output += `export { ${type} as ${lowerFirst(type)} }\n`;
}
});
Object.keys(definitions.DEPRECATED_KEYS).forEach(type => {
const newType = definitions.DEPRECATED_KEYS[type];
output += `export function ${type}(...args: Array<any>): Object {
console.trace("The node type ${type} has been renamed to ${newType}");
return ${type}("${type}", ...args);
}
export { ${type} as ${formatBuilderName(type)} };\n`;
// This is needed for backwards compatibility.
// It should be removed in the next major version.
// JSXIdentifier -> jSXIdentifier
if (/^[A-Z]{2}/.test(type)) {
output += `export { ${type} as ${lowerFirst(type)} }\n`;
}
});
return output;
};
"use strict";
const definitions = require("../../lib/definitions");
module.exports = function generateConstants() {
let output = `// @flow
/*
* This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build'
*/
import { FLIPPED_ALIAS_KEYS } from "../../definitions";\n\n`;
Object.keys(definitions.FLIPPED_ALIAS_KEYS).forEach(type => {
output += `export const ${type.toUpperCase()}_TYPES = FLIPPED_ALIAS_KEYS["${type}"];\n`;
});
return output;
};
"use strict";
const definitions = require("../../lib/definitions");
const has = Function.call.bind(Object.prototype.hasOwnProperty);
function joinComparisons(leftArr, right) {
return (
leftArr.map(JSON.stringify).join(` === ${right} || `) + ` === ${right}`
);
}
function addIsHelper(type, aliasKeys, deprecated) {
const targetType = JSON.stringify(type);
let aliasSource = "";
if (aliasKeys) {
aliasSource = " || " + joinComparisons(aliasKeys, "nodeType");
}
let placeholderSource = "";
const placeholderTypes = [];
if (
definitions.PLACEHOLDERS.includes(type) &&
has(definitions.FLIPPED_ALIAS_KEYS, type)
) {
placeholderTypes.push(type);
}
if (has(definitions.PLACEHOLDERS_FLIPPED_ALIAS, type)) {
placeholderTypes.push(...definitions.PLACEHOLDERS_FLIPPED_ALIAS[type]);
}
if (placeholderTypes.length > 0) {
placeholderSource =
' || nodeType === "Placeholder" && (' +
joinComparisons(placeholderTypes, "node.expectedNode") +
")";
}
return `export function is${type}(node: ?Object, opts?: Object): boolean {
${deprecated || ""}
if (!node) return false;
const nodeType = node.type;
if (nodeType === ${targetType}${aliasSource}${placeholderSource}) {
if (typeof opts === "undefined") {
return true;
} else {
return shallowEqual(node, opts);
}
}
return false;
}
`;
}
module.exports = function generateValidators() {
let output = `// @flow
/*
* This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build'
*/
import shallowEqual from "../../utils/shallowEqual";\n\n`;
Object.keys(definitions.VISITOR_KEYS).forEach(type => {
output += addIsHelper(type);
});
Object.keys(definitions.FLIPPED_ALIAS_KEYS).forEach(type => {
output += addIsHelper(type, definitions.FLIPPED_ALIAS_KEYS[type]);
});
Object.keys(definitions.DEPRECATED_KEYS).forEach(type => {
const newType = definitions.DEPRECATED_KEYS[type];
const deprecated = `console.trace("The node type ${type} has been renamed to ${newType}");`;
output += addIsHelper(type, null, deprecated);
});
return output;
};
"use strict";
const t = require("../../");
const stringifyValidator = require("../utils/stringifyValidator");
const toFunctionName = require("../utils/toFunctionName");
let code = `// NOTE: This file is autogenerated. Do not modify.
// See packages/babel-types/scripts/generators/typescript.js for script used.
interface BaseComment {
value: string;
start: number;
end: number;
loc: SourceLocation;
type: "CommentBlock" | "CommentLine";
}
export interface CommentBlock extends BaseComment {
type: "CommentBlock";
}
export interface CommentLine extends BaseComment {
type: "CommentLine";
}
export type Comment = CommentBlock | CommentLine;
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];
// Future / annoying TODO:
// MemberExpression.property, ObjectProperty.key and ObjectMethod.key need special cases; either:
// - convert the declaration to chain() like ClassProperty.key and ClassMethod.key,
// - declare an alias type for valid keys, detect the case and reuse it here,
// - declare a disjoint union with, for example, ObjectPropertyBase,
// ObjectPropertyLiteralKey and ObjectPropertyComputedKey, and declare ObjectProperty
// as "ObjectPropertyBase & (ObjectPropertyLiteralKey | ObjectPropertyComputedKey)"
let typeAnnotation = 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" : ""
}`
);
}
const alphaNumeric = /^\w+$/;
if (t.isValidIdentifier(fieldName) || alphaNumeric.test(fieldName)) {
struct.push(`${fieldName}: ${typeAnnotation};`);
} else {
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 ${toFunctionName(type)}(${args.join(", ")}): ${type};`
);
} else {
const functionName = toFunctionName(type);
lines.push(
`declare function _${functionName}(${args.join(", ")}): ${type};`,
`export { _${functionName} as ${functionName}}`
);
}
}
for (const typeName of t.TYPES) {
const result =
t.NODE_FIELDS[typeName] || t.FLIPPED_ALIAS_KEYS[typeName]
? `node is ${typeName}`
: "boolean";
lines.push(
`export function is${typeName}(node: object | null | undefined, opts?: object | null): ${result};`,
// TypeScript 3.7: https://github.com/microsoft/TypeScript/pull/32695 will allow assert declarations
// eslint-disable-next-line max-len
`// export function assert${typeName}(node: object | null | undefined, opts?: object | null): asserts ${
result === "boolean" ? "node" : result
};`
);
}
lines.push(
// assert/
// Commented out as this declaration requires TypeScript 3.7 (what do?)
`// export function assertNode(obj: any): asserts obj is Node`,
// builders/
// eslint-disable-next-line max-len
`export function createTypeAnnotationBasedOnTypeof(type: 'string' | 'number' | 'undefined' | 'boolean' | 'function' | 'object' | 'symbol'): StringTypeAnnotation | VoidTypeAnnotation | NumberTypeAnnotation | BooleanTypeAnnotation | GenericTypeAnnotation`,
`export function createUnionTypeAnnotation<T extends FlowType>(types: [T]): T`,
// this probably misbehaves if there are 0 elements, and it's not a UnionTypeAnnotation if there's only 1
// it is possible to require "2 or more" for this overload ([T, T, ...T[]]) but it requires typescript 3.0
`export function createUnionTypeAnnotation(types: ReadonlyArray<FlowType>): UnionTypeAnnotation`,
// this smells like "internal API"
// eslint-disable-next-line max-len
`export function buildChildren(node: { children: ReadonlyArray<JSXText | JSXExpressionContainer | JSXSpreadChild | JSXElement | JSXFragment | JSXEmptyExpression> }): JSXElement['children']`,
// clone/
`export function clone<T extends Node>(n: T): T;`,
`export function cloneDeep<T extends Node>(n: T): T;`,
`export function cloneNode<T extends Node>(n: T, deep?: boolean): T;`,
`export function cloneWithoutLoc<T extends Node>(n: T): T;`,
// comments/
`export type CommentTypeShorthand = 'leading' | 'inner' | 'trailing'`,
// eslint-disable-next-line max-len
`export function addComment<T extends Node>(node: T, type: CommentTypeShorthand, content: string, line?: boolean): T`,
// eslint-disable-next-line max-len
`export function addComments<T extends Node>(node: T, type: CommentTypeShorthand, comments: ReadonlyArray<Comment>): T`,
`export function inheritInnerComments(node: Node, parent: Node): void`,
`export function inheritLeadingComments(node: Node, parent: Node): void`,
`export function inheritsComments<T extends Node>(node: T, parent: Node): void`,
`export function inheritTrailingComments(node: Node, parent: Node): void`,
`export function removeComments<T extends Node>(node: T): T`,
// converters/
// eslint-disable-next-line max-len
`export function ensureBlock(node: Extract<Node, { body: BlockStatement | Statement | Expression }>): BlockStatement`,
// too complex?
// eslint-disable-next-line max-len
`export function ensureBlock<K extends keyof Extract<Node, { body: BlockStatement | Statement | Expression }> = 'body'>(node: Extract<Node, Record<K, BlockStatement | Statement | Expression>>, key: K): BlockStatement`,
// gatherSequenceExpressions is not exported
`export function toBindingIdentifierName(name: { toString(): string } | null | undefined): string`,
`export function toBlock(node: Statement | Expression, parent?: Function | null): BlockStatement`,
// it is possible for `node` to be an arbitrary object if `key` is always provided,
// but that doesn't look like intended API
// eslint-disable-next-line max-len
`export function toComputedKey<T extends Extract<Node, { computed: boolean | null }>>(node: T, key?: Expression | Identifier): Expression`,
`export function toExpression(node: Function): FunctionExpression`,
`export function toExpression(node: Class): ClassExpression`,
`export function toExpression(node: ExpressionStatement | Expression | Class | Function): Expression`,
`export function toIdentifier(name: { toString(): string } | null | undefined): string`,
`export function toKeyAlias(node: Method | Property, key?: Node): string`,
// NOTE: this actually uses Scope from @babel/traverse, but we can't add a dependency on its types,
// as they live in @types. Declare the structural subset that is required.
// eslint-disable-next-line max-len
`export function toSequenceExpression(nodes: ReadonlyArray<Node>, scope: { push(value: { id: LVal; kind: 'var'; init?: Expression}): void; buildUndefinedNode(): Node }): SequenceExpression | undefined`,
`export function toStatement(node: AssignmentExpression, ignore?: boolean): ExpressionStatement`,
`export function toStatement(node: Statement | AssignmentExpression, ignore?: boolean): Statement`,
`export function toStatement(node: Class, ignore: true): ClassDeclaration | undefined`,
`export function toStatement(node: Class, ignore?: boolean): ClassDeclaration`,
`export function toStatement(node: Function, ignore: true): FunctionDeclaration | undefined`,
`export function toStatement(node: Function, ignore?: boolean): FunctionDeclaration`,
// eslint-disable-next-line max-len
`export function toStatement(node: Statement | Class | Function | AssignmentExpression, ignore: true): Statement | undefined`,
// eslint-disable-next-line max-len
`export function toStatement(node: Statement | Class | Function | AssignmentExpression, ignore?: boolean): Statement`,
// eslint-disable-next-line max-len
`export function valueToNode(value: undefined): Identifier`, // (should this not be a UnaryExpression to avoid shadowing?)
`export function valueToNode(value: boolean): BooleanLiteral`,
`export function valueToNode(value: null): NullLiteral`,
`export function valueToNode(value: string): StringLiteral`,
// Infinities and NaN need to use a BinaryExpression; negative values must be wrapped in UnaryExpression
`export function valueToNode(value: number): NumericLiteral | BinaryExpression | UnaryExpression`,
`export function valueToNode(value: RegExp): RegExpLiteral`,
// eslint-disable-next-line max-len
`export function valueToNode(value: ReadonlyArray<undefined | boolean | null | string | number | RegExp | object>): ArrayExpression`,
// this throws with objects that are not PlainObject according to lodash,
// or if there are non-valueToNode-able values
`export function valueToNode(value: object): ObjectExpression`,
// eslint-disable-next-line max-len
`export function valueToNode(value: undefined | boolean | null | string | number | RegExp | object): Expression`,
// modifications/
// eslint-disable-next-line max-len
`export function removeTypeDuplicates(types: ReadonlyArray<FlowType | false | null | undefined>): FlowType[]`,
// eslint-disable-next-line max-len
`export function appendToMemberExpression<T extends Pick<MemberExpression, 'object' | 'property'>>(member: T, append: MemberExpression['property'], computed?: boolean): T`,
// eslint-disable-next-line max-len
`export function inherits<T extends Node | null | undefined>(child: T, parent: Node | null | undefined): T`,
// eslint-disable-next-line max-len
`export function prependToMemberExpression<T extends Pick<MemberExpression, 'object' | 'property'>>(member: T, prepend: MemberExpression['object']): T`,
`export function removeProperties(
n: Node,
opts?: { preserveComments: boolean } | null
): void;`,
`export function removePropertiesDeep<T extends Node>(
n: T,
opts?: { preserveComments: boolean } | null
): T;`,
// retrievers/
// eslint-disable-next-line max-len
`export function getBindingIdentifiers(node: Node, duplicates: true, outerOnly?: boolean): Record<string, Array<Identifier>>`,
// eslint-disable-next-line max-len
`export function getBindingIdentifiers(node: Node, duplicates?: false, outerOnly?: boolean): Record<string, Identifier>`,
// eslint-disable-next-line max-len
`export function getBindingIdentifiers(node: Node, duplicates: boolean, outerOnly?: boolean): Record<string, Identifier | Array<Identifier>>`,
// eslint-disable-next-line max-len
`export function getOuterBindingIdentifiers(node: Node, duplicates: true): Record<string, Array<Identifier>>`,
`export function getOuterBindingIdentifiers(node: Node, duplicates?: false): Record<string, Identifier>`,
// eslint-disable-next-line max-len
`export function getOuterBindingIdentifiers(node: Node, duplicates: boolean): Record<string, Identifier | Array<Identifier>>`,
// traverse/
`export type TraversalAncestors = ReadonlyArray<{
node: Node,
key: string,
index?: number,
}>;
export type TraversalHandler<T> = (
this: undefined, 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;`,
`export function traverseFast<T>(n: Node, h: TraversalHandler<T>, state?: T): void;`,
// utils/
// cleanJSXElementLiteralChild is not exported
// inherit is not exported
`export function shallowEqual<T extends object>(actual: object, expected: T): actual is T`,
// validators/
// eslint-disable-next-line max-len
`export function buildMatchMemberExpression(match: string, allowPartial?: boolean): (node: Node | null | undefined) => node is MemberExpression`,
// eslint-disable-next-line max-len
`export function is<T extends Node['type']>(type: T, n: Node | null | undefined, required?: undefined): n is Extract<Node, { type: T }>`,
// eslint-disable-next-line max-len
`export function is<T extends Node['type'], P extends Extract<Node, { type: T }>>(type: T, n: Node | null | undefined, required: Partial<P>): n is P`,
// eslint-disable-next-line max-len
`export function is<P extends Node>(type: string, n: Node | null | undefined, required: Partial<P>): n is P`,
`export function is(type: string, n: Node | null | undefined, required?: Partial<Node>): n is Node`,
`export function isBinding(node: Node, parent: Node, grandparent?: Node): boolean`,
// eslint-disable-next-line max-len
`export function isBlockScoped(node: Node): node is FunctionDeclaration | ClassDeclaration | VariableDeclaration`,
`export function isImmutable(node: Node): node is Immutable`,
`export function isLet(node: Node): node is VariableDeclaration`,
`export function isNode(node: object | null | undefined): node is Node`,
`export function isNodesEquivalent<T extends Partial<Node>>(a: T, b: any): b is T`,
`export function isNodesEquivalent(a: any, b: any): boolean`,
`export function isPlaceholderType(placeholderType: Node['type'], targetType: Node['type']): boolean`,
`export function isReferenced(node: Node, parent: Node, grandparent?: Node): boolean`,
`export function isScope(node: Node, parent: Node): node is Scopable`,
`export function isSpecifierDefault(specifier: ModuleSpecifier): boolean`,
`export function isType<T extends Node['type']>(nodetype: string, targetType: T): nodetype is T`,
`export function isType(nodetype: string | null | undefined, targetType: string): boolean`,
`export function isValidES3Identifier(name: string): boolean`,
`export function isValidIdentifier(name: string): boolean`,
`export function isVar(node: Node): node is VariableDeclaration`,
// the MemberExpression implication is incidental, but it follows from the implementation
// eslint-disable-next-line max-len
`export function matchesPattern(node: Node | null | undefined, match: string | ReadonlyArray<string>, allowPartial?: boolean): node is MemberExpression`,
// TypeScript 3.7: ": asserts n is T"
// eslint-disable-next-line max-len
`export function validate<T extends Node, K extends keyof T>(n: Node | null | undefined, key: K, value: T[K]): void`,
`export function validate(n: Node, key: string, value: any): 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 += "\n";
code += "export interface Aliases {\n";
for (const type in t.FLIPPED_ALIAS_KEYS) {
code += ` ${type}: ${type};\n`;
}
code += "}\n\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;
});
}
"use strict";
const toLowerCase = Function.call.bind("".toLowerCase); const toLowerCase = Function.call.bind("".toLowerCase);
module.exports = function formatBuilderName(type) { export default function formatBuilderName(type) {
// FunctionExpression -> functionExpression // FunctionExpression -> functionExpression
// JSXIdentifier -> jsxIdentifier // JSXIdentifier -> jsxIdentifier
// V8IntrinsicIdentifier -> v8IntrinsicIdentifier // V8IntrinsicIdentifier -> v8IntrinsicIdentifier
return type.replace(/^([A-Z](?=[a-z0-9])|[A-Z]+(?=[A-Z]))/, toLowerCase); return type.replace(/^([A-Z](?=[a-z0-9])|[A-Z]+(?=[A-Z]))/, toLowerCase);
}; }
"use strict"; export default function lowerFirst(string) {
module.exports = function lowerFirst(string) {
return string[0].toLowerCase() + string.slice(1); return string[0].toLowerCase() + string.slice(1);
}; }
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment