Extend hasPlugin to accept plugin-configuration array pairs (#13982)

Co-authored-by: Nicolò Ribaudo <nicolo.ribaudo@gmail.com>
This commit is contained in:
J. S. Choi 2021-12-02 17:17:51 -05:00 committed by GitHub
parent ecae53a98e
commit f4236f43a1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
42 changed files with 165 additions and 94 deletions

View File

@ -378,7 +378,7 @@ Note that the code shown in Chrome DevTools is compiled code and therefore diffe
- After the ESTree PR is accepted, update [ast/spec.md](https://github.com/babel/babel/blob/master/packages/babel-parser/ast/spec.md). Note that there are differences between Babel AST and ESTree. In these cases, consistency with current Babel AST outweighs alignment to ESTree. Otherwise it should follow ESTree. - After the ESTree PR is accepted, update [ast/spec.md](https://github.com/babel/babel/blob/master/packages/babel-parser/ast/spec.md). Note that there are differences between Babel AST and ESTree. In these cases, consistency with current Babel AST outweighs alignment to ESTree. Otherwise it should follow ESTree.
- [ ] Implement parser plugins based on the new AST. The parser plugin name should be the unprefixed slug of the TC39 proposal URL in _camelcase_, i.e. `exportDefaultFrom` from `https://github.com/tc39/proposal-export-default-from`. - [ ] Implement parser plugins based on the new AST. The parser plugin name should be the unprefixed slug of the TC39 proposal URL in _camelcase_, i.e. `exportDefaultFrom` from `https://github.com/tc39/proposal-export-default-from`.
- [ ] Use the `this.expectPlugin("newSyntax")` check within `@babel/parser` to ensure your new plugin code only runs when that flag is turned on (not default behavior), and a friendly error is thrown if users forget to enable a plugin. - [ ] Use the `this.expectPlugin("pluginName")` check within `@babel/parser` to ensure your new plugin code only runs when that flag is turned on (not default behavior), and a friendly error is thrown if users forget to enable a plugin. You can also supply an array pair to require certain configuration options, e.g., `this.expectPlugin(["pluginName", { configOption: value }])`.
- [ ] Add failing/passing tests according to spec behavior - [ ] Add failing/passing tests according to spec behavior
- [ ] Add `@babel/syntax-new-syntax` package. You can copy `packages/babel-plugin-syntax-decimal` and replace `decimal` to `new-syntax`. - [ ] Add `@babel/syntax-new-syntax` package. You can copy `packages/babel-plugin-syntax-decimal` and replace `decimal` to `new-syntax`.
- [ ] Add `@babel/syntax-new-syntax` to `@babel/standalone`. - [ ] Add `@babel/syntax-new-syntax` to `@babel/standalone`.

View File

@ -31,12 +31,31 @@ export default class BaseParser {
declare input: string; declare input: string;
declare length: number; declare length: number;
hasPlugin(name: string): boolean { // This method accepts either a string (plugin name) or an array pair
return this.plugins.has(name); // (plugin name and options object). If an options object is given,
// then each value is non-recursively checked for identity with that
// plugins actual option value.
hasPlugin(pluginConfig: PluginConfig): boolean {
if (typeof pluginConfig === "string") {
return this.plugins.has(pluginConfig);
} else {
const [pluginName, pluginOptions] = pluginConfig;
if (!this.hasPlugin(pluginName)) {
return false;
}
const actualOptions = this.plugins.get(pluginName);
for (const key of Object.keys(pluginOptions)) {
if (actualOptions?.[key] !== pluginOptions[key]) {
return false;
}
}
return true;
}
} }
getPluginOption(plugin: string, name: string) { getPluginOption(plugin: string, name: string) {
// $FlowIssue return this.plugins.get(plugin)?.[name];
if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name];
} }
} }
export type PluginConfig = string | [string, { [string]: any }];

View File

