Skip to content

Commit

Permalink
Use ?. where it represents the intended semantics (#11512)
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo committed May 9, 2020
1 parent aeb51f4 commit 31b361b
Show file tree
Hide file tree
Showing 47 changed files with 99 additions and 118 deletions.
5 changes: 3 additions & 2 deletions packages/babel-core/src/config/files/configuration.js
Expand Up @@ -71,8 +71,9 @@ export function* findRelativeConfig(
loc,
envName,
caller,
packageData.pkg && packageData.pkg.dirname === loc
? packageToBabelConfig(packageData.pkg)
packageData.pkg?.dirname === loc
? // $FlowIgnore - packageData.pkg is not null
packageToBabelConfig((packageData.pkg: ConfigFile))
: null,
);
}
Expand Down
3 changes: 2 additions & 1 deletion packages/babel-core/src/config/index.js
Expand Up @@ -17,7 +17,8 @@ export type { PartialConfig } from "./partial";

const loadOptionsRunner = gensync<[mixed], Object | null>(function*(opts) {
const config = yield* loadFullConfig(opts);
return config ? config.options : null;
// NOTE: We want to return "null" explicitly, while ?. alone returns undefined
return config?.options ?? null;
});

const maybeErrback = runner => (opts: mixed, callback: Function) => {
Expand Down
10 changes: 1 addition & 9 deletions packages/babel-core/src/transform-file.js
Expand Up @@ -25,15 +25,7 @@ type TransformFile = {

const transformFileRunner = gensync<[string, ?InputOptions], FileResult | null>(
function*(filename, opts) {
let options;
if (opts == null) {
options = { filename };
} else if (opts && typeof opts === "object") {
options = {
...opts,
filename,
};
}
const options = { ...opts, filename };

const config: ResolvedConfig | null = yield* loadConfig(options);
if (config === null) return null;
Expand Down
4 changes: 2 additions & 2 deletions packages/babel-core/src/transformation/block-hoist-plugin.js
Expand Up @@ -44,15 +44,15 @@ const blockHoistPlugin = {
let hasChange = false;
for (let i = 0; i < node.body.length; i++) {
const bodyNode = node.body[i];
if (bodyNode && bodyNode._blockHoist != null) {
if (bodyNode?._blockHoist != null) {
hasChange = true;
break;
}
}
if (!hasChange) return;

node.body = sortBy(node.body, function(bodyNode) {
let priority = bodyNode && bodyNode._blockHoist;
let priority = bodyNode?._blockHoist;
if (priority == null) priority = 1;
if (priority === true) priority = 2;

Expand Down
10 changes: 5 additions & 5 deletions packages/babel-generator/src/buffer.js
Expand Up @@ -44,7 +44,7 @@ export default class Buffer {
// source string since it may be arbitrarily large after all transformations
code: this._buf.join("").trimRight(),
map: null,
rawMappings: map && map.getRawMappings(),
rawMappings: map?.getRawMappings(),
};

if (map) {
Expand Down Expand Up @@ -315,10 +315,10 @@ export default class Buffer {
const origFilename = targetObj.filename;

targetObj.identifierName =
(prop === "start" && loc && loc.identifierName) || null;
targetObj.line = pos ? pos.line : null;
targetObj.column = pos ? pos.column : null;
targetObj.filename = (loc && loc.filename) || null;
(prop === "start" && loc?.identifierName) || null;
targetObj.line = pos?.line;
targetObj.column = pos?.column;
targetObj.filename = loc?.filename;

// We want to skip reassigning `force` if we're re-setting the same position.
if (
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-generator/src/generators/base.js
Expand Up @@ -21,7 +21,7 @@ export function BlockStatement(node: Object) {
this.token("{");
this.printInnerComments(node);

const hasDirectives = node.directives && node.directives.length;
const hasDirectives = node.directives?.length;

if (node.body.length || hasDirectives) {
this.newline();
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-generator/src/generators/modules.js
Expand Up @@ -147,7 +147,7 @@ export function ImportDeclaration(node: Object) {
}

const specifiers = node.specifiers.slice(0);
if (specifiers && specifiers.length) {
if (specifiers?.length) {
// print "special" specifiers first
for (;;) {
const first = specifiers[0];
Expand Down
15 changes: 6 additions & 9 deletions packages/babel-generator/src/node/whitespace.js
Expand Up @@ -196,10 +196,7 @@ nodes.ObjectTypeCallProperty = function(
node: Object,
parent,
): ?WhitespaceObject {
if (
parent.callProperties[0] === node &&
(!parent.properties || !parent.properties.length)
) {
if (parent.callProperties[0] === node && !parent.properties?.length) {
return {
before: true,
};
Expand All @@ -209,8 +206,8 @@ nodes.ObjectTypeCallProperty = function(
nodes.ObjectTypeIndexer = function(node: Object, parent): ?WhitespaceObject {
if (
parent.indexers[0] === node &&
(!parent.properties || !parent.properties.length) &&
(!parent.callProperties || !parent.callProperties.length)
!parent.properties?.length &&
!parent.callProperties?.length
) {
return {
before: true,
Expand All @@ -224,9 +221,9 @@ nodes.ObjectTypeInternalSlot = function(
): ?WhitespaceObject {
if (
parent.internalSlots[0] === node &&
(!parent.properties || !parent.properties.length) &&
(!parent.callProperties || !parent.callProperties.length) &&
(!parent.indexers || !parent.indexers.length)
!parent.properties?.length &&
!parent.callProperties?.length &&
!parent.indexers?.length
) {
return {
before: true,
Expand Down
14 changes: 7 additions & 7 deletions packages/babel-generator/src/printer.js
Expand Up @@ -310,7 +310,7 @@ export default class Printer {

// catch up to this nodes newline if we're behind
const pos = loc ? loc[prop] : null;
if (pos && pos.line !== null) {
if (pos?.line != null) {
const count = pos.line - this._buf.getCurrentLine();

for (let i = 0; i < count; i++) {
Expand Down Expand Up @@ -360,7 +360,7 @@ export default class Printer {

endTerminatorless(state: Object) {
this._noLineTerminator = false;
if (state && state.printed) {
if (state?.printed) {
this.dedent();
this.newline();
this.token(")");
Expand All @@ -380,7 +380,7 @@ export default class Printer {
throw new ReferenceError(
`unknown node of type ${JSON.stringify(
node.type,
)} with constructor ${JSON.stringify(node && node.constructor.name)}`,
)} with constructor ${JSON.stringify(node?.constructor.name)}`,
);
}

Expand Down Expand Up @@ -463,7 +463,7 @@ export default class Printer {
}

printJoin(nodes: ?Array, parent: Object, opts = {}) {
if (!nodes || !nodes.length) return;
if (!nodes?.length) return;

if (opts.indent) this.indent();

Expand Down Expand Up @@ -523,7 +523,7 @@ export default class Printer {
}

printInnerComments(node, indent = true) {
if (!node.innerComments || !node.innerComments.length) return;
if (!node.innerComments?.length) return;
if (indent) this.indent();
this._printComments(node.innerComments);
if (indent) this.dedent();
Expand Down Expand Up @@ -606,7 +606,7 @@ export default class Printer {
: `/*${comment.value}*/`;

if (isBlockComment && this.format.indent.adjustMultilineComment) {
const offset = comment.loc && comment.loc.start.column;
const offset = comment.loc?.start.column;
if (offset) {
const newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
val = val.replace(newlineRegex, "\n");
Expand All @@ -630,7 +630,7 @@ export default class Printer {
}

_printComments(comments?: Array<Object>, inlinePureAnnotation?: boolean) {
if (!comments || !comments.length) return;
if (!comments?.length) return;

if (
inlinePureAnnotation &&
Expand Down
4 changes: 2 additions & 2 deletions packages/babel-helper-compilation-targets/src/filter-items.js
Expand Up @@ -70,8 +70,8 @@ export function isRequired(
excludes?: Set<string>,
} = {},
) {
if (excludes && excludes.has(name)) return false;
if (includes && includes.has(name)) return true;
if (excludes?.has(name)) return false;
if (includes?.has(name)) return true;
return !targetsSupported(targets, compatData[name]);
}

Expand Down
2 changes: 1 addition & 1 deletion packages/babel-helper-compilation-targets/src/index.js
Expand Up @@ -111,7 +111,7 @@ function getLowestVersions(browsers: Array<string>): Targets {
}

function outputDecimalWarning(decimalTargets: Array<Object>): void {
if (!decimalTargets || !decimalTargets.length) {
if (!decimalTargets?.length) {
return;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/babel-helpers/src/index.js
Expand Up @@ -108,7 +108,7 @@ function getHelperMetadata(file) {

const binding = child.scope.getBinding(exportName);

if (binding && binding.scope.path.isProgram()) {
if (binding?.scope.path.isProgram()) {
exportBindingAssignments.push(makePath(child));
}
},
Expand Down
4 changes: 2 additions & 2 deletions packages/babel-parser/src/index.js
Expand Up @@ -16,7 +16,7 @@ import "./tokenizer/context";
import type { Expression, File } from "./types";

export function parse(input: string, options?: Options): File {
if (options && options.sourceType === "unambiguous") {
if (options?.sourceType === "unambiguous") {
options = {
...options,
};
Expand Down Expand Up @@ -71,7 +71,7 @@ export { tokTypes };

function getParser(options: ?Options, input: string): Parser {
let cls = Parser;
if (options && options.plugins) {
if (options?.plugins) {
validatePlugins(options.plugins);
cls = getParserClass(options.plugins);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-parser/src/parser/expression.js
Expand Up @@ -769,7 +769,7 @@ export default class ExpressionParser extends LValParser {
this.raise(node.start, Errors.ImportCallArity);
} else {
const importArg = node.arguments[0];
if (importArg && importArg.type === "SpreadElement") {
if (importArg?.type === "SpreadElement") {
this.raise(importArg.start, Errors.ImportCallSpreadArgument);
}
}
Expand Down
6 changes: 3 additions & 3 deletions packages/babel-parser/src/parser/lval.js
Expand Up @@ -160,9 +160,9 @@ export default class LValParser extends NodeUtils {
let end = exprList.length;
if (end) {
const last = exprList[end - 1];
if (last && last.type === "RestElement") {
if (last?.type === "RestElement") {
--end;
} else if (last && last.type === "SpreadElement") {
} else if (last?.type === "SpreadElement") {
last.type = "RestElement";
const arg = last.argument;
this.toAssignable(arg);
Expand Down Expand Up @@ -210,7 +210,7 @@ export default class LValParser extends NodeUtils {
this.toReferencedList(exprList, isParenthesizedExpr);

for (const expr of exprList) {
if (expr && expr.type === "ArrayExpression") {
if (expr?.type === "ArrayExpression") {
this.toReferencedListDeep(expr.elements);
}
}
Expand Down
4 changes: 2 additions & 2 deletions packages/babel-parser/src/parser/node.js
Expand Up @@ -13,8 +13,8 @@ class Node implements NodeBase {
this.start = pos;
this.end = 0;
this.loc = new SourceLocation(loc);
if (parser && parser.options.ranges) this.range = [pos, 0];
if (parser && parser.filename) this.loc.filename = parser.filename;
if (parser?.options.ranges) this.range = [pos, 0];
if (parser?.filename) this.loc.filename = parser.filename;
}

type: string;
Expand Down
4 changes: 2 additions & 2 deletions packages/babel-parser/src/plugins/estree.js
Expand Up @@ -165,7 +165,7 @@ export default (superClass: Class<Parser>): Class<Parser> =>
if (name === "__proto__" && prop.kind === "init") {
// Store the first redefinition's position
if (protoRef.used) {
if (refExpressionErrors && refExpressionErrors.doubleProto === -1) {
if (refExpressionErrors?.doubleProto === -1) {
refExpressionErrors.doubleProto = key.start;
} else {
this.raise(key.start, Errors.DuplicateProto);
Expand All @@ -181,7 +181,7 @@ export default (superClass: Class<Parser>): Class<Parser> =>
stmt.type === "ExpressionStatement" &&
stmt.expression.type === "Literal" &&
typeof stmt.expression.value === "string" &&
(!stmt.expression.extra || !stmt.expression.extra.parenthesized)
!stmt.expression.extra?.parenthesized
);
}

Expand Down
14 changes: 6 additions & 8 deletions packages/babel-parser/src/plugins/flow.js
Expand Up @@ -2198,7 +2198,7 @@ export default (superClass: Class<Parser>): Class<Parser> =>
): $ReadOnlyArray<N.Pattern> {
for (let i = 0; i < exprList.length; i++) {
const expr = exprList[i];
if (expr && expr.type === "TypeCastExpression") {
if (expr?.type === "TypeCastExpression") {
exprList[i] = this.typeCastToParameter(expr);
}
}
Expand All @@ -2216,7 +2216,7 @@ export default (superClass: Class<Parser>): Class<Parser> =>
if (
expr &&
expr.type === "TypeCastExpression" &&
(!expr.extra || !expr.extra.parenthesized) &&
!expr.extra?.parenthesized &&
(exprList.length > 1 || !isParenthesizedExpr)
) {
this.raise(expr.typeAnnotation.start, FlowErrors.TypeCastInPattern);
Expand Down Expand Up @@ -2665,7 +2665,7 @@ export default (superClass: Class<Parser>): Class<Parser> =>
}
}

if ((jsx && jsx.error) || this.isRelational("<")) {
if (jsx?.error || this.isRelational("<")) {
state = state || this.state.clone();

let typeParameters;
Expand All @@ -2690,9 +2690,7 @@ export default (superClass: Class<Parser>): Class<Parser> =>
}, state);

const arrowExpression: ?N.ArrowFunctionExpression =
arrow.node && arrow.node.type === "ArrowFunctionExpression"
? arrow.node
: null;
arrow.node?.type === "ArrowFunctionExpression" ? arrow.node : null;

if (!arrow.error && arrowExpression) return arrowExpression;

Expand All @@ -2702,7 +2700,7 @@ export default (superClass: Class<Parser>): Class<Parser> =>
// If the error is recoverable, we can only re-report it if there is
// a node we can return.

if (jsx && jsx.node) {
if (jsx?.node) {
/*:: invariant(jsx.failState) */
this.state = jsx.failState;
return jsx.node;
Expand All @@ -2714,7 +2712,7 @@ export default (superClass: Class<Parser>): Class<Parser> =>
return arrowExpression;
}

if (jsx && jsx.thrown) throw jsx.error;
if (jsx?.thrown) throw jsx.error;
if (arrow.thrown) throw arrow.error;

/*:: invariant(typeParameters) */
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-parser/src/plugins/placeholders.js
Expand Up @@ -261,7 +261,7 @@ export default (superClass: Class<Parser>): Class<Parser> =>

checkExport(node: N.ExportNamedDeclaration): void {
const { specifiers } = node;
if (specifiers && specifiers.length) {
if (specifiers?.length) {
node.specifiers = specifiers.filter(
node => node.exported.type === "Placeholder",
);
Expand Down

0 comments on commit 31b361b

Please sign in to comment.