Skip to content

[DNM][stdlib] Add exponentiation precedence group and operator declaration #36074

New issue

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

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

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion include/swift/AST/Attr.def
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
Expand Down Expand Up @@ -630,6 +630,11 @@ DECL_ATTR(hasAsyncAlternative, HasAsyncAlternative,
APIStableToAdd | APIStableToRemove,
111)

SIMPLE_DECL_ATTR(apex, Apex,
OnPrecedenceGroup |
ABIStableToAdd | ABIStableToRemove | APIBreakingToAdd | APIBreakingToRemove,
112)

#undef TYPE_ATTR
#undef DECL_ATTR_ALIAS
#undef CONTEXTUAL_DECL_ATTR_ALIAS
Expand Down
6 changes: 5 additions & 1 deletion include/swift/AST/Decl.h
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
Expand Down Expand Up @@ -6995,6 +6995,10 @@ class PrecedenceGroupDecl : public Decl {
return { getLowerThanBuffer(), NumLowerThan };
}

bool isApex() const {
return getAttrs().hasAttribute<ApexAttr>();
}

static bool classof(const Decl *D) {
return D->getKind() == DeclKind::PrecedenceGroup;
}
Expand Down
11 changes: 9 additions & 2 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
Expand Down Expand Up @@ -976,6 +976,9 @@ NOTE(previous_precedence_group_decl,none,
"previous precedence group declaration here", ())
NOTE(circular_reference_through_precedence_group, none,
"through reference to precedence group %0 here", (Identifier))
ERROR(precedence_group_higher_than_apex,none,
"precedence group cannot be given higher precedence than '@apex' group",
())

