Skip to content

Commit

Permalink
[fix] optional chain
Browse files Browse the repository at this point in the history
  • Loading branch information
Siubaak committed Feb 20, 2024
1 parent e8f1b12 commit 92a54e2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
24 changes: 17 additions & 7 deletions src/transformer.js
Expand Up @@ -378,6 +378,8 @@ export default class Transformer {
);
return;
}
const grandParentNode = ancestors[ancestors.length - 3];
const isOptionalChain = grandParentNode.type === 'ChainExpression';
const tmpObjIdentifier = this.createIdentifier(TMP_VARIABLE_NAME + 'o');
const tmpFuncIdentifier = this.createIdentifier(TMP_VARIABLE_NAME + 'f');
Object.assign(parentNode, this.createSequenceExpression([
Expand All @@ -387,14 +389,17 @@ export default class Transformer {
),
this.createAssignmentExpression(
tmpFuncIdentifier,
this.createYieldExpression(Object.assign({}, node, { object: tmpObjIdentifier }), false)
this.createYieldExpression(
isOptionalChain
? this.createChainExpression(Object.assign({}, node, { object: tmpObjIdentifier, optional: true }))
: Object.assign({}, node, { object: tmpObjIdentifier })
, false)
),
this.createCallExpression(
this.createCallExpression(
this.createMemberExpression(
tmpFuncIdentifier,
this.createIdentifier('bind')
),
isOptionalChain
? this.createChainExpression(this.createMemberExpression(tmpFuncIdentifier, this.createIdentifier('bind'), true))
: this.createMemberExpression(tmpFuncIdentifier, this.createIdentifier('bind')),
[tmpObjIdentifier]
),
parentNode.arguments
Expand Down Expand Up @@ -830,8 +835,13 @@ export default class Transformer {
}

// 创建对象成员AST节点
createMemberExpression(object, property) {
return { type: 'MemberExpression', computed: false, optional: false, object, property };
createMemberExpression(object, property, optional = false) {
return { type: 'MemberExpression', computed: false, optional, object, property };
}

// 创建可选链表达式AST节点
createChainExpression(expression) {
return { type: 'ChainExpression', expression };
}

// 创建序列表达式AST节点
Expand Down
4 changes: 2 additions & 2 deletions tests/transform.test.js
Expand Up @@ -44,8 +44,8 @@ describe('compiler tests', () => {

it('compile chain expression normally', () => {
const res = vDebugger.transform(
'const a = { b: () => 7 }\n' +
'window.__trans_res__ = 6 && a?.b();\n'
'const a = { b: { c: () => 7 } }\n' +
'window.__trans_res__ = 6 && a?.b.c();\n'
, 'chain-expr-transform.js');
expect(res).toBeTruthy();

Expand Down

0 comments on commit 92a54e2

Please sign in to comment.