diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index ff755ff281ffb..905a1f3aa3067 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -68,6 +68,9 @@ C++23 Feature Support C++2c Feature Support ^^^^^^^^^^^^^^^^^^^^^ +- Implemented `P2662R3 Pack Indexing `_. + + Resolutions to C++ Defect Reports ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h index 64ab3378957c7..b667d406dfa5e 100644 --- a/clang/include/clang-c/Index.h +++ b/clang/include/clang-c/Index.h @@ -1685,7 +1685,12 @@ enum CXCursorKind { */ CXCursor_CXXParenListInitExpr = 155, - CXCursor_LastExpr = CXCursor_CXXParenListInitExpr, + /** + * Represents a C++26 pack indexing expression. + */ + CXCursor_PackIndexingExpr = 156, + + CXCursor_LastExpr = CXCursor_PackIndexingExpr, /* Statements */ CXCursor_FirstStmt = 200, diff --git a/clang/include/clang/AST/ASTContext.h b/clang/include/clang/AST/ASTContext.h index 3e46a5da3fc04..668462ef54606 100644 --- a/clang/include/clang/AST/ASTContext.h +++ b/clang/include/clang/AST/ASTContext.h @@ -214,6 +214,9 @@ class ASTContext : public RefCountedBase { DependentTypeOfExprTypes; mutable llvm::ContextualFoldingSet DependentDecltypeTypes; + + mutable llvm::FoldingSet DependentPackIndexingTypes; + mutable llvm::FoldingSet TemplateTypeParmTypes; mutable llvm::FoldingSet ObjCTypeParamTypes; mutable llvm::FoldingSet @@ -1713,6 +1716,11 @@ class ASTContext : public RefCountedBase { /// C++11 decltype. QualType getDecltypeType(Expr *e, QualType UnderlyingType) const; + QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr, + bool FullySubstituted = false, + ArrayRef Expansions = {}, + int Index = -1) const; + /// Unary type transforms QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, UnaryTransformType::UTTKind UKind) const; diff --git a/clang/include/clang/AST/ASTNodeTraverser.h b/clang/include/clang/AST/ASTNodeTraverser.h index cc8dab97f8b01..950da2b8d2c45 100644 --- a/clang/include/clang/AST/ASTNodeTraverser.h +++ b/clang/include/clang/AST/ASTNodeTraverser.h @@ -385,6 +385,12 @@ class ASTNodeTraverser void VisitDecltypeType(const DecltypeType *T) { Visit(T->getUnderlyingExpr()); } + + void VisitPackIndexingType(const PackIndexingType *T) { + Visit(T->getPattern()); + Visit(T->getIndexExpr()); + } + void VisitUnaryTransformType(const UnaryTransformType *T) { Visit(T->getBaseType()); } diff --git a/clang/include/clang/AST/ComputeDependence.h b/clang/include/clang/AST/ComputeDependence.h index f62611cb4c3cf..7abf9141237dc 100644 --- a/clang/include/clang/AST/ComputeDependence.h +++ b/clang/include/clang/AST/ComputeDependence.h @@ -63,6 +63,7 @@ class ArrayTypeTraitExpr; class ExpressionTraitExpr; class CXXNoexceptExpr; class PackExpansionExpr; +class PackIndexingExpr; class SubstNonTypeTemplateParmExpr; class CoroutineSuspendExpr; class DependentCoawaitExpr; @@ -150,6 +151,7 @@ ExprDependence computeDependence(ArrayTypeTraitExpr *E); ExprDependence computeDependence(ExpressionTraitExpr *E); ExprDependence computeDependence(CXXNoexceptExpr *E, CanThrowResult CT); ExprDependence computeDependence(PackExpansionExpr *E); +ExprDependence computeDependence(PackIndexingExpr *E); ExprDependence computeDependence(SubstNonTypeTemplateParmExpr *E); ExprDependence computeDependence(CoroutineSuspendExpr *E); ExprDependence computeDependence(DependentCoawaitExpr *E); diff --git a/clang/include/clang/AST/ExprCXX.h b/clang/include/clang/AST/ExprCXX.h index 9a7c632c36c5e..a0e467b35778c 100644 --- a/clang/include/clang/AST/ExprCXX.h +++ b/clang/include/clang/AST/ExprCXX.h @@ -4331,6 +4331,105 @@ class SizeOfPackExpr final } }; +class PackIndexingExpr final + : public Expr, + private llvm::TrailingObjects { + friend class ASTStmtReader; + friend class ASTStmtWriter; + friend TrailingObjects; + + SourceLocation EllipsisLoc; + + // The location of the closing bracket + SourceLocation RSquareLoc; + + // The pack being indexed, followed by the index + Stmt *SubExprs[2]; + + size_t TransformedExpressions; + + PackIndexingExpr(QualType Type, SourceLocation EllipsisLoc, + SourceLocation RSquareLoc, Expr *PackIdExpr, Expr *IndexExpr, + ArrayRef SubstitutedExprs = {}) + : Expr(PackIndexingExprClass, Type, VK_LValue, OK_Ordinary), + EllipsisLoc(EllipsisLoc), RSquareLoc(RSquareLoc), + SubExprs{PackIdExpr, IndexExpr}, + TransformedExpressions(SubstitutedExprs.size()) { + + auto *Exprs = getTrailingObjects(); + std::uninitialized_copy(SubstitutedExprs.begin(), SubstitutedExprs.end(), + Exprs); + + setDependence(computeDependence(this)); + if (!isInstantiationDependent()) + setValueKind(getSelectedExpr()->getValueKind()); + } + + /// Create an empty expression. + PackIndexingExpr(EmptyShell Empty) : Expr(PackIndexingExprClass, Empty) {} + + unsigned numTrailingObjects(OverloadToken) const { + return TransformedExpressions; + } + +public: + static PackIndexingExpr *Create(ASTContext &Context, + SourceLocation EllipsisLoc, + SourceLocation RSquareLoc, Expr *PackIdExpr, + Expr *IndexExpr, std::optional Index, + ArrayRef SubstitutedExprs = {}); + static PackIndexingExpr *CreateDeserialized(ASTContext &Context, + unsigned NumTransformedExprs); + + /// Determine the location of the 'sizeof' keyword. + SourceLocation getEllipsisLoc() const { return EllipsisLoc; } + + /// Determine the location of the parameter pack. + SourceLocation getPackLoc() const { return SubExprs[0]->getBeginLoc(); } + + /// Determine the location of the right parenthesis. + SourceLocation getRSquareLoc() const { return RSquareLoc; } + + SourceLocation getBeginLoc() const LLVM_READONLY { return getPackLoc(); } + SourceLocation getEndLoc() const LLVM_READONLY { return RSquareLoc; } + + Expr *getPackIdExpression() const { return cast(SubExprs[0]); } + + NamedDecl *getPackDecl() const; + + Expr *getIndexExpr() const { return cast(SubExprs[1]); } + + std::optional getSelectedIndex() const { + if (isInstantiationDependent()) + return std::nullopt; + ConstantExpr *CE = cast(getIndexExpr()); + auto Index = CE->getResultAsAPSInt(); + assert(Index.isNonNegative() && "Invalid index"); + return static_cast(Index.getExtValue()); + } + + Expr *getSelectedExpr() const { + std::optional Index = getSelectedIndex(); + assert(Index && "extracting the indexed expression of a dependant pack"); + return getTrailingObjects()[*Index]; + } + + ArrayRef getExpressions() const { + return {getTrailingObjects(), TransformedExpressions}; + } + + static bool classof(const Stmt *T) { + return T->getStmtClass() == PackIndexingExprClass; + } + + // Iterators + child_range children() { return child_range(SubExprs, SubExprs + 2); } + + const_child_range children() const { + return const_child_range(SubExprs, SubExprs + 2); + } +}; + /// Represents a reference to a non-type template parameter /// that has been substituted with a template argument. class SubstNonTypeTemplateParmExpr : public Expr { diff --git a/clang/include/clang/AST/RecursiveASTVisitor.h b/clang/include/clang/AST/RecursiveASTVisitor.h index 2aee6a947141b..16b98b364eaca 100644 --- a/clang/include/clang/AST/RecursiveASTVisitor.h +++ b/clang/include/clang/AST/RecursiveASTVisitor.h @@ -1065,6 +1065,11 @@ DEF_TRAVERSE_TYPE(TypeOfType, { TRY_TO(TraverseType(T->getUnmodifiedType())); }) DEF_TRAVERSE_TYPE(DecltypeType, { TRY_TO(TraverseStmt(T->getUnderlyingExpr())); }) +DEF_TRAVERSE_TYPE(PackIndexingType, { + TRY_TO(TraverseType(T->getPattern())); + TRY_TO(TraverseStmt(T->getIndexExpr())); +}) + DEF_TRAVERSE_TYPE(UnaryTransformType, { TRY_TO(TraverseType(T->getBaseType())); TRY_TO(TraverseType(T->getUnderlyingType())); @@ -1343,6 +1348,11 @@ DEF_TRAVERSE_TYPELOC(DecltypeType, { TRY_TO(TraverseStmt(TL.getTypePtr()->getUnderlyingExpr())); }) +DEF_TRAVERSE_TYPELOC(PackIndexingType, { + TRY_TO(TraverseType(TL.getPattern())); + TRY_TO(TraverseStmt(TL.getTypePtr()->getIndexExpr())); +}) + DEF_TRAVERSE_TYPELOC(UnaryTransformType, { TRY_TO(TraverseTypeLoc(TL.getUnderlyingTInfo()->getTypeLoc())); }) @@ -2854,6 +2864,7 @@ DEF_TRAVERSE_STMT(CompoundAssignOperator, {}) DEF_TRAVERSE_STMT(CXXNoexceptExpr, {}) DEF_TRAVERSE_STMT(PackExpansionExpr, {}) DEF_TRAVERSE_STMT(SizeOfPackExpr, {}) +DEF_TRAVERSE_STMT(PackIndexingExpr, {}) DEF_TRAVERSE_STMT(SubstNonTypeTemplateParmPackExpr, {}) DEF_TRAVERSE_STMT(SubstNonTypeTemplateParmExpr, {}) DEF_TRAVERSE_STMT(FunctionParmPackExpr, {}) diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h index 9336c4c41410d..d6a55f39a4bed 100644 --- a/clang/include/clang/AST/Type.h +++ b/clang/include/clang/AST/Type.h @@ -4934,6 +4934,73 @@ class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode { Expr *E); }; +class PackIndexingType final + : public Type, + public llvm::FoldingSetNode, + private llvm::TrailingObjects { + friend TrailingObjects; + + const ASTContext &Context; + QualType Pattern; + Expr *IndexExpr; + + unsigned Size; + +protected: + friend class ASTContext; // ASTContext creates these. + PackIndexingType(const ASTContext &Context, QualType Canonical, + QualType Pattern, Expr *IndexExpr, + ArrayRef Expansions = {}); + +public: + Expr *getIndexExpr() const { return IndexExpr; } + QualType getPattern() const { return Pattern; } + + bool isSugared() const { return hasSelectedType(); } + + QualType desugar() const { + if (hasSelectedType()) + return getSelectedType(); + return QualType(this, 0); + } + + QualType getSelectedType() const { + assert(hasSelectedType() && "Type is dependant"); + return *(getExpansionsPtr() + *getSelectedIndex()); + } + + std::optional getSelectedIndex() const; + + bool hasSelectedType() const { return getSelectedIndex() != std::nullopt; } + + ArrayRef getExpansions() const { + return {getExpansionsPtr(), Size}; + } + + static bool classof(const Type *T) { + return T->getTypeClass() == PackIndexing; + } + + void Profile(llvm::FoldingSetNodeID &ID) { + if (hasSelectedType()) + getSelectedType().Profile(ID); + else + Profile(ID, Context, getPattern(), getIndexExpr()); + } + static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, + QualType Pattern, Expr *E); + +private: + const QualType *getExpansionsPtr() const { + return getTrailingObjects(); + } + + static TypeDependence computeDependence(QualType Pattern, Expr *IndexExpr, + ArrayRef Expansions = {}); + + unsigned numTrailingObjects(OverloadToken) const { return Size; } +}; + /// A unary type transform, which is a type constructed from another. class UnaryTransformType : public Type { public: diff --git a/clang/include/clang/AST/TypeLoc.h b/clang/include/clang/AST/TypeLoc.h index 04780fdeae3bc..a17b4af13d03f 100644 --- a/clang/include/clang/AST/TypeLoc.h +++ b/clang/include/clang/AST/TypeLoc.h @@ -2059,6 +2059,34 @@ class DecltypeTypeLoc } }; +struct PackIndexingTypeLocInfo { + SourceLocation EllipsisLoc; +}; + +class PackIndexingTypeLoc + : public ConcreteTypeLoc { + +public: + Expr *getIndexExpr() const { return getTypePtr()->getIndexExpr(); } + QualType getPattern() const { return getTypePtr()->getPattern(); } + + SourceLocation getEllipsisLoc() const { return getLocalData()->EllipsisLoc; } + void setEllipsisLoc(SourceLocation Loc) { getLocalData()->EllipsisLoc = Loc; } + + void initializeLocal(ASTContext &Context, SourceLocation Loc) { + setEllipsisLoc(Loc); + } + + TypeLoc getPatternLoc() const { return getInnerTypeLoc(); } + + QualType getInnerType() const { return this->getTypePtr()->getPattern(); } + + SourceRange getLocalSourceRange() const { + return SourceRange(getEllipsisLoc(), getEllipsisLoc()); + } +}; + struct UnaryTransformTypeLocInfo { // FIXME: While there's only one unary transform right now, future ones may // need different representations diff --git a/clang/include/clang/AST/TypeProperties.td b/clang/include/clang/AST/TypeProperties.td index 682c869b0c584..0ba172a4035fd 100644 --- a/clang/include/clang/AST/TypeProperties.td +++ b/clang/include/clang/AST/TypeProperties.td @@ -433,6 +433,20 @@ let Class = DecltypeType in { }]>; } +let Class = PackIndexingType in { + def : Property<"pattern", QualType> { + let Read = [{ node->getPattern() }]; + } + def : Property<"indexExpression", ExprRef> { + let Read = [{ node->getIndexExpr() }]; + } + + def : Creator<[{ + return ctx.getPackIndexingType(pattern, indexExpression); + }]>; +} + + let Class = UnaryTransformType in { def : Property<"baseType", QualType> { let Read = [{ node->getBaseType() }]; diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index 649de9f47c461..24d32cb87c89e 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -5721,9 +5721,18 @@ def err_function_parameter_pack_without_parameter_packs : Error< def err_ellipsis_in_declarator_not_parameter : Error< "only function and template parameters can be parameter packs">; -def err_sizeof_pack_no_pack_name : Error< +def err_expected_name_of_pack : Error< "%0 does not refer to the name of a parameter pack">; +def err_pack_index_out_of_bound : Error< + "invalid index %0 for pack %1 of size %2">; + +def ext_pack_indexing : ExtWarn< + "pack indexing is a C++2c extension">, InGroup; +def warn_cxx23_pack_indexing : Warning< + "pack indexing is incompatible with C++ standards before C++2c">, + DefaultIgnore, InGroup; + def err_fold_expression_packs_both_sides : Error< "binary fold expression has unexpanded parameter packs in both operands">; def err_fold_expression_empty : Error< diff --git a/clang/include/clang/Basic/Specifiers.h b/clang/include/clang/Basic/Specifiers.h index 87f29c8ae10bd..cf849b9b0f008 100644 --- a/clang/include/clang/Basic/Specifiers.h +++ b/clang/include/clang/Basic/Specifiers.h @@ -79,14 +79,14 @@ namespace clang { TST_enum, TST_union, TST_struct, - TST_class, // C++ class type - TST_interface, // C++ (Microsoft-specific) __interface type - TST_typename, // Typedef, C++ class-name or enum name, etc. + TST_class, // C++ class type + TST_interface, // C++ (Microsoft-specific) __interface type + TST_typename, // Typedef, C++ class-name or enum name, etc. TST_typeofType, // C23 (and GNU extension) typeof(type-name) TST_typeofExpr, // C23 (and GNU extension) typeof(expression) TST_typeof_unqualType, // C23 typeof_unqual(type-name) TST_typeof_unqualExpr, // C23 typeof_unqual(expression) - TST_decltype, // C++11 decltype + TST_decltype, // C++11 decltype #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) TST_##Trait, #include "clang/Basic/TransformTypeTraits.def" TST_auto, // C++11 auto @@ -94,7 +94,9 @@ namespace clang { TST_auto_type, // __auto_type extension TST_unknown_anytype, // __unknown_anytype extension TST_atomic, // C11 _Atomic -#define GENERIC_IMAGE_TYPE(ImgType, Id) TST_##ImgType##_t, // OpenCL image types + TST_typename_pack_indexing, +#define GENERIC_IMAGE_TYPE(ImgType, Id) \ + TST_##ImgType##_t, // OpenCL image types #include "clang/Basic/OpenCLImageTypes.def" TST_error // erroneous type }; diff --git a/clang/include/clang/Basic/StmtNodes.td b/clang/include/clang/Basic/StmtNodes.td index cec301dfca281..9d03800840fcd 100644 --- a/clang/include/clang/Basic/StmtNodes.td +++ b/clang/include/clang/Basic/StmtNodes.td @@ -154,6 +154,7 @@ def UnresolvedMemberExpr : StmtNode; def CXXNoexceptExpr : StmtNode; def PackExpansionExpr : StmtNode; def SizeOfPackExpr : StmtNode; +def PackIndexingExpr : StmtNode; def SubstNonTypeTemplateParmExpr : StmtNode; def SubstNonTypeTemplateParmPackExpr : StmtNode; def FunctionParmPackExpr : StmtNode; diff --git a/clang/include/clang/Basic/TokenKinds.def b/clang/include/clang/Basic/TokenKinds.def index c10e2adfbe6e9..9117e4376c371 100644 --- a/clang/include/clang/Basic/TokenKinds.def +++ b/clang/include/clang/Basic/TokenKinds.def @@ -840,6 +840,8 @@ ANNOTATION(primary_expr) // annotation for a primary expression, used when // message send ANNOTATION(decltype) // annotation for a decltype expression, // e.g., "decltype(foo.bar())" +ANNOTATION(pack_indexing_type) // annotation for an indexed pack of type, + // e.g., "T...[expr]" // Annotation for #pragma unused(...) // For each argument inside the parentheses the pragma handler will produce diff --git a/clang/include/clang/Basic/TypeNodes.td b/clang/include/clang/Basic/TypeNodes.td index 649b071cebb94..6419762417371 100644 --- a/clang/include/clang/Basic/TypeNodes.td +++ b/clang/include/clang/Basic/TypeNodes.td @@ -103,6 +103,7 @@ def InjectedClassNameType : TypeNode, AlwaysDependent, LeafType; def DependentNameType : TypeNode, AlwaysDependent; def DependentTemplateSpecializationType : TypeNode, AlwaysDependent; def PackExpansionType : TypeNode, AlwaysDependent; +def PackIndexingType : TypeNode, NeverCanonicalUnlessDependent; def ObjCTypeParamType : TypeNode, NeverCanonical; def ObjCObjectType : TypeNode; def ObjCInterfaceType : TypeNode, LeafType; diff --git a/clang/include/clang/Parse/Parser.h b/clang/include/clang/Parse/Parser.h index bde1ac2242cd6..baad6155b7c63 100644 --- a/clang/include/clang/Parse/Parser.h +++ b/clang/include/clang/Parse/Parser.h @@ -1911,6 +1911,10 @@ class Parser : public CodeCompletionHandler { // C++ Expressions ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand, Token &Replacement); + + ExprResult tryParseCXXPackIndexingExpression(ExprResult PackIdExpression); + ExprResult ParseCXXPackIndexingExpression(ExprResult PackIdExpression); + ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false); bool areTokensAdjacent(const Token &A, const Token &B); @@ -2457,6 +2461,11 @@ class Parser : public CodeCompletionHandler { DeclSpecContext DSC, LateParsedAttrList *LateAttrs, ImplicitTypenameContext AllowImplicitTypename); + SourceLocation ParsePackIndexingType(DeclSpec &DS); + void AnnotateExistingIndexedTypeNamePack(ParsedType T, + SourceLocation StartLoc, + SourceLocation EndLoc); + bool DiagnoseMissingSemiAfterTagDefinition( DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext, LateParsedAttrList *LateAttrs = nullptr); diff --git a/clang/include/clang/Sema/DeclSpec.h b/clang/include/clang/Sema/DeclSpec.h index 4561cca929c0d..77638def60063 100644 --- a/clang/include/clang/Sema/DeclSpec.h +++ b/clang/include/clang/Sema/DeclSpec.h @@ -309,6 +309,8 @@ class DeclSpec { static const TST TST_typeof_unqualExpr = clang::TST_typeof_unqualExpr; static const TST TST_decltype = clang::TST_decltype; static const TST TST_decltype_auto = clang::TST_decltype_auto; + static const TST TST_typename_pack_indexing = + clang::TST_typename_pack_indexing; #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) \ static const TST TST_##Trait = clang::TST_##Trait; #include "clang/Basic/TransformTypeTraits.def" @@ -389,6 +391,7 @@ class DeclSpec { Expr *ExprRep; TemplateIdAnnotation *TemplateIdRep; }; + Expr *PackIndexingExpr = nullptr; /// ExplicitSpecifier - Store information about explicit spicifer. ExplicitSpecifier FS_explicit_specifier; @@ -405,7 +408,7 @@ class DeclSpec { SourceLocation StorageClassSpecLoc, ThreadStorageClassSpecLoc; SourceRange TSWRange; - SourceLocation TSCLoc, TSSLoc, TSTLoc, AltiVecLoc, TSSatLoc; + SourceLocation TSCLoc, TSSLoc, TSTLoc, AltiVecLoc, TSSatLoc, EllipsisLoc; /// TSTNameLoc - If TypeSpecType is any of class, enum, struct, union, /// typename, then this is the location of the named type (if present); /// otherwise, it is the same as TSTLoc. Hence, the pair TSTLoc and @@ -427,7 +430,8 @@ class DeclSpec { static bool isTypeRep(TST T) { return T == TST_atomic || T == TST_typename || T == TST_typeofType || - T == TST_typeof_unqualType || isTransformTypeTrait(T); + T == TST_typeof_unqualType || isTransformTypeTrait(T) || + T == TST_typename_pack_indexing; } static bool isExprRep(TST T) { return T == TST_typeofExpr || T == TST_typeof_unqualExpr || @@ -530,6 +534,13 @@ class DeclSpec { assert(isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr"); return ExprRep; } + + Expr *getPackIndexingExpr() const { + assert(TypeSpecType == TST_typename_pack_indexing && + "DeclSpec is not a pack indexing expr"); + return PackIndexingExpr; + } + TemplateIdAnnotation *getRepAsTemplateId() const { assert(isTemplateIdRep((TST) TypeSpecType) && "DeclSpec does not store a template id"); @@ -587,6 +598,7 @@ class DeclSpec { SourceLocation getAtomicSpecLoc() const { return TQ_atomicLoc; } SourceLocation getUnalignedSpecLoc() const { return TQ_unalignedLoc; } SourceLocation getPipeLoc() const { return TQ_pipeLoc; } + SourceLocation getEllipsisLoc() const { return EllipsisLoc; } /// Clear out all of the type qualifiers. void ClearTypeQualifiers() { @@ -743,6 +755,9 @@ class DeclSpec { const PrintingPolicy &Policy); bool SetTypeSpecSat(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID); + + void SetPackIndexingExpr(SourceLocation EllipsisLoc, Expr *Pack); + bool SetTypeSpecError(); void UpdateDeclRep(Decl *Rep) { assert(isDeclRep((TST) TypeSpecType)); @@ -1939,6 +1954,8 @@ class Declarator { /// this declarator as a parameter pack. SourceLocation EllipsisLoc; + Expr *PackIndexingExpr; + friend struct DeclaratorChunk; public: @@ -2063,6 +2080,7 @@ class Declarator { ObjCWeakProperty = false; CommaLoc = SourceLocation(); EllipsisLoc = SourceLocation(); + PackIndexingExpr = nullptr; } /// mayOmitIdentifier - Return true if the identifier is either optional or @@ -2648,6 +2666,10 @@ class Declarator { SourceLocation getEllipsisLoc() const { return EllipsisLoc; } void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; } + bool hasPackIndexing() const { return PackIndexingExpr != nullptr; } + Expr *getPackIndexingExpr() const { return PackIndexingExpr; } + void setPackIndexingExpr(Expr *PI) { PackIndexingExpr = PI; } + void setFunctionDefinitionKind(FunctionDefinitionKind Val) { FunctionDefinition = static_cast(Val); } diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index 1f1cbd11ff735..b5946e3f3178f 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -2602,6 +2602,14 @@ class Sema final { /// context, such as when building a type for decltype(auto). QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true); + QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr, + SourceLocation Loc, + SourceLocation EllipsisLoc); + QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, + SourceLocation Loc, SourceLocation EllipsisLoc, + bool FullySubstituted = false, + ArrayRef Expansions = {}); + using UTTKind = UnaryTransformType::UTTKind; QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind, SourceLocation Loc); @@ -5873,6 +5881,18 @@ class Sema final { IdentifierInfo &Name, SourceLocation NameLoc, SourceLocation RParenLoc); + + ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression, + SourceLocation EllipsisLoc, + SourceLocation LSquareLoc, Expr *IndexExpr, + SourceLocation RSquareLoc); + + ExprResult BuildPackIndexingExpr(Expr *PackExpression, + SourceLocation EllipsisLoc, Expr *IndexExpr, + SourceLocation RSquareLoc, + ArrayRef ExpandedExprs = {}, + bool EmptyPack = false); + ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input); @@ -7140,6 +7160,11 @@ class Sema final { const DeclSpec &DS, SourceLocation ColonColonLoc); + bool ActOnCXXNestedNameSpecifierIndexedPack(CXXScopeSpec &SS, + const DeclSpec &DS, + SourceLocation ColonColonLoc, + QualType Type); + bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo, bool EnteringContext); diff --git a/clang/include/clang/Serialization/ASTBitCodes.h b/clang/include/clang/Serialization/ASTBitCodes.h index fdd64f2abbe93..ea084b328d612 100644 --- a/clang/include/clang/Serialization/ASTBitCodes.h +++ b/clang/include/clang/Serialization/ASTBitCodes.h @@ -1895,6 +1895,7 @@ enum StmtCode { EXPR_ARRAY_TYPE_TRAIT, // ArrayTypeTraitIntExpr EXPR_PACK_EXPANSION, // PackExpansionExpr + EXPR_PACK_INDEXING, // PackIndexingExpr EXPR_SIZEOF_PACK, // SizeOfPackExpr EXPR_SUBST_NON_TYPE_TEMPLATE_PARM, // SubstNonTypeTemplateParmExpr EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK, // SubstNonTypeTemplateParmPackExpr diff --git a/clang/include/clang/Serialization/TypeBitCodes.def b/clang/include/clang/Serialization/TypeBitCodes.def index 89ae1a2fa3954..adbd5ec5d4b54 100644 --- a/clang/include/clang/Serialization/TypeBitCodes.def +++ b/clang/include/clang/Serialization/TypeBitCodes.def @@ -64,5 +64,7 @@ TYPE_BIT_CODE(ConstantMatrix, CONSTANT_MATRIX, 52) TYPE_BIT_CODE(DependentSizedMatrix, DEPENDENT_SIZE_MATRIX, 53) TYPE_BIT_CODE(Using, USING, 54) TYPE_BIT_CODE(BTFTagAttributed, BTFTAG_ATTRIBUTED, 55) +TYPE_BIT_CODE(PackIndexing, PACK_INDEXING, 56) + #undef TYPE_BIT_CODE diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp index ab16ca10395fa..2aa6ed089a081 100644 --- a/clang/lib/AST/ASTContext.cpp +++ b/clang/lib/AST/ASTContext.cpp @@ -3598,6 +3598,7 @@ QualType ASTContext::getVariableArrayDecayedType(QualType type) const { case Type::Auto: case Type::DeducedTemplateSpecialization: case Type::PackExpansion: + case Type::PackIndexing: case Type::BitInt: case Type::DependentBitInt: llvm_unreachable("type should never be variably-modified"); @@ -5701,6 +5702,39 @@ QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { return QualType(dt, 0); } +QualType ASTContext::getPackIndexingType(QualType Pattern, Expr *IndexExpr, + bool FullySubstituted, + ArrayRef Expansions, + int Index) const { + QualType Canonical; + if (FullySubstituted && Index != -1) { + Canonical = getCanonicalType(Expansions[Index]); + } else { + llvm::FoldingSetNodeID ID; + PackIndexingType::Profile(ID, *this, Pattern, IndexExpr); + void *InsertPos = nullptr; + PackIndexingType *Canon = + DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos); + if (!Canon) { + void *Mem = Allocate( + PackIndexingType::totalSizeToAlloc(Expansions.size()), + TypeAlignment); + Canon = new (Mem) + PackIndexingType(*this, QualType(), Pattern, IndexExpr, Expansions); + DependentPackIndexingTypes.InsertNode(Canon, InsertPos); + } + Canonical = QualType(Canon, 0); + } + + void *Mem = + Allocate(PackIndexingType::totalSizeToAlloc(Expansions.size()), + TypeAlignment); + auto *T = new (Mem) + PackIndexingType(*this, Canonical, Pattern, IndexExpr, Expansions); + Types.push_back(T); + return QualType(T, 0); +} + /// getUnaryTransformationType - We don't unique these, since the memory /// savings are minimal and these are rare. QualType ASTContext::getUnaryTransformType(QualType BaseType, @@ -12917,6 +12951,14 @@ static QualType getCommonNonSugarTypeNode(ASTContext &Ctx, const Type *X, // As Decltype is not uniqued, building a common type would be wasteful. return QualType(DX, 0); } + case Type::PackIndexing: { + const auto *DX = cast(X); + [[maybe_unused]] const auto *DY = cast(Y); + assert(DX->isDependentType()); + assert(DY->isDependentType()); + assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr())); + return QualType(DX, 0); + } case Type::DependentName: { const auto *NX = cast(X), *NY = cast(Y); @@ -13077,6 +13119,7 @@ static QualType getCommonSugarTypeNode(ASTContext &Ctx, const Type *X, return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(), /*IsDependent=*/false, /*IsPack=*/false, CD, As); } + case Type::PackIndexing: case Type::Decltype: return QualType(); case Type::DeducedTemplateSpecialization: diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp index 12734d62ed9fb..30567aa1163c4 100644 --- a/clang/lib/AST/ASTImporter.cpp +++ b/clang/lib/AST/ASTImporter.cpp @@ -1369,6 +1369,18 @@ ExpectedType ASTNodeImporter::VisitParenType(const ParenType *T) { return Importer.getToContext().getParenType(*ToInnerTypeOrErr); } +ExpectedType +ASTNodeImporter::VisitPackIndexingType(clang::PackIndexingType const *T) { + + ExpectedType Pattern = import(T->getPattern()); + if (!Pattern) + return Pattern.takeError(); + ExpectedExpr Index = import(T->getIndexExpr()); + if (!Index) + return Index.takeError(); + return Importer.getToContext().getPackIndexingType(*Pattern, *Index); +} + ExpectedType ASTNodeImporter::VisitTypedefType(const TypedefType *T) { Expected ToDeclOrErr = import(T->getDecl()); if (!ToDeclOrErr) diff --git a/clang/lib/AST/ASTStructuralEquivalence.cpp b/clang/lib/AST/ASTStructuralEquivalence.cpp index be7a850a2982c..a7ddf6d6f896d 100644 --- a/clang/lib/AST/ASTStructuralEquivalence.cpp +++ b/clang/lib/AST/ASTStructuralEquivalence.cpp @@ -1292,6 +1292,16 @@ static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, return false; break; + case Type::PackIndexing: + if (!IsStructurallyEquivalent(Context, + cast(T1)->getPattern(), + cast(T2)->getPattern())) + if (!IsStructurallyEquivalent(Context, + cast(T1)->getIndexExpr(), + cast(T2)->getIndexExpr())) + return false; + break; + case Type::ObjCInterface: { const auto *Iface1 = cast(T1); const auto *Iface2 = cast(T2); diff --git a/clang/lib/AST/ComputeDependence.cpp b/clang/lib/AST/ComputeDependence.cpp index 584b58473294b..9d3856b8f7e08 100644 --- a/clang/lib/AST/ComputeDependence.cpp +++ b/clang/lib/AST/ComputeDependence.cpp @@ -364,6 +364,21 @@ ExprDependence clang::computeDependence(PackExpansionExpr *E) { ExprDependence::TypeValueInstantiation; } +ExprDependence clang::computeDependence(PackIndexingExpr *E) { + ExprDependence D = E->getIndexExpr()->getDependence(); + ArrayRef Exprs = E->getExpressions(); + if (Exprs.empty()) + D |= (E->getPackIdExpression()->getDependence() | + ExprDependence::TypeValueInstantiation) & + ~ExprDependence::UnexpandedPack; + else if (!E->getIndexExpr()->isInstantiationDependent()) { + std::optional Index = E->getSelectedIndex(); + assert(Index && *Index < Exprs.size() && "pack index out of bound"); + D |= Exprs[*Index]->getDependence(); + } + return D; +} + ExprDependence clang::computeDependence(SubstNonTypeTemplateParmExpr *E) { return E->getReplacement()->getDependence(); } diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp index f1efa98e175ed..c2cd46dfbafcd 100644 --- a/clang/lib/AST/Expr.cpp +++ b/clang/lib/AST/Expr.cpp @@ -3397,6 +3397,11 @@ bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef, return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit); break; } + case PackIndexingExprClass: { + return cast(this) + ->getSelectedExpr() + ->isConstantInitializer(Ctx, false, Culprit); + } case CXXFunctionalCastExprClass: case CXXStaticCastExprClass: case ImplicitCastExprClass: @@ -3572,6 +3577,9 @@ bool Expr::HasSideEffects(const ASTContext &Ctx, // These never have a side-effect. return false; + case PackIndexingExprClass: + return cast(this)->getSelectedExpr()->HasSideEffects( + Ctx, IncludePossibleEffects); case ConstantExprClass: // FIXME: Move this into the "return false;" block above. return cast(this)->getSubExpr()->HasSideEffects( diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp index a775beadff9da..a581963188433 100644 --- a/clang/lib/AST/ExprCXX.cpp +++ b/clang/lib/AST/ExprCXX.cpp @@ -1665,6 +1665,42 @@ NonTypeTemplateParmDecl *SubstNonTypeTemplateParmExpr::getParameter() const { getReplacedTemplateParameterList(getAssociatedDecl())->asArray()[Index]); } +PackIndexingExpr *PackIndexingExpr::Create(ASTContext &Context, + SourceLocation EllipsisLoc, + SourceLocation RSquareLoc, + Expr *PackIdExpr, Expr *IndexExpr, + std::optional Index, + ArrayRef SubstitutedExprs) { + QualType Type; + if (Index && !SubstitutedExprs.empty()) + Type = SubstitutedExprs[*Index]->getType(); + else + Type = Context.DependentTy; + + void *Storage = + Context.Allocate(totalSizeToAlloc(SubstitutedExprs.size())); + return new (Storage) PackIndexingExpr( + Type, EllipsisLoc, RSquareLoc, PackIdExpr, IndexExpr, SubstitutedExprs); +} + +NamedDecl *PackIndexingExpr::getPackDecl() const { + if (auto *D = dyn_cast(getPackIdExpression()); D) { + NamedDecl *ND = dyn_cast(D->getDecl()); + assert(ND && "exected a named decl"); + return ND; + } + assert(false && "invalid declaration kind in pack indexing expression"); + return nullptr; +} + +PackIndexingExpr * +PackIndexingExpr::CreateDeserialized(ASTContext &Context, + unsigned NumTransformedExprs) { + void *Storage = + Context.Allocate(totalSizeToAlloc(NumTransformedExprs)); + return new (Storage) PackIndexingExpr(EmptyShell{}); +} + QualType SubstNonTypeTemplateParmExpr::getParameterType( const ASTContext &Context) const { // Note that, for a class type NTTP, we will have an lvalue of type 'const diff --git a/clang/lib/AST/ExprClassification.cpp b/clang/lib/AST/ExprClassification.cpp index ffa7c6802ea6e..7026fca8554ce 100644 --- a/clang/lib/AST/ExprClassification.cpp +++ b/clang/lib/AST/ExprClassification.cpp @@ -216,6 +216,9 @@ static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) { return ClassifyInternal(Ctx, cast(E)->getReplacement()); + case Expr::PackIndexingExprClass: + return ClassifyInternal(Ctx, cast(E)->getSelectedExpr()); + // C, C++98 [expr.sub]p1: The result is an lvalue of type "T". // C++11 (DR1213): in the case of an array operand, the result is an lvalue // if that operand is an lvalue and an xvalue otherwise. diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp index f1d07d022b258..a41bdac46c814 100644 --- a/clang/lib/AST/ExprConstant.cpp +++ b/clang/lib/AST/ExprConstant.cpp @@ -8254,6 +8254,10 @@ class ExprEvaluatorBase llvm_unreachable("Return from function from the loop above."); } + bool VisitPackIndexingExpr(const PackIndexingExpr *E) { + return StmtVisitorTy::Visit(E->getSelectedExpr()); + } + /// Visit a value which is evaluated, but whose value is ignored. void VisitIgnoredValue(const Expr *E) { EvaluateIgnoredValue(Info, E); @@ -16062,6 +16066,9 @@ static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { case Expr::SourceLocExprClass: return NoDiag(); + case Expr::PackIndexingExprClass: + return CheckICE(cast(E)->getSelectedExpr(), Ctx); + case Expr::SubstNonTypeTemplateParmExprClass: return CheckICE(cast(E)->getReplacement(), Ctx); diff --git a/clang/lib/AST/ItaniumMangle.cpp b/clang/lib/AST/ItaniumMangle.cpp index 688141b30441e..c0add78bf90ff 100644 --- a/clang/lib/AST/ItaniumMangle.cpp +++ b/clang/lib/AST/ItaniumMangle.cpp @@ -2448,6 +2448,7 @@ bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty, case Type::TypeOfExpr: case Type::TypeOf: case Type::Decltype: + case Type::PackIndexing: case Type::TemplateTypeParm: case Type::UnaryTransform: case Type::SubstTemplateTypeParm: @@ -4202,6 +4203,13 @@ void CXXNameMangler::mangleType(const PackExpansionType *T) { mangleType(T->getPattern()); } +void CXXNameMangler::mangleType(const PackIndexingType *T) { + if (!T->hasSelectedType()) + mangleType(T->getPattern()); + else + mangleType(T->getSelectedType()); +} + void CXXNameMangler::mangleType(const ObjCInterfaceType *T) { mangleSourceName(T->getDecl()->getIdentifier()); } @@ -4704,6 +4712,7 @@ void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity, case Expr::OMPIteratorExprClass: case Expr::CXXInheritedCtorInitExprClass: case Expr::CXXParenListInitExprClass: + case Expr::PackIndexingExprClass: llvm_unreachable("unexpected statement kind"); case Expr::ConstantExprClass: diff --git a/clang/lib/AST/MicrosoftMangle.cpp b/clang/lib/AST/MicrosoftMangle.cpp index 36b5bf64f675a..b272a546573a3 100644 --- a/clang/lib/AST/MicrosoftMangle.cpp +++ b/clang/lib/AST/MicrosoftMangle.cpp @@ -3408,6 +3408,12 @@ void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers, << Range; } +void MicrosoftCXXNameMangler::mangleType(const PackIndexingType *T, + Qualifiers Quals, SourceRange Range) { + manglePointerCVQualifiers(Quals); + mangleType(T->getSelectedType(), Range); +} + void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers, SourceRange Range) { DiagnosticsEngine &Diags = Context.getDiags(); diff --git a/clang/lib/AST/StmtPrinter.cpp b/clang/lib/AST/StmtPrinter.cpp index 9b5bf436c13be..1df040e06db35 100644 --- a/clang/lib/AST/StmtPrinter.cpp +++ b/clang/lib/AST/StmtPrinter.cpp @@ -2449,6 +2449,10 @@ void StmtPrinter::VisitSizeOfPackExpr(SizeOfPackExpr *E) { OS << "sizeof...(" << *E->getPack() << ")"; } +void StmtPrinter::VisitPackIndexingExpr(PackIndexingExpr *E) { + OS << E->getPackIdExpression() << "...[" << E->getIndexExpr() << "]"; +} + void StmtPrinter::VisitSubstNonTypeTemplateParmPackExpr( SubstNonTypeTemplateParmPackExpr *Node) { OS << *Node->getParameterPack(); diff --git a/clang/lib/AST/StmtProfile.cpp b/clang/lib/AST/StmtProfile.cpp index dd0838edab7b3..7459f967da095 100644 --- a/clang/lib/AST/StmtProfile.cpp +++ b/clang/lib/AST/StmtProfile.cpp @@ -2219,6 +2219,12 @@ void StmtProfiler::VisitSizeOfPackExpr(const SizeOfPackExpr *S) { } } +void StmtProfiler::VisitPackIndexingExpr(const PackIndexingExpr *E) { + VisitExpr(E); + VisitExpr(E->getPackIdExpression()); + VisitExpr(E->getIndexExpr()); +} + void StmtProfiler::VisitSubstNonTypeTemplateParmPackExpr( const SubstNonTypeTemplateParmPackExpr *S) { VisitExpr(S); diff --git a/clang/lib/AST/Type.cpp b/clang/lib/AST/Type.cpp index d4103025591e7..11ca02be13ab4 100644 --- a/clang/lib/AST/Type.cpp +++ b/clang/lib/AST/Type.cpp @@ -3813,6 +3813,57 @@ void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID, E->Profile(ID, Context, true); } +PackIndexingType::PackIndexingType(const ASTContext &Context, + QualType Canonical, QualType Pattern, + Expr *IndexExpr, + ArrayRef Expansions) + : Type(PackIndexing, Canonical, + computeDependence(Pattern, IndexExpr, Expansions)), + Context(Context), Pattern(Pattern), IndexExpr(IndexExpr), + Size(Expansions.size()) { + + std::uninitialized_copy(Expansions.begin(), Expansions.end(), + getTrailingObjects()); +} + +std::optional PackIndexingType::getSelectedIndex() const { + if (isInstantiationDependentType()) + return std::nullopt; + // Should only be not a constant for error recovery. + ConstantExpr *CE = dyn_cast(getIndexExpr()); + if (!CE) + return std::nullopt; + auto Index = CE->getResultAsAPSInt(); + assert(Index.isNonNegative() && "Invalid index"); + return static_cast(Index.getExtValue()); +} + +TypeDependence +PackIndexingType::computeDependence(QualType Pattern, Expr *IndexExpr, + ArrayRef Expansions) { + TypeDependence IndexD = toTypeDependence(IndexExpr->getDependence()); + + TypeDependence TD = IndexD | (IndexExpr->isInstantiationDependent() + ? TypeDependence::DependentInstantiation + : TypeDependence::None); + if (Expansions.empty()) + TD |= Pattern->getDependence() & TypeDependence::DependentInstantiation; + else + for (const QualType &T : Expansions) + TD |= T->getDependence(); + + if (!(IndexD & TypeDependence::UnexpandedPack)) + TD &= ~TypeDependence::UnexpandedPack; + return TD; +} + +void PackIndexingType::Profile(llvm::FoldingSetNodeID &ID, + const ASTContext &Context, QualType Pattern, + Expr *E) { + Pattern.Profile(ID); + E->Profile(ID, Context, true); +} + UnaryTransformType::UnaryTransformType(QualType BaseType, QualType UnderlyingType, UTTKind UKind, QualType CanonicalType) @@ -4488,6 +4539,7 @@ bool Type::canHaveNullability(bool ResultIfUnknown) const { case Type::TypeOfExpr: case Type::TypeOf: case Type::Decltype: + case Type::PackIndexing: case Type::UnaryTransform: case Type::TemplateTypeParm: case Type::SubstTemplateTypeParmPack: diff --git a/clang/lib/AST/TypePrinter.cpp b/clang/lib/AST/TypePrinter.cpp index e9b6e810b02e8..63e56a8296db3 100644 --- a/clang/lib/AST/TypePrinter.cpp +++ b/clang/lib/AST/TypePrinter.cpp @@ -296,6 +296,11 @@ bool TypePrinter::canPrefixQualifiers(const Type *T, CanPrefixQualifiers = AttrTy->getAttrKind() == attr::AddressSpace; break; } + case Type::PackIndexing: { + return canPrefixQualifiers( + cast(UnderlyingType)->getPattern().getTypePtr(), + NeedARCStrongQualifier); + } } return CanPrefixQualifiers; @@ -1188,6 +1193,18 @@ void TypePrinter::printDecltypeBefore(const DecltypeType *T, raw_ostream &OS) { spaceBeforePlaceHolder(OS); } +void TypePrinter::printPackIndexingBefore(const PackIndexingType *T, + raw_ostream &OS) { + if (T->isInstantiationDependentType()) + OS << T->getPattern() << "...[" << T->getIndexExpr() << "]"; + else + OS << T->getSelectedType(); + spaceBeforePlaceHolder(OS); +} + +void TypePrinter::printPackIndexingAfter(const PackIndexingType *T, + raw_ostream &OS) {} + void TypePrinter::printDecltypeAfter(const DecltypeType *T, raw_ostream &OS) {} void TypePrinter::printUnaryTransformBefore(const UnaryTransformType *T, diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp b/clang/lib/CodeGen/CGDebugInfo.cpp index 0f3f684d61dc9..81af8317300d9 100644 --- a/clang/lib/CodeGen/CGDebugInfo.cpp +++ b/clang/lib/CodeGen/CGDebugInfo.cpp @@ -3483,6 +3483,10 @@ static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) { T = DT; break; } + case Type::PackIndexing: { + T = cast(T)->getSelectedType(); + break; + } case Type::Adjusted: case Type::Decayed: // Decayed and adjusted types use the adjusted type in LLVM and DWARF. @@ -3666,6 +3670,7 @@ llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) { case Type::TypeOfExpr: case Type::TypeOf: case Type::Decltype: + case Type::PackIndexing: case Type::UnaryTransform: break; } diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp index 9196c953145b2..8c8c937b512ac 100644 --- a/clang/lib/CodeGen/CGExpr.cpp +++ b/clang/lib/CodeGen/CGExpr.cpp @@ -1675,6 +1675,8 @@ LValue CodeGenFunction::EmitLValueHelper(const Expr *E, return EmitCoawaitLValue(cast(E)); case Expr::CoyieldExprClass: return EmitCoyieldLValue(cast(E)); + case Expr::PackIndexingExprClass: + return EmitLValue(cast(E)->getSelectedExpr()); } } diff --git a/clang/lib/CodeGen/CGExprAgg.cpp b/clang/lib/CodeGen/CGExprAgg.cpp index 810b28f25fa18..22f55fe9aac90 100644 --- a/clang/lib/CodeGen/CGExprAgg.cpp +++ b/clang/lib/CodeGen/CGExprAgg.cpp @@ -235,6 +235,9 @@ class AggExprEmitter : public StmtVisitor { RValue Res = CGF.EmitAtomicExpr(E); EmitFinalDestCopy(E->getType(), Res); } + void VisitPackIndexingExpr(PackIndexingExpr *E) { + Visit(E->getSelectedExpr()); + } }; } // end anonymous namespace. diff --git a/clang/lib/CodeGen/CGExprComplex.cpp b/clang/lib/CodeGen/CGExprComplex.cpp index 839fe16cd7725..9ddf0e763f139 100644 --- a/clang/lib/CodeGen/CGExprComplex.cpp +++ b/clang/lib/CodeGen/CGExprComplex.cpp @@ -354,6 +354,10 @@ class ComplexExprEmitter ComplexPairTy VisitAtomicExpr(AtomicExpr *E) { return CGF.EmitAtomicExpr(E).getComplexVal(); } + + ComplexPairTy VisitPackIndexingExpr(PackIndexingExpr *E) { + return Visit(E->getSelectedExpr()); + } }; } // end anonymous namespace. diff --git a/clang/lib/CodeGen/CGExprConstant.cpp b/clang/lib/CodeGen/CGExprConstant.cpp index 604e3958161db..afadef7c4c105 100644 --- a/clang/lib/CodeGen/CGExprConstant.cpp +++ b/clang/lib/CodeGen/CGExprConstant.cpp @@ -1388,6 +1388,10 @@ class ConstExprEmitter : return nullptr; } + llvm::Constant *VisitPackIndexingExpr(PackIndexingExpr *E, QualType T) { + return Visit(E->getSelectedExpr(), T); + } + // Utility methods llvm::Type *ConvertType(QualType T) { return CGM.getTypes().ConvertType(T); diff --git a/clang/lib/CodeGen/CGExprScalar.cpp b/clang/lib/CodeGen/CGExprScalar.cpp index 181b15e9c7d0a..5502f685f6474 100644 --- a/clang/lib/CodeGen/CGExprScalar.cpp +++ b/clang/lib/CodeGen/CGExprScalar.cpp @@ -904,6 +904,9 @@ class ScalarExprEmitter } Value *VisitAsTypeExpr(AsTypeExpr *CE); Value *VisitAtomicExpr(AtomicExpr *AE); + Value *VisitPackIndexingExpr(PackIndexingExpr *E) { + return Visit(E->getSelectedExpr()); + } }; } // end anonymous namespace. diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp b/clang/lib/CodeGen/CodeGenFunction.cpp index 2673e4a5cee7b..1ad905078d349 100644 --- a/clang/lib/CodeGen/CodeGenFunction.cpp +++ b/clang/lib/CodeGen/CodeGenFunction.cpp @@ -2407,6 +2407,7 @@ void CodeGenFunction::EmitVariablyModifiedType(QualType type) { case Type::Decltype: case Type::Auto: case Type::DeducedTemplateSpecialization: + case Type::PackIndexing: // Stop walking: nothing to do. return; diff --git a/clang/lib/Parse/ParseCXXInlineMethods.cpp b/clang/lib/Parse/ParseCXXInlineMethods.cpp index 573c90a36eeab..d790060c17c04 100644 --- a/clang/lib/Parse/ParseCXXInlineMethods.cpp +++ b/clang/lib/Parse/ParseCXXInlineMethods.cpp @@ -978,6 +978,19 @@ bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) { } else { break; } + // Pack indexing + if (Tok.is(tok::ellipsis) && NextToken().is(tok::l_square)) { + Toks.push_back(Tok); + SourceLocation OpenLoc = ConsumeToken(); + Toks.push_back(Tok); + ConsumeBracket(); + if (!ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/true)) { + Diag(Tok.getLocation(), diag::err_expected) << tok::r_square; + Diag(OpenLoc, diag::note_matching) << tok::l_square; + return true; + } + } + } while (Tok.is(tok::coloncolon)); if (Tok.is(tok::code_completion)) { diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp index 356e7851ec639..7ea0dccd1c724 100644 --- a/clang/lib/Parse/ParseDecl.cpp +++ b/clang/lib/Parse/ParseDecl.cpp @@ -4447,6 +4447,10 @@ void Parser::ParseDeclarationSpecifiers( ParseDecltypeSpecifier(DS); continue; + case tok::annot_pack_indexing_type: + ParsePackIndexingType(DS); + continue; + case tok::annot_pragma_pack: HandlePragmaPack(); continue; @@ -5756,6 +5760,7 @@ bool Parser::isDeclarationSpecifier( // C++11 decltype and constexpr. case tok::annot_decltype: + case tok::annot_pack_indexing_type: case tok::kw_constexpr: // C++20 consteval and constinit. diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp index 82fe12170f666..06ccc1e3d04e9 100644 --- a/clang/lib/Parse/ParseDeclCXX.cpp +++ b/clang/lib/Parse/ParseDeclCXX.cpp @@ -1196,6 +1196,93 @@ void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec &DS, PP.AnnotateCachedTokens(Tok); } +SourceLocation Parser::ParsePackIndexingType(DeclSpec &DS) { + assert(Tok.isOneOf(tok::annot_pack_indexing_type, tok::identifier) && + "Expected an identifier"); + + TypeResult Type; + SourceLocation StartLoc; + SourceLocation EllipsisLoc; + const char *PrevSpec; + unsigned DiagID; + const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy(); + + if (Tok.is(tok::annot_pack_indexing_type)) { + StartLoc = Tok.getLocation(); + SourceLocation EndLoc; + Type = getTypeAnnotation(Tok); + EndLoc = Tok.getAnnotationEndLoc(); + // Unfortunately, we don't know the LParen source location as the annotated + // token doesn't have it. + DS.setTypeArgumentRange(SourceRange(SourceLocation(), EndLoc)); + ConsumeAnnotationToken(); + if (Type.isInvalid()) { + DS.SetTypeSpecError(); + return EndLoc; + } + DS.SetTypeSpecType(DeclSpec::TST_typename_pack_indexing, StartLoc, PrevSpec, + DiagID, Type, Policy); + return EndLoc; + } + if (!NextToken().is(tok::ellipsis) || + !GetLookAheadToken(2).is(tok::l_square)) { + DS.SetTypeSpecError(); + return Tok.getEndLoc(); + } + + ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(), + Tok.getLocation(), getCurScope()); + if (!Ty) { + DS.SetTypeSpecError(); + return Tok.getEndLoc(); + } + Type = Ty; + + StartLoc = ConsumeToken(); + EllipsisLoc = ConsumeToken(); + BalancedDelimiterTracker T(*this, tok::l_square); + T.consumeOpen(); + ExprResult IndexExpr = ParseConstantExpression(); + T.consumeClose(); + + DS.SetRangeStart(StartLoc); + DS.SetRangeEnd(T.getCloseLocation()); + + if (!IndexExpr.isUsable()) { + ASTContext &C = Actions.getASTContext(); + IndexExpr = IntegerLiteral::Create(C, C.MakeIntValue(0, C.getSizeType()), + C.getSizeType(), SourceLocation()); + } + + DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, PrevSpec, DiagID, Type, + Policy); + DS.SetPackIndexingExpr(EllipsisLoc, IndexExpr.get()); + return T.getCloseLocation(); +} + +void Parser::AnnotateExistingIndexedTypeNamePack(ParsedType T, + SourceLocation StartLoc, + SourceLocation EndLoc) { + // make sure we have a token we can turn into an annotation token + if (PP.isBacktrackEnabled()) { + PP.RevertCachedTokens(1); + if (!T) { + // We encountered an error in parsing 'decltype(...)' so lets annotate all + // the tokens in the backtracking cache - that we likely had to skip over + // to get to a token that allows us to resume parsing, such as a + // semi-colon. + EndLoc = PP.getLastCachedTokenLocation(); + } + } else + PP.EnterToken(Tok, /*IsReinject*/ true); + + Tok.setKind(tok::annot_pack_indexing_type); + setTypeAnnotation(Tok, T); + Tok.setAnnotationEndLoc(EndLoc); + Tok.setLocation(StartLoc); + PP.AnnotateCachedTokens(Tok); +} + DeclSpec::TST Parser::TypeTransformTokToDeclSpec() { switch (Tok.getKind()) { #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) \ @@ -1293,6 +1380,14 @@ TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc, return Actions.ActOnTypeName(DeclaratorInfo); } + if (Tok.is(tok::annot_pack_indexing_type)) { + DeclSpec DS(AttrFactory); + ParsePackIndexingType(DS); + Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), + DeclaratorContext::TypeName); + return Actions.ActOnTypeName(DeclaratorInfo); + } + // Check whether we have a template-id that names a type. if (Tok.is(tok::annot_template_id)) { TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); @@ -3836,6 +3931,10 @@ MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) { // ParseOptionalCXXScopeSpecifier at this point. // FIXME: Can we get here with a scope specifier? ParseDecltypeSpecifier(DS); + } else if (Tok.is(tok::annot_pack_indexing_type)) { + // Uses of T...[N] will already have been converted to + // annot_pack_indexing_type by ParseOptionalCXXScopeSpecifier at this point. + ParsePackIndexingType(DS); } else { TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id) ? takeTemplateIdAnnotation(Tok) diff --git a/clang/lib/Parse/ParseExpr.cpp b/clang/lib/Parse/ParseExpr.cpp index e862856a08ca1..6e83b7aa3441b 100644 --- a/clang/lib/Parse/ParseExpr.cpp +++ b/clang/lib/Parse/ParseExpr.cpp @@ -1067,6 +1067,17 @@ ExprResult Parser::ParseCastExpression(CastParseKind ParseKind, // where the syntax forbids a type. const Token &Next = NextToken(); + if (Next.is(tok::ellipsis) && Tok.is(tok::identifier) && + GetLookAheadToken(2).is(tok::l_square)) { + // Annotate the token and tail recurse. + // If the token is not annotated, then it might be an expression pack + // indexing + if (!TryAnnotateTypeOrScopeToken() && + Tok.is(tok::annot_pack_indexing_type)) + return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast, + isVectorLiteral, NotPrimaryExpression); + } + // If this identifier was reverted from a token ID, and the next token // is a parenthesis, this is likely to be a use of a type trait. Check // those tokens. @@ -1289,6 +1300,7 @@ ExprResult Parser::ParseCastExpression(CastParseKind ParseKind, /*isVectorLiteral=*/false, NotPrimaryExpression); } + Res = tryParseCXXPackIndexingExpression(Res); if (!Res.isInvalid() && Tok.is(tok::less)) checkPotentialAngleBracket(Res); break; @@ -1549,6 +1561,7 @@ ExprResult Parser::ParseCastExpression(CastParseKind ParseKind, [[fallthrough]]; case tok::annot_decltype: + case tok::annot_pack_indexing_type: case tok::kw_char: case tok::kw_wchar_t: case tok::kw_char8_t: diff --git a/clang/lib/Parse/ParseExprCXX.cpp b/clang/lib/Parse/ParseExprCXX.cpp index d61f414406f02..fd262ff31e661 100644 --- a/clang/lib/Parse/ParseExprCXX.cpp +++ b/clang/lib/Parse/ParseExprCXX.cpp @@ -233,6 +233,34 @@ bool Parser::ParseOptionalCXXScopeSpecifier( HasScopeSpecifier = true; } + else if (!HasScopeSpecifier && Tok.is(tok::identifier) && + GetLookAheadToken(1).is(tok::ellipsis) && + GetLookAheadToken(2).is(tok::l_square)) { + SourceLocation Start = Tok.getLocation(); + DeclSpec DS(AttrFactory); + SourceLocation CCLoc; + SourceLocation EndLoc = ParsePackIndexingType(DS); + if (DS.getTypeSpecType() == DeclSpec::TST_error) + return false; + + QualType Type = Actions.ActOnPackIndexingType( + DS.getRepAsType().get(), DS.getPackIndexingExpr(), DS.getBeginLoc(), + DS.getEllipsisLoc()); + + if (Type.isNull()) + return false; + + if (!TryConsumeToken(tok::coloncolon, CCLoc)) { + AnnotateExistingIndexedTypeNamePack(ParsedType::make(Type), Start, + EndLoc); + return false; + } + if (Actions.ActOnCXXNestedNameSpecifierIndexedPack(SS, DS, CCLoc, + std::move(Type))) + SS.SetInvalid(SourceRange(Start, CCLoc)); + HasScopeSpecifier = true; + } + // Preferred type might change when parsing qualifiers, we need the original. auto SavedType = PreferredType; while (true) { @@ -617,11 +645,38 @@ ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, break; } + // Might be a pack index expression! + E = tryParseCXXPackIndexingExpression(E); + if (!E.isInvalid() && !E.isUnset() && Tok.is(tok::less)) checkPotentialAngleBracket(E); return E; } +ExprResult Parser::ParseCXXPackIndexingExpression(ExprResult PackIdExpression) { + assert(Tok.is(tok::ellipsis) && NextToken().is(tok::l_square) && + "expected ...["); + SourceLocation EllipsisLoc = ConsumeToken(); + BalancedDelimiterTracker T(*this, tok::l_square); + T.consumeOpen(); + ExprResult IndexExpr = ParseConstantExpression(); + if (T.consumeClose() || IndexExpr.isInvalid()) + return ExprError(); + return Actions.ActOnPackIndexingExpr(getCurScope(), PackIdExpression.get(), + EllipsisLoc, T.getOpenLocation(), + IndexExpr.get(), T.getCloseLocation()); +} + +ExprResult +Parser::tryParseCXXPackIndexingExpression(ExprResult PackIdExpression) { + ExprResult E = PackIdExpression; + if (!PackIdExpression.isInvalid() && !PackIdExpression.isUnset() && + Tok.is(tok::ellipsis) && NextToken().is(tok::l_square)) { + E = ParseCXXPackIndexingExpression(E); + } + return E; +} + /// ParseCXXIdExpression - Handle id-expression. /// /// id-expression: @@ -1810,6 +1865,15 @@ Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, return ExprError(); } + // pack-index-specifier + if (GetLookAheadToken(1).is(tok::ellipsis) && + GetLookAheadToken(2).is(tok::l_square)) { + DeclSpec DS(AttrFactory); + ParsePackIndexingType(DS); + return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind, + TildeLoc, DS); + } + // Parse the second type. UnqualifiedId SecondTypeName; IdentifierInfo *Name = Tok.getIdentifierInfo(); @@ -2253,7 +2317,6 @@ void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) { getTypeAnnotation(Tok), Policy); DS.SetRangeEnd(Tok.getAnnotationEndLoc()); ConsumeAnnotationToken(); - DS.Finish(Actions, Policy); return; } @@ -2364,6 +2427,10 @@ void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) { DS.SetRangeEnd(ParseDecltypeSpecifier(DS)); return DS.Finish(Actions, Policy); + case tok::annot_pack_indexing_type: + DS.SetRangeEnd(ParsePackIndexingType(DS)); + return DS.Finish(Actions, Policy); + // GNU typeof support. case tok::kw_typeof: ParseTypeofSpecifier(DS); diff --git a/clang/lib/Parse/ParseTentative.cpp b/clang/lib/Parse/ParseTentative.cpp index 5bfabf55f50c4..f1737cb844767 100644 --- a/clang/lib/Parse/ParseTentative.cpp +++ b/clang/lib/Parse/ParseTentative.cpp @@ -1363,6 +1363,17 @@ Parser::isCXXDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename, }; switch (Tok.getKind()) { case tok::identifier: { + if (GetLookAheadToken(1).is(tok::ellipsis) && + GetLookAheadToken(2).is(tok::l_square)) { + + if (TryAnnotateTypeOrScopeToken()) + return TPResult::Error; + if (Tok.is(tok::identifier)) + return TPResult::False; + return isCXXDeclarationSpecifier(ImplicitTypenameContext::No, + BracedCastResult, InvalidAsDeclSpec); + } + // Check for need to substitute AltiVec __vector keyword // for "vector" identifier. if (TryAltiVecVectorToken()) @@ -1755,6 +1766,7 @@ Parser::isCXXDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename, return TPResult::True; } + [[fallthrough]]; case tok::kw_char: @@ -1782,6 +1794,7 @@ Parser::isCXXDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename, case tok::kw__Accum: case tok::kw__Fract: case tok::kw__Sat: + case tok::annot_pack_indexing_type: #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t: #include "clang/Basic/OpenCLImageTypes.def" if (NextToken().is(tok::l_paren)) @@ -1860,6 +1873,7 @@ bool Parser::isCXXDeclarationSpecifierAType() { switch (Tok.getKind()) { // typename-specifier case tok::annot_decltype: + case tok::annot_pack_indexing_type: case tok::annot_template_id: case tok::annot_typename: case tok::kw_typeof: diff --git a/clang/lib/Parse/Parser.cpp b/clang/lib/Parse/Parser.cpp index 0b092181bca7b..3dfd44677e5a2 100644 --- a/clang/lib/Parse/Parser.cpp +++ b/clang/lib/Parse/Parser.cpp @@ -1992,7 +1992,8 @@ bool Parser::TryAnnotateTypeOrScopeToken( assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) || Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) || - Tok.is(tok::kw___super) || Tok.is(tok::kw_auto)) && + Tok.is(tok::kw___super) || Tok.is(tok::kw_auto) || + Tok.is(tok::annot_pack_indexing_type)) && "Cannot be a type or scope token!"); if (Tok.is(tok::kw_typename)) { diff --git a/clang/lib/Sema/DeclSpec.cpp b/clang/lib/Sema/DeclSpec.cpp index 781f24cb71ae9..313f073445e8f 100644 --- a/clang/lib/Sema/DeclSpec.cpp +++ b/clang/lib/Sema/DeclSpec.cpp @@ -374,6 +374,7 @@ bool Declarator::isDeclarationOfFunction() const { case TST_void: case TST_wchar: case TST_BFloat16: + case TST_typename_pack_indexing: #define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t: #include "clang/Basic/OpenCLImageTypes.def" return false; @@ -585,6 +586,8 @@ const char *DeclSpec::getSpecifierName(DeclSpec::TST T, case DeclSpec::TST_struct: return "struct"; case DeclSpec::TST_interface: return "__interface"; case DeclSpec::TST_typename: return "type-name"; + case DeclSpec::TST_typename_pack_indexing: + return "type-name-pack-indexing"; case DeclSpec::TST_typeofType: case DeclSpec::TST_typeofExpr: return "typeof"; case DeclSpec::TST_typeof_unqualType: @@ -775,6 +778,15 @@ bool DeclSpec::SetTypeSpecType(TST T, SourceLocation TagKwLoc, TSTLoc = TagKwLoc; TSTNameLoc = TagNameLoc; TypeSpecOwned = false; + + if (T == TST_typename_pack_indexing) { + // we got there from a an annotation. Reconstruct the type + // Ugly... + QualType QT = Rep.get(); + const PackIndexingType *LIT = cast(QT); + TypeRep = ParsedType::make(LIT->getPattern()); + PackIndexingExpr = LIT->getIndexExpr(); + } return false; } @@ -973,6 +985,15 @@ bool DeclSpec::SetBitIntType(SourceLocation KWLoc, Expr *BitsExpr, return false; } +void DeclSpec::SetPackIndexingExpr(SourceLocation EllipsisLoc, + Expr *IndexingExpr) { + assert(TypeSpecType == TST_typename && + "pack indexing can only be applied to typename"); + TypeSpecType = TST_typename_pack_indexing; + PackIndexingExpr = IndexingExpr; + this->EllipsisLoc = EllipsisLoc; +} + bool DeclSpec::SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const LangOptions &Lang) { // Duplicates are permitted in C99 onwards, but are not permitted in C89 or diff --git a/clang/lib/Sema/SemaCXXScopeSpec.cpp b/clang/lib/Sema/SemaCXXScopeSpec.cpp index 44a40215b90df..fca5bd131bbc0 100644 --- a/clang/lib/Sema/SemaCXXScopeSpec.cpp +++ b/clang/lib/Sema/SemaCXXScopeSpec.cpp @@ -867,6 +867,29 @@ bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, return false; } +bool Sema::ActOnCXXNestedNameSpecifierIndexedPack(CXXScopeSpec &SS, + const DeclSpec &DS, + SourceLocation ColonColonLoc, + QualType Type) { + if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error) + return true; + + assert(DS.getTypeSpecType() == DeclSpec::TST_typename_pack_indexing); + + if (Type.isNull()) + return true; + + TypeLocBuilder TLB; + TLB.pushTrivial(getASTContext(), + cast(Type.getTypePtr())->getPattern(), + DS.getBeginLoc()); + PackIndexingTypeLoc PIT = TLB.push(Type); + PIT.setEllipsisLoc(DS.getEllipsisLoc()); + SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, Type), + ColonColonLoc); + return false; +} + /// IsInvalidUnlessNestedName - This method is used for error recovery /// purposes to determine whether the specified identifier is only valid as /// a nested name specifier, for example a namespace name. It is diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index f9bf1d14bdc4f..e725e187fc9ea 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -163,6 +163,7 @@ bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { case tok::kw_char32_t: case tok::kw_typeof: case tok::annot_decltype: + case tok::annot_pack_indexing_type: case tok::kw_decltype: return getLangOpts().CPlusPlus; diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp index df5bd55e7c283..5adc262cd6bc9 100644 --- a/clang/lib/Sema/SemaDeclCXX.cpp +++ b/clang/lib/Sema/SemaDeclCXX.cpp @@ -4494,6 +4494,10 @@ Sema::BuildMemInitializer(Decl *ConstructorD, } else if (DS.getTypeSpecType() == TST_decltype_auto) { Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); return true; + } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) { + BaseType = + BuildPackIndexingType(DS.getRepAsType().get(), DS.getPackIndexingExpr(), + DS.getBeginLoc(), DS.getEllipsisLoc()); } else { LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); LookupParsedName(R, S, &SS); diff --git a/clang/lib/Sema/SemaExceptionSpec.cpp b/clang/lib/Sema/SemaExceptionSpec.cpp index 75730ea888afb..8d58ef5ee16d5 100644 --- a/clang/lib/Sema/SemaExceptionSpec.cpp +++ b/clang/lib/Sema/SemaExceptionSpec.cpp @@ -1410,6 +1410,7 @@ CanThrowResult Sema::canThrow(const Stmt *S) { case Expr::OpaqueValueExprClass: case Expr::PredefinedExprClass: case Expr::SizeOfPackExprClass: + case Expr::PackIndexingExprClass: case Expr::StringLiteralClass: case Expr::SourceLocExprClass: case Expr::ConceptSpecializationExprClass: diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 790ea217ef819..2f1ddfb215116 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -4715,6 +4715,9 @@ static void captureVariablyModifiedType(ASTContext &Context, QualType T, case Type::Decltype: T = cast(Ty)->desugar(); break; + case Type::PackIndexing: + T = cast(Ty)->desugar(); + break; case Type::Using: T = cast(Ty)->desugar(); break; diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp index 953bfe484a528..51c61886739bb 100644 --- a/clang/lib/Sema/SemaExprCXX.cpp +++ b/clang/lib/Sema/SemaExprCXX.cpp @@ -8099,20 +8099,36 @@ ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation TildeLoc, const DeclSpec& DS) { QualType ObjectType; + QualType T; + TypeLocBuilder TLB; if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) return ExprError(); - if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) { + switch (DS.getTypeSpecType()) { + case DeclSpec::TST_decltype_auto: { Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); return true; } - - QualType T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false); - - TypeLocBuilder TLB; - DecltypeTypeLoc DecltypeTL = TLB.push(T); - DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); - DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd()); + case DeclSpec::TST_decltype: { + T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false); + DecltypeTypeLoc DecltypeTL = TLB.push(T); + DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); + DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd()); + break; + } + case DeclSpec::TST_typename_pack_indexing: { + T = ActOnPackIndexingType(DS.getRepAsType().get(), DS.getPackIndexingExpr(), + DS.getBeginLoc(), DS.getEllipsisLoc()); + TLB.pushTrivial(getASTContext(), + cast(T.getTypePtr())->getPattern(), + DS.getBeginLoc()); + PackIndexingTypeLoc PITL = TLB.push(T); + PITL.setEllipsisLoc(DS.getEllipsisLoc()); + break; + } + default: + llvm_unreachable("Unsupported type in pseudo destructor"); + } TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T); PseudoDestructorTypeStorage Destructed(DestructedTypeInfo); diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp index 9bfa71dc8bcf1..3f33ecb89502e 100644 --- a/clang/lib/Sema/SemaTemplate.cpp +++ b/clang/lib/Sema/SemaTemplate.cpp @@ -6440,6 +6440,11 @@ bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) { return false; } +bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType( + const PackIndexingType *) { + return false; +} + bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType( const UnaryTransformType*) { return false; diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp b/clang/lib/Sema/SemaTemplateDeduction.cpp index e9e7ab5bb6698..c9234bf30a528 100644 --- a/clang/lib/Sema/SemaTemplateDeduction.cpp +++ b/clang/lib/Sema/SemaTemplateDeduction.cpp @@ -646,6 +646,7 @@ static bool IsPossiblyOpaquelyQualifiedTypeInternal(const Type *T) { case Type::TypeOf: case Type::DependentName: case Type::Decltype: + case Type::PackIndexing: case Type::UnresolvedUsing: case Type::TemplateTypeParm: return true; @@ -2244,6 +2245,15 @@ static Sema::TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch( case Type::Pipe: // No template argument deduction for these types return Sema::TDK_Success; + + case Type::PackIndexing: { + const PackIndexingType *PIT = P->getAs(); + if (PIT->hasSelectedType()) { + return DeduceTemplateArgumentsByTypeMatch( + S, TemplateParams, PIT->getSelectedType(), A, Info, Deduced, TDF); + } + return Sema::TDK_IncompletePack; + } } llvm_unreachable("Invalid Type Class!"); @@ -6422,6 +6432,15 @@ MarkUsedTemplateParameters(ASTContext &Ctx, QualType T, OnlyDeduced, Depth, Used); break; + case Type::PackIndexing: + if (!OnlyDeduced) { + MarkUsedTemplateParameters(Ctx, cast(T)->getPattern(), + OnlyDeduced, Depth, Used); + MarkUsedTemplateParameters(Ctx, cast(T)->getIndexExpr(), + OnlyDeduced, Depth, Used); + } + break; + case Type::UnaryTransform: if (!OnlyDeduced) MarkUsedTemplateParameters(Ctx, diff --git a/clang/lib/Sema/SemaTemplateVariadic.cpp b/clang/lib/Sema/SemaTemplateVariadic.cpp index 4a7872b2cc73c..903fbfd18e779 100644 --- a/clang/lib/Sema/SemaTemplateVariadic.cpp +++ b/clang/lib/Sema/SemaTemplateVariadic.cpp @@ -184,6 +184,15 @@ namespace { bool TraversePackExpansionTypeLoc(PackExpansionTypeLoc TL) { return true; } bool TraversePackExpansionExpr(PackExpansionExpr *E) { return true; } bool TraverseCXXFoldExpr(CXXFoldExpr *E) { return true; } + bool TraversePackIndexingExpr(PackIndexingExpr *E) { + return inherited::TraverseStmt(E->getIndexExpr()); + } + bool TraversePackIndexingType(PackIndexingType *E) { + return inherited::TraverseStmt(E->getIndexExpr()); + } + bool TraversePackIndexingTypeLoc(PackIndexingTypeLoc TL) { + return inherited::TraverseStmt(TL.getIndexExpr()); + } ///@} @@ -865,6 +874,7 @@ std::optional Sema::getNumArgumentsInExpansion( bool Sema::containsUnexpandedParameterPacks(Declarator &D) { const DeclSpec &DS = D.getDeclSpec(); switch (DS.getTypeSpecType()) { + case TST_typename_pack_indexing: case TST_typename: case TST_typeof_unqualType: case TST_typeofType: @@ -1050,8 +1060,7 @@ ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S, } if (!ParameterPack || !ParameterPack->isParameterPack()) { - Diag(NameLoc, diag::err_sizeof_pack_no_pack_name) - << &Name; + Diag(NameLoc, diag::err_expected_name_of_pack) << &Name; return ExprError(); } @@ -1061,6 +1070,65 @@ ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S, RParenLoc); } +static bool isParameterPack(Expr *PackExpression) { + if (auto *D = dyn_cast(PackExpression); D) { + ValueDecl *VD = D->getDecl(); + return VD->isParameterPack(); + } + return false; +} + +ExprResult Sema::ActOnPackIndexingExpr(Scope *S, Expr *PackExpression, + SourceLocation EllipsisLoc, + SourceLocation LSquareLoc, + Expr *IndexExpr, + SourceLocation RSquareLoc) { + bool isParameterPack = ::isParameterPack(PackExpression); + if (!isParameterPack) { + CorrectDelayedTyposInExpr(IndexExpr); + Diag(PackExpression->getBeginLoc(), diag::err_expected_name_of_pack) + << PackExpression; + return ExprError(); + } + ExprResult Res = + BuildPackIndexingExpr(PackExpression, EllipsisLoc, IndexExpr, RSquareLoc); + if (!Res.isInvalid()) + Diag(Res.get()->getBeginLoc(), getLangOpts().CPlusPlus26 + ? diag::warn_cxx23_pack_indexing + : diag::ext_pack_indexing); + return Res; +} + +ExprResult +Sema::BuildPackIndexingExpr(Expr *PackExpression, SourceLocation EllipsisLoc, + Expr *IndexExpr, SourceLocation RSquareLoc, + ArrayRef ExpandedExprs, bool EmptyPack) { + + std::optional Index; + if (!IndexExpr->isInstantiationDependent()) { + llvm::APSInt Value(Context.getIntWidth(Context.getSizeType())); + + ExprResult Res = CheckConvertedConstantExpression( + IndexExpr, Context.getSizeType(), Value, CCEK_ArrayBound); + if (!Res.isUsable()) + return ExprError(); + Index = Value.getExtValue(); + IndexExpr = Res.get(); + } + + if (Index && (!ExpandedExprs.empty() || EmptyPack)) { + if (*Index < 0 || EmptyPack || *Index >= int64_t(ExpandedExprs.size())) { + Diag(PackExpression->getBeginLoc(), diag::err_pack_index_out_of_bound) + << *Index << PackExpression << ExpandedExprs.size(); + return ExprError(); + } + } + + return PackIndexingExpr::Create(getASTContext(), EllipsisLoc, RSquareLoc, + PackExpression, IndexExpr, Index, + ExpandedExprs); +} + TemplateArgumentLoc Sema::getTemplateArgumentPackExpansionPattern( TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, std::optional &NumExpansions) const { diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp index 92086d7277fd1..7cee73d5d6bae 100644 --- a/clang/lib/Sema/SemaType.cpp +++ b/clang/lib/Sema/SemaType.cpp @@ -1667,6 +1667,19 @@ static QualType ConvertDeclSpecToType(TypeProcessingState &state) { } break; } + case DeclSpec::TST_typename_pack_indexing: { + Expr *E = DS.getPackIndexingExpr(); + assert(E && "Didn't get an expression for pack indexing"); + QualType Pattern = S.GetTypeFromParser(DS.getRepAsType()); + Result = S.BuildPackIndexingType(Pattern, E, DS.getBeginLoc(), + DS.getEllipsisLoc()); + if (Result.isNull()) { + declarator.setInvalidType(true); + Result = Context.IntTy; + } + break; + } + #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait: #include "clang/Basic/TransformTypeTraits.def" Result = S.GetTypeFromParser(DS.getRepAsType()); @@ -6312,6 +6325,10 @@ namespace { TL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); TL.setRParenLoc(DS.getTypeofParensRange().getEnd()); } + void VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) { + assert(DS.getTypeSpecType() == DeclSpec::TST_typename_pack_indexing); + TL.setEllipsisLoc(DS.getEllipsisLoc()); + } void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { assert(DS.isTransformTypeTrait(DS.getTypeSpecType())); TL.setKWLoc(DS.getTypeSpecTypeLoc()); @@ -9727,6 +9744,9 @@ QualType Sema::getDecltypeForExpr(Expr *E) { if (auto *ImplCastExpr = dyn_cast(E)) IDExpr = ImplCastExpr->getSubExpr(); + if (auto *PackExpr = dyn_cast(E)) + IDExpr = PackExpr->getSelectedExpr(); + // C++11 [dcl.type.simple]p4: // The type denoted by decltype(e) is defined as follows: @@ -9798,6 +9818,54 @@ QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) { return Context.getDecltypeType(E, getDecltypeForExpr(E)); } +QualType Sema::ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr, + SourceLocation Loc, + SourceLocation EllipsisLoc) { + if (!IndexExpr) + return QualType(); + + // Diagnose unexpanded packs but continue to improve recovery. + if (!Pattern->containsUnexpandedParameterPack()) + Diag(Loc, diag::err_expected_name_of_pack) << Pattern; + + QualType Type = BuildPackIndexingType(Pattern, IndexExpr, Loc, EllipsisLoc); + + if (!Type.isNull()) + Diag(Loc, getLangOpts().CPlusPlus26 ? diag::warn_cxx23_pack_indexing + : diag::ext_pack_indexing); + return Type; +} + +QualType Sema::BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, + SourceLocation Loc, + SourceLocation EllipsisLoc, + bool FullySubstituted, + ArrayRef Expansions) { + + std::optional Index; + if (FullySubstituted && !IndexExpr->isValueDependent() && + !IndexExpr->isTypeDependent()) { + llvm::APSInt Value(Context.getIntWidth(Context.getSizeType())); + ExprResult Res = CheckConvertedConstantExpression( + IndexExpr, Context.getSizeType(), Value, CCEK_ArrayBound); + if (!Res.isUsable()) + return QualType(); + Index = Value.getExtValue(); + IndexExpr = Res.get(); + } + + if (FullySubstituted && Index) { + if (*Index < 0 || *Index >= int64_t(Expansions.size())) { + Diag(IndexExpr->getBeginLoc(), diag::err_pack_index_out_of_bound) + << *Index << Pattern << Expansions.size(); + return QualType(); + } + } + + return Context.getPackIndexingType(Pattern, IndexExpr, FullySubstituted, + Expansions, Index.value_or(-1)); +} + static QualType GetEnumUnderlyingType(Sema &S, QualType BaseType, SourceLocation Loc) { assert(BaseType->isEnumeralType()); diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h index 40028544e23c8..2922924e550d0 100644 --- a/clang/lib/Sema/TreeTransform.h +++ b/clang/lib/Sema/TreeTransform.h @@ -1047,6 +1047,12 @@ class TreeTransform { /// Subclasses may override this routine to provide different behavior. QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc); + QualType RebuildPackIndexingType(QualType Pattern, Expr *IndexExpr, + SourceLocation Loc, + SourceLocation EllipsisLoc, + bool FullySubstituted, + ArrayRef Expansions = {}); + /// Build a new C++11 auto type. /// /// By default, builds a new AutoType with the given deduced type. @@ -3582,6 +3588,16 @@ class TreeTransform { RParenLoc, Length, PartialArgs); } + ExprResult RebuildPackIndexingExpr(SourceLocation EllipsisLoc, + SourceLocation RSquareLoc, + Expr *PackIdExpression, Expr *IndexExpr, + ArrayRef ExpandedExprs, + bool EmptyPack = false) { + return getSema().BuildPackIndexingExpr(PackIdExpression, EllipsisLoc, + IndexExpr, RSquareLoc, ExpandedExprs, + EmptyPack); + } + /// Build a new expression representing a call to a source location /// builtin. /// @@ -6482,6 +6498,100 @@ QualType TreeTransform::TransformDecltypeType(TypeLocBuilder &TLB, return Result; } +template +QualType +TreeTransform::TransformPackIndexingType(TypeLocBuilder &TLB, + PackIndexingTypeLoc TL) { + // Transform the index + ExprResult IndexExpr = getDerived().TransformExpr(TL.getIndexExpr()); + if (IndexExpr.isInvalid()) + return QualType(); + QualType Pattern = TL.getPattern(); + + const PackIndexingType *PIT = TL.getTypePtr(); + SmallVector SubtitutedTypes; + llvm::ArrayRef Types = PIT->getExpansions(); + + bool NotYetExpanded = Types.empty(); + bool FullySubstituted = true; + + if (Types.empty()) + Types = llvm::ArrayRef(&Pattern, 1); + + for (const QualType &T : Types) { + if (!T->containsUnexpandedParameterPack()) { + QualType Transformed = getDerived().TransformType(T); + if (Transformed.isNull()) + return QualType(); + SubtitutedTypes.push_back(Transformed); + continue; + } + + SmallVector Unexpanded; + getSema().collectUnexpandedParameterPacks(T, Unexpanded); + assert(!Unexpanded.empty() && "Pack expansion without parameter packs?"); + // Determine whether the set of unexpanded parameter packs can and should + // be expanded. + bool ShouldExpand = true; + bool RetainExpansion = false; + std::optional OrigNumExpansions; + std::optional NumExpansions = OrigNumExpansions; + if (getDerived().TryExpandParameterPacks(TL.getEllipsisLoc(), SourceRange(), + Unexpanded, ShouldExpand, + RetainExpansion, NumExpansions)) + return QualType(); + if (!ShouldExpand) { + Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1); + QualType Pack = getDerived().TransformType(T); + if (Pack.isNull()) + return QualType(); + if (NotYetExpanded) { + FullySubstituted = false; + QualType Out = getDerived().RebuildPackIndexingType( + Pack, IndexExpr.get(), SourceLocation(), TL.getEllipsisLoc(), + FullySubstituted); + if (Out.isNull()) + return QualType(); + + PackIndexingTypeLoc Loc = TLB.push(Out); + Loc.setEllipsisLoc(TL.getEllipsisLoc()); + return Out; + } + SubtitutedTypes.push_back(Pack); + continue; + } + for (unsigned I = 0; I != *NumExpansions; ++I) { + Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I); + QualType Out = getDerived().TransformType(T); + if (Out.isNull()) + return QualType(); + SubtitutedTypes.push_back(Out); + } + // If we're supposed to retain a pack expansion, do so by temporarily + // forgetting the partially-substituted parameter pack. + if (RetainExpansion) { + FullySubstituted = false; + ForgetPartiallySubstitutedPackRAII Forget(getDerived()); + QualType Out = getDerived().TransformType(T); + if (Out.isNull()) + return QualType(); + SubtitutedTypes.push_back(Out); + } + } + + QualType Result = getDerived().TransformType(TLB, TL.getPatternLoc()); + + QualType Out = getDerived().RebuildPackIndexingType( + Result, IndexExpr.get(), SourceLocation(), TL.getEllipsisLoc(), + FullySubstituted, SubtitutedTypes); + if (Out.isNull()) + return Out; + + PackIndexingTypeLoc Loc = TLB.push(Out); + Loc.setEllipsisLoc(TL.getEllipsisLoc()); + return Out; +} + template QualType TreeTransform::TransformUnaryTransformType( TypeLocBuilder &TLB, @@ -14158,6 +14268,87 @@ TreeTransform::TransformSizeOfPackExpr(SizeOfPackExpr *E) { Args.size(), std::nullopt); } +template +ExprResult +TreeTransform::TransformPackIndexingExpr(PackIndexingExpr *E) { + if (!E->isValueDependent()) + return E; + + // Transform the index + ExprResult IndexExpr = getDerived().TransformExpr(E->getIndexExpr()); + if (IndexExpr.isInvalid()) + return ExprError(); + + SmallVector ExpandedExprs; + if (E->getExpressions().empty()) { + Expr *Pattern = E->getPackIdExpression(); + SmallVector Unexpanded; + getSema().collectUnexpandedParameterPacks(E->getPackIdExpression(), + Unexpanded); + assert(!Unexpanded.empty() && "Pack expansion without parameter packs?"); + + // Determine whether the set of unexpanded parameter packs can and should + // be expanded. + bool ShouldExpand = true; + bool RetainExpansion = false; + std::optional OrigNumExpansions; + std::optional NumExpansions = OrigNumExpansions; + if (getDerived().TryExpandParameterPacks( + E->getEllipsisLoc(), Pattern->getSourceRange(), Unexpanded, + ShouldExpand, RetainExpansion, NumExpansions)) + return true; + if (!ShouldExpand) { + Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1); + ExprResult Pack = getDerived().TransformExpr(Pattern); + if (Pack.isInvalid()) + return ExprError(); + return getDerived().RebuildPackIndexingExpr( + E->getEllipsisLoc(), E->getRSquareLoc(), Pack.get(), IndexExpr.get(), + std::nullopt); + } + for (unsigned I = 0; I != *NumExpansions; ++I) { + Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I); + ExprResult Out = getDerived().TransformExpr(Pattern); + if (Out.isInvalid()) + return true; + if (Out.get()->containsUnexpandedParameterPack()) { + Out = getDerived().RebuildPackExpansion(Out.get(), E->getEllipsisLoc(), + OrigNumExpansions); + if (Out.isInvalid()) + return true; + } + ExpandedExprs.push_back(Out.get()); + } + // If we're supposed to retain a pack expansion, do so by temporarily + // forgetting the partially-substituted parameter pack. + if (RetainExpansion) { + ForgetPartiallySubstitutedPackRAII Forget(getDerived()); + + ExprResult Out = getDerived().TransformExpr(Pattern); + if (Out.isInvalid()) + return true; + + Out = getDerived().RebuildPackExpansion(Out.get(), E->getEllipsisLoc(), + OrigNumExpansions); + if (Out.isInvalid()) + return true; + ExpandedExprs.push_back(Out.get()); + } + } + + else { + if (getDerived().TransformExprs(E->getExpressions().data(), + E->getExpressions().size(), false, + ExpandedExprs)) + return ExprError(); + } + + return getDerived().RebuildPackIndexingExpr( + E->getEllipsisLoc(), E->getRSquareLoc(), E->getPackIdExpression(), + IndexExpr.get(), ExpandedExprs, + /*EmptyPack=*/ExpandedExprs.size() == 0); +} + template ExprResult TreeTransform::TransformSubstNonTypeTemplateParmPackExpr( @@ -15199,6 +15390,15 @@ QualType TreeTransform::RebuildDecltypeType(Expr *E, SourceLocation) { return SemaRef.BuildDecltypeType(E); } +template +QualType TreeTransform::RebuildPackIndexingType( + QualType Pattern, Expr *IndexExpr, SourceLocation Loc, + SourceLocation EllipsisLoc, bool FullySubstituted, + ArrayRef Expansions) { + return SemaRef.BuildPackIndexingType(Pattern, IndexExpr, Loc, EllipsisLoc, + FullySubstituted, Expansions); +} + template QualType TreeTransform::RebuildUnaryTransformType(QualType BaseType, UnaryTransformType::UTTKind UKind, diff --git a/clang/lib/Serialization/ASTReader.cpp b/clang/lib/Serialization/ASTReader.cpp index fecd94e875f67..89b044a61a7b1 100644 --- a/clang/lib/Serialization/ASTReader.cpp +++ b/clang/lib/Serialization/ASTReader.cpp @@ -6946,6 +6946,10 @@ void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { TL.setRParenLoc(readSourceLocation()); } +void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) { + TL.setEllipsisLoc(readSourceLocation()); +} + void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { TL.setKWLoc(readSourceLocation()); TL.setLParenLoc(readSourceLocation()); diff --git a/clang/lib/Serialization/ASTReaderStmt.cpp b/clang/lib/Serialization/ASTReaderStmt.cpp index 85ecfa1a1a0bf..d79f194fd16c6 100644 --- a/clang/lib/Serialization/ASTReaderStmt.cpp +++ b/clang/lib/Serialization/ASTReaderStmt.cpp @@ -2174,6 +2174,18 @@ void ASTStmtReader::VisitSizeOfPackExpr(SizeOfPackExpr *E) { } } +void ASTStmtReader::VisitPackIndexingExpr(PackIndexingExpr *E) { + VisitExpr(E); + E->TransformedExpressions = Record.readInt(); + E->EllipsisLoc = readSourceLocation(); + E->RSquareLoc = readSourceLocation(); + E->SubExprs[0] = Record.readStmt(); + E->SubExprs[1] = Record.readStmt(); + auto **Exprs = E->getTrailingObjects(); + for (unsigned I = 0; I < E->TransformedExpressions; ++I) + Exprs[I] = Record.readExpr(); +} + void ASTStmtReader::VisitSubstNonTypeTemplateParmExpr( SubstNonTypeTemplateParmExpr *E) { VisitExpr(E); @@ -4102,6 +4114,12 @@ Stmt *ASTReader::ReadStmtFromStream(ModuleFile &F) { /*NumPartialArgs=*/Record[ASTStmtReader::NumExprFields]); break; + case EXPR_PACK_INDEXING: + S = PackIndexingExpr::CreateDeserialized( + Context, + /*TransformedExprs=*/Record[ASTStmtReader::NumExprFields]); + break; + case EXPR_SUBST_NON_TYPE_TEMPLATE_PARM: S = new (Context) SubstNonTypeTemplateParmExpr(Empty); break; diff --git a/clang/lib/Serialization/ASTWriter.cpp b/clang/lib/Serialization/ASTWriter.cpp index 03bddfe0f5047..eb2f8e2371099 100644 --- a/clang/lib/Serialization/ASTWriter.cpp +++ b/clang/lib/Serialization/ASTWriter.cpp @@ -482,6 +482,10 @@ void ASTRecordWriter::AddConceptReference(const ConceptReference *CR) { AddASTTemplateArgumentListInfo(CR->getTemplateArgsAsWritten()); } +void TypeLocWriter::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) { + addSourceLocation(TL.getEllipsisLoc()); +} + void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) { addSourceLocation(TL.getNameLoc()); auto *CR = TL.getConceptReference(); @@ -784,6 +788,7 @@ static void AddStmtsExprs(llvm::BitstreamWriter &Stream, RECORD(EXPR_ARRAY_TYPE_TRAIT); RECORD(EXPR_PACK_EXPANSION); RECORD(EXPR_SIZEOF_PACK); + RECORD(EXPR_PACK_INDEXING); RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM); RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK); RECORD(EXPR_FUNCTION_PARM_PACK); diff --git a/clang/lib/Serialization/ASTWriterStmt.cpp b/clang/lib/Serialization/ASTWriterStmt.cpp index e5836f5dcbe95..5b0b90234c410 100644 --- a/clang/lib/Serialization/ASTWriterStmt.cpp +++ b/clang/lib/Serialization/ASTWriterStmt.cpp @@ -2153,6 +2153,19 @@ void ASTStmtWriter::VisitSizeOfPackExpr(SizeOfPackExpr *E) { Code = serialization::EXPR_SIZEOF_PACK; } +void ASTStmtWriter::VisitPackIndexingExpr(PackIndexingExpr *E) { + VisitExpr(E); + Record.push_back(E->TransformedExpressions); + Record.AddSourceLocation(E->getEllipsisLoc()); + Record.AddSourceLocation(E->getRSquareLoc()); + Record.AddStmt(E->getPackIdExpression()); + Record.AddStmt(E->getIndexExpr()); + Record.push_back(E->TransformedExpressions); + for (Expr *Sub : E->getExpressions()) + Record.AddStmt(Sub); + Code = serialization::EXPR_PACK_INDEXING; +} + void ASTStmtWriter::VisitSubstNonTypeTemplateParmExpr( SubstNonTypeTemplateParmExpr *E) { VisitExpr(E); diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp index 24e91a22fd688..ccc3c0f1e0c10 100644 --- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp +++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp @@ -1737,6 +1737,7 @@ void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred, case Stmt::RecoveryExprClass: case Stmt::CXXNoexceptExprClass: case Stmt::PackExpansionExprClass: + case Stmt::PackIndexingExprClass: case Stmt::SubstNonTypeTemplateParmPackExprClass: case Stmt::FunctionParmPackExprClass: case Stmt::CoroutineBodyStmtClass: diff --git a/clang/test/AST/ast-dump-templates.cpp b/clang/test/AST/ast-dump-templates.cpp index 3d26eb917c120..d25ef36dd4d32 100644 --- a/clang/test/AST/ast-dump-templates.cpp +++ b/clang/test/AST/ast-dump-templates.cpp @@ -45,9 +45,9 @@ template struct A { template struct B {}; }; -// CHECK1-LABEL: template void f(T ...[3]) { +// CHECK1-LABEL: template void f() { // CHECK1-NEXT: A a; -template void f(T ...[3]) { +template void f() { A a; } diff --git a/clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p13.cpp b/clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p13.cpp index 9cc13b4efb80f..dbb6e60d9b93d 100644 --- a/clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p13.cpp +++ b/clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p13.cpp @@ -57,7 +57,9 @@ template void b(T[] ...); template -void c(T ... []); // expected-error{{type 'T[]' of function parameter pack does not contain any unexpanded parameter packs}} +void c(T ... []); // expected-error {{expected expression}} \ + // expected-error {{'T' does not refer to the name of a parameter pack}} \ + // expected-warning {{pack indexing is a C++2c extension}} template void d(T ... x[]); // expected-error{{type 'T[]' of function parameter pack does not contain any unexpanded parameter packs}} diff --git a/clang/test/PCH/pack_indexing.cpp b/clang/test/PCH/pack_indexing.cpp new file mode 100644 index 0000000000000..cf8124617b3c6 --- /dev/null +++ b/clang/test/PCH/pack_indexing.cpp @@ -0,0 +1,16 @@ +// RUN: %clang_cc1 -std=c++2c -x c++-header %s -emit-pch -o %t.pch +// RUN: %clang_cc1 -std=c++2c -x c++ /dev/null -include-pch %t.pch + +// RUN: %clang_cc1 -std=c++2c -x c++-header %s -emit-pch -fpch-instantiate-templates -o %t.pch +// RUN: %clang_cc1 -std=c++2c -x c++ /dev/null -include-pch %t.pch + +template +using Type = U...[I]; + +template +constexpr auto Var = V...[I]; + +void fn1() { + using A = Type<1, int, long, double>; + constexpr auto V = Var<2, 0, 1, 42>; +} diff --git a/clang/test/Parser/cxx0x-ambig.cpp b/clang/test/Parser/cxx0x-ambig.cpp index 7f3398ad1386c..9a266aac88512 100644 --- a/clang/test/Parser/cxx0x-ambig.cpp +++ b/clang/test/Parser/cxx0x-ambig.cpp @@ -122,9 +122,8 @@ namespace ellipsis { void f(S(...args[sizeof(T)])); // expected-note {{here}} expected-note {{here}} void f(S(...args)[sizeof(T)]); // expected-error {{redeclared}} void f(S ...args[sizeof(T)]); // expected-error {{redeclared}} - void g(S(...[sizeof(T)])); // expected-note {{here}} expected-warning {{ISO C++11 requires a parenthesized pack declaration to have a name}} + void g(S(...[sizeof(T)])); // expected-warning {{ISO C++11 requires a parenthesized pack declaration to have a name}} void g(S(...)[sizeof(T)]); // expected-error {{function cannot return array type}} - void g(S ...[sizeof(T)]); // expected-error {{redeclared}} void h(T(...)); // function type, expected-error {{unexpanded parameter pack}} void h(T...); // pack expansion, ok void i(int(T...)); // expected-note {{here}} diff --git a/clang/test/Parser/cxx0x-decl.cpp b/clang/test/Parser/cxx0x-decl.cpp index 8be98d6ef2998..18095a4d989dd 100644 --- a/clang/test/Parser/cxx0x-decl.cpp +++ b/clang/test/Parser/cxx0x-decl.cpp @@ -213,8 +213,13 @@ struct MemberComponentOrder : Base { void NoMissingSemicolonHere(struct S [3]); -template void NoMissingSemicolonHereEither(struct S - ... [N]); +template void NoMissingSemicolonHereEither(struct S... [N]); +// expected-error@-1 {{'S' does not refer to the name of a parameter pack}} \ +// expected-error@-1 {{declaration of anonymous struct must be a definition}} \ +// expected-error@-1 {{expected parameter declarator}} \ +// expected-error@-1 {{pack indexing is a C++2c extension}} \ + + // This must be at the end of the file; we used to look ahead past the EOF token here. // expected-error@+1 {{expected unqualified-id}} expected-error@+1{{expected ';'}} diff --git a/clang/test/Parser/cxx2c-pack-indexing.cpp b/clang/test/Parser/cxx2c-pack-indexing.cpp new file mode 100644 index 0000000000000..1b84ddfc6c20a --- /dev/null +++ b/clang/test/Parser/cxx2c-pack-indexing.cpp @@ -0,0 +1,65 @@ +// RUN: %clang_cc1 -std=c++2c -verify -fsyntax-only %s + +template +struct S { + T...1; // expected-error{{expected member name or ';' after declaration specifiers}} + T...[; // expected-error{{expected expression}} \ + // expected-error{{expected ']'}} \ + // expected-note {{to match this '['}} \ + // expected-warning{{declaration does not declare anything}} + + T...[1; // expected-error{{expected ']'}} \ + // expected-note {{to match this '['}} \ + // expected-warning{{declaration does not declare anything}} + + T...[]; // expected-error{{expected expression}} \ + // expected-warning{{declaration does not declare anything}} + + void f(auto... v) { + decltype(v...[1]) a = v...[1]; + decltype(v...[1]) b = v...[]; // expected-error{{expected expression}} + + decltype(v...[1]) c = v...[ ; // expected-error{{expected expression}}\ + // expected-error{{expected ']'}} \ + // expected-note {{to match this '['}} + } +}; + + +template +struct typelist{}; + +template +requires requires(T...[0]) { {T...[0](0)}; } +struct SS : T...[1] { + [[maybe_unused]] T...[1] base = {}; + using foo = T...[1]; + SS() + : T...[1]() + {} + typelist a; + const T...[0] f(T...[0] && p) noexcept((T...[0])0) { + T...[0] (*test)(const volatile T...[0]**); + thread_local T...[0] d; + [[maybe_unused]] T...[0] a = p; + auto ptr = new T...[0](0); + (*ptr).~T...[0](); + return T...[0](0); + typename T...[1]::foo b = 0; + T...[1]::i = 0; + return (T...[0])(a); + new T...[0]; + [[maybe_unused]] auto l = [](T...[0][1]) -> T...[0]{return{};}; + [[maybe_unused]] auto _ = l.template operator()({0}); + } + operator T...[0]() const{} +}; + +struct base { + using foo = int; + static inline int i = 42; +}; + +int main() { + SS().f(0); +} diff --git a/clang/test/SemaCXX/cxx2c-pack-indexing-ext-diags.cpp b/clang/test/SemaCXX/cxx2c-pack-indexing-ext-diags.cpp new file mode 100644 index 0000000000000..80dfeb9b6a8bf --- /dev/null +++ b/clang/test/SemaCXX/cxx2c-pack-indexing-ext-diags.cpp @@ -0,0 +1,21 @@ +// RUN: %clang_cc1 -std=c++2c -verify=cxx26 -fsyntax-only -Wpre-c++26-compat %s +// RUN: %clang_cc1 -std=c++11 -verify=cxx11 -fsyntax-only -Wc++26-extensions %s + +template +void f(T... t) { + // cxx26-warning@+2 {{pack indexing is incompatible with C++ standards before C++2c}} + // cxx11-warning@+1 {{pack indexing is a C++2c extension}} + using a = T...[0]; + + // cxx26-warning@+2 {{pack indexing is incompatible with C++ standards before C++2c}} + // cxx11-warning@+1 {{pack indexing is a C++2c extension}} + using b = typename T...[0]::a; + + // cxx26-warning@+2 2{{pack indexing is incompatible with C++ standards before C++2c}} + // cxx11-warning@+1 2{{pack indexing is a C++2c extension}} + t...[0].~T...[0](); + + // cxx26-warning@+2 {{pack indexing is incompatible with C++ standards before C++2c}} + // cxx11-warning@+1 {{pack indexing is a C++2c extension}} + T...[0] c; +} diff --git a/clang/test/SemaCXX/cxx2c-pack-indexing.cpp b/clang/test/SemaCXX/cxx2c-pack-indexing.cpp new file mode 100644 index 0000000000000..bd75c1180a1c1 --- /dev/null +++ b/clang/test/SemaCXX/cxx2c-pack-indexing.cpp @@ -0,0 +1,122 @@ +// RUN: %clang_cc1 -std=c++2c -verify %s + +struct NotAPack; +template typename Tp> +void not_pack() { + int i = 0; + i...[0]; // expected-error {{i does not refer to the name of a parameter pack}} + V...[0]; // expected-error {{V does not refer to the name of a parameter pack}} + NotAPack...[0] a; // expected-error{{'NotAPack' does not refer to the name of a parameter pack}} + T...[0] b; // expected-error{{'T' does not refer to the name of a parameter pack}} + Tp...[0] c; // expected-error{{'Tp' does not refer to the name of a parameter pack}} +} + +namespace invalid_indexes { + +int non_constant_index(); // expected-note 2{{declared here}} + +template +int params(auto... p) { + return p...[idx]; // #error-param-size +} + +template +int test_types() { + T...[N] a; // #error-type-size +} + +void test() { + params<0>(); // expected-note{{here}} \ + // expected-error@#error-param-size {{invalid index 0 for pack p of size 0}} + params<1>(0); // expected-note{{here}} \ + // expected-error@#error-param-size {{invalid index 1 for pack p of size 1}} + params<-1>(0); // expected-note{{here}} \ + // expected-error@#error-param-size {{invalid index -1 for pack p of size 1}} + + test_types<-1>(); //expected-note {{in instantiation}} \ + // expected-error@#error-type-size {{invalid index -1 for pack 'T' of size 0}} + test_types<-1, int>(); //expected-note {{in instantiation}} \ + // expected-error@#error-type-size {{invalid index -1 for pack 'T' of size 1}} + test_types<0>(); //expected-note {{in instantiation}} \ + // expected-error@#error-type-size {{invalid index 0 for pack 'T' of size 0}} + test_types<1, int>(); //expected-note {{in instantiation}} \ + // expected-error@#error-type-size {{invalid index 1 for pack 'T' of size 1}} +} + +void invalid_indexes(auto... p) { + p...[non_constant_index()]; // expected-error {{array size is not a constant expression}}\ + // expected-note {{cannot be used in a constant expression}} + + const char* no_index = ""; + p...[no_index]; // expected-error {{value of type 'const char *' is not implicitly convertible}} +} + +void invalid_index_types() { + [] { + T...[non_constant_index()] a; // expected-error {{array size is not a constant expression}}\ + // expected-note {{cannot be used in a constant expression}} + }(); //expected-note {{in instantiation}} +} + +} + +template +constexpr bool is_same = false; + +template +constexpr bool is_same = true; + +template +constexpr bool f(auto&&... p) { + return is_same; +} + +void g() { + int a = 0; + const int b = 0; + static_assert(f(0)); + static_assert(f(a)); + static_assert(f(b)); +} + +template +struct check_ice { + enum e { + x = p...[0] + }; +}; + +static_assert(check_ice<42>::x == 42); + +struct S{}; +template +constexpr auto constant_initializer = p...[0]; +constexpr auto InitOk = constant_initializer; + +consteval int evaluate(auto... p) { + return p...[0]; +} +constexpr int x = evaluate(42, S{}); +static_assert(x == 42); + + +namespace splice { +template +struct IL{}; + +template +struct TL{}; + +template +struct SpliceImpl; + +template +struct SpliceImpl, IL>{ + using type = TL; +}; + +template +using Splice = typename SpliceImpl::type; +using type = Splice, IL<1, 2>>; +static_assert(is_same>); +} diff --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp index b03ad6054b9ac..0f92d3395a3f5 100644 --- a/clang/tools/libclang/CIndex.cpp +++ b/clang/tools/libclang/CIndex.cpp @@ -1891,6 +1891,12 @@ bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { return false; } +bool CursorVisitor::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) { + if (Visit(TL.getPatternLoc())) + return true; + return Visit(MakeCXCursor(TL.getIndexExpr(), StmtParent, TU)); +} + bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); } @@ -5718,6 +5724,8 @@ CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) { return cxstring::createRef("PackExpansionExpr"); case CXCursor_SizeOfPackExpr: return cxstring::createRef("SizeOfPackExpr"); + case CXCursor_PackIndexingExpr: + return cxstring::createRef("PackIndexingExpr"); case CXCursor_LambdaExpr: return cxstring::createRef("LambdaExpr"); case CXCursor_UnexposedExpr: diff --git a/clang/tools/libclang/CXCursor.cpp b/clang/tools/libclang/CXCursor.cpp index 978adac5521aa..01b8a23f6eac3 100644 --- a/clang/tools/libclang/CXCursor.cpp +++ b/clang/tools/libclang/CXCursor.cpp @@ -567,6 +567,10 @@ CXCursor cxcursor::MakeCXCursor(const Stmt *S, const Decl *Parent, K = CXCursor_SizeOfPackExpr; break; + case Stmt::PackIndexingExprClass: + K = CXCursor_PackIndexingExpr; + break; + case Stmt::DeclRefExprClass: if (const ImplicitParamDecl *IPD = dyn_cast_or_null( cast(S)->getDecl())) { diff --git a/clang/www/cxx_status.html b/clang/www/cxx_status.html index a48f35eb50483..a3c176d02129c 100755 --- a/clang/www/cxx_status.html +++ b/clang/www/cxx_status.html @@ -156,7 +156,7 @@

C++2c implementation status

Pack Indexing P2662R3 - No + Clang 19 Remove Deprecated Arithmetic Conversion on Enumerations