Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optional chaining #6973

Draft
wants to merge 23 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/Common/ConfigFlagsList.h
Original file line number Diff line number Diff line change
Expand Up @@ -673,6 +673,7 @@ PHASE(All)
#define DEFAULT_CONFIG_ESArrayFindFromLast (true)
#define DEFAULT_CONFIG_ESPromiseAny (true)
#define DEFAULT_CONFIG_ESNullishCoalescingOperator (true)
#define DEFAULT_CONFIG_ESOptionalChaining (true)
#define DEFAULT_CONFIG_ESGlobalThis (true)

// Jitting generators has not been tested on ARM
Expand Down Expand Up @@ -1199,6 +1200,9 @@ FLAGR(Boolean, ESNumericSeparator, "Enable Numeric Separator flag", DEFAULT_CONF
// ES Nullish coalescing operator support (??)
FLAGR(Boolean, ESNullishCoalescingOperator, "Enable nullish coalescing operator", DEFAULT_CONFIG_ESNullishCoalescingOperator)

// ES Optional chaining operator support (?.)
FLAGR(Boolean, ESOptionalChaining, "Enable optional chaining operator", DEFAULT_CONFIG_ESOptionalChaining)

// ES Hashbang support for interpreter directive syntax
FLAGR(Boolean, ESHashbang, "Enable Hashbang syntax", DEFAULT_CONFIG_ESHashbang)

Expand Down
90 changes: 76 additions & 14 deletions lib/Parser/Parse.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,7 @@ LPCWSTR Parser::GetTokenString(tokens token)
case tkLParen: return _u("(");
case tkLBrack: return _u("[");
case tkDot: return _u(".");
case tkOptChain: return _u("?.");

default:
return _u("unknown token");
Expand Down Expand Up @@ -894,13 +895,13 @@ ParseNodeUni * Parser::CreateUniNode(OpCode nop, ParseNodePtr pnode1, charcount_
}

// Create ParseNodeBin
ParseNodeBin * Parser::StaticCreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, ArenaAllocator* alloc, charcount_t ichMin, charcount_t ichLim)
ParseNodeBin * Parser::StaticCreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, ArenaAllocator* alloc, charcount_t ichMin, charcount_t ichLim, bool isNullPropagating)
{
DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeBin)));
return Anew(alloc, ParseNodeBin, nop, ichMin, ichLim, pnode1, pnode2);
return Anew(alloc, ParseNodeBin, nop, ichMin, ichLim, pnode1, pnode2, isNullPropagating);
}

ParseNodeBin * Parser::CreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2)
ParseNodeBin * Parser::CreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, bool isNullPropagating)
{
Assert(!this->m_deferringAST);
charcount_t ichMin;
Expand Down Expand Up @@ -937,15 +938,15 @@ ParseNodeBin * Parser::CreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodeP
}
}

return CreateBinNode(nop, pnode1, pnode2, ichMin, ichLim);
return CreateBinNode(nop, pnode1, pnode2, ichMin, ichLim, isNullPropagating);
}


ParseNodeBin * Parser::CreateBinNode(OpCode nop, ParseNodePtr pnode1,
ParseNodePtr pnode2, charcount_t ichMin, charcount_t ichLim)
ParseNodePtr pnode2, charcount_t ichMin, charcount_t ichLim, bool isNullPropagating)
{
Assert(!this->m_deferringAST);
ParseNodeBin * pnode = StaticCreateBinNode(nop, pnode1, pnode2, &m_nodeAllocator, ichMin, ichLim);
ParseNodeBin * pnode = StaticCreateBinNode(nop, pnode1, pnode2, &m_nodeAllocator, ichMin, ichLim, isNullPropagating);
AddAstSize(sizeof(ParseNodeBin));
return pnode;
}
Expand Down Expand Up @@ -3909,6 +3910,7 @@ ParseNodePtr Parser::ParsePostfixOperators(
*pfIsDotOrIndex = false;
}

