Skip to content

Commit

Permalink
Remove old safecall code
Browse files Browse the repository at this point in the history
  • Loading branch information
wcjohnson committed Sep 24, 2017
1 parent 0141061 commit 9ac1dd4
Showing 1 changed file with 0 additions and 75 deletions.
75 changes: 0 additions & 75 deletions src/safe.lsc
Original file line number Diff line number Diff line change
Expand Up @@ -97,78 +97,3 @@ export transformExistentialExpression(path) ->
t.nullLiteral()~atNode(path.node)
)~atNode(path.node)
)

export replaceWithSafeCall(path, callExpr) ->
undef = path.scope.buildUndefinedNode()
let callee, typeofExpr

if is("MemberExpression", callExpr.callee):
memberExpr = callExpr.callee
{ ref: objectRef, assign: object } = hoistRef(path, memberExpr.object, "obj")

let property = memberExpr.property, propertyRef = memberExpr.property
if memberExpr.computed:
now { ref: propertyRef, assign: property } = hoistRef(path, memberExpr.property, "prop")

now typeofExpr = t.memberExpression(object, property, memberExpr.computed)
now callee = t.memberExpression(objectRef, propertyRef, memberExpr.computed)
else:
now { ref: callee, assign: typeofExpr } = hoistRef(path, callExpr.callee)

// Generate actual safecall expr
// f?(x) -> (typeof f === "function") ? f(x) : undefined
path.replaceWith(
t.conditionalExpression(
t.binaryExpression("===",
t.unaryExpression("typeof", typeofExpr),
t.stringLiteral("function")
),
t.callExpression(callee, callExpr.arguments),
undef
)~allAtLoc(getLoc(path.node))
)

export transformSafeMemberExpression(path) ->
// x?.y -> x == null ? x : x.y
// x?[y] -> x == null ? x : x[y]
{ node } = path
{ object } = node

// Transform to vanilla member expr
node.optional = false

// Generate null check, hoisting ref if necessary.
left = if object.type === "Identifier" or (object.type === "MemberExpression" and object.optional):
object
else:
ref = path.scope.generateDeclaredUidIdentifier("ref")~atNode(object)
node.object = ref
t.assignmentExpression("=", ref, object)~atNode(object)

nullCheck = t.binaryExpression("==", left, t.nullLiteral()~atNode(object))~atNode(object)

// Gather trailing subscripts/calls, which are parent nodes:
// eg; in `o?.x.y()`, group trailing `.x.y()` into the ternary
let tail = path
while tail.parentPath:
parent = tail.parentPath;
hasChainedParent = (
parent.isMemberExpression() ||
(parent.isCallExpression() && parent.get("callee") === tail) ||
(parent.node.type === "TildeCallExpression" && parent.get("left") === tail)
)

if hasChainedParent:
now tail = tail.parentPath
else:
break

undef = tail.scope.buildUndefinedNode()

ternary = t.conditionalExpression(
nullCheck
undef~atNode(tail.node)
tail.node
)~atNode(tail.node)

tail.replaceWith(ternary);

0 comments on commit 9ac1dd4

Please sign in to comment.