Skip to content

Commit

Permalink
refactor: track [Return] parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
JLHwung committed Jan 16, 2020
1 parent 04336bd commit e36aeb3
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 6 deletions.
5 changes: 5 additions & 0 deletions packages/babel-parser/src/parser/expression.js
Expand Up @@ -43,6 +43,7 @@ import {
import { ExpressionErrors } from "./util";
import {
PARAM_AWAIT,
PARAM_RETURN,
PARAM,
functionFlags,
} from "../util/production-parameter";
Expand Down Expand Up @@ -1986,7 +1987,11 @@ export default class ExpressionParser extends LValParser {
allowExpression,
!oldStrict && useStrict,
);
// FunctionBody[Yield, Await]:
// StatementList[?Yield, ?Await, +Return] opt
this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
node.body = this.parseBlock(true, false);
this.prodParam.exit();
this.state.labels = oldLabels;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/babel-parser/src/parser/statement.js
Expand Up @@ -575,7 +575,7 @@ export default class StatementParser extends ExpressionParser {
}

parseReturnStatement(node: N.ReturnStatement): N.ReturnStatement {
if (!this.scope.inFunction && !this.options.allowReturnOutsideFunction) {
if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) {
this.raise(this.state.start, "'return' outside of function");
}

Expand Down
15 changes: 10 additions & 5 deletions packages/babel-parser/src/util/production-parameter.js
@@ -1,12 +1,13 @@
// @flow
export const PARAM = 0b00, // Initial Parameter flags
PARAM_YIELD = 0b01, // track [Await] production parameter
PARAM_AWAIT = 0b10; // track [Yield] production parameter
export const PARAM = 0b000, // Initial Parameter flags
PARAM_YIELD = 0b001, // track [Yield] production parameter
PARAM_AWAIT = 0b010, // track [Await] production parameter
PARAM_RETURN = 0b100; // track [Return] production parameter

// ProductionParameterHandler is a stack fashioned production parameter tracker
// https://tc39.es/ecma262/#sec-grammar-notation
// It only tracks [Await] and [Yield] parameter. The [In] parameter is tracked
// in `noIn` argument of `parseExpression`.
// The tracked parameters are defined above. Note that the [In] parameter is
// tracked in `noIn` argument of `parseExpression`.
//
// Whenever [+Await]/[+Yield] appears in the right-hand sides of a production,
// we must enter a new tracking stack. For example when parsing
Expand Down Expand Up @@ -48,6 +49,10 @@ export default class ProductionParameterHandler {
get hasYield(): boolean {
return (this.currentFlags() & PARAM_YIELD) > 0;
}

get hasReturn(): boolean {
return (this.currentFlags() & PARAM_RETURN) > 0;
}
}

export function functionFlags(
Expand Down

0 comments on commit e36aeb3

Please sign in to comment.