bool isOptionalChain = false;
for (;;)
{
uint16 spreadArgCount = 0;
Expand All @@ -3918,8 +3920,14 @@ ParseNodePtr Parser::ParsePostfixOperators(
{
AutoMarkInParsingArgs autoMarkInParsingArgs(this);

bool isNullPropagating = tkOptChain == this->GetScanner()->GetPrevious();
if (fInNew)
{
if (isNullPropagating)
{
Error(ERRInvalidOptChainInNew);
}

ParseNodePtr pnodeArgs = ParseArgList<buildAST>(&callOfConstants, &spreadArgCount, &count);
if (buildAST)
{
Expand Down Expand Up @@ -3972,6 +3980,11 @@ ParseNodePtr Parser::ParsePostfixOperators(
// Detect super()
if (this->NodeIsSuperName(pnode))
{
if (isNullPropagating)
{
Error(ERRInvalidOptChainInSuper);
}

pnode = CreateSuperCallNode(pnode->AsParseNodeSpecialName(), pnodeArgs);
Assert(pnode);

Expand Down Expand Up @@ -4006,6 +4019,7 @@ ParseNodePtr Parser::ParsePostfixOperators(
pnode->AsParseNodeCall()->isApplyCall = false;
pnode->AsParseNodeCall()->isEvalCall = fCallIsEval;
pnode->AsParseNodeCall()->hasDestructuring = m_hasDestructuringPattern;
pnode->AsParseNodeCall()->isNullPropagating = isNullPropagating;
Assert(!m_hasDestructuringPattern || count > 0);
pnode->AsParseNodeCall()->argCount = count;
pnode->ichLim = this->GetScanner()->IchLimTok();
Expand Down Expand Up @@ -4041,7 +4055,7 @@ ParseNodePtr Parser::ParsePostfixOperators(
}
if (pfCanAssign)
{
*pfCanAssign = fCanAssignToCallResult &&
*pfCanAssign = !isOptionalChain && fCanAssignToCallResult &&
(m_sourceContextInfo ?
!PHASE_ON_RAW(Js::EarlyErrorOnAssignToCallPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId) :
!PHASE_ON1(Js::EarlyErrorOnAssignToCallPhase));
Expand All @@ -4054,6 +4068,8 @@ ParseNodePtr Parser::ParsePostfixOperators(
}
case tkLBrack:
{
bool isNullPropagating = tkOptChain == this->GetScanner()->GetPrevious();

this->GetScanner()->Scan();
IdentToken tok;
ParseNodePtr pnodeExpr = ParseExpr<buildAST>(0, FALSE, TRUE, FALSE, nullptr, nullptr, nullptr, &tok);
Expand All @@ -4062,12 +4078,17 @@ ParseNodePtr Parser::ParsePostfixOperators(
AnalysisAssert(pnodeExpr);
if (pnode && pnode->nop == knopName && pnode->AsParseNodeName()->IsSpecialName() && pnode->AsParseNodeSpecialName()->isSuper)
{
if (isNullPropagating)
{
Error(ERRInvalidOptChainInSuper);
}

pnode = CreateSuperReferenceNode(knopIndex, pnode->AsParseNodeSpecialName(), pnodeExpr);
pnode->AsParseNodeSuperReference()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, pnode->ichLim, true);
}
else
{
pnode = CreateBinNode(knopIndex, pnode, pnodeExpr);
pnode = CreateBinNode(knopIndex, pnode, pnodeExpr, isNullPropagating);
}

AnalysisAssert(pnode);
Expand All @@ -4081,7 +4102,8 @@ ParseNodePtr Parser::ParsePostfixOperators(
ChkCurTok(tkRBrack, ERRnoRbrack);
if (pfCanAssign)
{
*pfCanAssign = TRUE;
// optional assignment not permitted
*pfCanAssign = !isOptionalChain;
}
if (pfIsDotOrIndex)
{
Expand Down Expand Up @@ -4163,17 +4185,41 @@ ParseNodePtr Parser::ParsePostfixOperators(
}
}
break;


case tkOptChain:
case tkDot:
{
ParseNodePtr name = nullptr;
OpCode opCode = knopDot;

// We don't use separate knops for optional-chains
// Instead mark nodes as null-propagating
bool isNullPropagating = tkOptChain == m_token.tk;
if (isNullPropagating)
{
isOptionalChain = true;
}

this->GetScanner()->Scan();
if (!m_token.IsIdentifier())
{
//allow reserved words in ES5 mode
if (!(m_token.IsReservedWord()))
if (isNullPropagating)
{
// We don't need an identifier for an Index `?.[` or Call `?.(`
switch (m_token.tk)
{
case tkLParen:
case tkLBrack:
// Continue to parse function or index (loop)
// Check previous token to check for null-propagation
continue;

case tkStrTmplBasic:
case tkStrTmplBegin:
Error(ERRInvalidOptChainWithTaggedTemplate);
}
}
else if (!(m_token.IsReservedWord())) //allow reserved words in ES5 mode
{
IdentifierExpectedError(m_token);
}
Expand All @@ -4200,12 +4246,17 @@ ParseNodePtr Parser::ParsePostfixOperators(
}
if (pnode && pnode->nop == knopName && pnode->AsParseNodeName()->IsSpecialName() && pnode->AsParseNodeSpecialName()->isSuper)
{
if (isNullPropagating)
{
Error(ERRInvalidOptChainInSuper);
}

pnode = CreateSuperReferenceNode(opCode, pnode->AsParseNodeSpecialName(), name);
pnode->AsParseNodeSuperReference()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, pnode->ichLim, true);
}
else
{
pnode = CreateBinNode(opCode, pnode, name);
pnode = CreateBinNode(opCode, pnode, name, isNullPropagating);
}
}
else
Expand All @@ -4216,7 +4267,8 @@ ParseNodePtr Parser::ParsePostfixOperators(

if (pfCanAssign)
{
*pfCanAssign = TRUE;
// optional assignment not permitted
*pfCanAssign = !isOptionalChain;
}
if (pfIsDotOrIndex)
{
Expand All @@ -4230,6 +4282,11 @@ ParseNodePtr Parser::ParsePostfixOperators(
case tkStrTmplBasic:
case tkStrTmplBegin:
{
if (isOptionalChain)
{
Error(ERRInvalidOptChainWithTaggedTemplate);
}

ParseNode* templateNode = nullptr;
if (pnode != nullptr)
{
Expand Down Expand Up @@ -4258,6 +4315,11 @@ ParseNodePtr Parser::ParsePostfixOperators(
break;
}
default:
if (buildAST && isOptionalChain)
{
// Wrap the whole expression as an optional-chain
return CreateUniNode(knopOptChain, pnode);
}
return pnode;
}
}
Expand Down
7 changes: 4 additions & 3 deletions lib/Parser/Parse.h
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Copyright (c) ChakraCore Project Contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#pragma once
Expand Down Expand Up @@ -371,16 +372,16 @@ class Parser
return Anew(alloc, typename OpCodeTrait<nop>::ParseNodeType, nop, ichMin, ichLim);
}

static ParseNodeBin * StaticCreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, ArenaAllocator* alloc, charcount_t ichMin = 0, charcount_t ichLim = 0);
static ParseNodeBin * StaticCreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, ArenaAllocator* alloc, charcount_t ichMin = 0, charcount_t ichLim = 0, bool isNullPropagating = false);
static ParseNodeBlock * StaticCreateBlockNode(ArenaAllocator* alloc, charcount_t ichMin = 0, charcount_t ichLim = 0, int blockId = -1, PnodeBlockType blockType = PnodeBlockType::Regular);
static ParseNodeVar * StaticCreateTempNode(ParseNode* initExpr, ArenaAllocator* alloc);
static ParseNodeUni * StaticCreateTempRef(ParseNode* tempNode, ArenaAllocator* alloc);

private:
ParseNodeUni * CreateUniNode(OpCode nop, ParseNodePtr pnodeOp);
ParseNodeUni * CreateUniNode(OpCode nop, ParseNodePtr pnode1, charcount_t ichMin, charcount_t ichLim);
ParseNodeBin * CreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2);
ParseNodeBin * CreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, charcount_t ichMin, charcount_t ichLim);
ParseNodeBin * CreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, bool isNullPropagating = false);
ParseNodeBin * CreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, charcount_t ichMin, charcount_t ichLim, bool isNullPropagating = false);
ParseNodeTri * CreateTriNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, ParseNodePtr pnode3);
ParseNodeTri * CreateTriNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, ParseNodePtr pnode3, charcount_t ichMin, charcount_t ichLim);
ParseNodeBlock * CreateBlockNode(PnodeBlockType blockType = PnodeBlockType::Regular);
Expand Down
11 changes: 11 additions & 0 deletions lib/Parser/Scan.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1781,6 +1781,17 @@ tokens Scanner<EncodingPolicy>::ScanCore(bool identifyKwds)
token = tkCoalesce;
break;
}
else if (m_scriptContext->GetConfig()->IsESOptionalChainingEnabled() && this->PeekFirst(p, last) == '.')
{
// `a?.3:0` is actually a ternary operator containing the number `0.3`
bool isTernary = CharTypes::_C_DIG == this->charClassifier->GetCharType(this->PeekFirst(p + 1, last));
if (isTernary)
break;

p++;
token = tkOptChain;
break;
}
break;

case '{': Assert(chType == _C_LC); token = tkLCurly; break;
Expand Down
2 changes: 2 additions & 0 deletions lib/Parser/kwd-lsc.h
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Copyright (c) ChakraCore Project Contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#ifndef KEYWORD
Expand Down Expand Up @@ -174,6 +175,7 @@ TOK_DCL(tkEllipsis , No, knopNone ,Spr, knopEllipsis ) // ...
TOK_DCL(tkLParen , No, knopNone , No, knopNone ) // (
TOK_DCL(tkLBrack , No, knopNone , No, knopNone ) // [
TOK_DCL(tkDot , No, knopNone , No, knopNone ) // .
TOK_DCL(tkOptChain , No, knopNone , No, knopNone ) // ?.

// String template tokens
TOK_DCL(tkStrTmplBasic , No, knopNone , No, knopNone ) // `...`
Expand Down
6 changes: 5 additions & 1 deletion lib/Parser/perrors.h
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,11 @@ LSC_ERROR_MSG(1102, ERRInvalidAsgTarget, "Invalid left-hand side in assignment."
LSC_ERROR_MSG(1103, ERRMissingFrom, "Expected 'from' after import or export clause.")

// 1104 ERRsyntaxEOF
// 1105-1199 available for future use

LSC_ERROR_MSG(1105, ERRInvalidOptChainInNew, "Invalid optional chain in new expression.")
LSC_ERROR_MSG(1106, ERRInvalidOptChainInSuper, "Invalid optional chain in call to 'super'.")
LSC_ERROR_MSG(1107, ERRInvalidOptChainWithTaggedTemplate, "Invalid tagged template in optional chain.")
// 1108-1199 available for future use

// Generic errors intended to be re-usable
LSC_ERROR_MSG(1200, ERRKeywordAfter, "Unexpected keyword '%s' after '%s'")
Expand Down
2 changes: 2 additions & 0 deletions lib/Parser/ptlist.h
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Copyright (c) ChakraCore Project Contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
/*****************************************************************************/
Expand Down Expand Up @@ -80,6 +81,7 @@ PTNODE(knopGe , ">=" , OP(Ge) , Bin , fnopBin|fn
PTNODE(knopGt , ">" , OP(Gt) , Bin , fnopBin|fnopRel , "GreaterThanOper" )
PTNODE(knopCall , "()" , Nop , Call , fnopNone , "CallExpr" )
PTNODE(knopDot , "." , Nop , Bin , fnopBin , "DotOper" )
PTNODE(knopOptChain , "?." , Nop , Uni , fnopUni , "OptChain" )
PTNODE(knopAsg , "=" , Nop , Bin , fnopBin|fnopAsg , "AssignmentOper" )
PTNODE(knopInstOf , "instanceof" , IsInst , Bin , fnopBin|fnopRel , "InstanceOfExpr" )
PTNODE(knopIn , "in" , IsIn , Bin , fnopBin|fnopRel , "InOper" )
Expand Down
5 changes: 4 additions & 1 deletion lib/Parser/ptree.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Copyright (c) ChakraCore Project Contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "ParserPch.h"
Expand Down Expand Up @@ -301,7 +302,7 @@ ParseNodeUni::ParseNodeUni(OpCode nop, charcount_t ichMin, charcount_t ichLim, P
this->pnode1 = pnode1;
}

ParseNodeBin::ParseNodeBin(OpCode nop, charcount_t ichMin, charcount_t ichLim, ParseNode * pnode1, ParseNode * pnode2)
ParseNodeBin::ParseNodeBin(OpCode nop, charcount_t ichMin, charcount_t ichLim, ParseNode * pnode1, ParseNode * pnode2, bool isNullPropagating)
: ParseNode(nop, ichMin, ichLim)
{
// Member name is either a string or a computed name
Expand All @@ -313,6 +314,7 @@ ParseNodeBin::ParseNodeBin(OpCode nop, charcount_t ichMin, charcount_t ichLim, P

this->pnode1 = pnode1;
this->pnode2 = pnode2;
this->isNullPropagating = isNullPropagating;

// Statically detect if the add is a concat
if (!PHASE_OFF1(Js::ByteCodeConcatExprOptPhase))
Expand Down Expand Up @@ -495,6 +497,7 @@ ParseNodeCall::ParseNodeCall(OpCode nop, charcount_t ichMin, charcount_t ichLim,
this->isEvalCall = false;
this->isSuperCall = false;
this->hasDestructuring = false;
this->isNullPropagating = false;
}

ParseNodeStmt::ParseNodeStmt(OpCode nop, charcount_t ichMin, charcount_t ichLim)
Expand Down
5 changes: 4 additions & 1 deletion lib/Parser/ptree.h
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Copyright (c) ChakraCore Project Contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#pragma once
Expand Down Expand Up @@ -277,10 +278,11 @@ class ParseNodeUni : public ParseNode
class ParseNodeBin : public ParseNode
{
public:
ParseNodeBin(OpCode nop, charcount_t ichMin, charcount_t ichLim, ParseNode * pnode1, ParseNode * pnode2);
ParseNodeBin(OpCode nop, charcount_t ichMin, charcount_t ichLim, ParseNode * pnode1, ParseNode * pnode2, bool isNullPropagating = false);

ParseNodePtr pnode1;
ParseNodePtr pnode2;
bool isNullPropagating;

DISABLE_SELF_CAST(ParseNodeBin);
};
Expand Down Expand Up @@ -791,6 +793,7 @@ class ParseNodeCall : public ParseNode
BYTE isEvalCall : 1;
BYTE isSuperCall : 1;
BYTE hasDestructuring : 1;
bool isNullPropagating;

DISABLE_SELF_CAST(ParseNodeCall);
};
Expand Down