//------------------------------------------------------------------------------
// MARK: Expression Type Checking Errors
Expand Down Expand Up @@ -3381,7 +3384,11 @@ ERROR(construct_protocol_by_name,none,

// Operators
ERROR(unknown_binop,none,
"operator is not a known binary operator", ())
"operator is not a known binary operator", ())
ERROR(unordered_adjacent_unary_operator,none,
"operator in precedence group %0 and adjacent unary operator have "
"undefined relative precedence; use grouping parentheses",
(Identifier))
ERROR(non_associative_adjacent_operators,none,
"adjacent operators are in non-associative precedence group %0",
(Identifier))
Expand Down
3 changes: 2 additions & 1 deletion lib/Sema/TypeCheckAttr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
Expand Down Expand Up @@ -99,6 +99,7 @@ class AttributeChecker : public AttributeVisitor<AttributeChecker> {

#define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {}
IGNORED_ATTR(AlwaysEmitIntoClient)
IGNORED_ATTR(Apex)
IGNORED_ATTR(HasInitialValue)
IGNORED_ATTR(ClangImporterSynthesizedType)
IGNORED_ATTR(Convenience)
Expand Down
22 changes: 20 additions & 2 deletions lib/Sema/TypeCheckDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
Expand Down Expand Up @@ -1450,8 +1450,19 @@ void swift::validatePrecedenceGroup(PrecedenceGroupDecl *PGD) {
continue;

// TODO: Requestify the lookup of a relation's group.
rel.Group = lookupPrecedenceGroupForRelation(
auto *group = lookupPrecedenceGroupForRelation(
dc, rel, PrecedenceGroupDescriptor::HigherThan);
rel.Group = group;

if (group && group->isApex()) {
if (!PGD->isInvalid()) {
Diags.diagnose(rel.NameLoc, diag::precedence_group_higher_than_apex);
Diags.diagnose(group->getNameLoc(), diag::kind_declared_here,
DescriptiveDeclKind::PrecedenceGroup);
}
PGD->setInvalid();
}

if (rel.Group) {
addedHigherThan = true;
} else {
Expand All @@ -1474,6 +1485,13 @@ void swift::validatePrecedenceGroup(PrecedenceGroupDecl *PGD) {
if (!group)
group = dc->lookupPrecedenceGroup(rel.Name).getSingle();

if (group && PGD->isApex()) {
if (!PGD->isInvalid()) {
Diags.diagnose(rel.NameLoc, diag::precedence_group_higher_than_apex);
}
PGD->setInvalid();
}

if (group &&
group->getDeclContext()->getParentModule() == dc->getParentModule()) {
if (!PGD->isInvalid()) {
Expand Down
4 changes: 3 additions & 1 deletion lib/Sema/TypeCheckDeclOverride.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
Expand Down Expand Up @@ -1541,6 +1541,8 @@ namespace {

UNINTERESTING_ATTR(AtReasync)

UNINTERESTING_ATTR(Apex)

#undef UNINTERESTING_ATTR

void visitAvailableAttr(AvailableAttr *attr) {
Expand Down
31 changes: 29 additions & 2 deletions lib/Sema/TypeCheckExpr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
Expand Down Expand Up @@ -281,7 +281,34 @@ static Expr *makeBinOp(ASTContext &Ctx, Expr *Op, Expr *LHS, Expr *RHS,
await->setSubExpr(sub);
return await;
}


// Operators in apex precedence groups are unordered relative to prefix and
// postfix operators.
if (opPrecedence && opPrecedence->isApex()) {
if (auto *prefixUnary = dyn_cast<PrefixUnaryExpr>(LHS)) {
Ctx.Diags.diagnose(Op->getLoc(),
diag::unordered_adjacent_unary_operator,
opPrecedence->getName())
.highlight(prefixUnary->getFn()->getSourceRange());
}
// Prefix '-' (but not '+') is lexed as part of a number literal rather than
// as a standalone operator.
else if (auto *numberLiteral = dyn_cast<NumberLiteralExpr>(LHS)) {
if (numberLiteral->isNegative()) {
Ctx.Diags.diagnose(Op->getLoc(),
diag::unordered_adjacent_unary_operator,
opPrecedence->getName())
.highlight(numberLiteral->getMinusLoc());
}
}
if (auto *postfixUnary = dyn_cast<PostfixUnaryExpr>(RHS)) {
Ctx.Diags.diagnose(Op->getLoc(),
diag::unordered_adjacent_unary_operator,
opPrecedence->getName())
.highlight(postfixUnary->getFn()->getSourceRange());
}
}

// If this is an assignment operator, and the left operand is an optional
// evaluation, pull the operator into the chain.
if (opPrecedence && opPrecedence->isAssignment()) {
Expand Down
34 changes: 29 additions & 5 deletions stdlib/public/core/FloatingPointTypes.swift.gyb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
Expand Down Expand Up @@ -1243,6 +1243,30 @@ extension ${Self} {
}
}

//===----------------------------------------------------------------------===//
// Placeholder Operators
//===----------------------------------------------------------------------===//

// TODO: Remove these operators once protocol-based math functions are
// incorporated from Swift Numerics into the standard library.

${Availability(bits)}
extension ${Self} {
@_alwaysEmitIntoClient
@available(*, unavailable,
message: "Import C standard library or Foundation to use 'pow' instead")
public static func ** (_ lhs: Self, _ rhs: Self) -> Self {
fatalError()
}

@_alwaysEmitIntoClient
@available(*, unavailable,
message: "Import C standard library or Foundation to use 'pow' instead")
public static func **= (_ lhs: inout Self, _ rhs: Self) {
fatalError()
}
}

//===----------------------------------------------------------------------===//
// Strideable Conformance
//===----------------------------------------------------------------------===//
Expand Down Expand Up @@ -1346,10 +1370,6 @@ internal struct _${Self}AnyHashableBox: _AnyHashableBox {
${Availability(bits)}
extension ${Self} : ConcurrentValue { }

//===----------------------------------------------------------------------===//
// Deprecated operators
//===----------------------------------------------------------------------===//

% if bits in [16,80]:
#else

Expand All @@ -1374,6 +1394,10 @@ public struct ${Self} {
% end
% end # for bits in all_floating_point_types

//===----------------------------------------------------------------------===//
// Deprecated Operators
//===----------------------------------------------------------------------===//

@_transparent
@available(*, unavailable,
message: "For floating point numbers use truncatingRemainder instead")
Expand Down
10 changes: 8 additions & 2 deletions stdlib/public/core/Policy.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
Expand Down Expand Up @@ -368,7 +368,11 @@ precedencegroup MultiplicationPrecedence {
precedencegroup BitwiseShiftPrecedence {
higherThan: MultiplicationPrecedence
}

@apex
precedencegroup ExponentiationPrecedence {
associativity: right
higherThan: MultiplicationPrecedence
}

//===----------------------------------------------------------------------===//
// Standard operators
Expand Down Expand Up @@ -397,6 +401,7 @@ prefix operator ..<: Comparable
// Standard infix operators.

// "Exponentiative"
infix operator **: ExponentiationPrecedence

infix operator <<: BitwiseShiftPrecedence, BinaryInteger
infix operator &<<: BitwiseShiftPrecedence, FixedWidthInteger
Expand Down Expand Up @@ -463,6 +468,7 @@ infix operator ||: LogicalDisjunctionPrecedence, Bool

// Compound

infix operator **=: AssignmentPrecedence
infix operator *=: AssignmentPrecedence, Numeric
infix operator &*=: AssignmentPrecedence, FixedWidthInteger
infix operator /=: AssignmentPrecedence, BinaryInteger
Expand Down
2 changes: 2 additions & 0 deletions test/IDE/complete_decl_attribute.swift
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ struct _S {
// ON_MEMBER_LAST-DAG: Keyword/None: transpose[#Declaration Attribute#]; name=transpose
// ON_MEMBER_LAST-DAG: Keyword/None: noDerivative[#Declaration Attribute#]; name=noDerivative
// ON_MEMBER_LAST-DAG: Keyword/None: concurrent[#Declaration Attribute#]; name=concurrent
// ON_MEMBER_LAST-DAG: Keyword/None: apex[#Declaration Attribute#]; name=apex
// ON_MEMBER_LAST-NOT: Keyword
// ON_MEMBER_LAST: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// ON_MEMBER_LAST-NOT: Decl[PrecedenceGroup]
Expand Down Expand Up @@ -306,6 +307,7 @@ func dummy2() {}
// KEYWORD_LAST-DAG: Keyword/None: transpose[#Declaration Attribute#]; name=transpose
// KEYWORD_LAST-DAG: Keyword/None: noDerivative[#Declaration Attribute#]; name=noDerivative
// KEYWORD_LAST-DAG: Keyword/None: concurrent[#Declaration Attribute#]; name=concurrent
// KEYWORD_LAST-DAG: Keyword/None: apex[#Declaration Attribute#]; name=apex
// KEYWORD_LAST-NOT: Keyword
// KEYWORD_LAST: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// KEYWORD_LAST: End completions