@ -448,7 +448,7 @@ export default class ExpressionParser extends LValParser {
if ( if (
op === tt.pipeline && op === tt.pipeline &&
this.getPluginOption("pipelineOperator", "proposal") === "minimal" this.hasPlugin(["pipelineOperator", { proposal: "minimal" }])
) { ) {
if (this.state.type === tt._await && this.prodParam.hasAwait) { if (this.state.type === tt._await && this.prodParam.hasAwait) {
throw this.raise( throw this.raise(
@ -1422,11 +1422,12 @@ export default class ExpressionParser extends LValParser {
): boolean { ): boolean {
switch (pipeProposal) { switch (pipeProposal) {
case "hack": { case "hack": {
const pluginTopicToken = this.getPluginOption( return this.hasPlugin([
"pipelineOperator", "pipelineOperator",
"topicToken", {
); topicToken: tokenLabelName(tokenType),
return tokenLabelName(tokenType) === pluginTopicToken; },
]);
} }
case "smart": case "smart":
return tokenType === tt.hash; return tokenType === tt.hash;
@ -2740,7 +2741,7 @@ export default class ExpressionParser extends LValParser {
// of the infix operator `|>`. // of the infix operator `|>`.
checkPipelineAtInfixOperator(left: N.Expression, leftStartPos: number) { checkPipelineAtInfixOperator(left: N.Expression, leftStartPos: number) {
if (this.getPluginOption("pipelineOperator", "proposal") === "smart") { if (this.hasPlugin(["pipelineOperator", { proposal: "smart" }])) {
if (left.type === "SequenceExpression") { if (left.type === "SequenceExpression") {
// Ensure that the pipeline head is not a comma-delimited // Ensure that the pipeline head is not a comma-delimited
// sequence expression. // sequence expression.
@ -2841,8 +2842,7 @@ export default class ExpressionParser extends LValParser {
// had before the function was called. // had before the function was called.
withSmartMixTopicForbiddingContext<T>(callback: () => T): T { withSmartMixTopicForbiddingContext<T>(callback: () => T): T {
const proposal = this.getPluginOption("pipelineOperator", "proposal"); if (this.hasPlugin(["pipelineOperator", { proposal: "smart" }])) {
if (proposal === "smart") {
// Reset the parsers topic context only if the smart-mix pipe proposal is active. // Reset the parsers topic context only if the smart-mix pipe proposal is active.
const outerContextTopicState = this.state.topicContext; const outerContextTopicState = this.state.topicContext;
this.state.topicContext = { this.state.topicContext = {

View File

@ -21,6 +21,7 @@ import ProductionParameterHandler, {
} from "../util/production-parameter"; } from "../util/production-parameter";
import { Errors, type ErrorTemplate, ErrorCodes } from "./error"; import { Errors, type ErrorTemplate, ErrorCodes } from "./error";
import type { ParsingError } from "./error"; import type { ParsingError } from "./error";
import type { PluginConfig } from "./base";
/*:: /*::
import type ScopeHandler from "../util/scope"; import type ScopeHandler from "../util/scope";
*/ */
@ -175,26 +176,38 @@ export default class UtilParser extends Tokenizer {
/* eslint-enable @babel/development-internal/dry-error-messages */ /* eslint-enable @babel/development-internal/dry-error-messages */
} }
expectPlugin(name: string, pos?: ?number): true { getPluginNamesFromConfigs(pluginConfigs: Array<PluginConfig>): Array<string> {
if (!this.hasPlugin(name)) { return pluginConfigs.map(c => {
if (typeof c === "string") {
return c;
} else {
return c[0];
}
});
}
expectPlugin(pluginConfig: PluginConfig, pos?: ?number): true {
if (!this.hasPlugin(pluginConfig)) {
throw this.raiseWithData( throw this.raiseWithData(
pos != null ? pos : this.state.start, pos != null ? pos : this.state.start,
{ missingPlugin: [name] }, { missingPlugin: this.getPluginNamesFromConfigs([pluginConfig]) },
`This experimental syntax requires enabling the parser plugin: '${name}'`, `This experimental syntax requires enabling the parser plugin: ${JSON.stringify(
pluginConfig,
)}.`,
); );
} }
return true; return true;
} }
expectOnePlugin(names: Array<string>, pos?: ?number): void { expectOnePlugin(pluginConfigs: Array<PluginConfig>, pos?: ?number): void {
if (!names.some(n => this.hasPlugin(n))) { if (!pluginConfigs.some(c => this.hasPlugin(c))) {
throw this.raiseWithData( throw this.raiseWithData(
pos != null ? pos : this.state.start, pos != null ? pos : this.state.start,
{ missingPlugin: names }, { missingPlugin: this.getPluginNamesFromConfigs(pluginConfigs) },
`This experimental syntax requires enabling one of the following parser plugin(s): '${names.join( `This experimental syntax requires enabling one of the following parser plugin(s): ${pluginConfigs
", ", .map(c => JSON.stringify(c))
)}'`, .join(", ")}.`,
); );
} }
} }

View File

@ -1,19 +1,47 @@
// @flow // @flow
import type Parser from "./parser"; import type Parser from "./parser";
import type { PluginConfig } from "./parser/base";
export type Plugin = string | [string, Object]; export type Plugin = PluginConfig;
export type PluginList = $ReadOnlyArray<Plugin>; export type PluginList = $ReadOnlyArray<PluginConfig>;
export type MixinPlugin = (superClass: Class<Parser>) => Class<Parser>; export type MixinPlugin = (superClass: Class<Parser>) => Class<Parser>;
export function hasPlugin(plugins: PluginList, name: string): boolean { // This functions second parameter accepts either a string (plugin name) or an
return plugins.some(plugin => { // array pair (plugin name and options object). If an options object is given,
if (Array.isArray(plugin)) { // then each value is non-recursively checked for identity with the actual
return plugin[0] === name; // option value of each plugin in the first argument (which is an array of
// plugin names or array pairs).
export function hasPlugin(
plugins: PluginList,
expectedConfig: PluginConfig,
): boolean {
// The expectedOptions object is by default an empty object if the given
// expectedConfig argument does not give an options object (i.e., if it is a
// string).
const [expectedName, expectedOptions] =
typeof expectedConfig === "string" ? [expectedConfig, {}] : expectedConfig;
const expectedKeys = Object.keys(expectedOptions);
const expectedOptionsIsEmpty = expectedKeys.length === 0;
return plugins.some(p => {
if (typeof p === "string") {
return expectedOptionsIsEmpty && p === expectedName;
} else { } else {
return plugin === name; const [pluginName, pluginOptions] = p;
if (pluginName !== expectedName) {
return false;
}
for (const key of expectedKeys) {
if (pluginOptions[key] !== expectedOptions[key]) {
return false;
}
}
return true;
} }
}); });
} }
@ -85,9 +113,10 @@ export function validatePlugins(plugins: PluginList) {
); );
} }
const tupleSyntaxIsHash = const tupleSyntaxIsHash = hasPlugin(plugins, [
hasPlugin(plugins, "recordAndTuple") && "recordAndTuple",
getPluginOption(plugins, "recordAndTuple", "syntaxType") === "hash"; { syntaxType: "hash" },
]);
if (proposal === "hack") { if (proposal === "hack") {
if (hasPlugin(plugins, "placeholders")) { if (hasPlugin(plugins, "placeholders")) {

View File

@ -1,4 +1,3 @@
{ {
"sourceType": "module",
"throws": "Unexpected token (1:18)" "throws": "Unexpected token (1:18)"
} }

View File

@ -1,3 +1,4 @@
{ {
"throws": "This experimental syntax requires enabling the parser plugin: 'exportDefaultFrom' (1:7)" "sourceType": "module",
} "throws": "This experimental syntax requires enabling the parser plugin: \"exportDefaultFrom\". (1:7)"
}

View File

@ -1,6 +1,6 @@
{ {
"throws": "This experimental syntax requires enabling the parser plugin: 'asyncDoExpressions' (1:7)", "throws": "This experimental syntax requires enabling the parser plugin: \"asyncDoExpressions\". (1:7)",
"plugins": [ "plugins": [
"doExpressions" "doExpressions"
] ]
} }

View File

@ -1,4 +1,4 @@
{ {
"throws": "This experimental syntax requires enabling the parser plugin: 'doExpressions' (1:7)", "throws": "This experimental syntax requires enabling the parser plugin: \"doExpressions\". (1:7)",
"plugins": [] "plugins": []
} }

View File

@ -1,3 +1,3 @@
{ {
"throws": "This experimental syntax requires enabling the parser plugin: 'decimal' (1:2)" "throws": "This experimental syntax requires enabling the parser plugin: \"decimal\". (1:2)"
} }

View File

@ -1,4 +1,4 @@
{ {
"throws": "This experimental syntax requires enabling one of the following parser plugin(s): 'decorators-legacy, decorators' (1:0)", "throws": "This experimental syntax requires enabling one of the following parser plugin(s): \"decorators-legacy\", \"decorators\". (1:0)",
"plugins": [] "plugins": []
} }

View File

@ -1,4 +1,4 @@
{ {
"throws": "This experimental syntax requires enabling the parser plugin: 'doExpressions' (1:1)", "throws": "This experimental syntax requires enabling the parser plugin: \"doExpressions\". (1:1)",
"plugins": [] "plugins": []
} }

View File

@ -1,4 +1,4 @@
{ {
"throws": "This experimental syntax requires enabling the parser plugin: 'exportDefaultFrom' (1:7)", "throws": "This experimental syntax requires enabling the parser plugin: \"exportDefaultFrom\". (1:7)",
"plugins": [] "plugins": []
} }

View File

@ -1,5 +1,5 @@
{ {
"throws": "This experimental syntax requires enabling the parser plugin: 'importAssertions' (1:24)", "throws": "This experimental syntax requires enabling the parser plugin: \"importAssertions\". (1:24)",
"sourceType": "module", "sourceType": "module",
"plugins": [] "plugins": []
} }

View File

@ -1,5 +1,5 @@
{ {
"throws": "This experimental syntax requires enabling the parser plugin: 'importAssertions' (1:27)", "throws": "This experimental syntax requires enabling the parser plugin: \"importAssertions\". (1:27)",
"sourceType": "module", "sourceType": "module",
"plugins": [] "plugins": []
} }

View File

@ -1,4 +1,4 @@
{ {
"throws": "This experimental syntax requires enabling the parser plugin: 'moduleAttributes' (1:27)", "throws": "This experimental syntax requires enabling the parser plugin: \"moduleAttributes\". (1:27)",
"BABEL_8_BREAKING": false "BABEL_8_BREAKING": false
} }

View File

@ -1,3 +1,3 @@
{ {
"throws": "This experimental syntax requires enabling the parser plugin: 'moduleBlocks' (1:18)" "throws": "This experimental syntax requires enabling the parser plugin: \"moduleBlocks\". (1:18)"
} }

View File

@ -1,5 +1,5 @@
{ {
"plugins": null,
"sourceType": "module", "sourceType": "module",
"throws": "This experimental syntax requires enabling one of the following parser plugin(s): 'decorators, decorators-legacy' (1:7)", "throws": "This experimental syntax requires enabling one of the following parser plugin(s): \"decorators\", \"decorators-legacy\". (1:7)"
"plugins": null }
}

View File

@ -1,3 +1,3 @@
{ {
"throws": "This experimental syntax requires enabling the parser plugin: 'functionSent' (2:11)" "throws": "This experimental syntax requires enabling the parser plugin: \"functionSent\". (2:11)"
} }

View File

@ -1,3 +1,3 @@
{ {
"throws": "This experimental syntax requires enabling the parser plugin: 'functionSent' (2:12)" "throws": "This experimental syntax requires enabling the parser plugin: \"functionSent\". (2:12)"
} }

View File

@ -1,3 +1,3 @@
{ {
"throws": "This experimental syntax requires enabling the parser plugin: 'functionSent' (2:18)" "throws": "This experimental syntax requires enabling the parser plugin: \"functionSent\". (2:18)"
} }

View File

@ -1,4 +1,5 @@
{ {
"throws": "This experimental syntax requires enabling the parser plugin: 'importAssertions' (1:27)", "plugins": [],
"plugins": [] "sourceType": "module",
"throws": "This experimental syntax requires enabling the parser plugin: \"importAssertions\". (1:27)"
} }

View File

@ -1,4 +1,4 @@
{ {
"throws": "This experimental syntax requires enabling the parser plugin: 'moduleAttributes' (1:27)", "throws": "This experimental syntax requires enabling the parser plugin: \"moduleAttributes\". (1:27)",
"plugins": [] "plugins": []
} }

View File

@ -1,3 +1,3 @@
{ {
"throws": "This experimental syntax requires enabling the parser plugin: 'pipelineOperator' (1:2)" "throws": "This experimental syntax requires enabling the parser plugin: \"pipelineOperator\". (1:2)"
} }

View File

@ -1,3 +1,3 @@
{ {
"throws": "This experimental syntax requires enabling the parser plugin: 'recordAndTuple' (1:0)" "throws": "This experimental syntax requires enabling the parser plugin: \"recordAndTuple\". (1:0)"
} }

View File

@ -1,3 +1,3 @@
{ {
"throws": "This experimental syntax requires enabling the parser plugin: 'throwExpressions' (2:3)" "throws": "This experimental syntax requires enabling the parser plugin: \"throwExpressions\". (2:3)"
} }

View File

@ -3,5 +3,5 @@
"plugins": [ "plugins": [
"jsx" "jsx"
], ],
"throws": "This experimental syntax requires enabling one of the following parser plugin(s): 'flow, typescript' (1:7)" "throws": "This experimental syntax requires enabling one of the following parser plugin(s): \"flow\", \"typescript\". (1:7)"
} }

View File

@ -3,5 +3,5 @@
"plugins": [ "plugins": [
"jsx" "jsx"
], ],
"throws": "This experimental syntax requires enabling one of the following parser plugin(s): 'flow, typescript' (2:7)" "throws": "This experimental syntax requires enabling one of the following parser plugin(s): \"flow\", \"typescript\". (2:7)"
} }

View File

@ -3,5 +3,5 @@
"plugins": [ "plugins": [
"jsx" "jsx"
], ],
"throws": "This experimental syntax requires enabling one of the following parser plugin(s): 'flow, typescript' (1:7)" "throws": "This experimental syntax requires enabling one of the following parser plugin(s): \"flow\", \"typescript\". (1:7)"
} }

View File

@ -1,4 +1,4 @@
{ {
"throws": "This experimental syntax requires enabling one of the following parser plugin(s): 'jsx, flow, typescript' (3:4)", "plugins": [],
"plugins": [] "throws": "This experimental syntax requires enabling one of the following parser plugin(s): \"jsx\", \"flow\", \"typescript\". (3:4)"
} }

View File

@ -1,4 +1,4 @@
{ {
"plugins": [], "plugins": [],
"throws": "This experimental syntax requires enabling one of the following parser plugin(s): 'jsx, flow, typescript' (1:0)" "throws": "This experimental syntax requires enabling one of the following parser plugin(s): \"jsx\", \"flow\", \"typescript\". (1:0)"
} }

View File

@ -1,4 +1,4 @@
{ {
"plugins": [], "plugins": [],
"throws": "This experimental syntax requires enabling one of the following parser plugin(s): 'jsx, flow, typescript' (1:0)" "throws": "This experimental syntax requires enabling one of the following parser plugin(s): \"jsx\", \"flow\", \"typescript\". (1:0)"
} }

View File

@ -1,4 +1,4 @@
{ {
"throws": "This experimental syntax requires enabling one of the following parser plugin(s): 'jsx, flow, typescript' (1:0)", "plugins": [],
"plugins": [] "throws": "This experimental syntax requires enabling one of the following parser plugin(s): \"jsx\", \"flow\", \"typescript\". (1:0)"
} }

View File

@ -1,4 +1,4 @@
{ {
"throws": "This experimental syntax requires enabling one of the following parser plugin(s): 'jsx, flow, typescript' (1:0)", "plugins": [],
"plugins": [] "throws": "This experimental syntax requires enabling one of the following parser plugin(s): \"jsx\", \"flow\", \"typescript\". (1:0)"
} }

View File

@ -1,5 +1,7 @@
{ {
"plugins": ["placeholders"], "plugins": [
"placeholders"
],
"sourceType": "module", "sourceType": "module",
"throws": "This experimental syntax requires enabling the parser plugin: 'exportDefaultFrom' (1:7)" "throws": "This experimental syntax requires enabling the parser plugin: \"exportDefaultFrom\". (1:7)"
} }

View File

@ -1,5 +1,7 @@
{ {
"plugins": ["placeholders"], "plugins": [
"placeholders"
],
"sourceType": "module", "sourceType": "module",
"throws": "This experimental syntax requires enabling the parser plugin: 'exportDefaultFrom' (1:16)" "throws": "This experimental syntax requires enabling the parser plugin: \"exportDefaultFrom\". (1:16)"
} }

View File

@ -1,5 +1,7 @@
{ {
"plugins": ["placeholders"], "plugins": [
"placeholders"
],
"sourceType": "module", "sourceType": "module",
"throws": "This experimental syntax requires enabling the parser plugin: 'exportDefaultFrom' (1:16)" "throws": "This experimental syntax requires enabling the parser plugin: \"exportDefaultFrom\". (1:16)"
} }

View File

@ -1,5 +1,7 @@
{ {
"plugins": ["placeholders"], "plugins": [
"placeholders"
],
"sourceType": "module", "sourceType": "module",
"throws": "This experimental syntax requires enabling the parser plugin: 'exportDefaultFrom' (1:7)" "throws": "This experimental syntax requires enabling the parser plugin: \"exportDefaultFrom\". (1:7)"
} }

View File

@ -1,4 +1,4 @@
{ {
"sourceType": "module", "sourceType": "module",
"throws": "This experimental syntax requires enabling one of the following parser plugin(s): 'flow, typescript' (1:7)" "throws": "This experimental syntax requires enabling one of the following parser plugin(s): \"flow\", \"typescript\". (1:7)"
} }

View File

@ -1,4 +1,4 @@
{ {
"sourceType": "module", "sourceType": "module",
"throws": "This experimental syntax requires enabling one of the following parser plugin(s): 'flow, typescript' (2:7)" "throws": "This experimental syntax requires enabling one of the following parser plugin(s): \"flow\", \"typescript\". (2:7)"
} }

View File

@ -1,4 +1,4 @@
{ {
"sourceType": "module", "sourceType": "module",
"throws": "This experimental syntax requires enabling one of the following parser plugin(s): 'flow, typescript' (1:7)" "throws": "This experimental syntax requires enabling one of the following parser plugin(s): \"flow\", \"typescript\". (1:7)"
} }

View File

@ -153,6 +153,7 @@ const ignoredFeatures = [
const ignoredTests = ["built-ins/RegExp/", "language/literals/regexp/"]; const ignoredTests = ["built-ins/RegExp/", "language/literals/regexp/"];
const featuresToPlugins = { const featuresToPlugins = {
__proto__: null,
"import-assertions": "importAssertions", "import-assertions": "importAssertions",
}; };