From e47f5c97d7a961620015f73fab71e5cd63047534 Mon Sep 17 00:00:00 2001 From: Hamish Knight Date: Mon, 17 Nov 2025 17:33:46 +0000 Subject: [PATCH 1/8] [Sema] Catch use-before-declarations in nested closures Previously we would allow these in Sema and diagnose them in SILGen, but allowing them in Sema is unsound because it means the constraint system ends up kicking interface type requests for declarations that should be type-checked as part of the closure itself. Adjust the name lookup logic to look through parent closures when detecting invalid forward references. For now we don't fallback to an outer result on encountering a use-before-declaration to preserve the current behavior. I'm planning on changing that in the next commit though. rdar://74430478 --- lib/Sema/PreCheckTarget.cpp | 72 +++++---- test/NameLookup/name_lookup.swift | 4 +- .../use_before_declaration_shadowing.swift | 73 +++++++++ test/SILGen/capture_order.swift | 141 ++---------------- .../closure_lifetime_fixup_undef.swift | 5 +- .../definite_init_closures_fail.swift | 4 + test/Sema/diag_use_before_declaration.swift | 135 +++++++++++++++++ test/expr/closure/multi_statement.swift | 21 ++- test/expr/expressions.swift | 11 +- test/expr/unary/if_expr.swift | 11 ++ ...tSystem-getTypeOfReferencePre-1a97a7.swift | 2 +- .../rdar100753270.swift | 4 +- .../rdar141012049.swift | 4 +- .../KeyPathExpr-getKeyPathType-c80788.swift | 2 +- ...typeCheckStmtConditionElement-08b850.swift | 11 ++ ...Verifier-dispatchVisitPreExpr-9ebf7c.swift | 2 +- 16 files changed, 315 insertions(+), 187 deletions(-) create mode 100644 test/NameLookup/use_before_declaration_shadowing.swift rename validation-test/IDE/{crashers => crashers_fixed}/ConstraintSystem-getTypeOfReferencePre-1a97a7.swift (76%) rename validation-test/{compiler_crashers => compiler_crashers_fixed}/KeyPathExpr-getKeyPathType-c80788.swift (81%) create mode 100644 validation-test/compiler_crashers_fixed/TypeChecker-typeCheckStmtConditionElement-08b850.swift rename validation-test/{compiler_crashers => compiler_crashers_fixed}/Verifier-dispatchVisitPreExpr-9ebf7c.swift (89%) diff --git a/lib/Sema/PreCheckTarget.cpp b/lib/Sema/PreCheckTarget.cpp index 4ee4290dd81b4..b6d3fb6964183 100644 --- a/lib/Sema/PreCheckTarget.cpp +++ b/lib/Sema/PreCheckTarget.cpp @@ -393,29 +393,34 @@ static bool isMemberChainTail(Expr *expr, Expr *parent, MemberChainKind kind) { } static bool isValidForwardReference(ValueDecl *D, DeclContext *DC, - ValueDecl **localDeclAfterUse) { - *localDeclAfterUse = nullptr; - - // References to variables injected by lldb are always valid. - if (isa(D) && cast(D)->isDebuggerVar()) + ValueDecl *&localDeclAfterUse, + bool &shouldUseOuterResults) { + // Only VarDecls require declaration before use. + auto *VD = dyn_cast(D); + if (!VD) return true; - // If we find something in the current context, it must be a forward - // reference, because otherwise if it was in scope, it would have - // been returned by the call to ASTScope::lookupLocalDecls() above. - if (D->getDeclContext()->isLocalContext()) { - do { - if (D->getDeclContext() == DC) { - *localDeclAfterUse = D; - return false; - } + // Non-local and variables injected by lldb are always valid. + auto *varDC = VD->getDeclContext(); + if (!varDC->isLocalContext() || VD->isDebuggerVar()) + return true; - // If we're inside of a 'defer' context, walk up to the parent - // and check again. We don't want 'defer' bodies to forward - // reference bindings in the immediate outer scope. - } while (isa(DC) && - cast(DC)->isDeferBody() && - (DC = DC->getParent())); + while (true) { + if (varDC == DC) { + localDeclAfterUse = VD; + return false; + } + if (isa(DC) || + (isa(DC) && cast(DC)->isDeferBody())) { + // If we cross a closure, don't allow falling back to an outer result if + // we have a forward reference. This preserves the behavior prior to + // diagnosing this in Sema. + if (isa(DC)) + shouldUseOuterResults = false; + DC = DC->getParent(); + continue; + } + break; } return true; } @@ -587,19 +592,20 @@ static Expr *resolveDeclRefExpr(UnresolvedDeclRefExpr *UDRE, DeclContext *DC, Lookup = TypeChecker::lookupUnqualified(DC, LookupName, Loc, lookupOptions); ValueDecl *localDeclAfterUse = nullptr; - AllDeclRefs = - findNonMembers(Lookup.innerResults(), UDRE->getRefKind(), - /*breakOnMember=*/true, ResultValues, - [&](ValueDecl *D) { - return isValidForwardReference(D, DC, &localDeclAfterUse); - }); + bool shouldUseOuterResults = true; + AllDeclRefs = findNonMembers( + Lookup.innerResults(), UDRE->getRefKind(), + /*breakOnMember=*/true, ResultValues, [&](ValueDecl *D) { + return isValidForwardReference(D, DC, localDeclAfterUse, + shouldUseOuterResults); + }); // If local declaration after use is found, check outer results for // better matching candidates. if (ResultValues.empty() && localDeclAfterUse) { auto innerDecl = localDeclAfterUse; while (localDeclAfterUse) { - if (Lookup.outerResults().empty()) { + if (!shouldUseOuterResults || Lookup.outerResults().empty()) { Context.Diags.diagnose(Loc, diag::use_local_before_declaration, Name); Context.Diags.diagnose(innerDecl, diag::decl_declared_here, localDeclAfterUse); @@ -609,12 +615,12 @@ static Expr *resolveDeclRefExpr(UnresolvedDeclRefExpr *UDRE, DeclContext *DC, Lookup.shiftDownResults(); ResultValues.clear(); localDeclAfterUse = nullptr; - AllDeclRefs = - findNonMembers(Lookup.innerResults(), UDRE->getRefKind(), - /*breakOnMember=*/true, ResultValues, - [&](ValueDecl *D) { - return isValidForwardReference(D, DC, &localDeclAfterUse); - }); + AllDeclRefs = findNonMembers( + Lookup.innerResults(), UDRE->getRefKind(), + /*breakOnMember=*/true, ResultValues, [&](ValueDecl *D) { + return isValidForwardReference(D, DC, localDeclAfterUse, + shouldUseOuterResults); + }); } } } diff --git a/test/NameLookup/name_lookup.swift b/test/NameLookup/name_lookup.swift index 0b969aab367a0..4a1cfb3d17fd2 100644 --- a/test/NameLookup/name_lookup.swift +++ b/test/NameLookup/name_lookup.swift @@ -643,8 +643,8 @@ struct PatternBindingWithTwoVars3 { var x = y, y = x } // https://github.com/apple/swift/issues/51518 do { - let closure1 = { closure2() } // expected-error {{circular reference}} expected-note {{through reference here}} - let closure2 = { closure1() } // expected-note {{through reference here}} expected-note {{through reference here}} + let closure1 = { closure2() } // expected-error {{use of local variable 'closure2' before its declaration}} + let closure2 = { closure1() } // expected-note {{'closure2' declared here}} } func color(with value: Int) -> Int { diff --git a/test/NameLookup/use_before_declaration_shadowing.swift b/test/NameLookup/use_before_declaration_shadowing.swift new file mode 100644 index 0000000000000..75c0f64c2fba2 --- /dev/null +++ b/test/NameLookup/use_before_declaration_shadowing.swift @@ -0,0 +1,73 @@ +// RUN: %target-typecheck-verify-swift +// RUN: %target-typecheck-verify-swift -parse-as-library + +func testLocal() { + // The first `y` here is considered the inner result. + do { + let y = "" + do { + let _: String = y + let y = 0 + _ = y + } + } + do { + let y = "" + do { + _ = { + let _: String = y + } + let y = 0 + _ = y + } + } + do { + let y = "" + _ = { + _ = { + let _: String = y + } + let y = 0 + _ = y + } + } + do { + let y = "" + func bar() { + _ = { + let _: String = y + } + let y = 0 + _ = y + } + } +} + +let topLevelString = "" + +func testTopLevel() { + // Here 'topLevelString' is now an outer result. + do { + let _: String = topLevelString + let topLevelString = 0 + _ = topLevelString + } + do { + _ = { + let _: String = topLevelString // expected-error {{use of local variable 'topLevelString' before its declaration}} + } + let topLevelString = 0 // expected-note {{'topLevelString' declared here}} + } + _ = { + _ = { + let _: String = topLevelString // expected-error {{use of local variable 'topLevelString' before its declaration}} + } + let topLevelString = 0 // expected-note {{'topLevelString' declared here}} + } + func bar() { + _ = { + let _: String = topLevelString // expected-error {{use of local variable 'topLevelString' before its declaration}} + } + let topLevelString = 0 // expected-note {{'topLevelString' declared here}} + } +} diff --git a/test/SILGen/capture_order.swift b/test/SILGen/capture_order.swift index 564224e5dbfd0..50d8e452cdad4 100644 --- a/test/SILGen/capture_order.swift +++ b/test/SILGen/capture_order.swift @@ -109,16 +109,6 @@ func transitiveForwardCapture3() { } } -func captureInClosure() { - let x = { (i: Int) in // expected-error {{closure captures 'currentTotal' before it is declared}} - currentTotal += i // expected-note {{captured here}} - } - - var currentTotal = 0 // expected-note {{captured value declared here}} - - _ = x -} - /// Regression tests // https://github.com/apple/swift/issues/47389 @@ -183,16 +173,6 @@ func f_57097() { // expected-warning@-1 {{variable 'r' was never mutated; consider changing to 'let' constant}} } -class class77933460 {} - -func func77933460() { - var obj: class77933460 = { obj }() - // expected-error@-1 {{closure captures 'obj' before it is declared}} - // expected-note@-2 {{captured here}} - // expected-note@-3 {{captured value declared here}} - // expected-warning@-4 {{variable 'obj' was never mutated; consider changing to 'let' constant}} -} - // MARK: - Forward Declared Lets // https://github.com/swiftlang/swift/issues/84909 @@ -208,110 +188,6 @@ func global_fwd(_ a: () -> Any) -> Any { a() } func global_gen_fwd(_ g: () -> T) -> T { g() } func global_fwd_p(_ p: () -> any P) -> any P { p() } -func forward_declared_let_captures() { - do { - let bad: Any = { bad }() - // expected-error@-1 {{closure captures 'bad' before it is declared}} - // expected-note@-2 {{captured here}} - // expected-note@-3 {{captured value declared here}} - } - - do { - func fwd(_ i: () -> Any) -> Any { i() } - let bad = fwd { bad } - // expected-error@-1 {{closure captures 'bad' before it is declared}} - // expected-note@-2 {{captured here}} - // expected-note@-3 {{captured value declared here}} - } - - do { - let bad = global_fwd { bad } - // expected-error@-1 {{closure captures 'bad' before it is declared}} - // expected-note@-2 {{captured here}} - // expected-note@-3 {{captured value declared here}} - } - - do { - let bad: Any = global_gen_fwd { bad } - // expected-error@-1 {{closure captures 'bad' before it is declared}} - // expected-note@-2 {{captured here}} - // expected-note@-3 {{captured value declared here}} - } - - do { - let bad: Any = E.static_gen_fwd { bad } - // expected-error@-1 {{closure captures 'bad' before it is declared}} - // expected-note@-2 {{captured here}} - // expected-note@-3 {{captured value declared here}} - } - - do { - let badNested: Any = global_fwd { { [badNested] in badNested }() } - // expected-error@-1 {{closure captures 'badNested' before it is declared}} - // expected-note@-2 {{captured here}} - // expected-note@-3 {{captured value declared here}} - } - - do { - let badOpt: Any? = { () -> Any? in badOpt }() - // expected-error@-1 {{closure captures 'badOpt' before it is declared}} - // expected-note@-2 {{captured here}} - // expected-note@-3 {{captured value declared here}} - } - - do { - let badTup: (Any, Any) = { (badTup.0, badTup.1) }() - // expected-error@-1 {{closure captures 'badTup' before it is declared}} - // expected-note@-2 {{captured here}} - // expected-note@-3 {{captured value declared here}} - } - - do { - let badTup: (Int, Any) = { (badTup.0, badTup.1) }() - // expected-error@-1 {{closure captures 'badTup' before it is declared}} - // expected-note@-2 {{captured here}} - // expected-note@-3 {{captured value declared here}} - } - - do { - let (badTup3, badTup4): (Any, Any) = { (badTup4, badTup3) }() - // expected-error@-1 {{closure captures 'badTup4' before it is declared}} - // expected-note@-2 {{captured here}} - // expected-note@-3 {{captured value declared here}} - // expected-error@-4 {{closure captures 'badTup3' before it is declared}} - // expected-note@-5 {{captured here}} - // expected-note@-6 {{captured value declared here}} - } - - do { - struct S { var p: Any } - let badStruct: S = { S(p: badStruct.p) }() - // expected-error@-1 {{closure captures 'badStruct' before it is declared}} - // expected-note@-2 {{captured here}} - // expected-note@-3 {{captured value declared here}} - } - - do { - enum EE { - case boring - case weird(Any) - case strange(Any) - } - - let badEnum: EE = { .weird(EE.strange(badEnum)) }() - // expected-error@-1 {{closure captures 'badEnum' before it is declared}} - // expected-note@-2 {{captured here}} - // expected-note@-3 {{captured value declared here}} - } - - do { - let badproto: any P = global_fwd_p { badproto } - // expected-error@-1 {{closure captures 'badproto' before it is declared}} - // expected-note@-2 {{captured here}} - // expected-note@-3 {{captured value declared here}} - } -} - func forward_declared_let_captures_local_fn() { do { func bad_local_f() -> Any { bad } @@ -441,10 +317,13 @@ func forward_declared_let_captures_local_fn() { } } -func forward_declared_local_lazy_captures() { - // runtime stack overflow - lazy var infiniteRecurse: Any = { infiniteRecurse }() - - // function that returns itself - lazy var hmm: () -> Any = { hmm } -} +// FIXME: Currently they crash SILGen (TypeConverter-setCaptureTypeExpansionContext-e72208.swift) +//func forward_declared_local_lazy_captures() { +// // runtime stack overflow +// var _infiniteRecurse: Any { infiniteRecurse } +// lazy var infiniteRecurse = _infiniteRecurse +// +// // function that returns itself +// func _hmm() -> Any { hmm } +// lazy var hmm = _hmm +//} diff --git a/test/SILOptimizer/closure_lifetime_fixup_undef.swift b/test/SILOptimizer/closure_lifetime_fixup_undef.swift index cf27396999f52..05f1be95a5e21 100644 --- a/test/SILOptimizer/closure_lifetime_fixup_undef.swift +++ b/test/SILOptimizer/closure_lifetime_fixup_undef.swift @@ -1,13 +1,14 @@ -// RUN: not %target-swift-frontend %s -sil-verify-all -c 2>&1 | %FileCheck %s +// RUN: %target-typecheck-verify-swift // Report the error but don't crash. -// CHECK: error: closure captures 'stringList' before it is declared class TestUndefined { private var stringList: [String]! func dontCrash(strings: [String]) { assert(stringList.allSatisfy({ $0 == stringList.first!})) + // expected-error@-1 {{use of local variable 'stringList' before its declaration}} let stringList = strings.filter({ $0 == "a" }) + // expected-note@-1 {{'stringList' declared here}} } } diff --git a/test/SILOptimizer/definite_init_closures_fail.swift b/test/SILOptimizer/definite_init_closures_fail.swift index 64d05e31c6e5d..af616b935ab08 100644 --- a/test/SILOptimizer/definite_init_closures_fail.swift +++ b/test/SILOptimizer/definite_init_closures_fail.swift @@ -65,3 +65,7 @@ struct Generic { } // expected-error {{return from initializer without initializing all stored properties}} } +func captureUninitialized() { + let fn: () -> Void // expected-note {{constant defined here}} + fn = { fn() } // expected-error {{constant 'fn' captured by a closure before being initialized}} +} diff --git a/test/Sema/diag_use_before_declaration.swift b/test/Sema/diag_use_before_declaration.swift index 216490315daf9..d07bc05d5e7f1 100644 --- a/test/Sema/diag_use_before_declaration.swift +++ b/test/Sema/diag_use_before_declaration.swift @@ -80,6 +80,141 @@ func nested_scope_3() { } } +func captureInClosure() { + let x = { (i: Int) in + currentTotal += i // expected-error {{use of local variable 'currentTotal' before its declaration}} + } + + var currentTotal = 0 // expected-note {{'currentTotal' declared here}} + + _ = x +} + +class class77933460 {} + +func func77933460() { + var obj: class77933460 = { obj }() + // expected-error@-1 {{use of local variable 'obj' before its declaration}} + // expected-note@-2 {{'obj' declared here}} +} + +protocol P {} + +enum E { + static func static_gen_fwd(_ g: () -> T) -> T { g() } +} + +func global_fwd(_ a: () -> Any) -> Any { a() } +func global_gen_fwd(_ g: () -> T) -> T { g() } +func global_fwd_p(_ p: () -> any P) -> any P { p() } + +func forward_declared_let_captures() { + do { + let bad: Any = { bad }() + // expected-error@-1 {{use of local variable 'bad' before its declaration}} + // expected-note@-2 {{'bad' declared here}} + } + + do { + func fwd(_ i: () -> Any) -> Any { i() } + let bad = fwd { bad } + // expected-error@-1 {{use of local variable 'bad' before its declaration}} + // expected-note@-2 {{'bad' declared here}} + } + + do { + let bad = global_fwd { bad } + // expected-error@-1 {{use of local variable 'bad' before its declaration}} + // expected-note@-2 {{'bad' declared here}} + } + + do { + let bad: Any = global_gen_fwd { bad } + // expected-error@-1 {{use of local variable 'bad' before its declaration}} + // expected-note@-2 {{'bad' declared here}} + } + + do { + let bad: Any = E.static_gen_fwd { bad } + // expected-error@-1 {{use of local variable 'bad' before its declaration}} + // expected-note@-2 {{'bad' declared here}} + } + + do { + let badNested: Any = global_fwd { { [badNested] in badNested }() } + // expected-error@-1 {{use of local variable 'badNested' before its declaration}} + // expected-note@-2 {{'badNested' declared here}} + } + + do { + let badOpt: Any? = { () -> Any? in badOpt }() + // expected-error@-1 {{use of local variable 'badOpt' before its declaration}} + // expected-note@-2 {{'badOpt' declared here}} + } + + do { + let badTup: (Any, Any) = { (badTup.0, badTup.1) }() + // expected-error@-1 2{{use of local variable 'badTup' before its declaration}} + // expected-note@-2 2{{'badTup' declared here}} + } + + do { + let badTup: (Int, Any) = { (badTup.0, badTup.1) }() + // expected-error@-1 2{{use of local variable 'badTup' before its declaration}} + // expected-note@-2 2{{'badTup' declared here}} + } + + do { + let (badTup3, badTup4): (Any, Any) = { (badTup4, badTup3) }() + // expected-error@-1 {{use of local variable 'badTup3' before its declaration}} + // expected-note@-2 {{'badTup3' declared here}} + // expected-error@-3 {{use of local variable 'badTup4' before its declaration}} + // expected-note@-4 {{'badTup4' declared here}} + } + + do { + struct S { var p: Any } + let badStruct: S = { S(p: badStruct.p) }() + // expected-error@-1 {{use of local variable 'badStruct' before its declaration}} + // expected-note@-2 {{'badStruct' declared here}} + } + + do { + enum EE { + case boring + case weird(Any) + case strange(Any) + } + + let badEnum: EE = { .weird(EE.strange(badEnum)) }() + // expected-error@-1 {{use of local variable 'badEnum' before its declaration}} + // expected-note@-2 {{'badEnum' declared here}} + } + + do { + let badproto: any P = global_fwd_p { badproto } + // expected-error@-1 {{use of local variable 'badproto' before its declaration}} + // expected-note@-2 {{'badproto' declared here}} + } +} + +func forward_declared_local_lazy_captures() { + lazy var infiniteRecurse: Any = { infiniteRecurse }() + // expected-error@-1 {{use of local variable 'infiniteRecurse' before its declaration}} + // expected-note@-2 {{'infiniteRecurse' declared here}} + + lazy var hmm: () -> Any = { hmm } + // expected-error@-1 {{use of local variable 'hmm' before its declaration}} + // expected-note@-2 {{'hmm' declared here}} +} + +func forward_declared_computed_locals() { + // In principle we could allow these, but it's simpler to just reject them. + let x = z // expected-error {{use of local variable 'z' before its declaration}} + let y = { z } // expected-error {{use of local variable 'z' before its declaration}} + var z: Int { 0 } // expected-note 2{{'z' declared here}} +} + //===----------------------------------------------------------------------===// // Type scope //===----------------------------------------------------------------------===// diff --git a/test/expr/closure/multi_statement.swift b/test/expr/closure/multi_statement.swift index c37d1ecb3f2f4..1a28a55ab758d 100644 --- a/test/expr/closure/multi_statement.swift +++ b/test/expr/closure/multi_statement.swift @@ -358,7 +358,8 @@ func test_no_crash_with_circular_ref_due_to_error() { // expected-error@-1 {{consecutive statements on a line must be separated by ';'}} // expected-error@-2 {{'let' cannot appear nested inside another 'var' or 'let' pattern}} // expected-error@-3 {{cannot call value of non-function type 'Int?'}} - print(next) + // expected-note@-4 {{'next' declared here}} + print(next) // expected-error {{use of local variable 'next' before its declaration}} return x } return 0 @@ -676,20 +677,26 @@ func test_recursive_var_reference_in_multistatement_closure() { func test(optionalInt: Int?, themes: MyStruct?) { takeClosure { - let int = optionalInt { // expected-error {{cannot call value of non-function type 'Int?'}} - print(int) + let int = optionalInt { + // expected-error@-1 {{cannot call value of non-function type 'Int?'}} + // expected-note@-2 {{'int' declared here}} + print(int) // expected-error {{use of local variable 'int' before its declaration}} } } takeClosure { - let theme = themes?.someMethod() { // expected-error {{extra trailing closure passed in call}} - _ = theme + let theme = themes?.someMethod() { + // expected-error@-1 {{extra trailing closure passed in call}} + // expected-note@-2 {{'theme' declared here}} + _ = theme // expected-error {{use of local variable 'theme' before its declaration}} } } takeClosure { - let theme = themes?.filter({ $0 }) { // expected-error {{value of type 'MyStruct' has no member 'filter'}} - _ = theme + let theme = themes?.filter({ $0 }) { + // expected-error@-1 {{value of type 'MyStruct' has no member 'filter'}} + // expected-note@-2 {{'theme' declared here}} + _ = theme // expected-error {{use of local variable 'theme' before its declaration}} } } } diff --git a/test/expr/expressions.swift b/test/expr/expressions.swift index b4416db19c5bd..0dfde1f9f5263 100644 --- a/test/expr/expressions.swift +++ b/test/expr/expressions.swift @@ -244,23 +244,24 @@ func test_as_2() { x as [] // expected-error {{expected element type}} {{9-9= <#type#>}} } -func test_lambda() { +func test_lambda1() { // A simple closure. var a = { (value: Int) -> () in markUsed(value+1) } // expected-warning@-1 {{initialization of variable 'a' was never used; consider replacing with assignment to '_' or removing it}} +} +func test_lambda2() { // A recursive lambda. - var fib = { (n: Int) -> Int in - // expected-warning@-1 {{variable 'fib' was never mutated; consider changing to 'let' constant}} + var fib = { (n: Int) -> Int in // expected-note 2{{'fib' declared here}} if (n < 2) { return n } - return fib(n-1)+fib(n-2) + return fib(n-1)+fib(n-2) // expected-error 2{{use of local variable 'fib' before its declaration}} } } -func test_lambda2() { +func test_lambda3() { { () -> protocol in // expected-error @-1 {{'protocol<...>' composition syntax has been removed and is not needed here}} {{11-24=Int}} // expected-error @-2 {{non-protocol, non-class type 'Int' cannot be used within a protocol-constrained type}} diff --git a/test/expr/unary/if_expr.swift b/test/expr/unary/if_expr.swift index f7775d99ff97c..761abb5a9f5df 100644 --- a/test/expr/unary/if_expr.swift +++ b/test/expr/unary/if_expr.swift @@ -1647,3 +1647,14 @@ func testCaptureList() { let _ = { [x = (if .random() { 0 } else { 1 })] in x } // expected-error@-1 {{'if' may only be used as expression in return, throw, or as the source of an assignment}} } + +func testUseBeforeDecl() throws { + let x = if .random() { // expected-note {{'x' declared here}} + print(y) // expected-error {{use of local variable 'y' before its declaration}} + let y = 0 // expected-note {{'y' declared here}} + print(x) // expected-error {{use of local variable 'x' before its declaration}} + throw Err() + } else { + 0 + } +} diff --git a/validation-test/IDE/crashers/ConstraintSystem-getTypeOfReferencePre-1a97a7.swift b/validation-test/IDE/crashers_fixed/ConstraintSystem-getTypeOfReferencePre-1a97a7.swift similarity index 76% rename from validation-test/IDE/crashers/ConstraintSystem-getTypeOfReferencePre-1a97a7.swift rename to validation-test/IDE/crashers_fixed/ConstraintSystem-getTypeOfReferencePre-1a97a7.swift index a8b10f008bb19..94fea2ca1eb63 100644 --- a/validation-test/IDE/crashers/ConstraintSystem-getTypeOfReferencePre-1a97a7.swift +++ b/validation-test/IDE/crashers_fixed/ConstraintSystem-getTypeOfReferencePre-1a97a7.swift @@ -1,5 +1,5 @@ // {"kind":"complete","original":"2d0bf5d7","signature":"swift::constraints::ConstraintSystem::getTypeOfReferencePre(swift::constraints::OverloadChoice, swift::DeclContext*, swift::constraints::ConstraintLocatorBuilder, swift::constraints::PreparedOverloadBuilder*)","signatureAssert":"Assertion failed: (!valueType->hasUnboundGenericType() && !valueType->hasTypeParameter()), function getTypeOfReferencePre"} -// RUN: not --crash %target-swift-ide-test -code-completion -batch-code-completion -skip-filecheck -code-completion-diagnostics -source-filename %s +// RUN: %target-swift-ide-test -code-completion -batch-code-completion -skip-filecheck -code-completion-diagnostics -source-filename %s { (a: Dictionary) in #^^# let b = a { diff --git a/validation-test/Sema/type_checker_crashers_fixed/rdar100753270.swift b/validation-test/Sema/type_checker_crashers_fixed/rdar100753270.swift index bdac4d0d580bc..56282f4859dad 100644 --- a/validation-test/Sema/type_checker_crashers_fixed/rdar100753270.swift +++ b/validation-test/Sema/type_checker_crashers_fixed/rdar100753270.swift @@ -20,7 +20,7 @@ struct Test { // expected-note {{to match this opening '{'}} var infos = [Info]() for (index, info) in infos.enumerated() { - let dataPerHost = Dictionary(grouping: info.data) { data in + let dataPerHost = Dictionary(grouping: info.data) { data in // expected-note {{'dataPerHost' declared here}} let location = data.location() guard let host = location.host else { return 0 @@ -30,7 +30,7 @@ struct Test { // expected-note {{to match this opening '{'}} // Missing paren! } - for _ in dataPerHost { // `dataPerHost` is inside of the closure! + for _ in dataPerHost { // expected-error {{use of local variable 'dataPerHost' before its declaration}} } } } diff --git a/validation-test/Sema/type_checker_crashers_fixed/rdar141012049.swift b/validation-test/Sema/type_checker_crashers_fixed/rdar141012049.swift index cd132c2afa4cb..60b28806acd79 100644 --- a/validation-test/Sema/type_checker_crashers_fixed/rdar141012049.swift +++ b/validation-test/Sema/type_checker_crashers_fixed/rdar141012049.swift @@ -1,12 +1,12 @@ // RUN: %target-typecheck-verify-swift -verify-ignore-unrelated func test(_ v: [Int]) { - let result = v.filter { }.flatMap(\.wrong) { + let result = v.filter { }.flatMap(\.wrong) { // expected-note {{'result' declared here}} // expected-error@-1 {{type for closure argument list expects 1 argument, which cannot be implicitly ignored}} // expected-error@-2 {{cannot convert value of type '()' to closure result type 'Bool'}} // expected-error@-3 {{value of type 'Int' has no member 'wrong'}} // expected-error@-4 {{extra trailing closure passed in call}} - print(result) + print(result) // expected-error {{use of local variable 'result' before its declaration}} } let otherResult = v.filter { _ in false }.flatMap(\.wrong, { $0 }, 42) diff --git a/validation-test/compiler_crashers/KeyPathExpr-getKeyPathType-c80788.swift b/validation-test/compiler_crashers_fixed/KeyPathExpr-getKeyPathType-c80788.swift similarity index 81% rename from validation-test/compiler_crashers/KeyPathExpr-getKeyPathType-c80788.swift rename to validation-test/compiler_crashers_fixed/KeyPathExpr-getKeyPathType-c80788.swift index 90c97a3ff0cba..0565a77fa631b 100644 --- a/validation-test/compiler_crashers/KeyPathExpr-getKeyPathType-c80788.swift +++ b/validation-test/compiler_crashers_fixed/KeyPathExpr-getKeyPathType-c80788.swift @@ -1,3 +1,3 @@ // {"kind":"typecheck","original":"6bb0b020","signature":"swift::KeyPathExpr::getKeyPathType() const","signatureAssert":"Assertion failed: (isa(Val) && \"cast() argument of incompatible type!\"), function cast"} -// RUN: not --crash %target-swift-frontend -typecheck %s +// RUN: not %target-swift-frontend -typecheck %s { let a = \ .b { c} (let c = a diff --git a/validation-test/compiler_crashers_fixed/TypeChecker-typeCheckStmtConditionElement-08b850.swift b/validation-test/compiler_crashers_fixed/TypeChecker-typeCheckStmtConditionElement-08b850.swift new file mode 100644 index 0000000000000..e8a6229bdf79a --- /dev/null +++ b/validation-test/compiler_crashers_fixed/TypeChecker-typeCheckStmtConditionElement-08b850.swift @@ -0,0 +1,11 @@ +// {"kind":"typecheck","signature":"swift::TypeChecker::typeCheckStmtConditionElement(swift::StmtConditionElement&, bool&, swift::DeclContext*)","signatureAssert":"Assertion failed: (!elt.getPattern()->hasType() && \"the pattern binding condition is already type checked\"), function typeCheckPatternBindingStmtConditionElement"} +// RUN: not %target-swift-frontend -typecheck %s +struct a { + func b() {} +} +func foo() { + _ = { c } + var d: a? + guard let d else {} + let c = d.b() +} diff --git a/validation-test/compiler_crashers/Verifier-dispatchVisitPreExpr-9ebf7c.swift b/validation-test/compiler_crashers_fixed/Verifier-dispatchVisitPreExpr-9ebf7c.swift similarity index 89% rename from validation-test/compiler_crashers/Verifier-dispatchVisitPreExpr-9ebf7c.swift rename to validation-test/compiler_crashers_fixed/Verifier-dispatchVisitPreExpr-9ebf7c.swift index c397b5c884d9d..3b9104f879181 100644 --- a/validation-test/compiler_crashers/Verifier-dispatchVisitPreExpr-9ebf7c.swift +++ b/validation-test/compiler_crashers_fixed/Verifier-dispatchVisitPreExpr-9ebf7c.swift @@ -1,5 +1,5 @@ // {"kind":"typecheck","original":"5b785ef0","signature":"swift::ASTWalker::PreWalkResult (anonymous namespace)::Verifier::dispatchVisitPreExpr(swift::OpenExistentialExpr*)","signatureAssert":"Assertion failed: (isa(Val) && \"cast() argument of incompatible type!\"), function cast"} -// RUN: not --crash %target-swift-frontend -typecheck %s +// RUN: not %target-swift-frontend -typecheck %s extension Dictionary { a(b: Sequence) { From 9336e3ee5985ccc9a434e4067d31f9e3d02c9fde Mon Sep 17 00:00:00 2001 From: Hamish Knight Date: Mon, 17 Nov 2025 17:33:46 +0000 Subject: [PATCH 2/8] [Sema] Allow falling back to outer results from closure If we encounter a variable declared after its use within a closure, we can fallback to using an outer result if present. This matches the behavior outside of a closure and generally seems more consistent with the behavior we have if we also find an inner result. rdar://163656720 --- lib/Sema/PreCheckTarget.cpp | 17 +++------- .../use_before_declaration_shadowing.swift | 33 +++++++++++++++---- .../closure_lifetime_fixup_undef.swift | 6 ++-- test/expr/closure/closures.swift | 12 +++++++ test/expr/expressions.swift | 13 ++++++-- 5 files changed, 56 insertions(+), 25 deletions(-) diff --git a/lib/Sema/PreCheckTarget.cpp b/lib/Sema/PreCheckTarget.cpp index b6d3fb6964183..2d8b894788a15 100644 --- a/lib/Sema/PreCheckTarget.cpp +++ b/lib/Sema/PreCheckTarget.cpp @@ -393,8 +393,7 @@ static bool isMemberChainTail(Expr *expr, Expr *parent, MemberChainKind kind) { } static bool isValidForwardReference(ValueDecl *D, DeclContext *DC, - ValueDecl *&localDeclAfterUse, - bool &shouldUseOuterResults) { + ValueDecl *&localDeclAfterUse) { // Only VarDecls require declaration before use. auto *VD = dyn_cast(D); if (!VD) @@ -412,11 +411,6 @@ static bool isValidForwardReference(ValueDecl *D, DeclContext *DC, } if (isa(DC) || (isa(DC) && cast(DC)->isDeferBody())) { - // If we cross a closure, don't allow falling back to an outer result if - // we have a forward reference. This preserves the behavior prior to - // diagnosing this in Sema. - if (isa(DC)) - shouldUseOuterResults = false; DC = DC->getParent(); continue; } @@ -592,12 +586,10 @@ static Expr *resolveDeclRefExpr(UnresolvedDeclRefExpr *UDRE, DeclContext *DC, Lookup = TypeChecker::lookupUnqualified(DC, LookupName, Loc, lookupOptions); ValueDecl *localDeclAfterUse = nullptr; - bool shouldUseOuterResults = true; AllDeclRefs = findNonMembers( Lookup.innerResults(), UDRE->getRefKind(), /*breakOnMember=*/true, ResultValues, [&](ValueDecl *D) { - return isValidForwardReference(D, DC, localDeclAfterUse, - shouldUseOuterResults); + return isValidForwardReference(D, DC, localDeclAfterUse); }); // If local declaration after use is found, check outer results for @@ -605,7 +597,7 @@ static Expr *resolveDeclRefExpr(UnresolvedDeclRefExpr *UDRE, DeclContext *DC, if (ResultValues.empty() && localDeclAfterUse) { auto innerDecl = localDeclAfterUse; while (localDeclAfterUse) { - if (!shouldUseOuterResults || Lookup.outerResults().empty()) { + if (Lookup.outerResults().empty()) { Context.Diags.diagnose(Loc, diag::use_local_before_declaration, Name); Context.Diags.diagnose(innerDecl, diag::decl_declared_here, localDeclAfterUse); @@ -618,8 +610,7 @@ static Expr *resolveDeclRefExpr(UnresolvedDeclRefExpr *UDRE, DeclContext *DC, AllDeclRefs = findNonMembers( Lookup.innerResults(), UDRE->getRefKind(), /*breakOnMember=*/true, ResultValues, [&](ValueDecl *D) { - return isValidForwardReference(D, DC, localDeclAfterUse, - shouldUseOuterResults); + return isValidForwardReference(D, DC, localDeclAfterUse); }); } } diff --git a/test/NameLookup/use_before_declaration_shadowing.swift b/test/NameLookup/use_before_declaration_shadowing.swift index 75c0f64c2fba2..79bef0ad5521d 100644 --- a/test/NameLookup/use_before_declaration_shadowing.swift +++ b/test/NameLookup/use_before_declaration_shadowing.swift @@ -54,20 +54,41 @@ func testTopLevel() { } do { _ = { - let _: String = topLevelString // expected-error {{use of local variable 'topLevelString' before its declaration}} + let _: String = topLevelString } - let topLevelString = 0 // expected-note {{'topLevelString' declared here}} + let topLevelString = 0 + _ = topLevelString } _ = { _ = { - let _: String = topLevelString // expected-error {{use of local variable 'topLevelString' before its declaration}} + let _: String = topLevelString } - let topLevelString = 0 // expected-note {{'topLevelString' declared here}} + let topLevelString = 0 + _ = topLevelString } func bar() { _ = { - let _: String = topLevelString // expected-error {{use of local variable 'topLevelString' before its declaration}} + let _: String = topLevelString } - let topLevelString = 0 // expected-note {{'topLevelString' declared here}} + let topLevelString = 0 + _ = topLevelString + } +} + +struct TestLocalPropertyShadowing { + var str: String + + func foo() { + { _ = str }() + let str = str + _ = str + } + func bar() { + let str = { str } + _ = str + } + func baz() { + let str = str + _ = str } } diff --git a/test/SILOptimizer/closure_lifetime_fixup_undef.swift b/test/SILOptimizer/closure_lifetime_fixup_undef.swift index 05f1be95a5e21..88cd500183762 100644 --- a/test/SILOptimizer/closure_lifetime_fixup_undef.swift +++ b/test/SILOptimizer/closure_lifetime_fixup_undef.swift @@ -1,14 +1,12 @@ -// RUN: %target-typecheck-verify-swift +// RUN: %target-swift-frontend %s -sil-verify-all -c -// Report the error but don't crash. +// Make sure we don't crash. class TestUndefined { private var stringList: [String]! func dontCrash(strings: [String]) { assert(stringList.allSatisfy({ $0 == stringList.first!})) - // expected-error@-1 {{use of local variable 'stringList' before its declaration}} let stringList = strings.filter({ $0 == "a" }) - // expected-note@-1 {{'stringList' declared here}} } } diff --git a/test/expr/closure/closures.swift b/test/expr/closure/closures.swift index b8af7e06c653c..572153f6bd1ab 100644 --- a/test/expr/closure/closures.swift +++ b/test/expr/closure/closures.swift @@ -1852,6 +1852,18 @@ class TestLazyLocal { } } +class TestLocalPropertyShadowing { + var str: String = "" + + func foo() { + let str = { str } + // expected-error@-1 {{reference to property 'str' in closure requires explicit use of 'self' to make capture semantics explicit}} + // expected-note@-2 {{reference 'self.' explicitly}} + // expected-note@-3 {{capture 'self' explicitly to enable implicit 'self' in this closure}} + _ = str + } +} + class TestExtensionOnOptionalSelf { init() {} } diff --git a/test/expr/expressions.swift b/test/expr/expressions.swift index 0dfde1f9f5263..3a0710b8f4485 100644 --- a/test/expr/expressions.swift +++ b/test/expr/expressions.swift @@ -252,12 +252,21 @@ func test_lambda1() { func test_lambda2() { // A recursive lambda. - var fib = { (n: Int) -> Int in // expected-note 2{{'fib' declared here}} + var fibLocal = { (n: Int) -> Int in // expected-note 2{{'fibLocal' declared here}} if (n < 2) { return n } - return fib(n-1)+fib(n-2) // expected-error 2{{use of local variable 'fib' before its declaration}} + return fibLocal(n-1)+fibLocal(n-2) // expected-error 2{{use of local variable 'fibLocal' before its declaration}} + } + + var fib = { (n: Int) -> Int in + if (n < 2) { + return n + } + + // These resolve to the top-level function. + return fib(n-1)+fib(n-2) } } From 2f0dee491c647ef735fce5c70aecd758770002b0 Mon Sep 17 00:00:00 2001 From: Hamish Knight Date: Mon, 17 Nov 2025 17:33:46 +0000 Subject: [PATCH 3/8] [Changelog] Add changelog entry for forward declaration rule change --- CHANGELOG.md | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 63 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 83edf56791968..b4a845a54e6e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,69 @@ > [!NOTE] > This is in reverse chronological order, so newer entries are added to the top. -## Swift (next) +## Swift 6.3 + +* The checking for illegal forward references to local variables is now consistent regardless of + whether the reference appears in a closure. Previously the type-checker could incorrectly permit + forward references within a closure that it would reject outside of the closure, however this + is not something that can be supported in general in the type-checker. In most cases this should + have no impact since such invalid references would have already been rejected by later diagnostic + passes in the compiler. However there are a couple of cases that were previously legal that are + now illegal. + + These include: + + - `lazy` local variables with initializers that forward reference a local variable in a closure, + or local variables with attached macros that relocate the initializer into an accessor, e.g: + + ```swift + func foo() { + lazy var x = { y } // error: use of local variable 'y' before its declaration + let y = 0 + } + ``` + + ```swift + func foo() { + @LazyLikeMacro var x = { y } // error: use of local variable 'y' before its declaration + let y = 0 + } + ``` + + - Forward references to local computed variables from a closure, e.g: + + ```swift + func foo() { + var x = { y } // error: use of local variable 'y' before its declaration + var y: Int { 0 } + } + ``` + + Both cases were already invalid if there was no closure involved. These are now consistently + rejected. + + This then allows for consistent shadowing behavior inside and outside of closures, allowing the + following previously illegal case to become legal: + + ```swift + struct S { + var x: Int + func foo() { + // Already legal, both refer to `self.x` + let y = x + let x = x + + let z = x // Refers to the local var. + } + func bar() { + // Both previously illegal, now both refer to `self.x`. + let y = { x }() + let x: Int = { x }() + + let z = x // Still refers to the local var. + } + } + ``` * [SE-0491][]: You can now use a module selector to specify which module Swift should look inside to find a named declaration. A From c275b4aa47390779b99f9bc9305d62e7cae7e84f Mon Sep 17 00:00:00 2001 From: Hamish Knight Date: Sun, 26 Oct 2025 09:55:49 +0000 Subject: [PATCH 4/8] [Sema] Enforce we don't type-check bindings independently of closures Bindings in closures must be type-checked together with the surrounding closure, add an assertion to make sure we don't try this. Carve out an exception for code completion and error cases which may still kick lazy type-checking. We ought to eventually fix up all the error cases cases though since they imply we're leaving bits of the AST un-type-checked. --- lib/Sema/TypeCheckConstraints.cpp | 17 +++++++++++++++++ test/IDE/complete_unqualified_fallback.swift | 12 ++++++++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/lib/Sema/TypeCheckConstraints.cpp b/lib/Sema/TypeCheckConstraints.cpp index 06d7147259494..39522f2ad1db7 100644 --- a/lib/Sema/TypeCheckConstraints.cpp +++ b/lib/Sema/TypeCheckConstraints.cpp @@ -841,6 +841,23 @@ bool TypeChecker::typeCheckBinding(Pattern *&pattern, Expr *&initializer, initializer, DC, patternType, pattern, /*bindPatternVarsOneWay=*/false); + // Bindings cannot be type-checked independently from their context in a + // closure, make sure we don't ever attempt to do this. If we want to be able + // to lazily type-check these we'll need to type-check the entire surrounding + // expression. + if (auto *CE = dyn_cast(DC)) { + if (!PBD || !isPlaceholderVar(PBD)) { + // Completion may trigger lazy type-checking as part of fallback + // unqualified lookup, just decline to type-check. + auto &ctx = CE->getASTContext(); + if (ctx.SourceMgr.hasIDEInspectionTargetBuffer()) { + target.markInvalid(); + return true; + } + ABORT("Cannot type-check PatternBindingDecl without closure context"); + } + } + // Type-check the initializer. auto resultTarget = typeCheckExpression(target, options); diff --git a/test/IDE/complete_unqualified_fallback.swift b/test/IDE/complete_unqualified_fallback.swift index 826652eb38126..887683cdb2e49 100644 --- a/test/IDE/complete_unqualified_fallback.swift +++ b/test/IDE/complete_unqualified_fallback.swift @@ -1,4 +1,4 @@ -// RUN: %batch-code-completion +// RUN: %batch-code-completion -solver-scope-threshold=50 protocol P0 {} protocol P1 {} @@ -47,8 +47,16 @@ S { S { S { S { + let x = 0 + let y: Int = 0 #^COMPLETE^# - // COMPLETE: Decl[Struct]/CurrModule: FooBar[#FooBar#]; name=FooBar + // COMPLETE-DAG: Decl[Struct]/CurrModule: FooBar[#FooBar#]; name=FooBar + + // We decline to type-check a variable indepedently of the surrounding + // closure, so this has an ErrorType. If this changes, you either need + // to make this test case more complex or tweak the limits. + // COMPLETE-DAG: Decl[LocalVar]/Local: x[#_#]; name=x + // COMPLETE-DAG: Decl[LocalVar]/Local: y[#Int#]; name=y } } } From 46dfd7620e448bfed6ff0953da759f8c4000ec93 Mon Sep 17 00:00:00 2001 From: Hamish Knight Date: Wed, 17 Dec 2025 02:26:16 +0000 Subject: [PATCH 5/8] [test] Fix expectations in `Concurrency/toplevel/main.swift` FileCheck was matching against its own CHECK lines in the diagnostic output here so the test always succeeded. Convert to using the diagnostic verifier now we have `-verify-additional-prefix`. --- test/Concurrency/toplevel/Inputs/foo.swift | 3 -- test/Concurrency/toplevel/main.swift | 45 +++++++++++----------- 2 files changed, 22 insertions(+), 26 deletions(-) delete mode 100644 test/Concurrency/toplevel/Inputs/foo.swift diff --git a/test/Concurrency/toplevel/Inputs/foo.swift b/test/Concurrency/toplevel/Inputs/foo.swift deleted file mode 100644 index 6e30f1086caab..0000000000000 --- a/test/Concurrency/toplevel/Inputs/foo.swift +++ /dev/null @@ -1,3 +0,0 @@ -func foo() -> Int { - a + 10 -} diff --git a/test/Concurrency/toplevel/main.swift b/test/Concurrency/toplevel/main.swift index a3da6df655a4d..311856eb9d0d7 100644 --- a/test/Concurrency/toplevel/main.swift +++ b/test/Concurrency/toplevel/main.swift @@ -1,44 +1,43 @@ -// RUN: not %target-swift-frontend -enable-experimental-async-top-level -swift-version 6 -typecheck %s %S/Inputs/foo.swift 2>&1 | %FileCheck %s --check-prefixes='Swift6-CHECK,CHECK' -// RUN: not %target-swift-frontend -enable-experimental-async-top-level -swift-version 5 -typecheck %s %S/Inputs/foo.swift 2>&1 | %FileCheck %s --check-prefixes='Swift5-CHECK,CHECK' +// RUN: %empty-directory(%t) +// RUN: split-file --leading-lines %s %t -var a = 10 +// RUN: %target-swift-frontend -typecheck -verify %t/main.swift %t/foo.swift -enable-experimental-async-top-level -swift-version 6 -verify-additional-prefix swift6- +// RUN: %target-swift-frontend -typecheck -verify %t/main.swift %t/foo.swift -enable-experimental-async-top-level -swift-version 5 -verify-additional-prefix swift5- + +//--- foo.swift +func foo() -> Int { + // expected-swift6-note@-1 {{add '@MainActor' to make global function 'foo()' part of global actor 'MainActor'}} + a + 10 + // expected-swift6-error@-1 {{main actor-isolated var 'a' can not be referenced from a nonisolated context}} +} + +//--- main.swift +var a = 10 // expected-swift6-note 2{{var declared here}} @MainActor -var b = 14 -// CHECK: top-level code variables cannot have a global actor +var b = 14 // expected-error {{top-level code variables cannot have a global actor}} func nonIsolatedSynchronous() { + // expected-swift6-note@-1 {{add '@MainActor' to make global function 'nonIsolatedSynchronous()' part of global actor 'MainActor'}} print(a) -// Swift6-CHECK: main actor-isolated var 'a' can not be referenced from a nonisolated context -// Swift6-CHECK: add '@MainActor' to make global function 'nonIsolatedSynchronous()' part of global actor 'MainActor' - -// Swift5-CHECK-NOT: main actor-isolated var 'a' can not be referenced from a nonisolated context -// Swift5-CHECK-NOT: add '@MainActor' to make global function 'nonIsolatedSynchronous()' part of global actor 'MainActor' +// expected-swift6-error@-1 {{main actor-isolated var 'a' can not be referenced from a nonisolated context}} } func nonIsolatedAsync() async { - print(a) -// CHECK: expression is 'async' but is not marked with 'await' -// CHECK: property access is 'async' + print(a) + // expected-swift6-error@-1 {{main actor-isolated var 'a' cannot be accessed from outside of the actor}} + // expected-swift5-warning@-2 {{main actor-isolated var 'a' cannot be accessed from outside of the actor}} } await nonIsolatedAsync() -// Swift6-CHECK: foo.swift{{.*}}main actor-isolated var 'a' can not be referenced from a nonisolated context -// Swift6-CHECK-DAG: var declared here -// Swift6-CHECK-DAG: add '@MainActor' to make global function 'foo()' part of global actor 'MainActor' - -// Swift5-CHECK-NOT: foo.swift{{.*}}main actor-isolated var 'a' can not be referenced from a nonisolated context -// Swift5-CHECK-NOT: var declared here -// Swift5-CHECK-NOT: add '@MainActor' to make global function 'foo()' part of global actor 'MainActor' - @MainActor func isolated() { - print(a) + print(a) } func asyncFun() async { - await print(a) + await print(a) } await asyncFun() From ab0d198c27a1fb24d264083b4f17aaba315e9949 Mon Sep 17 00:00:00 2001 From: Hamish Knight Date: Thu, 18 Dec 2025 15:31:47 +0000 Subject: [PATCH 6/8] [test] Remove uses of `-enable-experimental-async-top-level` This is no longer experimental and is the default. --- test/Concurrency/toplevel/async-5-top-level.swift | 9 ++++----- test/Concurrency/toplevel/async-6-top-level.swift | 2 +- test/Concurrency/toplevel/main.swift | 4 ++-- test/Concurrency/toplevel/no-async-5-top-level.swift | 6 ++---- test/Concurrency/toplevel/no-async-6-top-level.swift | 7 +++---- test/Concurrency/toplevel/synchronous_mainactor.swift | 2 +- test/SILGen/top_level_captures.swift | 1 - test/SILGen/toplevel.swift | 1 - test/SILGen/toplevel_errors.swift | 1 - test/SILGen/toplevel_globalactorvars.swift | 2 +- 10 files changed, 14 insertions(+), 21 deletions(-) diff --git a/test/Concurrency/toplevel/async-5-top-level.swift b/test/Concurrency/toplevel/async-5-top-level.swift index f5236465051da..762504712129e 100644 --- a/test/Concurrency/toplevel/async-5-top-level.swift +++ b/test/Concurrency/toplevel/async-5-top-level.swift @@ -1,9 +1,8 @@ -// RUN: %target-swift-frontend -typecheck -target %target-swift-5.1-abi-triple -enable-experimental-async-top-level -swift-version 5 %s -verify +// RUN: %target-swift-frontend -typecheck -target %target-swift-5.1-abi-triple -swift-version 5 %s -verify -// enable-experimental-async-top-level is passed and an await is used in the -// top-level, so the top-level code is a concurrent context. Variables are -// declared with `@_predatesConcurrency @MainActor`, and the top-level is run on -// the main actor. +// An await is used in the top-level, so the top-level code is a concurrent +// context. Variables are declared with `@_predatesConcurrency @MainActor`, and +// the top-level is run on the main actor. var a = 10 // expected-note {{mutation of this var is only permitted within the actor}} diff --git a/test/Concurrency/toplevel/async-6-top-level.swift b/test/Concurrency/toplevel/async-6-top-level.swift index 1bc4eb299a8c4..7ba4e83c3822c 100644 --- a/test/Concurrency/toplevel/async-6-top-level.swift +++ b/test/Concurrency/toplevel/async-6-top-level.swift @@ -1,4 +1,4 @@ -// RUN: %target-swift-frontend -typecheck -target %target-swift-5.1-abi-triple -enable-experimental-async-top-level -swift-version 6 %s -verify +// RUN: %target-swift-frontend -typecheck -target %target-swift-5.1-abi-triple -swift-version 6 %s -verify var a = 10 // expected-note@-1 2 {{var declared here}} diff --git a/test/Concurrency/toplevel/main.swift b/test/Concurrency/toplevel/main.swift index 311856eb9d0d7..2b982edcddda9 100644 --- a/test/Concurrency/toplevel/main.swift +++ b/test/Concurrency/toplevel/main.swift @@ -1,8 +1,8 @@ // RUN: %empty-directory(%t) // RUN: split-file --leading-lines %s %t -// RUN: %target-swift-frontend -typecheck -verify %t/main.swift %t/foo.swift -enable-experimental-async-top-level -swift-version 6 -verify-additional-prefix swift6- -// RUN: %target-swift-frontend -typecheck -verify %t/main.swift %t/foo.swift -enable-experimental-async-top-level -swift-version 5 -verify-additional-prefix swift5- +// RUN: %target-swift-frontend -typecheck -verify %t/main.swift %t/foo.swift -swift-version 6 -verify-additional-prefix swift6- +// RUN: %target-swift-frontend -typecheck -verify %t/main.swift %t/foo.swift -swift-version 5 -verify-additional-prefix swift5- //--- foo.swift func foo() -> Int { diff --git a/test/Concurrency/toplevel/no-async-5-top-level.swift b/test/Concurrency/toplevel/no-async-5-top-level.swift index 1ab038035134e..dde67f1187274 100644 --- a/test/Concurrency/toplevel/no-async-5-top-level.swift +++ b/test/Concurrency/toplevel/no-async-5-top-level.swift @@ -1,9 +1,7 @@ -// RUN: %target-swift-frontend -typecheck -target %target-swift-5.1-abi-triple -enable-experimental-async-top-level -swift-version 5 %s -verify // RUN: %target-swift-frontend -typecheck -target %target-swift-5.1-abi-triple -swift-version 5 %s -verify -// Even though enable-experimental-async-top-level is enabled, there are no -// `await`s made from the top-level, so it is not an async context. `a` is just -// a normal top-level global variable with no actor isolation. +// There are no `await`s made from the top-level, so it is not an async context. +// `a` is just a normal top-level global variable with no actor isolation. var a = 10 diff --git a/test/Concurrency/toplevel/no-async-6-top-level.swift b/test/Concurrency/toplevel/no-async-6-top-level.swift index e5e27fcc994dd..4302f05db355d 100644 --- a/test/Concurrency/toplevel/no-async-6-top-level.swift +++ b/test/Concurrency/toplevel/no-async-6-top-level.swift @@ -1,9 +1,8 @@ // RUN: %target-swift-frontend -typecheck -target %target-swift-5.1-abi-triple -swift-version 6 %s -verify -// Even though enable-experimental-async-top-level is enabled, there are no -// 'await's made from the top-level, thus the top-level is not an asynchronous -// context. `a` is just a normal top-level global variable with no actor -// isolation. +// There are no 'await's made from the top-level, thus the top-level is not an +// asynchronous context. `a` is just a normal top-level global variable with no +// actor isolation. var a = 10 // expected-note 2 {{var declared here}} // expected-note@-1 2{{mutation of this var is only permitted within the actor}} diff --git a/test/Concurrency/toplevel/synchronous_mainactor.swift b/test/Concurrency/toplevel/synchronous_mainactor.swift index b28b15da122b8..22ed1f3248c41 100644 --- a/test/Concurrency/toplevel/synchronous_mainactor.swift +++ b/test/Concurrency/toplevel/synchronous_mainactor.swift @@ -1,4 +1,4 @@ -// RUN: %target-swift-frontend -target %target-swift-5.1-abi-triple -enable-experimental-async-top-level -strict-concurrency=complete -typecheck -verify %s +// RUN: %target-swift-frontend -target %target-swift-5.1-abi-triple -strict-concurrency=complete -typecheck -verify %s var a = 10 // expected-note{{var declared here}} diff --git a/test/SILGen/top_level_captures.swift b/test/SILGen/top_level_captures.swift index 5728655135b6f..d2d6aa831bc43 100644 --- a/test/SILGen/top_level_captures.swift +++ b/test/SILGen/top_level_captures.swift @@ -1,5 +1,4 @@ // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s -// RUN: %target-swift-frontend -enable-experimental-async-top-level -emit-silgen %s | %FileCheck %s // RUN: %target-swift-frontend -experimental-skip-non-inlinable-function-bodies -experimental-skip-non-inlinable-function-bodies-without-types -emit-silgen %s | %FileCheck -check-prefix=SKIPPED-FUNC-EMITTED %s guard let x: Int = nil else { while true { } } diff --git a/test/SILGen/toplevel.swift b/test/SILGen/toplevel.swift index ec52e361d2191..ad38df3fd6685 100644 --- a/test/SILGen/toplevel.swift +++ b/test/SILGen/toplevel.swift @@ -1,5 +1,4 @@ // RUN: %target-swift-emit-silgen -Xllvm -sil-print-types -Xllvm -sil-full-demangle %s | %FileCheck %s -// RUN: %target-swift-emit-silgen -Xllvm -sil-print-types -Xllvm -sil-full-demangle -enable-experimental-async-top-level %s | %FileCheck %s func markUsed(_ t: T) {} diff --git a/test/SILGen/toplevel_errors.swift b/test/SILGen/toplevel_errors.swift index ad08d88d4b404..6d9d563618456 100644 --- a/test/SILGen/toplevel_errors.swift +++ b/test/SILGen/toplevel_errors.swift @@ -1,5 +1,4 @@ // RUN: %target-swift-emit-silgen -Xllvm -sil-print-types %s | %FileCheck %s -// RUN: %target-swift-emit-silgen -Xllvm -sil-print-types -enable-experimental-async-top-level %s | %FileCheck %s enum MyError : Error { case A, B diff --git a/test/SILGen/toplevel_globalactorvars.swift b/test/SILGen/toplevel_globalactorvars.swift index 9a4d7228770fb..f482ccd7807fb 100644 --- a/test/SILGen/toplevel_globalactorvars.swift +++ b/test/SILGen/toplevel_globalactorvars.swift @@ -1,4 +1,4 @@ -// RUN: %target-swift-emit-silgen -Xllvm -sil-print-types -Xllvm -sil-full-demangle -target %target-swift-5.1-abi-triple -enable-experimental-async-top-level %s | %FileCheck %s +// RUN: %target-swift-emit-silgen -Xllvm -sil-print-types -Xllvm -sil-full-demangle -target %target-swift-5.1-abi-triple %s | %FileCheck %s // a // CHECK-LABEL: sil_global hidden @$s24toplevel_globalactorvars1aSivp : $Int From 4ac0239edd8196b0c8274f51cbfdeeb58dd29e01 Mon Sep 17 00:00:00 2001 From: Hamish Knight Date: Mon, 15 Dec 2025 17:38:03 +0000 Subject: [PATCH 7/8] fix top level vars --- include/swift/AST/ASTScope.h | 14 ++++--- include/swift/AST/Decl.h | 13 +++--- include/swift/AST/DiagnosticsSema.def | 10 ----- include/swift/Parse/Parser.h | 3 +- lib/AST/ASTDumper.cpp | 1 - lib/AST/ASTScope.cpp | 2 +- lib/AST/ASTScopeCreation.cpp | 25 ++++-------- lib/AST/ASTScopeLookup.cpp | 14 +++++++ lib/AST/ASTScopeSourceRange.cpp | 2 +- lib/AST/ASTVerifier.cpp | 4 ++ lib/AST/Bridging/DeclBridging.cpp | 1 - lib/AST/Decl.cpp | 37 ++++++++++++++--- lib/AST/Module.cpp | 5 --- lib/Parse/ParseDecl.cpp | 47 ++++++++++++---------- lib/SILGen/SILGenLValue.cpp | 3 +- lib/Sema/CSDiagnostics.cpp | 11 +---- lib/Sema/TypeCheckAttr.cpp | 11 ----- lib/Sema/TypeCheckConcurrency.cpp | 58 ++++++++++++++++----------- lib/Sema/TypeCheckConstraints.cpp | 12 ++++++ lib/Sema/TypeCheckStorage.cpp | 11 ++--- lib/Serialization/Deserialization.cpp | 4 -- lib/Serialization/ModuleFormat.h | 3 +- lib/Serialization/Serialization.cpp | 1 - 23 files changed, 151 insertions(+), 141 deletions(-) diff --git a/include/swift/AST/ASTScope.h b/include/swift/AST/ASTScope.h index 5b1ebcc4d053d..2dc02b778b810 100644 --- a/include/swift/AST/ASTScope.h +++ b/include/swift/AST/ASTScope.h @@ -140,6 +140,7 @@ class ASTScopeImpl : public ASTAllocated { friend class GenericTypeOrExtensionWherePortion; friend class GenericTypeOrExtensionWherePortion; friend class IterableTypeBodyPortion; + friend class TopLevelCodeScope; friend class ScopeCreator; friend class ASTSourceFileScope; friend class ABIAttributeScope; @@ -245,7 +246,7 @@ class ASTScopeImpl : public ASTAllocated { #pragma mark - debugging and printing public: - const SourceFile *getSourceFile() const; + SourceFile *getSourceFile() const; std::string getClassName() const; /// Print out this scope for debugging/reporting purposes. @@ -1212,18 +1213,19 @@ class ClosureParametersScope final : public ASTScopeImpl { class TopLevelCodeScope final : public ASTScopeImpl { public: TopLevelCodeDecl *const decl; - SourceLoc endLoc; + ASTScopeImpl *insertionPoint = nullptr; - TopLevelCodeScope(TopLevelCodeDecl *e, SourceLoc endLoc) - : ASTScopeImpl(ScopeKind::TopLevelCode), decl(e), endLoc(endLoc) {} + TopLevelCodeScope(TopLevelCodeDecl *e) + : ASTScopeImpl(ScopeKind::TopLevelCode), decl(e) {} virtual ~TopLevelCodeScope() {} protected: ASTScopeImpl *expandSpecifically(ScopeCreator &scopeCreator) override; + NullablePtr getLookupParent() const override; + private: - AnnotatedInsertionPoint - expandAScopeThatCreatesANewInsertionPoint(ScopeCreator &); + void expandAScopeThatDoesNotCreateANewInsertionPoint(ScopeCreator &); public: SourceRange diff --git a/include/swift/AST/Decl.h b/include/swift/AST/Decl.h index 80b587100830a..23570c20a1856 100644 --- a/include/swift/AST/Decl.h +++ b/include/swift/AST/Decl.h @@ -503,7 +503,7 @@ class alignas(1 << DeclAlignInBits) Decl : public ASTAllocated, public Swi IsStatic : 1 ); - SWIFT_INLINE_BITFIELD(VarDecl, AbstractStorageDecl, 2+1+1+1+1+1+1+1+1, + SWIFT_INLINE_BITFIELD(VarDecl, AbstractStorageDecl, 2+1+1+1+1+1+1+1, /// Encodes whether this is a 'let' binding. Introducer : 2, @@ -520,9 +520,6 @@ class alignas(1 << DeclAlignInBits) Decl : public ASTAllocated, public Swi /// Whether this is the backing storage for a property wrapper. IsPropertyWrapperBackingProperty : 1, - /// Whether this is a lazily top-level global variable from the main file. - IsTopLevelGlobal : 1, - /// Whether this variable has no attached property wrappers. NoAttachedPropertyWrappers : 1, @@ -2879,6 +2876,8 @@ class PatternBindingDecl final : public Decl, /// global variables. class TopLevelCodeDecl : public DeclContext, public Decl { BraceStmt *Body; + std::optional Previous; + SourceLoc getLocFromSource() const { return getStartLoc(); } friend class Decl; public: @@ -2890,6 +2889,8 @@ class TopLevelCodeDecl : public DeclContext, public Decl { BraceStmt *getBody() const { return Body; } void setBody(BraceStmt *b) { Body = b; } + TopLevelCodeDecl *getPrevious() const; + SourceLoc getStartLoc() const; SourceRange getSourceRange() const; @@ -6816,10 +6817,6 @@ class VarDecl : public AbstractStorageDecl { /// Retrieve the backing storage property for a lazy property. VarDecl *getLazyStorageProperty() const; - /// True if this is a top-level global variable from the main source file. - bool isTopLevelGlobal() const { return Bits.VarDecl.IsTopLevelGlobal; } - void setTopLevelGlobal(bool b) { Bits.VarDecl.IsTopLevelGlobal = b; } - /// True if this is any storage of static duration (global scope or static). bool isGlobalStorage() const; diff --git a/include/swift/AST/DiagnosticsSema.def b/include/swift/AST/DiagnosticsSema.def index 85f532689e213..99ef46993dbf1 100644 --- a/include/swift/AST/DiagnosticsSema.def +++ b/include/swift/AST/DiagnosticsSema.def @@ -6203,8 +6203,6 @@ ERROR(global_actor_arg,none, (Type)) ERROR(global_actor_non_final_class,none, "non-final class %0 cannot be a global actor", (DeclName)) -ERROR(global_actor_top_level_var,none, - "top-level code variables cannot have a global actor", ()) ERROR(global_actor_access,none, "%select{private|fileprivate|internal|package|public|open}0 %kind1 " "cannot have %select{private|fileprivate|internal|package|%error|%error}2 " @@ -7216,14 +7214,6 @@ ERROR(availability_decl_no_unavailable, none, "%kindonly0 cannot be marked unavailable with '@available'", (const Decl *)) -ERROR(availability_global_script_no_potential, - none, "global variable cannot be marked potentially " - "unavailable with '@available' in script mode", ()) - -ERROR(availability_global_script_no_unavailable, - none, "global variable cannot be marked unavailable " - "with '@available' in script mode", ()) - ERROR(availability_stored_property_no_potential, none, "stored properties cannot be marked potentially unavailable with " "'@available'", ()) diff --git a/include/swift/Parse/Parser.h b/include/swift/Parse/Parser.h index c06cdc402a9e8..4faf1d1dc866f 100644 --- a/include/swift/Parse/Parser.h +++ b/include/swift/Parse/Parser.h @@ -1299,8 +1299,7 @@ class Parser { StaticSpellingKind StaticSpelling, SourceLoc VarLoc, bool hasInitializer, - const DeclAttributes &Attributes, - SmallVectorImpl &Decls); + const DeclAttributes &Attributes); ParserStatus parseGetEffectSpecifier(ParsedAccessors &accessors, SourceLoc &asyncLoc, SourceLoc &throwsLoc, diff --git a/lib/AST/ASTDumper.cpp b/lib/AST/ASTDumper.cpp index bef1826bc5c5c..8083167158db6 100644 --- a/lib/AST/ASTDumper.cpp +++ b/lib/AST/ASTDumper.cpp @@ -2620,7 +2620,6 @@ namespace { printFlag(VD->isDebuggerVar(), "debugger_var", DeclModifierColor); printFlag(VD->isLazyStorageProperty(), "lazy_storage_property", DeclModifierColor); - printFlag(VD->isTopLevelGlobal(), "top_level_global", DeclModifierColor); printFlag(VD->isLazyStorageProperty(), "lazy_storage_property", DeclModifierColor); diff --git a/lib/AST/ASTScope.cpp b/lib/AST/ASTScope.cpp index 784ba2ad744bd..4a3a0376b10ba 100644 --- a/lib/AST/ASTScope.cpp +++ b/lib/AST/ASTScope.cpp @@ -334,7 +334,7 @@ ASTContext &ASTScopeImpl::getASTContext() const { #pragma mark getSourceFile -const SourceFile *ASTScopeImpl::getSourceFile() const { +SourceFile *ASTScopeImpl::getSourceFile() const { if (auto sourceFileScope = dyn_cast(this)) return sourceFileScope->SF; diff --git a/lib/AST/ASTScopeCreation.cpp b/lib/AST/ASTScopeCreation.cpp index 4f3afb310f91d..a293537b3e7de 100644 --- a/lib/AST/ASTScopeCreation.cpp +++ b/lib/AST/ASTScopeCreation.cpp @@ -483,9 +483,7 @@ class NodeAdder ASTScopeImpl *visitTopLevelCodeDecl(TopLevelCodeDecl *d, ASTScopeImpl *p, ScopeCreator &scopeCreator) { - ASTScopeAssert(endLoc.has_value(), "TopLevelCodeDecl in wrong place?"); - return scopeCreator.constructExpandAndInsert( - p, d, *endLoc); + return scopeCreator.constructExpandAndInsert(p, d); } #pragma mark special-case creation @@ -800,10 +798,10 @@ CREATES_NEW_INSERTION_POINT(GuardStmtScope) CREATES_NEW_INSERTION_POINT(PatternEntryDeclScope) CREATES_NEW_INSERTION_POINT(GenericTypeOrExtensionScope) CREATES_NEW_INSERTION_POINT(BraceStmtScope) -CREATES_NEW_INSERTION_POINT(TopLevelCodeScope) CREATES_NEW_INSERTION_POINT(ConditionalClausePatternUseScope) CREATES_NEW_INSERTION_POINT(ABIAttributeScope) +NO_NEW_INSERTION_POINT(TopLevelCodeScope) NO_NEW_INSERTION_POINT(FunctionBodyScope) NO_NEW_INSERTION_POINT(AbstractFunctionDeclScope) NO_NEW_INSERTION_POINT(CustomAttributeScope) @@ -1017,19 +1015,6 @@ BraceStmtScope::expandAScopeThatCreatesANewInsertionPoint( "For top-level code decls, need the scope under, say a guard statement."}; } -AnnotatedInsertionPoint -TopLevelCodeScope::expandAScopeThatCreatesANewInsertionPoint(ScopeCreator & - scopeCreator) { - - auto *body = - scopeCreator - .addToScopeTreeAndReturnInsertionPoint(decl->getBody(), this, endLoc); - - return {body, "So next top level code scope and put its decls in its body " - "under a guard statement scope (etc) from the last top level " - "code scope"}; -} - AnnotatedInsertionPoint ABIAttributeScope::expandAScopeThatCreatesANewInsertionPoint( ScopeCreator &scopeCreator) { @@ -1294,6 +1279,12 @@ void CustomAttributeScope:: } } +void TopLevelCodeScope::expandAScopeThatDoesNotCreateANewInsertionPoint( + ScopeCreator &scopeCreator) { + insertionPoint = scopeCreator.addToScopeTreeAndReturnInsertionPoint(decl->getBody(), this, + std::nullopt); +} + #pragma mark expandScope ASTScopeImpl *GenericTypeOrExtensionWholePortion::expandScope( diff --git a/lib/AST/ASTScopeLookup.cpp b/lib/AST/ASTScopeLookup.cpp index 4b03da3e2a42e..36c99a90fb522 100644 --- a/lib/AST/ASTScopeLookup.cpp +++ b/lib/AST/ASTScopeLookup.cpp @@ -353,6 +353,20 @@ ConditionalClauseInitializerScope::getLookupParent() const { return parent->getLookupParent(); } +NullablePtr TopLevelCodeScope::getLookupParent() const { + auto parent = getParent().get(); + if (auto *prev = decl->getPrevious()) { + auto *fileScope = cast(parent); + auto prevScope = fileScope->findChildContaining(prev->getEndLoc(), getSourceManager()); + if (auto *prevTopLevel = dyn_cast(prevScope.getPtrOrNull())) { + if (!prevTopLevel->getWasExpanded()) + prevTopLevel->expandAndBeCurrent(const_cast(this)->getScopeCreator()); + return prevTopLevel->insertionPoint; + } + } + return parent; +} + #pragma mark looking in locals or members - locals bool GenericParamScope::lookupLocalsOrMembers(DeclConsumer consumer) const { diff --git a/lib/AST/ASTScopeSourceRange.cpp b/lib/AST/ASTScopeSourceRange.cpp index c2f217d79f686..3caaa2d3cd4a8 100644 --- a/lib/AST/ASTScopeSourceRange.cpp +++ b/lib/AST/ASTScopeSourceRange.cpp @@ -127,7 +127,7 @@ SourceRange FunctionBodyScope::getSourceRangeOfThisASTNode( SourceRange TopLevelCodeScope::getSourceRangeOfThisASTNode( const bool omitAssertions) const { - return SourceRange(decl->getStartLoc(), endLoc); + return decl->getSourceRange(); } SourceRange SubscriptDeclScope::getSourceRangeOfThisASTNode( diff --git a/lib/AST/ASTVerifier.cpp b/lib/AST/ASTVerifier.cpp index 1f4d3eced7d6f..68ce2562d7a6f 100644 --- a/lib/AST/ASTVerifier.cpp +++ b/lib/AST/ASTVerifier.cpp @@ -2642,10 +2642,14 @@ class Verifier : public ASTWalker { } void verifyChecked(PatternBindingDecl *binding) { + auto isTopLevel = isa(binding->getDeclContext()); // Look at all of the VarDecls being bound. for (auto idx : range(binding->getNumPatternEntries())) if (auto *P = binding->getPattern(idx)) P->forEachVariable([&](VarDecl *VD) { + auto varIsTopLevel = isa(VD->getDeclContext()); + ASSERT(isTopLevel == varIsTopLevel && + "Must have consistent top-level context"); // ParamDecls never get PBD's. assert(!isa(VD) && "ParamDecl has a PatternBindingDecl?"); }); diff --git a/lib/AST/Bridging/DeclBridging.cpp b/lib/AST/Bridging/DeclBridging.cpp index 1fed8d93549fc..f7257085a2352 100644 --- a/lib/AST/Bridging/DeclBridging.cpp +++ b/lib/AST/Bridging/DeclBridging.cpp @@ -179,7 +179,6 @@ BridgedPatternBindingDecl BridgedPatternBindingDecl_createParsed( VD->attachParsedAttrs(cAttrs.unbridged()); VD->setStatic(staticLoc.isValid()); VD->setIntroducer(introducer); - VD->setTopLevelGlobal(isa(declContext)); }); entries.emplace_back(pattern, entry.equalLoc, entry.init.unbridged(), diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp index 535479748b148..5d38819d84f7b 100644 --- a/lib/AST/Decl.cpp +++ b/lib/AST/Decl.cpp @@ -1231,8 +1231,16 @@ bool Decl::preconcurrency() const { // Variables declared in top-level code are @_predatesConcurrency if (const VarDecl *var = dyn_cast(this)) { + auto *DC = var->getDeclContext(); + auto isTopLevelScriptVar = [&]() { + if (!DC->isModuleScopeContext()) + return false; + auto varLoc = var->getLoc(/*SerializedOK*/ false); + auto *SF = DC->getParentModule()->getSourceFileContainingLocation(varLoc); + return SF && SF->isScriptMode(); + }; return !getASTContext().isLanguageModeAtLeast(6) && - var->isTopLevelGlobal() && var->getDeclContext()->isAsyncContext(); + isTopLevelScriptVar() && DC->isAsyncContext(); } return false; @@ -2967,6 +2975,25 @@ SourceLoc PatternBindingDecl::getEqualLoc(unsigned i) const { return entry.getEqualLoc(); } +TopLevelCodeDecl *TopLevelCodeDecl::getPrevious() const { + if (Previous) + return Previous.value(); + + auto *SF = getParentSourceFile(); + ASSERT(SF); + + TopLevelCodeDecl *prev = nullptr; + for (auto *D : SF->getTopLevelDecls()) { + auto *TLCD = dyn_cast(D); + if (!TLCD) + continue; + + TLCD->Previous = prev; + prev = TLCD; + } + return Previous.value(); +} + SourceLoc TopLevelCodeDecl::getStartLoc() const { return Body ? Body->getStartLoc() : SourceLoc(); } @@ -8054,7 +8081,6 @@ VarDecl::VarDecl(DeclKind kind, bool isStatic, VarDecl::Introducer introducer, Bits.VarDecl.IsDebuggerVar = false; Bits.VarDecl.IsLazyStorageProperty = false; Bits.VarDecl.IsPropertyWrapperBackingProperty = false; - Bits.VarDecl.IsTopLevelGlobal = false; Bits.VarDecl.NoAttachedPropertyWrappers = false; Bits.VarDecl.NoPropertyWrapperAuxiliaryVariables = false; Bits.VarDecl.IsPlaceholderVar = false; @@ -8192,7 +8218,8 @@ VarDecl::mutability(const DeclContext *UseDC, } if (isa(UseDC) && - getDeclContext() == UseDC->getParent()) + isa(getDeclContext()) && + getDeclContext()->getParent() == UseDC->getParent()) return StorageMutability::Initializable; return StorageMutability::Immutable; @@ -8217,9 +8244,7 @@ bool VarDecl::isLazilyInitializedGlobal() const { if (getAttrs().hasAttribute()) return false; - // Top-level global variables in the main source file and in the REPL are not - // lazily initialized. - return !isTopLevelGlobal(); + return true; } Expr *VarDecl::getParentExecutableInitializer() const { diff --git a/lib/AST/Module.cpp b/lib/AST/Module.cpp index ab10d2ebf03e9..f5d6d7eb73bba 100644 --- a/lib/AST/Module.cpp +++ b/lib/AST/Module.cpp @@ -341,11 +341,6 @@ void SourceLookupCache::addToUnqualifiedLookupCache(Range items, else if (auto *MED = dyn_cast(D)) { if (!onlyOperators) MayHaveAuxiliaryDecls.push_back(MED); - } else if (auto TLCD = dyn_cast(D)) { - if (auto body = TLCD->getBody()){ - addToUnqualifiedLookupCache(body->getElements(), onlyOperators, - onlyDerivatives); - } } } } diff --git a/lib/Parse/ParseDecl.cpp b/lib/Parse/ParseDecl.cpp index b54cab95ed9c3..582b2f1573e8c 100644 --- a/lib/Parse/ParseDecl.cpp +++ b/lib/Parse/ParseDecl.cpp @@ -3519,9 +3519,13 @@ ParserStatus Parser::parseNewDeclAttribute(DeclAttributes &Attributes, // FIXME: Do we need to reparent these decls to match their counterparts? // Feels like there might be more to do here. if (auto tlcd = dyn_cast(D)) { - ASSERT(tlcd->getBody()->getNumElements() == 1 - && "TopLevelCodeDecl with != 1 element?"); - D = tlcd->getBody()->getElements().front().dyn_cast(); + auto elts = tlcd->getBody()->getElements(); + ASSERT(!elts.empty()); + + auto *firstDecl = elts.front().dyn_cast(); + ASSERT(isa_and_nonnull(firstDecl) || + elts.size() == 1 && "TopLevelCodeDecl with != 1 element?"); + D = firstDecl; if (!D) return; } @@ -8537,8 +8541,7 @@ Parser::parseDeclVarGetSet(PatternBindingEntry &entry, ParseDeclOptions Flags, SourceLoc StaticLoc, StaticSpellingKind StaticSpelling, SourceLoc VarLoc, bool hasInitializer, - const DeclAttributes &Attributes, - SmallVectorImpl &Decls) { + const DeclAttributes &Attributes) { bool Invalid = false; auto *pattern = entry.getPattern(); @@ -8865,20 +8868,23 @@ Parser::parseDeclVar(ParseDeclOptions Flags, // We follow the same rule for @_extern. TopLevelCodeDecl *topLevelDecl = nullptr; if (allowTopLevelCode() && CurDeclContext->isModuleScopeContext() && - !IsConst) { + !IsConst && !Attributes.hasAttribute()) { // The body of topLevelDecl will get set later. topLevelDecl = new (Context) TopLevelCodeDecl(CurDeclContext); } + std::optional topLevelParser; + if (topLevelDecl) + topLevelParser.emplace(*this, topLevelDecl); bool HasAccessors = false; // Syntactically has accessor {}'s. ParserStatus Status; - unsigned NumDeclsInResult = Decls.size(); - + SmallVector NewDecls; + // In var/let decl with multiple patterns, accumulate them all in this list // so we can build our singular PatternBindingDecl at the end. SmallVector PBDEntries; - DeclContext *BindingContext = topLevelDecl ? topLevelDecl : CurDeclContext; + DeclContext *const BindingContext = CurDeclContext; // No matter what error path we take, make sure the // PatternBindingDecl/TopLevel code block are added. @@ -8894,22 +8900,26 @@ Parser::parseDeclVar(ParseDeclOptions Flags, // pattern/initializer pairs. auto *PBD = PatternBindingDecl::create(Context, StaticLoc, StaticSpelling, VarLoc, PBDEntries, BindingContext); + NewDecls.insert(NewDecls.begin(), PBD); // If we're setting up a TopLevelCodeDecl, configure it by setting up the // body that holds PBD and we're done. The TopLevelCodeDecl is already set // up in Decls to be returned to caller. if (topLevelDecl) { auto range = PBD->getSourceRangeIncludingAttrs(); + SmallVector Nodes; + for (auto *D : NewDecls) + Nodes.push_back(D); topLevelDecl->setBody(BraceStmt::create(Context, range.Start, - ASTNode(PBD), range.End, true)); - Decls.insert(Decls.begin()+NumDeclsInResult, topLevelDecl); + Nodes, range.End, true)); + Decls.push_back(topLevelDecl); return makeParserResult(Status, PBD); } // Otherwise return the PBD in "Decls" to the caller. We add it at a // specific spot to get it in before any accessors, which SILGen seems to // want. - Decls.insert(Decls.begin()+NumDeclsInResult, PBD); + Decls.append(NewDecls.begin(), NewDecls.end()); // Always return the result for PBD. return makeParserResult(Status, PBD); @@ -8943,9 +8953,7 @@ Parser::parseDeclVar(ParseDeclOptions Flags, pattern->forEachVariable([&](VarDecl *VD) { VD->setStatic(StaticLoc.isValid()); VD->attachParsedAttrs(Attributes); - VD->setTopLevelGlobal(topLevelDecl); - - Decls.push_back(VD); + NewDecls.push_back(VD); }); // Remember this pattern/init pair for our ultimate PatternBindingDecl. The @@ -8961,18 +8969,15 @@ Parser::parseDeclVar(ParseDeclOptions Flags, // If we have no local context to parse the initial value into, create one // for the PBD we'll eventually create. This allows us to have reasonable // DeclContexts for any closures that may live inside of initializers. - if (!CurDeclContext->isLocalContext() && !topLevelDecl) { + if (!BindingContext->isLocalContext()) { assert(!initContext && "There cannot be an init context yet"); - initContext = PatternBindingInitializer::create(CurDeclContext); + initContext = PatternBindingInitializer::create(BindingContext); } // If we're using a local context (either a TopLevelCodeDecl or a // PatternBindingContext) install it now so that CurDeclContext is set // right when parsing the initializer. std::optional initParser; - std::optional topLevelParser; - if (topLevelDecl) - topLevelParser.emplace(*this, topLevelDecl); if (initContext) initParser.emplace(*this, initContext); @@ -9030,7 +9035,7 @@ Parser::parseDeclVar(ParseDeclOptions Flags, HasAccessors = true; auto boundVar = parseDeclVarGetSet( PBDEntries.back(), Flags, StaticLoc, StaticSpelling, VarLoc, - PatternInit != nullptr, Attributes, Decls); + PatternInit != nullptr, Attributes); if (boundVar.hasCodeCompletion()) return makeResult(makeParserCodeCompletionStatus()); } diff --git a/lib/SILGen/SILGenLValue.cpp b/lib/SILGen/SILGenLValue.cpp index fdd8d978edfc0..647b678c5a2ba 100644 --- a/lib/SILGen/SILGenLValue.cpp +++ b/lib/SILGen/SILGenLValue.cpp @@ -3605,8 +3605,7 @@ void LValue::addNonMemberVarComponent( address = SGF.emitGlobalVariableRef(Loc, Storage, ActorIso); isLazyInitializedGlobal = Storage->isLazilyInitializedGlobal(); } else { - assert((!ActorIso || Storage->isTopLevelGlobal()) && - "local var should not be actor isolated!"); + assert(!ActorIso && "local var should not be actor isolated!"); } if (!address.isLValue()) { diff --git a/lib/Sema/CSDiagnostics.cpp b/lib/Sema/CSDiagnostics.cpp index 80abf67a9db35..003f8830eb135 100644 --- a/lib/Sema/CSDiagnostics.cpp +++ b/lib/Sema/CSDiagnostics.cpp @@ -7399,16 +7399,7 @@ void InOutConversionFailure::fixItChangeArgumentType() const { return; // Don't emit for non-local variables. - // (But in script-mode files, we consider module-scoped - // variables in the same file to be local variables.) - auto VDC = VD->getDeclContext(); - bool isLocalVar = VDC->isLocalContext(); - if (!isLocalVar && VDC->isModuleScopeContext()) { - auto argFile = DC->getParentSourceFile(); - auto varFile = VDC->getParentSourceFile(); - isLocalVar = (argFile == varFile && argFile->isScriptMode()); - } - if (!isLocalVar) + if (!VD->getDeclContext()->isLocalContext()) return; auto actualType = getFromType(); diff --git a/lib/Sema/TypeCheckAttr.cpp b/lib/Sema/TypeCheckAttr.cpp index 746113fe0d2c8..b5298cc4b745a 100644 --- a/lib/Sema/TypeCheckAttr.cpp +++ b/lib/Sema/TypeCheckAttr.cpp @@ -5677,12 +5677,6 @@ TypeChecker::diagnosticIfDeclCannotBePotentiallyUnavailable(const Decl *D) { if (!VD->hasStorageOrWrapsStorage()) return std::nullopt; - // Do not permit potential availability of script-mode global variables; - // their initializer expression is not lazily evaluated, so this would - // not be safe. - if (VD->isTopLevelGlobal()) - return diag::availability_global_script_no_potential; - // Globals and statics are lazily initialized, so they are safe // for potential unavailability. if (!VD->isStatic() && !DC->isModuleScopeContext()) @@ -5764,11 +5758,6 @@ TypeChecker::diagnosticIfDeclCannotBeUnavailable(const Decl *D, if (D->getDeclContext()->isInSwiftinterface()) return std::nullopt; - // Do not permit unavailable script-mode global variables; their initializer - // expression is not lazily evaluated, so this would not be safe. - if (VD->isTopLevelGlobal()) - return diag::availability_global_script_no_unavailable; - // Globals and statics are lazily initialized, so they are safe for // unavailability. if (!VD->isStatic() && !D->getDeclContext()->isModuleScopeContext()) diff --git a/lib/Sema/TypeCheckConcurrency.cpp b/lib/Sema/TypeCheckConcurrency.cpp index 9cfe3bac19fc5..48473dfe49ecc 100644 --- a/lib/Sema/TypeCheckConcurrency.cpp +++ b/lib/Sema/TypeCheckConcurrency.cpp @@ -422,18 +422,7 @@ GlobalActorAttributeRequest::evaluate( } else if (auto storage = dyn_cast(decl)) { // Subscripts and properties are fine... if (auto var = dyn_cast(storage)) { - - // ... but not if it's an async-context top-level global - if (var->isTopLevelGlobal() && - (var->getDeclContext()->isAsyncContext() || - var->getASTContext().LangOpts.StrictConcurrencyLevel >= - StrictConcurrency::Complete)) { - var->diagnose(diag::global_actor_top_level_var) - .highlight(globalActorAttr->getRangeWithAt()); - return std::nullopt; - } - - // ... and not if it's local property + // ... but not if it's local var if (var->getDeclContext()->isLocalContext()) { var->diagnose(diag::global_actor_on_local_variable, var->getName()) .highlight(globalActorAttr->getRangeWithAt()); @@ -6590,18 +6579,39 @@ static InferredActorIsolation computeActorIsolation(Evaluator &evaluator, if (auto var = dyn_cast(value)) { auto &ctx = var->getASTContext(); - if (!ctx.LangOpts.isConcurrencyModelTaskToThread() && - var->isTopLevelGlobal() && - (ctx.LangOpts.StrictConcurrencyLevel >= - StrictConcurrency::Complete || - var->getDeclContext()->isAsyncContext())) { - if (Type mainActor = var->getASTContext().getMainActorType()) - return { - inferredIsolation( - ActorIsolation::forGlobalActor(mainActor)) - .withPreconcurrency(var->preconcurrency()), - IsolationSource(/*source*/nullptr, IsolationSource::TopLevelCode) - }; + + // FIXME: Do we still want this? + auto getMainActorForTopLevelVar = [&]() -> Type { + Type mainActor = ctx.getMainActorType(); + if (!mainActor) + return Type(); + + if (ctx.LangOpts.isConcurrencyModelTaskToThread()) + return Type(); + + auto *DC = var->getDeclContext(); + if (!DC->isModuleScopeContext()) + return Type(); + + if (ctx.LangOpts.StrictConcurrencyLevel < StrictConcurrency::Complete && + !DC->isAsyncContext()) { + return Type(); + } + + auto varLoc = var->getLoc(/*SerializedOK*/ false); + auto *SF = DC->getParentModule()->getSourceFileContainingLocation(varLoc); + if (!SF || !SF->isScriptMode()) + return Type(); + + return mainActor; + }; + if (auto mainActor = getMainActorForTopLevelVar()) { + return { + inferredIsolation( + ActorIsolation::forGlobalActor(mainActor)) + .withPreconcurrency(var->preconcurrency()), + IsolationSource(/*source*/nullptr, IsolationSource::TopLevelCode) + }; } if (auto isolation = getActorIsolationFromWrappedProperty(var)) { return { diff --git a/lib/Sema/TypeCheckConstraints.cpp b/lib/Sema/TypeCheckConstraints.cpp index 71c5083d3751f..c3667952794db 100644 --- a/lib/Sema/TypeCheckConstraints.cpp +++ b/lib/Sema/TypeCheckConstraints.cpp @@ -835,6 +835,18 @@ bool TypeChecker::typeCheckBinding(Pattern *&pattern, Expr *&initializer, : SyntacticElementTarget::forInitialization( initializer, DC, patternType, pattern, /*bindPatternVarsOneWay=*/false); + if (PBD) { + auto pbdIsTopLevel = isa(PBD->getDeclContext()); + for (auto idx : range(PBD->getNumPatternEntries())) { + if (auto *P = PBD->getPattern(idx)) { + P->forEachVariable([&](VarDecl *VD) { + auto varIsTopLevel = isa(PBD->getDeclContext()); + ASSERT(pbdIsTopLevel == varIsTopLevel && + "Must have consistent top-level context"); + }); + } + } + } // Bindings cannot be type-checked independently from their context in a // closure, make sure we don't ever attempt to do this. If we want to be able diff --git a/lib/Sema/TypeCheckStorage.cpp b/lib/Sema/TypeCheckStorage.cpp index 83013c8207559..6d16082136ea7 100644 --- a/lib/Sema/TypeCheckStorage.cpp +++ b/lib/Sema/TypeCheckStorage.cpp @@ -89,15 +89,10 @@ static bool contextAllowsPatternBindingWithoutVariables(DeclContext *dc) { if (dc->isTypeContext()) return false; - // Global variable decls must bind variables, except in scripts. - if (dc->isModuleScopeContext()) { - if (dc->getParentSourceFile() - && dc->getParentSourceFile()->isScriptMode()) - return true; - + // Global variable decls must bind variables. + if (dc->isModuleScopeContext()) return false; - } - + return true; } diff --git a/lib/Serialization/Deserialization.cpp b/lib/Serialization/Deserialization.cpp index 6ce5d95049b27..52c1c947865d3 100644 --- a/lib/Serialization/Deserialization.cpp +++ b/lib/Serialization/Deserialization.cpp @@ -4002,7 +4002,6 @@ class DeclDeserializer { bool isImplicit, isObjC, isStatic; uint8_t rawIntroducer; bool isGetterMutating, isSetterMutating; - bool isTopLevelGlobal; DeclID lazyStorageID; unsigned numAccessors, numBackingProperties; uint8_t readImpl, writeImpl, readWriteImpl, opaqueReadOwnership; @@ -4017,7 +4016,6 @@ class DeclDeserializer { decls_block::VarLayout::readRecord(scratch, nameID, contextID, isImplicit, isObjC, isStatic, rawIntroducer, isGetterMutating, isSetterMutating, - isTopLevelGlobal, lazyStorageID, opaqueReadOwnership, readImpl, writeImpl, readWriteImpl, @@ -4170,8 +4168,6 @@ class DeclDeserializer { storage->setLazyStorageFor(var); } - var->setTopLevelGlobal(isTopLevelGlobal); - // If there are any backing properties, record them. if (numBackingProperties > 0) { auto backingDecl = MF.getDeclChecked(backingPropertyIDs[0]); diff --git a/lib/Serialization/ModuleFormat.h b/lib/Serialization/ModuleFormat.h index 2a41a0c01f913..54d2955f009a3 100644 --- a/lib/Serialization/ModuleFormat.h +++ b/lib/Serialization/ModuleFormat.h @@ -58,7 +58,7 @@ const uint16_t SWIFTMODULE_VERSION_MAJOR = 0; /// describe what change you made. The content of this comment isn't important; /// it just ensures a conflict if two people change the module format. /// Don't worry about adhering to the 80-column limit for this line. -const uint16_t SWIFTMODULE_VERSION_MINOR = 978; // @warn attribute +const uint16_t SWIFTMODULE_VERSION_MINOR = 979; // remove top level global /// A standard hash seed used for all string hashes in a serialized module. /// @@ -1730,7 +1730,6 @@ namespace decls_block { VarDeclIntroducerField, // introducer BCFixed<1>, // is getter mutating? BCFixed<1>, // is setter mutating? - BCFixed<1>, // top level global? DeclIDField, // if this is a lazy property, this is the backing storage OpaqueReadOwnershipField, // opaque read ownership ReadImplKindField, // read implementation diff --git a/lib/Serialization/Serialization.cpp b/lib/Serialization/Serialization.cpp index 22af1f5a88a4e..05a433027df1e 100644 --- a/lib/Serialization/Serialization.cpp +++ b/lib/Serialization/Serialization.cpp @@ -4769,7 +4769,6 @@ class Serializer::DeclSerializer : public DeclVisitor { rawIntroducer, var->isGetterMutating(), var->isSetterMutating(), - var->isTopLevelGlobal(), S.addDeclRef(lazyStorage), accessors.OpaqueReadOwnership, accessors.ReadImpl, From 3ae8bd46a0af96fb62136cbf33add4c1b091a2e7 Mon Sep 17 00:00:00 2001 From: Hamish Knight Date: Mon, 15 Dec 2025 17:38:03 +0000 Subject: [PATCH 8/8] adjust tests not even close to complete --- .../Runtime/isolated_conformance.swift | 4 +- .../Runtime/isolated_deinit_main_sync.swift | 2 +- .../Runtime/startImmediately.swift | 2 +- .../Runtime/startImmediately_order.swift | 2 +- test/Concurrency/actor_existentials.swift | 2 +- test/Concurrency/actor_inout_isolation.swift | 21 +++++----- test/Concurrency/assume_mainactor.swift | 2 +- test/Concurrency/freestanding_top_level.swift | 4 +- .../global_actor_from_ordinary_context.swift | 11 ++++-- test/Concurrency/global_actor_inference.swift | 3 +- .../sendable_checking_captures_swift5.swift | 2 +- .../sendable_checking_captures_swift6.swift | 2 +- test/Concurrency/task_local.swift | 2 +- .../toplevel/async-5-top-level.swift | 2 +- .../toplevel/async-6-top-level.swift | 2 +- test/Concurrency/toplevel/main.swift | 4 +- .../toplevel/no-async-5-top-level.swift | 2 +- .../toplevel/no-async-6-top-level.swift | 2 +- .../toplevel/synchronous_mainactor.swift | 4 +- test/Concurrency/transfernonsendable.swift | 6 +-- .../transfernonsendable_asynclet.swift | 2 +- ...dable_isolationcrossing_partialapply.swift | 2 +- ...ransfernonsendable_nonisolatedunsafe.swift | 6 +-- test/Concurrency/voucher_propagation.swift | 16 ++++---- test/IDE/complete_accessor.swift | 2 +- test/IDE/complete_at_top_level.swift | 2 +- test/IDE/complete_call_arg.swift | 2 +- test/IDE/complete_default_arguments.swift | 2 +- test/IDE/complete_doc_top_level.swift | 8 ++-- test/IDE/complete_effectful_accessor.swift | 2 +- test/IDE/complete_expr_postfix_begin.swift | 2 +- test/IDE/complete_from_swift_module.swift | 2 +- test/IDE/complete_global_actorisolation.swift | 2 +- test/IDE/complete_in_accessors.swift | 3 +- test/IDE/complete_in_result_builder.swift | 2 +- test/IDE/complete_macro_declaration.swift | 2 +- test/IDE/complete_optional_binding.swift | 8 ++-- test/IDE/complete_pattern.swift | 2 +- ...complete_property_delegate_attribute.swift | 2 +- test/IDE/complete_result_builder.swift | 10 ++--- test/IDE/complete_sequence_invalid.swift | 2 +- test/IDE/complete_shadowing.swift | 2 +- .../complete_single_expression_return.swift | 3 +- test/IDE/complete_sself.swift | 2 +- test/IDE/complete_string_interpolation.swift | 8 ++-- test/IDE/complete_type.swift | 2 +- test/IDE/complete_value_expr.swift | 2 +- test/IDE/complete_vararg.swift | 20 +++++----- test/IDE/local_types.swift | 12 +++--- test/IDE/print_ast_tc_decls.swift | 12 +++--- .../reconstruct_type_from_mangled_name.swift | 2 +- test/IDE/structure.swift | 15 +++++--- test/IDE/structure_object_literals.swift | 4 +- test/Interpreter/SDK/KVO.swift | 2 +- test/Interpreter/SDK/c_pointers.swift | 2 +- test/Interpreter/SDK/objc_bridge_cast.swift | 4 +- ...bjc_dynamic_subclass_protocol_lookup.swift | 2 +- test/Interpreter/SDK/objc_inner_pointer.swift | 2 +- .../SDK/objc_protocol_lookup.swift | 2 +- test/Interpreter/builtin_bridge_object.swift | 24 ++++++------ test/Interpreter/capture_top_level.swift | 9 +++-- .../conditional_conformances_smoke.swift | 2 +- .../convenience_init_peer_delegation.swift | 12 ++++-- .../deinit_recursive_no_overflow.swift | 4 +- .../failable_initializers_root_class.swift | 2 +- .../generic_subscript_static.swift | 2 +- test/Interpreter/initializers.swift | 2 +- test/Interpreter/issue-78598.swift | 2 +- test/Interpreter/lazy/globals.swift | 2 + test/Interpreter/lazy_properties.swift | 6 +-- .../moveonly_deinit_autoclosure.swift | 2 +- .../moveonly_escaping_capture_lifetimes.swift | 2 +- ...nly_escaping_definite_initialization.swift | 4 +- test/Interpreter/moveonly_linkedlist.swift | 2 +- test/Interpreter/objc_class_properties.swift | 4 +- test/Interpreter/objc_types_as_members.swift | 2 +- test/Interpreter/properties.swift | 9 +++-- test/Interpreter/protocol_extensions.swift | 8 ++-- test/Interpreter/refcount_bridgeobject.swift | 2 +- test/Interpreter/refcount_overflow.swift | 2 +- test/Interpreter/subclass_existentials.swift | 2 +- .../synthesized_extension_conformances.swift | 38 +++++++++---------- .../wildcard_dispatch_on_catch.swift | 2 +- .../Interpreter/withoutActuallyEscaping.swift | 4 +- .../moveonly_objectchecker_diagnostics.swift | 2 +- test/SILOptimizer/optimize_keypath.swift | 2 +- .../partial_apply_dynamic_type.swift | 2 +- .../SourceKit/CodeComplete/rdar95772803.swift | 9 +++-- .../ConformingMethods/ifconfigcrash.swift | 4 +- .../test_protocol_reorder_requirements.swift | 2 +- ...r-printWithParensIfNotSimple-e95a50.swift} | 2 +- ...er-printWithParensIfNotSimple-44e8aa.swift | 5 +++ .../slow/rdar21198787.swift.gyb | 2 +- ...ConnectedComponents-unionSets-51b4e1.swift | 6 +++ ...ph-computeConnectedComponents-8dd5e3.swift | 3 ++ ...traintSystem-getCalleeLocator-8b5d56.swift | 5 +++ .../ConstraintSystem-matchTypes-7c8101.swift | 2 +- ...ure-MissingConformanceFailure-25c9a2.swift | 6 +++ .../SILGenBuilder-createEnum-3f34a0.swift | 3 ++ ...ConnectedComponents-unionSets-7527be.swift | 2 +- ...ph-computeConnectedComponents-37d275.swift | 2 +- ...traintSystem-getCalleeLocator-a6b3bc.swift | 2 +- .../ConstraintSystem-matchTypes-7c8101.swift | 6 +++ ...ure-MissingConformanceFailure-da6465.swift | 2 +- .../SILGenBuilder-createEnum-845e70.swift | 2 +- ...typeCheckStmtConditionElement-029cff.swift | 2 +- ...typeCheckStmtConditionElement-266df8.swift | 2 +- ...etCaptureTypeExpansionContext-e72208.swift | 2 +- 108 files changed, 270 insertions(+), 217 deletions(-) rename validation-test/IDE/crashers/{TypePrinter-printWithParensIfNotSimple-44e8aa.swift => TypePrinter-printWithParensIfNotSimple-e95a50.swift} (87%) create mode 100644 validation-test/IDE/crashers_fixed/TypePrinter-printWithParensIfNotSimple-44e8aa.swift create mode 100644 validation-test/compiler_crashers/ConnectedComponents-unionSets-51b4e1.swift create mode 100644 validation-test/compiler_crashers/ConstraintGraph-computeConnectedComponents-8dd5e3.swift create mode 100644 validation-test/compiler_crashers/ConstraintSystem-getCalleeLocator-8b5d56.swift create mode 100644 validation-test/compiler_crashers/MissingConformanceFailure-MissingConformanceFailure-25c9a2.swift create mode 100644 validation-test/compiler_crashers/SILGenBuilder-createEnum-3f34a0.swift rename validation-test/{compiler_crashers => compiler_crashers_fixed}/ConnectedComponents-unionSets-7527be.swift (81%) rename validation-test/{compiler_crashers => compiler_crashers_fixed}/ConstraintGraph-computeConnectedComponents-37d275.swift (83%) rename validation-test/{compiler_crashers => compiler_crashers_fixed}/ConstraintSystem-getCalleeLocator-a6b3bc.swift (90%) create mode 100644 validation-test/compiler_crashers_fixed/ConstraintSystem-matchTypes-7c8101.swift rename validation-test/{compiler_crashers => compiler_crashers_fixed}/MissingConformanceFailure-MissingConformanceFailure-da6465.swift (88%) rename validation-test/{compiler_crashers => compiler_crashers_fixed}/SILGenBuilder-createEnum-845e70.swift (84%) rename validation-test/{compiler_crashers => compiler_crashers_fixed}/TypeChecker-typeCheckStmtConditionElement-029cff.swift (86%) rename validation-test/{compiler_crashers => compiler_crashers_fixed}/TypeChecker-typeCheckStmtConditionElement-266df8.swift (87%) rename validation-test/{compiler_crashers => compiler_crashers_fixed}/TypeConverter-setCaptureTypeExpansionContext-e72208.swift (88%) diff --git a/test/Concurrency/Runtime/isolated_conformance.swift b/test/Concurrency/Runtime/isolated_conformance.swift index 0399f4764b91f..70cb14c62f773 100644 --- a/test/Concurrency/Runtime/isolated_conformance.swift +++ b/test/Concurrency/Runtime/isolated_conformance.swift @@ -147,8 +147,8 @@ func tryCastToQ(_ value: any Sendable) -> Bool { // CHECK-NEXT: MyClass.f() // CHECK-NEXT: Wrapper for MyClass.f() print("Testing on the main actor") -nonisolated let mc = MyClass() -nonisolated let wrappedMC = Wrapper(wrapped: mc) +let mc = MyClass() +let wrappedMC = Wrapper(wrapped: mc) precondition(tryCastToP(mc)) precondition(tryCastToP(wrappedMC)) diff --git a/test/Concurrency/Runtime/isolated_deinit_main_sync.swift b/test/Concurrency/Runtime/isolated_deinit_main_sync.swift index 8b8dc75302ff6..f149bda681ff8 100644 --- a/test/Concurrency/Runtime/isolated_deinit_main_sync.swift +++ b/test/Concurrency/Runtime/isolated_deinit_main_sync.swift @@ -5,7 +5,7 @@ // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime -var isDead: Bool = false +internal var isDead: Bool = false public class Foo { @MainActor diff --git a/test/Concurrency/Runtime/startImmediately.swift b/test/Concurrency/Runtime/startImmediately.swift index 227a61970fc2b..e4fea885bf721 100644 --- a/test/Concurrency/Runtime/startImmediately.swift +++ b/test/Concurrency/Runtime/startImmediately.swift @@ -454,7 +454,7 @@ print("\n\n==== ---------------------------------------------------------------- print("call_taskImmediate_taskExecutor()") @TaskLocal -nonisolated(unsafe) var niceTaskLocalValueYouGotThere: String = "" +nonisolated(unsafe) internal var niceTaskLocalValueYouGotThere: String = "" // FIXME: rdar://155596073 Task executors execution may not always hop as expected func call_taskImmediate_taskExecutor(taskExecutor: NaiveQueueExecutor) async { diff --git a/test/Concurrency/Runtime/startImmediately_order.swift b/test/Concurrency/Runtime/startImmediately_order.swift index 7dbd579e37afa..3454391662fd1 100644 --- a/test/Concurrency/Runtime/startImmediately_order.swift +++ b/test/Concurrency/Runtime/startImmediately_order.swift @@ -14,7 +14,7 @@ import _Concurrency -let max = 1000 +internal nonisolated let max = 1000 func bar(x: Int, cc: CheckedContinuation) { Task.immediate { diff --git a/test/Concurrency/actor_existentials.swift b/test/Concurrency/actor_existentials.swift index c24a48ddc7a28..74b64fe76b266 100644 --- a/test/Concurrency/actor_existentials.swift +++ b/test/Concurrency/actor_existentials.swift @@ -51,7 +51,7 @@ func from_isolated_concrete(_ x: isolated A) async { actor Act { var i = 0 // expected-note {{mutation of this property is only permitted within the actor}} } -nonisolated let act = Act() +nonisolated internal let act = Act() func bad() async { // expected-warning@+3 {{no 'async' operations occur within 'await' expression}}{{5-11=}} diff --git a/test/Concurrency/actor_inout_isolation.swift b/test/Concurrency/actor_inout_isolation.swift index 20ef27f4c3aed..defa9b531bdf4 100644 --- a/test/Concurrency/actor_inout_isolation.swift +++ b/test/Concurrency/actor_inout_isolation.swift @@ -208,26 +208,25 @@ struct MyGlobalActor { static let shared = TestActor() } -@MyGlobalActor var number: Int = 0 -// expected-note @-1 {{var declared here}} -// expected-note @-2 {{var declared here}} -// expected-note @-3 {{mutation of this var is only permitted within the actor}} -// expected-complete-error @-4 {{top-level code variables cannot have a global actor}} -// expected-complete-note @-5 4{{mutation of this var is only permitted within the actor}} +internal var number: Int = 0 +// expected-complete-note@-1 2{{var declared here}} +// expected-complete-note@-2 {{mutation of this var is only permitted within the actor}} +// expected-complete-note@-3 4{{mutation of this var is only permitted within the actor}} +@MyGlobalActor var anotherNumber: Int = 0 +// expected-error @-1 {{local variable 'anotherNumber' cannot have a global actor}} if #available(SwiftStdlib 5.1, *) { let _ = Task.detached { await { (_ foo: inout Int) async in foo += 1 }(&number) } - // expected-error @-1 {{actor-isolated var 'number' cannot be passed 'inout' to 'async' function call}} - // expected-minimal-error @-2 {{global actor 'MyGlobalActor'-isolated var 'number' can not be used 'inout' from a nonisolated context}} - // expected-complete-warning @-3 {{main actor-isolated var 'number' can not be used 'inout' from a nonisolated context}} + // expected-complete-error@-1 {{actor-isolated var 'number' cannot be passed 'inout' to 'async' function call}} + // expected-complete-warning@-2 {{main actor-isolated var 'number' can not be used 'inout' from a nonisolated context}} } // attempt to pass global state owned by the global actor to another async function @available(SwiftStdlib 5.1, *) @MyGlobalActor func sneaky() async { await modifyAsynchronously(&number) } -// expected-error @-1 {{actor-isolated var 'number' cannot be passed 'inout' to 'async' function call}} -// expected-complete-error @-2 {{main actor-isolated var 'number' can not be used 'inout' from global actor 'MyGlobalActor'}} +// expected-complete-error@-1 {{actor-isolated var 'number' cannot be passed 'inout' to 'async' function call}} +// expected-complete-error@-2 {{main actor-isolated var 'number' can not be used 'inout' from global actor 'MyGlobalActor'}} // It's okay to pass actor state inout to synchronous functions! diff --git a/test/Concurrency/assume_mainactor.swift b/test/Concurrency/assume_mainactor.swift index 6e3dc002b66ae..84100642d1221 100644 --- a/test/Concurrency/assume_mainactor.swift +++ b/test/Concurrency/assume_mainactor.swift @@ -256,7 +256,7 @@ class CustomActorIsolated { } } -var global = 0 +internal var global = 0 func onMain() async { await withTaskGroup { group in diff --git a/test/Concurrency/freestanding_top_level.swift b/test/Concurrency/freestanding_top_level.swift index 6dc35cc510247..d15cd619478d6 100644 --- a/test/Concurrency/freestanding_top_level.swift +++ b/test/Concurrency/freestanding_top_level.swift @@ -4,8 +4,8 @@ // expected-complete-warning@+4 {{var 'global' is not concurrency-safe because it is nonisolated global shared mutable state; this is an error in the Swift 6 language mode}} // expected-complete-note@+3 {{add '@MainActor' to make var 'global' part of global actor 'MainActor'}}{{1-1=@MainActor }} // expected-complete-note@+2 {{disable concurrency-safety checks if accesses are protected by an external synchronization mechanism}}{{1-1=nonisolated(unsafe) }} -// expected-complete-note@+1 {{convert 'global' to a 'let' constant to make 'Sendable' shared state immutable}}{{1-4=let}} -var global = 10 +// expected-complete-note@+1 {{convert 'global' to a 'let' constant to make 'Sendable' shared state immutable}}{{10-13=let}} +internal var global = 10 // No warning because we're in the same module. print(global) diff --git a/test/Concurrency/global_actor_from_ordinary_context.swift b/test/Concurrency/global_actor_from_ordinary_context.swift index eb28b1db929e0..4b3a8fc336026 100644 --- a/test/Concurrency/global_actor_from_ordinary_context.swift +++ b/test/Concurrency/global_actor_from_ordinary_context.swift @@ -130,13 +130,16 @@ func fromAsync() async { a[0] = 1 // expected-error{{global actor 'SomeGlobalActor'-isolated subscript 'subscript(_:)' can not be mutated from a nonisolated context}} } -// expected-minimal-and-targeted-note @+2 {{mutation of this var is only permitted within the actor}} -// expected-complete-error @+1 {{top-level code variables cannot have a global actor}} -@SomeGlobalActor var value: Int = 42 +@SomeGlobalActor internal var value: Int = 42 +// expected-note@-1 {{mutation of this var is only permitted within the actor}} + +@SomeGlobalActor var anotherValue: Int = 42 +// expected-error@-1 {{local variable 'anotherValue' cannot have a global actor}} func topLevelSyncFunction(_ number: inout Int) { } -// expected-minimal-and-targeted-error @+1 {{global actor 'SomeGlobalActor'-isolated var 'value' can not be used 'inout' from a nonisolated context}} topLevelSyncFunction(&value) +// expected-minimal-and-targeted-error@-1 {{global actor 'SomeGlobalActor'-isolated var 'value' can not be used 'inout' from a nonisolated context}} +// expected-complete-warning@-2 {{global actor 'SomeGlobalActor'-isolated var 'value' can not be used 'inout' from the main actor}} // Strict checking based on inferred Sendable/async/etc. @preconcurrency @SomeGlobalActor class Super { } diff --git a/test/Concurrency/global_actor_inference.swift b/test/Concurrency/global_actor_inference.swift index bc089b5f46cd7..c331f7b3013b3 100644 --- a/test/Concurrency/global_actor_inference.swift +++ b/test/Concurrency/global_actor_inference.swift @@ -660,8 +660,7 @@ func acceptAsyncSendableClosureInheriting(@_inheritActorContext _: @Sendable // defer bodies inherit global actor-ness @MainActor -var statefulThingy: Bool = false // expected-minimal-targeted-note {{var declared here}} -// expected-complete-error @-1 {{top-level code variables cannot have a global actor}} +internal var statefulThingy: Bool = false // expected-minimal-targeted-note {{var declared here}} @MainActor func useFooInADefer() -> String { // expected-minimal-targeted-note {{calls to global function 'useFooInADefer()' from outside of its actor context are implicitly asynchronous}} diff --git a/test/Concurrency/sendable_checking_captures_swift5.swift b/test/Concurrency/sendable_checking_captures_swift5.swift index 470b40607e2f9..a046d2d9fbe0b 100644 --- a/test/Concurrency/sendable_checking_captures_swift5.swift +++ b/test/Concurrency/sendable_checking_captures_swift5.swift @@ -5,7 +5,7 @@ class NonSendable {} // expected-complete-note 3{{class 'NonSendable' does not c func callee(_: @Sendable () -> NonSendable) {} -var testLocalCaptures: Int { +internal var testLocalCaptures: Int { let ns = NonSendable() @Sendable func localFunc() -> NonSendable { diff --git a/test/Concurrency/sendable_checking_captures_swift6.swift b/test/Concurrency/sendable_checking_captures_swift6.swift index 84792cae4726c..0ba91a2211a87 100644 --- a/test/Concurrency/sendable_checking_captures_swift6.swift +++ b/test/Concurrency/sendable_checking_captures_swift6.swift @@ -4,7 +4,7 @@ class NonSendable {} // expected-note 3{{class 'NonSendable' does not conform to func callee(_: @Sendable () -> NonSendable) {} -var testLocalCaptures: Int { +internal var testLocalCaptures: Int { let ns = NonSendable() @Sendable func localFunc() -> NonSendable { diff --git a/test/Concurrency/task_local.swift b/test/Concurrency/task_local.swift index 12b6765632f6f..9bc430b344fd6 100644 --- a/test/Concurrency/task_local.swift +++ b/test/Concurrency/task_local.swift @@ -30,7 +30,7 @@ struct TL { } @TaskLocal -var global: Int = 0 +internal var global: Int = 0 class NotSendable {} diff --git a/test/Concurrency/toplevel/async-5-top-level.swift b/test/Concurrency/toplevel/async-5-top-level.swift index 762504712129e..6e977a0eb8645 100644 --- a/test/Concurrency/toplevel/async-5-top-level.swift +++ b/test/Concurrency/toplevel/async-5-top-level.swift @@ -4,7 +4,7 @@ // context. Variables are declared with `@_predatesConcurrency @MainActor`, and // the top-level is run on the main actor. -var a = 10 // expected-note {{mutation of this var is only permitted within the actor}} +internal var a = 10 // expected-note {{mutation of this var is only permitted within the actor}} func nonIsolatedSync() { // Okay because `a` is '@_predatesConcurrency' diff --git a/test/Concurrency/toplevel/async-6-top-level.swift b/test/Concurrency/toplevel/async-6-top-level.swift index 7ba4e83c3822c..b519f7964a192 100644 --- a/test/Concurrency/toplevel/async-6-top-level.swift +++ b/test/Concurrency/toplevel/async-6-top-level.swift @@ -1,6 +1,6 @@ // RUN: %target-swift-frontend -typecheck -target %target-swift-5.1-abi-triple -swift-version 6 %s -verify -var a = 10 +internal var a = 10 // expected-note@-1 2 {{var declared here}} // expected-note@-2 2 {{mutation of this var is only permitted within the actor}} diff --git a/test/Concurrency/toplevel/main.swift b/test/Concurrency/toplevel/main.swift index 2b982edcddda9..24929a0535b74 100644 --- a/test/Concurrency/toplevel/main.swift +++ b/test/Concurrency/toplevel/main.swift @@ -12,10 +12,10 @@ func foo() -> Int { } //--- main.swift -var a = 10 // expected-swift6-note 2{{var declared here}} +internal var a = 10 // expected-swift6-note 2{{var declared here}} @MainActor -var b = 14 // expected-error {{top-level code variables cannot have a global actor}} +var b = 14 // expected-error {{local variable 'b' cannot have a global actor}} func nonIsolatedSynchronous() { // expected-swift6-note@-1 {{add '@MainActor' to make global function 'nonIsolatedSynchronous()' part of global actor 'MainActor'}} diff --git a/test/Concurrency/toplevel/no-async-5-top-level.swift b/test/Concurrency/toplevel/no-async-5-top-level.swift index dde67f1187274..2ae97a1f5f5fd 100644 --- a/test/Concurrency/toplevel/no-async-5-top-level.swift +++ b/test/Concurrency/toplevel/no-async-5-top-level.swift @@ -3,7 +3,7 @@ // There are no `await`s made from the top-level, so it is not an async context. // `a` is just a normal top-level global variable with no actor isolation. -var a = 10 +internal var a = 10 func nonIsolatedSync() { print(a) diff --git a/test/Concurrency/toplevel/no-async-6-top-level.swift b/test/Concurrency/toplevel/no-async-6-top-level.swift index 4302f05db355d..a0f3b40da72a6 100644 --- a/test/Concurrency/toplevel/no-async-6-top-level.swift +++ b/test/Concurrency/toplevel/no-async-6-top-level.swift @@ -4,7 +4,7 @@ // asynchronous context. `a` is just a normal top-level global variable with no // actor isolation. -var a = 10 // expected-note 2 {{var declared here}} +internal var a = 10 // expected-note 2 {{var declared here}} // expected-note@-1 2{{mutation of this var is only permitted within the actor}} // expected-note@+1 3{{add '@MainActor' to make global function 'nonIsolatedSync()' part of global actor 'MainActor'}} diff --git a/test/Concurrency/toplevel/synchronous_mainactor.swift b/test/Concurrency/toplevel/synchronous_mainactor.swift index 22ed1f3248c41..f76554f5fecc1 100644 --- a/test/Concurrency/toplevel/synchronous_mainactor.swift +++ b/test/Concurrency/toplevel/synchronous_mainactor.swift @@ -1,9 +1,9 @@ // RUN: %target-swift-frontend -target %target-swift-5.1-abi-triple -strict-concurrency=complete -typecheck -verify %s -var a = 10 // expected-note{{var declared here}} +internal var a = 10 // expected-note{{var declared here}} @MainActor -var b = 15 // expected-error{{top-level code variables cannot have a global actor}} +var b = 15 // expected-error{{local variable 'b' cannot have a global actor}} func unsafeAccess() { // expected-note{{add '@MainActor' to make global function 'unsafeAccess()' part of global actor 'MainActor'}} print(a) // expected-error@:11{{main actor-isolated var 'a' can not be referenced from a nonisolated context}} diff --git a/test/Concurrency/transfernonsendable.swift b/test/Concurrency/transfernonsendable.swift index 1f262720c044f..47099507003a9 100644 --- a/test/Concurrency/transfernonsendable.swift +++ b/test/Concurrency/transfernonsendable.swift @@ -1,5 +1,5 @@ -// RUN: %target-swift-frontend -emit-sil -strict-concurrency=complete -disable-availability-checking -verify -verify-additional-prefix ni- %s -o /dev/null -enable-upcoming-feature GlobalActorIsolatedTypesUsability -// RUN: %target-swift-frontend -emit-sil -strict-concurrency=complete -disable-availability-checking -verify -verify-additional-prefix ni-ns- %s -o /dev/null -enable-upcoming-feature GlobalActorIsolatedTypesUsability -enable-upcoming-feature NonisolatedNonsendingByDefault +// RUN: %target-swift-frontend -parse-as-library -emit-sil -strict-concurrency=complete -disable-availability-checking -verify -verify-additional-prefix ni- %s -o /dev/null -enable-upcoming-feature GlobalActorIsolatedTypesUsability +// RUN: %target-swift-frontend -parse-as-library -emit-sil -strict-concurrency=complete -disable-availability-checking -verify -verify-additional-prefix ni-ns- %s -o /dev/null -enable-upcoming-feature GlobalActorIsolatedTypesUsability -enable-upcoming-feature NonisolatedNonsendingByDefault // REQUIRES: concurrency // REQUIRES: swift_feature_GlobalActorIsolatedTypesUsability @@ -70,7 +70,7 @@ func useValueNoncopyable(_ x: borrowing T) {} @MainActor func transferToMain(_ t: T) async {} -var booleanFlag: Bool { false } +@MainActor var booleanFlag: Bool { false } struct SingleFieldKlassBox { // expected-complete-note 2{{consider making struct 'SingleFieldKlassBox' conform to the 'Sendable' protocol}} var k = NonSendableKlass() diff --git a/test/Concurrency/transfernonsendable_asynclet.swift b/test/Concurrency/transfernonsendable_asynclet.swift index f00bb44a5876b..5be900b3c4ea0 100644 --- a/test/Concurrency/transfernonsendable_asynclet.swift +++ b/test/Concurrency/transfernonsendable_asynclet.swift @@ -68,7 +68,7 @@ func transferToNonIsolated(_ t: T) async {} func transferToNonIsolatedInt(_ t: T) async -> Int { 5 } func transferToNonIsolatedIntOpt(_ t: T) async -> Int? { 5 } -var booleanFlag: Bool { false } +internal var booleanFlag: Bool { false } struct SingleFieldKlassBox { var k = NonSendableKlass() diff --git a/test/Concurrency/transfernonsendable_isolationcrossing_partialapply.swift b/test/Concurrency/transfernonsendable_isolationcrossing_partialapply.swift index 0a293980726a1..27118ca271ddb 100644 --- a/test/Concurrency/transfernonsendable_isolationcrossing_partialapply.swift +++ b/test/Concurrency/transfernonsendable_isolationcrossing_partialapply.swift @@ -29,7 +29,7 @@ func useValue(_ t: T) {} @MainActor func transferToMain(_ t: T) {} @CustomActor func transferToCustom(_ t: T) {} -var boolValue: Bool { false } +internal var boolValue: Bool { false } ///////////////// // MARK: Tests // diff --git a/test/Concurrency/transfernonsendable_nonisolatedunsafe.swift b/test/Concurrency/transfernonsendable_nonisolatedunsafe.swift index d7d68899ddff2..7d26728e1dc1c 100644 --- a/test/Concurrency/transfernonsendable_nonisolatedunsafe.swift +++ b/test/Concurrency/transfernonsendable_nonisolatedunsafe.swift @@ -361,8 +361,8 @@ func testAccessStaticGlobals() async { // expected-complete-warning @-1 {{passing argument of non-Sendable type 'NonSendableKlass' into main actor-isolated context may introduce data races}} } -nonisolated(unsafe) let globalNonIsolatedUnsafeLetObject = NonSendableKlass() -nonisolated(unsafe) var globalNonIsolatedUnsafeVarObject = NonSendableKlass() +nonisolated(unsafe) internal let globalNonIsolatedUnsafeLetObject = NonSendableKlass() +nonisolated(unsafe) internal var globalNonIsolatedUnsafeVarObject = NonSendableKlass() func testPassGlobalToMainActorIsolatedFunction() async { await transferToMainDirect(globalNonIsolatedUnsafeLetObject) @@ -373,7 +373,7 @@ func testPassGlobalToMainActorIsolatedFunction() async { // We use this to force the modify in testPassGlobalToModify nonisolated(unsafe) -var computedGlobalNonIsolatedUnsafeVarObject : NonSendableKlass { +internal var computedGlobalNonIsolatedUnsafeVarObject : NonSendableKlass { _read { yield globalNonIsolatedUnsafeVarObject } diff --git a/test/Concurrency/voucher_propagation.swift b/test/Concurrency/voucher_propagation.swift index 2772812c87ec1..4908ae22689e4 100644 --- a/test/Concurrency/voucher_propagation.swift +++ b/test/Concurrency/voucher_propagation.swift @@ -161,23 +161,23 @@ func lookup(_ name: String) -> T { // We'll use os_activity calls to make our test vouchers. The calls aren't in // the headers so we need to look them up dynamically. -let _os_activity_create = lookup("_os_activity_create") +internal let _os_activity_create = lookup("_os_activity_create") as @convention(c) (UnsafeRawPointer, UnsafePointer, UnsafeRawPointer, UInt32) -> voucher_t? -let OS_ACTIVITY_NONE = lookup("_os_activity_none") as UnsafeRawPointer -let OS_ACTIVITY_FLAG_DETACHED = 1 as UInt32 +internal let OS_ACTIVITY_NONE = lookup("_os_activity_none") as UnsafeRawPointer +internal let OS_ACTIVITY_FLAG_DETACHED = 1 as UInt32 // Look up the voucher calls we'll be using. Vouchers are ObjC objects, but we // want total control over their memory management, so we'll treat them as raw // pointers instead, and manually manage their memory. typealias voucher_t = UnsafeMutableRawPointer -let voucher_copy = lookup("voucher_copy") as @convention(c) () -> voucher_t? -let voucher_adopt = lookup("voucher_adopt") as @convention(c) (voucher_t?) +internal let voucher_copy = lookup("voucher_copy") as @convention(c) () -> voucher_t? +internal let voucher_adopt = lookup("voucher_adopt") as @convention(c) (voucher_t?) -> voucher_t? -let os_retain = lookup("os_retain") as @convention(c) (voucher_t?) -> voucher_t? -let os_release = lookup("os_release") as @convention(c) (voucher_t?) -> Void +internal let os_retain = lookup("os_retain") as @convention(c) (voucher_t?) -> voucher_t? +internal let os_release = lookup("os_release") as @convention(c) (voucher_t?) -> Void -let isCurrentExecutor = lookup("swift_task_isCurrentExecutor") as @convention(thin) (UnownedSerialExecutor) -> Bool +internal let isCurrentExecutor = lookup("swift_task_isCurrentExecutor") as @convention(thin) (UnownedSerialExecutor) -> Bool // Run some async code with test vouchers. Wait for the async code to complete, // then verify that the vouchers aren't leaked. diff --git a/test/IDE/complete_accessor.swift b/test/IDE/complete_accessor.swift index 33b3ce25b86cb..e30adc28ede0c 100644 --- a/test/IDE/complete_accessor.swift +++ b/test/IDE/complete_accessor.swift @@ -1,4 +1,4 @@ -// RUN: %batch-code-completion +// RUN: %batch-code-completion -parse-as-library // WITH_GETSET: Keyword/None: get; name=get // WITH_GETSET: Keyword/None: set; name=set diff --git a/test/IDE/complete_at_top_level.swift b/test/IDE/complete_at_top_level.swift index 8aa7088fbedc3..3406a5654cb0f 100644 --- a/test/IDE/complete_at_top_level.swift +++ b/test/IDE/complete_at_top_level.swift @@ -17,7 +17,7 @@ struct FooStruct { // Add more stuff as needed. } -var fooObject : FooStruct +internal var fooObject : FooStruct func fooFunc1() {} func fooFunc2(_ a: Int, _ b: Double) {} diff --git a/test/IDE/complete_call_arg.swift b/test/IDE/complete_call_arg.swift index cb3722aaf43bb..d74f87b77137d 100644 --- a/test/IDE/complete_call_arg.swift +++ b/test/IDE/complete_call_arg.swift @@ -1,4 +1,4 @@ -// RUN: %batch-code-completion +// RUN: %batch-code-completion -parse-as-library var i1 = 1 var i2 = 2 diff --git a/test/IDE/complete_default_arguments.swift b/test/IDE/complete_default_arguments.swift index 47d8bf496a412..0615d650b02cb 100644 --- a/test/IDE/complete_default_arguments.swift +++ b/test/IDE/complete_default_arguments.swift @@ -134,7 +134,7 @@ func testDefaultArgs10() { } -let globalVar = 1 +internal let globalVar = 1 func testDefaultArgInit1(x = #^DEFAULT_ARG_INIT_1^#) { } func testDefaultArgInit2(_: Int = #^DEFAULT_ARG_INIT_2^#) { } func testDefaultArgInit3(_ x: Int = #^DEFAULT_ARG_INIT_3^#) { } diff --git a/test/IDE/complete_doc_top_level.swift b/test/IDE/complete_doc_top_level.swift index ef2abd986104f..607c3589d33ed 100644 --- a/test/IDE/complete_doc_top_level.swift +++ b/test/IDE/complete_doc_top_level.swift @@ -70,14 +70,14 @@ struct S2: P1 {} // TOP-LEVEL-SAME: xmlcomment=topLevelFunc2()s:15CompleteDocTest13topLevelFunc2yyFfunc topLevelFunc2()top-level func 2 comment; // TOP-LEVEL-SAME: rawcomment=top-level func 2 comment -// TOP-LEVEL-LABEL: Decl[GlobalVar]/Local: topLevelVar1[#String#]; name=topLevelVar1; +// TOP-LEVEL-LABEL: Decl[LocalVar]/Local: topLevelVar1[#String#]; name=topLevelVar1; // TOP-LEVEL-SAME: briefcomment=top-level var 1 comment; -// TOP-LEVEL-SAME: xmlcomment=topLevelVar1s:15CompleteDocTest12topLevelVar1SSvpvar topLevelVar1: Stringtop-level var 1 comment; +// TOP-LEVEL-SAME: xmlcomment=topLevelVar1s:15CompleteDocTest12topLevelVar1L_SSvpvar topLevelVar1: Stringtop-level var 1 comment; // TOP-LEVEL-SAME: rawcomment=top-level var 1 comment -// TOP-LEVEL-LABEL: Decl[GlobalVar]/Local: topLevelVar2[#Int#]; name=topLevelVar2; +// TOP-LEVEL-LABEL: Decl[LocalVar]/Local: topLevelVar2[#Int#]; name=topLevelVar2; // TOP-LEVEL-SAME: briefcomment=top-level var 2 comment; -// TOP-LEVEL-SAME: xmlcomment=topLevelVar2s:15CompleteDocTest12topLevelVar2Sivpvar topLevelVar2: Inttop-level var 2 commentthe meaning of life; +// TOP-LEVEL-SAME: xmlcomment=topLevelVar2s:15CompleteDocTest12topLevelVar2L0_Sivpvar topLevelVar2: Inttop-level var 2 commentthe meaning of life; // TOP-LEVEL-SAME: rawcomment=top-level var 2 comment // TOP-LEVEL-EMPTY: // TOP-LEVEL-NEXT: the meaning of life diff --git a/test/IDE/complete_effectful_accessor.swift b/test/IDE/complete_effectful_accessor.swift index f87dce1f09339..dcd765dbaa168 100644 --- a/test/IDE/complete_effectful_accessor.swift +++ b/test/IDE/complete_effectful_accessor.swift @@ -1,4 +1,4 @@ -// RUN: %batch-code-completion +// RUN: %batch-code-completion -parse-as-library var globalAsyncVar: Int { get async { diff --git a/test/IDE/complete_expr_postfix_begin.swift b/test/IDE/complete_expr_postfix_begin.swift index cf24d7bfaf249..b45ae70412877 100644 --- a/test/IDE/complete_expr_postfix_begin.swift +++ b/test/IDE/complete_expr_postfix_begin.swift @@ -1,4 +1,4 @@ -// RUN: %batch-code-completion +// RUN: %batch-code-completion -parse-as-library // // Test code completion at the beginning of expr-postfix. diff --git a/test/IDE/complete_from_swift_module.swift b/test/IDE/complete_from_swift_module.swift index 7be6ca09904d3..cf8d590220b64 100644 --- a/test/IDE/complete_from_swift_module.swift +++ b/test/IDE/complete_from_swift_module.swift @@ -78,7 +78,7 @@ func testQualifyingModulesNotSuggested() { // ALREADY_QUALIFIED-NOT: name=Type } -var hiddenImport : Int +internal var hiddenImport : Int // TOP_LEVEL_1_NEGATIVE-NOT: hiddenImport() func testCompleteModuleQualified1() { diff --git a/test/IDE/complete_global_actorisolation.swift b/test/IDE/complete_global_actorisolation.swift index fad2abb3ad244..65be506916387 100644 --- a/test/IDE/complete_global_actorisolation.swift +++ b/test/IDE/complete_global_actorisolation.swift @@ -1,5 +1,5 @@ // REQUIRES: concurrency -// RUN: %batch-code-completion +// RUN: %batch-code-completion -parse-as-library class MyNonSendable {} struct MySendable {} diff --git a/test/IDE/complete_in_accessors.swift b/test/IDE/complete_in_accessors.swift index af0ec1d26907a..fc44dda93791e 100644 --- a/test/IDE/complete_in_accessors.swift +++ b/test/IDE/complete_in_accessors.swift @@ -1,4 +1,5 @@ -// RUN: %batch-code-completion +// FIXME: Shouldn't need parse-as-library (https://github.com/swiftlang/swift/issues/84785) +// RUN: %batch-code-completion -parse-as-library //===--- Helper types that are used in this test diff --git a/test/IDE/complete_in_result_builder.swift b/test/IDE/complete_in_result_builder.swift index 37640845e9b82..46d10fb452454 100644 --- a/test/IDE/complete_in_result_builder.swift +++ b/test/IDE/complete_in_result_builder.swift @@ -1,4 +1,4 @@ -// RUN: %batch-code-completion +// RUN: %batch-code-completion -parse-as-library @resultBuilder struct TupleBuilder { diff --git a/test/IDE/complete_macro_declaration.swift b/test/IDE/complete_macro_declaration.swift index cf4d987e5e9b8..b22593a3f5f96 100644 --- a/test/IDE/complete_macro_declaration.swift +++ b/test/IDE/complete_macro_declaration.swift @@ -1,5 +1,5 @@ // REQUIRES: swift_swift_parser -// RUN: %batch-code-completion +// RUN: %batch-code-completion -parse-as-library let globalVar = 1 macro expect(file: Int = #^DEFAULT_ARG^#) = #externalMacro(module: "MyModule", type: "MyMacro") diff --git a/test/IDE/complete_optional_binding.swift b/test/IDE/complete_optional_binding.swift index 9f70b35f46a18..998703b3a2b9e 100644 --- a/test/IDE/complete_optional_binding.swift +++ b/test/IDE/complete_optional_binding.swift @@ -1,5 +1,6 @@ // RUN: %batch-code-completion +internal let globalOpt: Int? let topLevelOpt: Int? do { @@ -7,9 +8,10 @@ do { let topLevelLocalNonOpt: Int if let #^TOPLEVEL_IF_LET?check=TOPLEVEL^# -// TOPLEVEL: Begin completions, 1 items -// TOPLEVEL-DAG: Decl[LocalVar]/Local: topLevelLocalOpt[#Int?#]; -// FIXME: show 'topLevelOpt' +// TOPLEVEL: Begin completions, 2 items +// TOPLEVEL-DAG: Decl[LocalVar]/Local: topLevelLocalOpt[#Int?#]; +// TOPLEVEL-DAG: Decl[LocalVar]/Local: topLevelOpt[#Int?#]; +// FIXME: show 'globalOpt' } struct MyStruct { diff --git a/test/IDE/complete_pattern.swift b/test/IDE/complete_pattern.swift index 3b6747a65da6e..4f06bbc30a10d 100644 --- a/test/IDE/complete_pattern.swift +++ b/test/IDE/complete_pattern.swift @@ -5,7 +5,7 @@ struct FooStruct { } -var fooObject : FooStruct +internal var fooObject : FooStruct func fooFunc() -> FooStruct { return fooObject diff --git a/test/IDE/complete_property_delegate_attribute.swift b/test/IDE/complete_property_delegate_attribute.swift index 0a2b12f85434c..887c1c3563294 100644 --- a/test/IDE/complete_property_delegate_attribute.swift +++ b/test/IDE/complete_property_delegate_attribute.swift @@ -1,4 +1,4 @@ -// RUN: %batch-code-completion +// RUN: %batch-code-completion -parse-as-library enum MyEnum { case east, west diff --git a/test/IDE/complete_result_builder.swift b/test/IDE/complete_result_builder.swift index 25029c0cf7acd..82e78784e6ab1 100644 --- a/test/IDE/complete_result_builder.swift +++ b/test/IDE/complete_result_builder.swift @@ -1,8 +1,8 @@ -// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLOSURE_TOP | %FileCheck %s -check-prefix=IN_CLOSURE_TOP -// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLOSURE_NONTOP | %FileCheck %s -check-prefix=IN_CLOSURE_TOP -// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLOSURE_COLOR_CONTEXT | %FileCheck %s -check-prefix=IN_CLOSURE_COLOR_CONTEXT -// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_RESULT_BUILDER_DECL -code-completion-comments=true | %FileCheck %s -check-prefix=IN_RESULT_BUILDER_DECL -// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_RESULT_BUILDER_DECL_PREFIX -code-completion-comments=true | %FileCheck %s -check-prefix=IN_RESULT_BUILDER_DECL_PREFIX +// RUN: %target-swift-ide-test -parse-as-library -code-completion -source-filename %s -code-completion-token=IN_CLOSURE_TOP | %FileCheck %s -check-prefix=IN_CLOSURE_TOP +// RUN: %target-swift-ide-test -parse-as-library -code-completion -source-filename %s -code-completion-token=IN_CLOSURE_NONTOP | %FileCheck %s -check-prefix=IN_CLOSURE_TOP +// RUN: %target-swift-ide-test -parse-as-library -code-completion -source-filename %s -code-completion-token=IN_CLOSURE_COLOR_CONTEXT | %FileCheck %s -check-prefix=IN_CLOSURE_COLOR_CONTEXT +// RUN: %target-swift-ide-test -parse-as-library -code-completion -source-filename %s -code-completion-token=IN_RESULT_BUILDER_DECL -code-completion-comments=true | %FileCheck %s -check-prefix=IN_RESULT_BUILDER_DECL +// RUN: %target-swift-ide-test -parse-as-library -code-completion -source-filename %s -code-completion-token=IN_RESULT_BUILDER_DECL_PREFIX -code-completion-comments=true | %FileCheck %s -check-prefix=IN_RESULT_BUILDER_DECL_PREFIX struct Tagged { let tag: Tag diff --git a/test/IDE/complete_sequence_invalid.swift b/test/IDE/complete_sequence_invalid.swift index 40fb8aeb3b018..8f72419bfe559 100644 --- a/test/IDE/complete_sequence_invalid.swift +++ b/test/IDE/complete_sequence_invalid.swift @@ -1,4 +1,4 @@ -// RUN: %batch-code-completion +// RUN: %batch-code-completion -parse-as-library // GLOBAL: Decl[GlobalVar]/CurrModule: invalidDecl[#_#]; let invalidDecl = INVALID diff --git a/test/IDE/complete_shadowing.swift b/test/IDE/complete_shadowing.swift index 2cc67d72e8982..e11641d96fcb1 100644 --- a/test/IDE/complete_shadowing.swift +++ b/test/IDE/complete_shadowing.swift @@ -1,4 +1,4 @@ -// RUN: %batch-code-completion +// RUN: %batch-code-completion -parse-as-library // LOCAL_STRING_TESTVALUE-NOT: name=testValue // LOCAL_STRING_TESTVALUE: Decl[LocalVar]/Local: testValue[#String#]; name=testValue diff --git a/test/IDE/complete_single_expression_return.swift b/test/IDE/complete_single_expression_return.swift index 384a302b6a805..fe41111c1dd7d 100644 --- a/test/IDE/complete_single_expression_return.swift +++ b/test/IDE/complete_single_expression_return.swift @@ -1,4 +1,5 @@ -// RUN: %batch-code-completion +// FIXME: Shouldn't need parse-as-library (https://github.com/swiftlang/swift/issues/84785) +// RUN: %batch-code-completion -parse-as-library // MARK: Single-expression closures diff --git a/test/IDE/complete_sself.swift b/test/IDE/complete_sself.swift index 7ed9542884468..219e09eaeac9b 100644 --- a/test/IDE/complete_sself.swift +++ b/test/IDE/complete_sself.swift @@ -1,4 +1,4 @@ -// RUN: %batch-code-completion +// RUN: %batch-code-completion -parse-as-library // NOSELF-NOT: name=Self diff --git a/test/IDE/complete_string_interpolation.swift b/test/IDE/complete_string_interpolation.swift index a4958db0c518e..f73907ff99bc3 100644 --- a/test/IDE/complete_string_interpolation.swift +++ b/test/IDE/complete_string_interpolation.swift @@ -1,7 +1,7 @@ -// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OVERLOAD_INT -swift-version=5 | %FileCheck %s -check-prefix=OVERLOAD_INT -// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OVERLOAD_INTLITERAL -swift-version=5 | %FileCheck %s -check-prefix=OVERLOAD_INTLITERAL -// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OVERLOAD_FLT -swift-version=5 | %FileCheck %s -check-prefix=OVERLOAD_FLT -// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OVERLOAD_FLTLITERAL -swift-version=5 | %FileCheck %s -check-prefix=OVERLOAD_FLT +// RUN: %target-swift-ide-test -parse-as-library -code-completion -source-filename %s -code-completion-token=OVERLOAD_INT -swift-version=5 | %FileCheck %s -check-prefix=OVERLOAD_INT +// RUN: %target-swift-ide-test -parse-as-library -code-completion -source-filename %s -code-completion-token=OVERLOAD_INTLITERAL -swift-version=5 | %FileCheck %s -check-prefix=OVERLOAD_INTLITERAL +// RUN: %target-swift-ide-test -parse-as-library -code-completion -source-filename %s -code-completion-token=OVERLOAD_FLT -swift-version=5 | %FileCheck %s -check-prefix=OVERLOAD_FLT +// RUN: %target-swift-ide-test -parse-as-library -code-completion -source-filename %s -code-completion-token=OVERLOAD_FLTLITERAL -swift-version=5 | %FileCheck %s -check-prefix=OVERLOAD_FLT struct Messenger { init() {} diff --git a/test/IDE/complete_type.swift b/test/IDE/complete_type.swift index 4d33aa03e5af4..2d7e7f493f0d0 100644 --- a/test/IDE/complete_type.swift +++ b/test/IDE/complete_type.swift @@ -5,7 +5,7 @@ struct FooStruct { } -var fooObject: FooStruct +internal var fooObject: FooStruct func fooFunc() -> FooStruct { return fooObject diff --git a/test/IDE/complete_value_expr.swift b/test/IDE/complete_value_expr.swift index 43f94e9a33753..8d32f4ecff694 100644 --- a/test/IDE/complete_value_expr.swift +++ b/test/IDE/complete_value_expr.swift @@ -1,4 +1,4 @@ -// RUN: %batch-code-completion +// RUN: %batch-code-completion -parse-as-library // Test code completion of expressions that produce a value. diff --git a/test/IDE/complete_vararg.swift b/test/IDE/complete_vararg.swift index 193e599fcea87..bb6cf9324e76f 100644 --- a/test/IDE/complete_vararg.swift +++ b/test/IDE/complete_vararg.swift @@ -1,13 +1,13 @@ -// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_1 | %FileCheck %s -check-prefix=TOP_LEVEL_1 -// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OBJ_DOT_1 | %FileCheck %s -check-prefix=OBJ_DOT_1 -// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FREE_FUNC_1 | %FileCheck %s -check-prefix=FREE_FUNC_1 -// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FREE_FUNC_2 | %FileCheck %s -check-prefix=FREE_FUNC_2 -// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_1 | %FileCheck %s -check-prefix=INIT_1 -// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=METHOD_1 | %FileCheck %s -check-prefix=METHOD_1 -// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=METHOD_2 | %FileCheck %s -check-prefix=METHOD_2 -// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SUBSCRIPT_1 | %FileCheck %s -check-prefix=SUBSCRIPT_1 -// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GENERIC_FREE_FUNC_1 | %FileCheck %s -check-prefix=GENERIC_FREE_FUNC_1 -// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INTERESTING_TYPE_1 | %FileCheck %s -check-prefix=INTERESTING_TYPE_1 +// RUN: %target-swift-ide-test -parse-as-library -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_1 | %FileCheck %s -check-prefix=TOP_LEVEL_1 +// RUN: %target-swift-ide-test -parse-as-library -code-completion -source-filename %s -code-completion-token=OBJ_DOT_1 | %FileCheck %s -check-prefix=OBJ_DOT_1 +// RUN: %target-swift-ide-test -parse-as-library -code-completion -source-filename %s -code-completion-token=FREE_FUNC_1 | %FileCheck %s -check-prefix=FREE_FUNC_1 +// RUN: %target-swift-ide-test -parse-as-library -code-completion -source-filename %s -code-completion-token=FREE_FUNC_2 | %FileCheck %s -check-prefix=FREE_FUNC_2 +// RUN: %target-swift-ide-test -parse-as-library -code-completion -source-filename %s -code-completion-token=INIT_1 | %FileCheck %s -check-prefix=INIT_1 +// RUN: %target-swift-ide-test -parse-as-library -code-completion -source-filename %s -code-completion-token=METHOD_1 | %FileCheck %s -check-prefix=METHOD_1 +// RUN: %target-swift-ide-test -parse-as-library -code-completion -source-filename %s -code-completion-token=METHOD_2 | %FileCheck %s -check-prefix=METHOD_2 +// RUN: %target-swift-ide-test -parse-as-library -code-completion -source-filename %s -code-completion-token=SUBSCRIPT_1 | %FileCheck %s -check-prefix=SUBSCRIPT_1 +// RUN: %target-swift-ide-test -parse-as-library -code-completion -source-filename %s -code-completion-token=GENERIC_FREE_FUNC_1 | %FileCheck %s -check-prefix=GENERIC_FREE_FUNC_1 +// RUN: %target-swift-ide-test -parse-as-library -code-completion -source-filename %s -code-completion-token=INTERESTING_TYPE_1 | %FileCheck %s -check-prefix=INTERESTING_TYPE_1 func freeFunc1(x x: Int...) { } func freeFunc2(x x: Int, y y: Int...) { } diff --git a/test/IDE/local_types.swift b/test/IDE/local_types.swift index e957ee0d88ee2..cefb7d234efd4 100644 --- a/test/IDE/local_types.swift +++ b/test/IDE/local_types.swift @@ -86,18 +86,18 @@ public func singleFuncWithDuplicates(_ fake: Bool) { } public let singleClosure: () -> () = { - // CHECK-DAG: 10LocalTypesyycfU_19SingleClosureStructL_V + // CHECK-DAG: 10LocalTypes13singleClosureyycvpfiyycfU_06SingleD6StructL_V struct SingleClosureStruct { let scsi: Int } - // CHECK-DAG: 10LocalTypesyycfU_18SingleClosureClassL_C + // CHECK-DAG: 10LocalTypes13singleClosureyycvpfiyycfU_06SingleD5ClassL_C class SingleClosureClass { let sccs: String init(s: String) { self.sccs = s } } - // CHECK-DAG: 10LocalTypesyycfU_17SingleClosureEnumL_O + // CHECK-DAG: 10LocalTypes13singleClosureyycvpfiyycfU_06SingleD4EnumL_O enum SingleClosureEnum { case SCEI(Int) } @@ -169,18 +169,18 @@ public func doubleFunc() { public let doubleClosure: () -> () = { let singleClosure: () -> () = { - // CHECK-DAG: 10LocalTypesyycfU0_yycfU_19DoubleClosureStructL_V + // CHECK-DAG: 10LocalTypes13doubleClosureyycvpfiyycfU_yycfU_06DoubleD6StructL_V struct DoubleClosureStruct { let dcsi: Int } - // CHECK-DAG: 10LocalTypesyycfU0_yycfU_18DoubleClosureClassL_C + // CHECK-DAG: 10LocalTypes13doubleClosureyycvpfiyycfU_yycfU_06DoubleD5ClassL_C class DoubleClosureClass { let dccs: String init(s: String) { self.dccs = s } } - // CHECK-DAG: 10LocalTypesyycfU0_yycfU_17DoubleClosureEnumL_O + // CHECK-DAG: 10LocalTypes13doubleClosureyycvpfiyycfU_yycfU_06DoubleD4EnumL_O enum DoubleClosureEnum { case DCEI(Int) } diff --git a/test/IDE/print_ast_tc_decls.swift b/test/IDE/print_ast_tc_decls.swift index bbafcae286833..106cf2c2f1708 100644 --- a/test/IDE/print_ast_tc_decls.swift +++ b/test/IDE/print_ast_tc_decls.swift @@ -8,9 +8,9 @@ // FIXME: END -enable-source-import hackaround // // This file should not have any syntax or type checker errors. -// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -D ERRORS -typecheck -verify -verify-ignore-unrelated %s -F %S/Inputs/mock-sdk -enable-objc-interop -disable-objc-attr-requires-foundation-module +// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -parse-as-library -swift-version 4 -D ERRORS -typecheck -verify -verify-ignore-unrelated %s -F %S/Inputs/mock-sdk -enable-objc-interop -disable-objc-attr-requires-foundation-module // -// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -skip-deinit=false -print-ast-typechecked -source-filename %s -F %S/Inputs/mock-sdk -function-definitions=false -prefer-type-repr=false -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt +// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -parse-as-library -swift-version 4 -skip-deinit=false -print-ast-typechecked -source-filename %s -F %S/Inputs/mock-sdk -function-definitions=false -prefer-type-repr=false -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefixes=PASS_PRINT_AST,PASS_PRINT_AST_TYPE -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_RW_PROP_GET_SET -strict-whitespace < %t.printed.txt @@ -21,7 +21,7 @@ // RUN: %FileCheck %s -check-prefix=PREFER_TYPE_PRINTING -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt // -// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -skip-deinit=false -print-ast-typechecked -source-filename %s -F %S/Inputs/mock-sdk -function-definitions=false -prefer-type-repr=true -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt +// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -parse-as-library -swift-version 4 -skip-deinit=false -print-ast-typechecked -source-filename %s -F %S/Inputs/mock-sdk -function-definitions=false -prefer-type-repr=true -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefixes=PASS_PRINT_AST,PASS_PRINT_AST_TYPEREPR -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_RW_PROP_GET_SET -strict-whitespace < %t.printed.txt @@ -32,7 +32,7 @@ // RUN: %FileCheck %s -check-prefix=PREFER_TYPE_REPR_PRINTING -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt // -// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -emit-module -o %t -F %S/Inputs/mock-sdk -enable-objc-interop -disable-objc-attr-requires-foundation-module %s +// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -parse-as-library -swift-version 4 -emit-module -o %t -F %S/Inputs/mock-sdk -enable-objc-interop -disable-objc-attr-requires-foundation-module %s // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -module-to-print=print_ast_tc_decls -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt @@ -45,13 +45,13 @@ // RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt // -// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -I %t -module-to-print=print_ast_tc_decls -synthesize-sugar-on-types=true -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt +// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -parse-as-library -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -I %t -module-to-print=print_ast_tc_decls -synthesize-sugar-on-types=true -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=SYNTHESIZE_SUGAR_ON_TYPES -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt -// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -I %t -module-to-print=print_ast_tc_decls -synthesize-sugar-on-types=true -fully-qualified-types-if-ambiguous=true -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt +// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -parse-as-library -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -I %t -module-to-print=print_ast_tc_decls -synthesize-sugar-on-types=true -fully-qualified-types-if-ambiguous=true -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_QUAL_IF_AMBIGUOUS -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=SYNTHESIZE_SUGAR_ON_TYPES -strict-whitespace < %t.printed.txt diff --git a/test/IDE/reconstruct_type_from_mangled_name.swift b/test/IDE/reconstruct_type_from_mangled_name.swift index c66e681b724de..71c20d18b636e 100644 --- a/test/IDE/reconstruct_type_from_mangled_name.swift +++ b/test/IDE/reconstruct_type_from_mangled_name.swift @@ -1,4 +1,4 @@ -// RUN: %target-swift-ide-test -reconstruct-type -source-filename %s | %FileCheck %s -implicit-check-not="FAILURE" +// RUN: %target-swift-ide-test -parse-as-library -reconstruct-type -source-filename %s | %FileCheck %s -implicit-check-not="FAILURE" // This test doesn't test a whole lot now that the more general (but buggy) // getDeclFromMangledSymbolName() has been replaced with getTypeDeclForMangling(). diff --git a/test/IDE/structure.swift b/test/IDE/structure.swift index a58e4571c328e..0c399c032baf6 100644 --- a/test/IDE/structure.swift +++ b/test/IDE/structure.swift @@ -78,8 +78,11 @@ extension MyStruct { } } +// CHECK: var lvar : Int = 0 +var lvar : Int = 0 + // CHECK: var gvar : Int = 0 -var gvar : Int = 0 +internal var gvar : Int = 0 // CHECK: func ffoo() {} func ffoo() {} @@ -113,13 +116,13 @@ switch v { default: break; } -// CHECK: let myArray = [1, 2, 3] +// CHECK: let myArray = [1, 2, 3] let myArray = [1, 2, 3] -// CHECK: let myDict = [1:1, 2:2, 3:3] +// CHECK: let myDict = [1:1, 2:2, 3:3] let myDict = [1:1, 2:2, 3:3] -// CHECK: let myArray2 = [1] +// CHECK: let myArray2 = [1] let myArray2 = [1] -// CHECK: let myDict2 = [1:1] +// CHECK: let myDict2 = [1:1] let myDict2 = [1:1] // CHECK: for {} @@ -135,7 +138,7 @@ func <#test1#> () { for <#name#> in <#items#> {} } -// CHECK: let myArray = [<#item1#>, <#item2#>] +// CHECK: let myArray = [<#item1#>, <#item2#>] let myArray = [<#item1#>, <#item2#>] // CHECK: func test1() { diff --git a/test/IDE/structure_object_literals.swift b/test/IDE/structure_object_literals.swift index 33a678cf15d42..1123dc237776f 100644 --- a/test/IDE/structure_object_literals.swift +++ b/test/IDE/structure_object_literals.swift @@ -4,14 +4,14 @@ struct S: _ExpressibleByColorLiteral { init(_colorLiteralRed: Float, green: Float, blue: Float, alpha: Float) {} } -// CHECK: let y: S = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1) +// CHECK: let y: S = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1) let y: S = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1) struct I: _ExpressibleByImageLiteral { init?(imageLiteralResourceName: String) {} } -// CHECK: let z: I? = #imageLiteral(resourceName: "hello.png") +// CHECK: let z: I? = #imageLiteral(resourceName: "hello.png") let z: I? = #imageLiteral(resourceName: "hello.png") func before() {} diff --git a/test/Interpreter/SDK/KVO.swift b/test/Interpreter/SDK/KVO.swift index 308310b2a70e5..1dc46f289117a 100644 --- a/test/Interpreter/SDK/KVO.swift +++ b/test/Interpreter/SDK/KVO.swift @@ -5,7 +5,7 @@ import Foundation -var kvoContext = 0 +internal var kvoContext = 0 class Model : NSObject { @objc dynamic var name = "" diff --git a/test/Interpreter/SDK/c_pointers.swift b/test/Interpreter/SDK/c_pointers.swift index 6af214404e757..16a9942520aa5 100644 --- a/test/Interpreter/SDK/c_pointers.swift +++ b/test/Interpreter/SDK/c_pointers.swift @@ -74,7 +74,7 @@ class Canary: NSObject { } } -var CanaryAssocObjectHandle: UInt8 = 0 +internal var CanaryAssocObjectHandle: UInt8 = 0 // Attach an associated object with a loud deinit so we can see that the // error died. diff --git a/test/Interpreter/SDK/objc_bridge_cast.swift b/test/Interpreter/SDK/objc_bridge_cast.swift index e23164767e71f..c3a9d81b52f4b 100644 --- a/test/Interpreter/SDK/objc_bridge_cast.swift +++ b/test/Interpreter/SDK/objc_bridge_cast.swift @@ -231,14 +231,14 @@ class Canary: NSObject { print("died") } } -var CanaryAssocObjectHandle = 0 +internal var CanaryAssocObjectHandle = 0 class ImmortalCanary: NSObject { deinit { print("oh noes") } } -var ImmortalCanaryAssocObjectHandle = 0 +internal var ImmortalCanaryAssocObjectHandle = 0 func testValueToObjectBridgingInSwitch() { autoreleasepool { diff --git a/test/Interpreter/SDK/objc_dynamic_subclass_protocol_lookup.swift b/test/Interpreter/SDK/objc_dynamic_subclass_protocol_lookup.swift index 7ba60ae0a3f93..32a0a36c40590 100644 --- a/test/Interpreter/SDK/objc_dynamic_subclass_protocol_lookup.swift +++ b/test/Interpreter/SDK/objc_dynamic_subclass_protocol_lookup.swift @@ -23,7 +23,7 @@ class Model2 : NSObject, Q { extension Supermodel: P { } -var kvoContext = 0 +internal var kvoContext = 0 class Observer: NSObject { let model1 = Model1() diff --git a/test/Interpreter/SDK/objc_inner_pointer.swift b/test/Interpreter/SDK/objc_inner_pointer.swift index 710404075ac0d..3aee294023de9 100644 --- a/test/Interpreter/SDK/objc_inner_pointer.swift +++ b/test/Interpreter/SDK/objc_inner_pointer.swift @@ -13,7 +13,7 @@ class Canary: NSObject { } } -var CanaryAssocObjectHandle: UInt8 = 0 +internal var CanaryAssocObjectHandle: UInt8 = 0 // Attach an associated object with a loud deinit so we can see that the diff --git a/test/Interpreter/SDK/objc_protocol_lookup.swift b/test/Interpreter/SDK/objc_protocol_lookup.swift index ff76a2e97fdfa..7a0f3e1221fd0 100644 --- a/test/Interpreter/SDK/objc_protocol_lookup.swift +++ b/test/Interpreter/SDK/objc_protocol_lookup.swift @@ -41,7 +41,7 @@ check(D()) // CHECK: true true // Make sure partial application of methods with @autoreleased // return values works -var count = 0 +internal var count = 0 class Juice : NSObject { override init() { diff --git a/test/Interpreter/builtin_bridge_object.swift b/test/Interpreter/builtin_bridge_object.swift index 6cf1b6b2b37cd..836a60d9e4cbb 100644 --- a/test/Interpreter/builtin_bridge_object.swift +++ b/test/Interpreter/builtin_bridge_object.swift @@ -20,38 +20,38 @@ class C { #if _pointerBitWidth(_32) // We have no ObjC tagged pointers, and two low spare bits due to alignment. -let NATIVE_SPARE_BITS: UInt = 0x0000_0003 -let OBJC_TAGGED_POINTER_BITS: UInt = 0 +internal let NATIVE_SPARE_BITS: UInt = 0x0000_0003 +internal let OBJC_TAGGED_POINTER_BITS: UInt = 0 #elseif arch(x86_64) // We have ObjC tagged pointers in the lowest and highest bit -let NATIVE_SPARE_BITS: UInt = 0x7F00_0000_0000_0006 -let OBJC_TAGGED_POINTER_BITS: UInt = 0x8000_0000_0000_0001 +internal let NATIVE_SPARE_BITS: UInt = 0x7F00_0000_0000_0006 +internal let OBJC_TAGGED_POINTER_BITS: UInt = 0x8000_0000_0000_0001 #elseif arch(arm64) // We have ObjC tagged pointers in the highest bit -let NATIVE_SPARE_BITS: UInt = 0x7000_0000_0000_0007 -let OBJC_TAGGED_POINTER_BITS: UInt = 0x8000_0000_0000_0000 +internal let NATIVE_SPARE_BITS: UInt = 0x7000_0000_0000_0007 +internal let OBJC_TAGGED_POINTER_BITS: UInt = 0x8000_0000_0000_0000 #elseif arch(powerpc64) || arch(powerpc64le) // We have no ObjC tagged pointers, and three low spare bits due to alignment. -let NATIVE_SPARE_BITS: UInt = 0x0000_0000_0000_0007 -let OBJC_TAGGED_POINTER_BITS: UInt = 0 +internal let NATIVE_SPARE_BITS: UInt = 0x0000_0000_0000_0007 +internal let OBJC_TAGGED_POINTER_BITS: UInt = 0 #elseif arch(s390x) // We have no ObjC tagged pointers, and three low spare bits due to alignment. -let NATIVE_SPARE_BITS: UInt = 0x0000_0000_0000_0007 -let OBJC_TAGGED_POINTER_BITS: UInt = 0 +internal let NATIVE_SPARE_BITS: UInt = 0x0000_0000_0000_0007 +internal let OBJC_TAGGED_POINTER_BITS: UInt = 0 #elseif arch(riscv64) // We have no ObjC tagged pointers, and three low spare bits due to alignment. -let NATIVE_SPARE_BITS: UInt = 0x0000_0000_0000_0007 -let OBJC_TAGGED_POINTER_BITS: UInt = 0 +internal let NATIVE_SPARE_BITS: UInt = 0x0000_0000_0000_0007 +internal let OBJC_TAGGED_POINTER_BITS: UInt = 0 #endif diff --git a/test/Interpreter/capture_top_level.swift b/test/Interpreter/capture_top_level.swift index 874f8cb766820..fc625e58e17f4 100644 --- a/test/Interpreter/capture_top_level.swift +++ b/test/Interpreter/capture_top_level.swift @@ -10,13 +10,16 @@ // REQUIRES: executable_test +internal var x = { #if VAR_UPDATE -guard var x = Optional(0) else { fatalError() } + guard var x = Optional(0) else { fatalError() } #elseif VAR -guard var x = Optional(42) else { fatalError() } + guard var x = Optional(42) else { fatalError() } #else -guard let x = Optional(42) else { fatalError() } + guard let x = Optional(42) else { fatalError() } #endif + return x +}() _ = 0 // intervening code diff --git a/test/Interpreter/conditional_conformances_smoke.swift b/test/Interpreter/conditional_conformances_smoke.swift index aee921ecf796c..7ea1adfd84bfd 100644 --- a/test/Interpreter/conditional_conformances_smoke.swift +++ b/test/Interpreter/conditional_conformances_smoke.swift @@ -7,7 +7,7 @@ protocol P1 { func method1() } -var isp1_count = 0 +internal var isp1_count = 0 struct IsP1: P1 { var id: Int init() { diff --git a/test/Interpreter/convenience_init_peer_delegation.swift b/test/Interpreter/convenience_init_peer_delegation.swift index 477c44b177c5c..f3fba7e9bd8e6 100644 --- a/test/Interpreter/convenience_init_peer_delegation.swift +++ b/test/Interpreter/convenience_init_peer_delegation.swift @@ -89,12 +89,12 @@ class Sub: Base {} } // Replace swift_allocObject so that we can keep track of what gets allocated. -var baseCounter = 0 -var subCounter = 0 +internal var baseCounter = 0 +internal var subCounter = 0 typealias AllocObjectType = @convention(c) (UnsafeRawPointer, Int, Int) -> UnsafeMutableRawPointer -let allocObjectImpl = +internal let allocObjectImpl = dlsym(UnsafeMutableRawPointer(bitPattern: -1), "_swift_allocObject") .assumingMemoryBound(to: AllocObjectType.self) @@ -105,7 +105,11 @@ func asUnsafeRawPointer(_ someClass: AnyObject.Type) -> UnsafeRawPointer { return UnsafeRawPointer(opaque) } -let originalAllocObject = allocObjectImpl.pointee +internal let originalAllocObject = allocObjectImpl.pointee + +// Make sure we initialize the global before referencing it in the hook. +_ = originalAllocObject + allocObjectImpl.pointee = { switch $0 { case asUnsafeRawPointer(Base.self): diff --git a/test/Interpreter/deinit_recursive_no_overflow.swift b/test/Interpreter/deinit_recursive_no_overflow.swift index 2e50cfbac3ed8..eb4178ebc9283 100644 --- a/test/Interpreter/deinit_recursive_no_overflow.swift +++ b/test/Interpreter/deinit_recursive_no_overflow.swift @@ -6,7 +6,7 @@ class Node { var next: Node? } -var first: Node? = nil +internal var first: Node? = nil for _ in 1...3_000_000 { let next = Node() next.next = first @@ -17,4 +17,4 @@ for _ in 1...3_000_000 { func deallocList() { first = nil } -deallocList() \ No newline at end of file +deallocList() diff --git a/test/Interpreter/failable_initializers_root_class.swift b/test/Interpreter/failable_initializers_root_class.swift index 9caa08da0001e..680d1fb842fb7 100644 --- a/test/Interpreter/failable_initializers_root_class.swift +++ b/test/Interpreter/failable_initializers_root_class.swift @@ -7,7 +7,7 @@ import StdlibUnittest var FailableInitTestSuite = TestSuite("FailableInit") -var deinitCalled = 0 +internal var deinitCalled = 0 func mustFail(f: () -> T?) { if f() != nil { diff --git a/test/Interpreter/generic_subscript_static.swift b/test/Interpreter/generic_subscript_static.swift index 77fb6f117c53a..0a59f216e77e7 100644 --- a/test/Interpreter/generic_subscript_static.swift +++ b/test/Interpreter/generic_subscript_static.swift @@ -18,7 +18,7 @@ import StdlibUnittest var GenericSubscriptTestSuite = TestSuite("GenericSubscriptStatic") -var ts: [ObjectIdentifier: Any] = [:] +internal var ts: [ObjectIdentifier: Any] = [:] struct S : P { typealias Element = T diff --git a/test/Interpreter/initializers.swift b/test/Interpreter/initializers.swift index 97715d025cd58..12a7744702110 100644 --- a/test/Interpreter/initializers.swift +++ b/test/Interpreter/initializers.swift @@ -4,7 +4,7 @@ // REQUIRES: executable_test // Test initialization and initializer inheritance. -var depth = 0 +internal var depth = 0 func printAtDepth(_ s: String) { for i in 0.. { var isEmpty: Bool { true } diff --git a/test/Interpreter/lazy/globals.swift b/test/Interpreter/lazy/globals.swift index 3dc8d713403dc..68860eabae829 100644 --- a/test/Interpreter/lazy/globals.swift +++ b/test/Interpreter/lazy/globals.swift @@ -3,6 +3,8 @@ // REQUIRES: swift_feature_LazyImmediate // RUN: %target-jit-run %s -enable-experimental-feature LazyImmediate | %FileCheck %s +// REQUIRES: doesnt_correctly_handle_actual_globals + // Tests that piecewise compilation works with global variables let x = 1 diff --git a/test/Interpreter/lazy_properties.swift b/test/Interpreter/lazy_properties.swift index 3ed155f6395d9..c8ea6353ff6c2 100644 --- a/test/Interpreter/lazy_properties.swift +++ b/test/Interpreter/lazy_properties.swift @@ -5,9 +5,9 @@ import StdlibUnittest var LazyPropertyTestSuite = TestSuite("LazyProperty") -var lazyPropertyInitialized = 0 -var lazyPropertyInitialized2 = 0 -var lazyPropertyInitialized3 = 0 +internal var lazyPropertyInitialized = 0 +internal var lazyPropertyInitialized2 = 0 +internal var lazyPropertyInitialized3 = 0 func lazyInitFunction() -> Int { lazyPropertyInitialized += 1 diff --git a/test/Interpreter/moveonly_deinit_autoclosure.swift b/test/Interpreter/moveonly_deinit_autoclosure.swift index 3c89be208b8a5..10e7ba2c521e1 100644 --- a/test/Interpreter/moveonly_deinit_autoclosure.swift +++ b/test/Interpreter/moveonly_deinit_autoclosure.swift @@ -10,7 +10,7 @@ internal func _myPrecondition( } } -var deinitCounter = 0 +internal var deinitCounter = 0 struct MyCounter: ~Copyable { let expectedCount = 1 diff --git a/test/Interpreter/moveonly_escaping_capture_lifetimes.swift b/test/Interpreter/moveonly_escaping_capture_lifetimes.swift index 0619c28f6aa5e..034d075dc12c4 100644 --- a/test/Interpreter/moveonly_escaping_capture_lifetimes.swift +++ b/test/Interpreter/moveonly_escaping_capture_lifetimes.swift @@ -8,7 +8,7 @@ struct MO: ~Copyable { deinit { print("dying \(x)") } } -var f: () -> () = {} +internal var f: () -> () = {} func foo(x: consuming MO) { var counter = 42 diff --git a/test/Interpreter/moveonly_escaping_definite_initialization.swift b/test/Interpreter/moveonly_escaping_definite_initialization.swift index bcdc3f73644e6..3b7702b021fe1 100644 --- a/test/Interpreter/moveonly_escaping_definite_initialization.swift +++ b/test/Interpreter/moveonly_escaping_definite_initialization.swift @@ -11,8 +11,8 @@ struct MO: ~Copyable { deinit { print("destroying \(value)") } } -var closure: () -> () = {} -var counter = 42 +internal var closure: () -> () = {} +internal var counter = 42 func foo(goUp: Bool) { let mo: MO diff --git a/test/Interpreter/moveonly_linkedlist.swift b/test/Interpreter/moveonly_linkedlist.swift index b063400ef52de..ce6a5d109a5d7 100644 --- a/test/Interpreter/moveonly_linkedlist.swift +++ b/test/Interpreter/moveonly_linkedlist.swift @@ -79,7 +79,7 @@ struct ListEntry : ~Copyable { } let target = "ogyfbssvlh" -let strings = [ +internal let strings = [ "nulbhqylps", "hpdovhuybl", "bjjvpakqbm", diff --git a/test/Interpreter/objc_class_properties.swift b/test/Interpreter/objc_class_properties.swift index 541f0f20a637c..de11ec8ef72c0 100644 --- a/test/Interpreter/objc_class_properties.swift +++ b/test/Interpreter/objc_class_properties.swift @@ -208,9 +208,9 @@ ClassProperties.test("namingConflict/protocol") { expectNil(type.protoProp) } -var global1: Int = 0 +internal var global1: Int = 0 -var global2: Int = 0 +internal var global2: Int = 0 class Steak : NSObject { @objc override var thickness: Int { diff --git a/test/Interpreter/objc_types_as_members.swift b/test/Interpreter/objc_types_as_members.swift index 0eb1d1fb89c1f..f6b40edbb8524 100644 --- a/test/Interpreter/objc_types_as_members.swift +++ b/test/Interpreter/objc_types_as_members.swift @@ -27,7 +27,7 @@ extension OuterType.InnerType: InnerProto { } } -var innerthing:InnerProto = OuterType.InnerType() +internal var innerthing:InnerProto = OuterType.InnerType() @inline(never) func getInnerThing() -> InnerProto { diff --git a/test/Interpreter/properties.swift b/test/Interpreter/properties.swift index 8d960f0ecc653..0431e1d345c7b 100644 --- a/test/Interpreter/properties.swift +++ b/test/Interpreter/properties.swift @@ -1,7 +1,8 @@ // RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test -var foo: Int { +// FIXME: Should computed always be global? +internal var foo: Int { get { print("foo gotten") return 219 @@ -198,8 +199,8 @@ protocol rdar38514252_ProtocolWithArray { var arrayOfInt: [Int] { get set } } -var rdar38514252_flag = false -var rdar38514252_questionSet: rdar38514252_ProtocolWithArray? { +internal var rdar38514252_flag = false +internal var rdar38514252_questionSet: rdar38514252_ProtocolWithArray? { didSet { rdar38514252_flag = true } @@ -260,7 +261,7 @@ assert(HasStaticVar.i == DerivesHasStaticVar.i) HasStaticVar.i = 2020 assert(HasStaticVar.i == DerivesHasStaticVar.i) -var _x: Int = 0 +internal var _x: Int = 0 class HasClassVar { class var x: Int { diff --git a/test/Interpreter/protocol_extensions.swift b/test/Interpreter/protocol_extensions.swift index e657f1e0f4e3d..15207e0c7ad3f 100644 --- a/test/Interpreter/protocol_extensions.swift +++ b/test/Interpreter/protocol_extensions.swift @@ -136,9 +136,9 @@ ProtocolExtensionTestSuite.test("ConstrainedExtension") { } // Existentials -var runExistP1 = 0 -var existP1_struct = 0 -var existP1_class = 0 +internal var runExistP1 = 0 +internal var existP1_struct = 0 +internal var existP1_class = 0 protocol ExistP1 { func existP1() @@ -250,7 +250,7 @@ ProtocolExtensionTestSuite.test("ExistentialLValue") { expectFalse(hasP.p.extValue) } -var metatypes: [(Int, Any.Type)] = [] +internal var metatypes: [(Int, Any.Type)] = [] // rdar://problem/20739719 class Super: Init { diff --git a/test/Interpreter/refcount_bridgeobject.swift b/test/Interpreter/refcount_bridgeobject.swift index 8b96d910efe6b..4b042931c4511 100644 --- a/test/Interpreter/refcount_bridgeobject.swift +++ b/test/Interpreter/refcount_bridgeobject.swift @@ -21,7 +21,7 @@ func wrapper_swift_bridgeObjectRelease(_ obj: UnsafeMutableRawPointer?) let RefcountBridgeObjectTests = TestSuite("RefcountBridgeObject") -var didDeinit = false +internal var didDeinit = false class C { deinit { diff --git a/test/Interpreter/refcount_overflow.swift b/test/Interpreter/refcount_overflow.swift index 7c17f37f4e1cd..ae075dafcb4e8 100644 --- a/test/Interpreter/refcount_overflow.swift +++ b/test/Interpreter/refcount_overflow.swift @@ -43,7 +43,7 @@ let maxInlineRC32 = (1 as UInt32) << 22 // Maximum unowned count that fits inline on 32-bit. let maxInlineURC32 = (1 as UInt32) << 7 -var didDeinit = false +internal var didDeinit = false class C { deinit { diff --git a/test/Interpreter/subclass_existentials.swift b/test/Interpreter/subclass_existentials.swift index 8d1be045616c8..12965964c5f8c 100644 --- a/test/Interpreter/subclass_existentials.swift +++ b/test/Interpreter/subclass_existentials.swift @@ -39,7 +39,7 @@ extension R { } } -var globalVar = 8 +internal var globalVar = 8 class Base : R { var x: T diff --git a/test/Interpreter/synthesized_extension_conformances.swift b/test/Interpreter/synthesized_extension_conformances.swift index 520896d780e98..6395d85df32bf 100644 --- a/test/Interpreter/synthesized_extension_conformances.swift +++ b/test/Interpreter/synthesized_extension_conformances.swift @@ -53,25 +53,25 @@ extension NoValues: CaseIterable {} // Cache some values, and make them all have the same width (within a type) for // formatting niceness. -let SIOne = SInt(x: 1) -let SITwo = SInt(x: 2) - -let SFOne = SFloat(y: 1.0) -let SFTwo = SFloat(y: 2.0) -let SFInf = SFloat(y: .infinity) -let SFNan = SFloat(y: .nan) - -let SGOneOne = SGeneric(t: SIOne, u: SFOne) -let SGTwoOne = SGeneric(t: SITwo, u: SFOne) -let SGTwoTwo = SGeneric(t: SITwo, u: SFTwo) -let SGOneInf = SGeneric(t: SIOne, u: SFInf) -let SGOneNan = SGeneric(t: SIOne, u: SFNan) - -let EGaOne: EGeneric = .a(SIOne) -let EGaTwo: EGeneric = .a(SITwo) -let EGbOne: EGeneric = .b(1) -let EGbTwo: EGeneric = .b(2) -let EGc___: EGeneric = .c +internal let SIOne = SInt(x: 1) +internal let SITwo = SInt(x: 2) + +internal let SFOne = SFloat(y: 1.0) +internal let SFTwo = SFloat(y: 2.0) +internal let SFInf = SFloat(y: .infinity) +internal let SFNan = SFloat(y: .nan) + +internal let SGOneOne = SGeneric(t: SIOne, u: SFOne) +internal let SGTwoOne = SGeneric(t: SITwo, u: SFOne) +internal let SGTwoTwo = SGeneric(t: SITwo, u: SFTwo) +internal let SGOneInf = SGeneric(t: SIOne, u: SFInf) +internal let SGOneNan = SGeneric(t: SIOne, u: SFNan) + +internal let EGaOne: EGeneric = .a(SIOne) +internal let EGaTwo: EGeneric = .a(SITwo) +internal let EGbOne: EGeneric = .b(1) +internal let EGbTwo: EGeneric = .b(2) +internal let EGc___: EGeneric = .c func debugDescription(_ value: T) -> String { diff --git a/test/Interpreter/wildcard_dispatch_on_catch.swift b/test/Interpreter/wildcard_dispatch_on_catch.swift index d04955956c534..b192f1bf73780 100644 --- a/test/Interpreter/wildcard_dispatch_on_catch.swift +++ b/test/Interpreter/wildcard_dispatch_on_catch.swift @@ -16,7 +16,7 @@ public func someFunc(_ str: String) throws -> String { return str } -let testData: [String] = [ +internal let testData: [String] = [ "ABC", "DEF", ] diff --git a/test/Interpreter/withoutActuallyEscaping.swift b/test/Interpreter/withoutActuallyEscaping.swift index 1b13db2cf7826..fd2728b483c2d 100644 --- a/test/Interpreter/withoutActuallyEscaping.swift +++ b/test/Interpreter/withoutActuallyEscaping.swift @@ -5,7 +5,7 @@ import StdlibUnittest var WithoutEscapingSuite = TestSuite("WithoutActuallyEscaping") -var sink: Any = () +internal var sink: Any = () func dontEscape(f: () -> ()) { withoutActuallyEscaping(f) { @@ -17,7 +17,7 @@ func letEscape(f: () -> ()) -> () -> () { return withoutActuallyEscaping(f) { return $0 } } -var testShouldThrow = false +internal var testShouldThrow = false struct MyError : Error {} diff --git a/test/SILOptimizer/moveonly_objectchecker_diagnostics.swift b/test/SILOptimizer/moveonly_objectchecker_diagnostics.swift index e64d67d975fbf..42c37e623e237 100644 --- a/test/SILOptimizer/moveonly_objectchecker_diagnostics.swift +++ b/test/SILOptimizer/moveonly_objectchecker_diagnostics.swift @@ -1,4 +1,4 @@ -// RUN: %target-swift-emit-sil -sil-verify-all -verify -enable-experimental-feature MoveOnlyClasses %s +// RUN: %target-swift-emit-sil -parse-as-library -sil-verify-all -verify -enable-experimental-feature MoveOnlyClasses %s // REQUIRES: swift_feature_MoveOnlyClasses diff --git a/test/SILOptimizer/optimize_keypath.swift b/test/SILOptimizer/optimize_keypath.swift index 6af9bd93cc538..2ba1e9d341e12 100644 --- a/test/SILOptimizer/optimize_keypath.swift +++ b/test/SILOptimizer/optimize_keypath.swift @@ -37,7 +37,7 @@ struct GenStruct : P { } #if !swift(>=6) -var numGenClassObjs = 0 +internal var numGenClassObjs = 0 #endif final class GenClass : P { diff --git a/test/SILOptimizer/partial_apply_dynamic_type.swift b/test/SILOptimizer/partial_apply_dynamic_type.swift index 089082b613e12..e2add73203b0d 100644 --- a/test/SILOptimizer/partial_apply_dynamic_type.swift +++ b/test/SILOptimizer/partial_apply_dynamic_type.swift @@ -17,7 +17,7 @@ class C: P { } } -let c = C() +internal let c = C() public func test_PartialApplyDynamicType() -> Int { var result = 0 diff --git a/test/SourceKit/CodeComplete/rdar95772803.swift b/test/SourceKit/CodeComplete/rdar95772803.swift index eec4f67e38ad2..b50bec5f3f2fc 100644 --- a/test/SourceKit/CodeComplete/rdar95772803.swift +++ b/test/SourceKit/CodeComplete/rdar95772803.swift @@ -4,11 +4,12 @@ var bar: Regex { /x/ } var baz: Regex { / x/ } var qux: Regex { / x}/ } +// FIXME: Shouldn't need parse-as-library (https://github.com/swiftlang/swift/issues/84785) // Check that we are not crashing // RUN: %sourcekitd-test \ -// RUN: -req=complete -pos=2:18 %s -- -enable-bare-slash-regex %s == \ -// RUN: -req=complete -pos=3:28 %s -- -enable-bare-slash-regex %s == \ -// RUN: -req=complete -pos=4:28 %s -- -enable-bare-slash-regex %s == \ -// RUN: -req=complete -pos=5:28 %s -- -enable-bare-slash-regex %s +// RUN: -req=complete -pos=2:18 %s -- -enable-bare-slash-regex -parse-as-library %s == \ +// RUN: -req=complete -pos=3:28 %s -- -enable-bare-slash-regex -parse-as-library %s == \ +// RUN: -req=complete -pos=4:28 %s -- -enable-bare-slash-regex -parse-as-library %s == \ +// RUN: -req=complete -pos=5:28 %s -- -enable-bare-slash-regex -parse-as-library %s // REQUIRES: swift_swift_parser diff --git a/test/SourceKit/ConformingMethods/ifconfigcrash.swift b/test/SourceKit/ConformingMethods/ifconfigcrash.swift index cad06f739eb57..fae71b294e15e 100644 --- a/test/SourceKit/ConformingMethods/ifconfigcrash.swift +++ b/test/SourceKit/ConformingMethods/ifconfigcrash.swift @@ -5,6 +5,6 @@ func test() {} #if compiler() #endif - -// RUN: %sourcekitd-test -req=conformingmethods -pos=3:6 -repeat-request=2 %s -- %s +// FIXME: Shouldn't need parse-as-library (https://github.com/swiftlang/swift/issues/84785) +// RUN: %sourcekitd-test -req=conformingmethods -pos=3:6 -repeat-request=2 %s -- %s -parse-as-library diff --git a/validation-test/Evolution/test_protocol_reorder_requirements.swift b/validation-test/Evolution/test_protocol_reorder_requirements.swift index d7aef9863f5fe..eeefb89e92445 100644 --- a/validation-test/Evolution/test_protocol_reorder_requirements.swift +++ b/validation-test/Evolution/test_protocol_reorder_requirements.swift @@ -7,7 +7,7 @@ import protocol_reorder_requirements var ProtocolReorderRequirementsTest = TestSuite("ProtocolReorderRequirements") -var log = [String]() +internal var log = [String]() struct MyBassinet : Bed { func squiggle() { diff --git a/validation-test/IDE/crashers/TypePrinter-printWithParensIfNotSimple-44e8aa.swift b/validation-test/IDE/crashers/TypePrinter-printWithParensIfNotSimple-e95a50.swift similarity index 87% rename from validation-test/IDE/crashers/TypePrinter-printWithParensIfNotSimple-44e8aa.swift rename to validation-test/IDE/crashers/TypePrinter-printWithParensIfNotSimple-e95a50.swift index c7c19e72c1f15..9662acd3a605f 100644 --- a/validation-test/IDE/crashers/TypePrinter-printWithParensIfNotSimple-44e8aa.swift +++ b/validation-test/IDE/crashers/TypePrinter-printWithParensIfNotSimple-e95a50.swift @@ -2,4 +2,4 @@ // RUN: not --crash %target-swift-ide-test -code-completion -batch-code-completion -skip-filecheck -code-completion-diagnostics -source-filename %s // REQUIRES: OS=macosx import Foundation -var a: some NSMutableArray = a == #^^# = <#expression#> +internal var a: some NSMutableArray = a == #^^# = <#expression#> diff --git a/validation-test/IDE/crashers_fixed/TypePrinter-printWithParensIfNotSimple-44e8aa.swift b/validation-test/IDE/crashers_fixed/TypePrinter-printWithParensIfNotSimple-44e8aa.swift new file mode 100644 index 0000000000000..2727b447f19a1 --- /dev/null +++ b/validation-test/IDE/crashers_fixed/TypePrinter-printWithParensIfNotSimple-44e8aa.swift @@ -0,0 +1,5 @@ +// {"kind":"complete","original":"8af9696a","signature":"(anonymous namespace)::TypePrinter::printWithParensIfNotSimple(swift::Type)","signatureAssert":"Assertion failed: (isa(Val) && \"cast() argument of incompatible type!\"), function cast"} +// RUN: %target-swift-ide-test -code-completion -batch-code-completion -skip-filecheck -code-completion-diagnostics -source-filename %s +// REQUIRES: OS=macosx +import Foundation +var a: some NSMutableArray = a == #^^# = <#expression#> diff --git a/validation-test/Sema/type_checker_perf/slow/rdar21198787.swift.gyb b/validation-test/Sema/type_checker_perf/slow/rdar21198787.swift.gyb index 1f869b9009017..b434a96dd8111 100644 --- a/validation-test/Sema/type_checker_perf/slow/rdar21198787.swift.gyb +++ b/validation-test/Sema/type_checker_perf/slow/rdar21198787.swift.gyb @@ -1,7 +1,7 @@ // RUN: %scale-test --invert-result --begin 1 --end 10 --step 1 --select NumLeafScopes %s // REQUIRES: asserts,no_asan -private let _: [Any?] = [[ +let _: [Any?] = [[ %for i in range(0, N): "A": [ "B" : "C", diff --git a/validation-test/compiler_crashers/ConnectedComponents-unionSets-51b4e1.swift b/validation-test/compiler_crashers/ConnectedComponents-unionSets-51b4e1.swift new file mode 100644 index 0000000000000..1dc6e561b07ec --- /dev/null +++ b/validation-test/compiler_crashers/ConnectedComponents-unionSets-51b4e1.swift @@ -0,0 +1,6 @@ +// {"kind":"typecheck","signature":"(anonymous namespace)::ConnectedComponents::unionSets(swift::TypeVariableType*, swift::TypeVariableType*)","signatureAssert":"Assertion failed: (validComponentCount > 0), function unionSets"} +// RUN: not --crash %target-swift-frontend -typecheck %s +internal let b = (c(), d() +a { + e + b diff --git a/validation-test/compiler_crashers/ConstraintGraph-computeConnectedComponents-8dd5e3.swift b/validation-test/compiler_crashers/ConstraintGraph-computeConnectedComponents-8dd5e3.swift new file mode 100644 index 0000000000000..7e22323b617fd --- /dev/null +++ b/validation-test/compiler_crashers/ConstraintGraph-computeConnectedComponents-8dd5e3.swift @@ -0,0 +1,3 @@ +// {"kind":"typecheck","original":"1d97bdbd","signature":"swift::constraints::ConstraintGraph::computeConnectedComponents(llvm::ArrayRef)","signatureAssert":"Assertion failed: (component != components.end()), function operator()"} +// RUN: not --crash %target-swift-frontend -typecheck %s +internal let i =... a { " ? \(i Array* )" [ diff --git a/validation-test/compiler_crashers/ConstraintSystem-getCalleeLocator-8b5d56.swift b/validation-test/compiler_crashers/ConstraintSystem-getCalleeLocator-8b5d56.swift new file mode 100644 index 0000000000000..b9a0040e2c777 --- /dev/null +++ b/validation-test/compiler_crashers/ConstraintSystem-getCalleeLocator-8b5d56.swift @@ -0,0 +1,5 @@ +// {"kind":"typecheck","original":"901f9c6d","signature":"swift::constraints::ConstraintSystem::getCalleeLocator(swift::constraints::ConstraintLocator*, bool, llvm::function_ref, llvm::function_ref, llvm::function_ref (swift::constraints::ConstraintLocator*)>)","signatureAssert":"Assertion failed: (!fnTy->is()), function operator()"} +// RUN: not --crash %target-swift-frontend -typecheck %s +internal let a = [].reduce([]) { + 0 && a($1 == a + $1 { diff --git a/validation-test/compiler_crashers/ConstraintSystem-matchTypes-7c8101.swift b/validation-test/compiler_crashers/ConstraintSystem-matchTypes-7c8101.swift index 690b9f58c90f2..50a0fa8e8e13d 100644 --- a/validation-test/compiler_crashers/ConstraintSystem-matchTypes-7c8101.swift +++ b/validation-test/compiler_crashers/ConstraintSystem-matchTypes-7c8101.swift @@ -1,5 +1,5 @@ // {"kind":"typecheck","signature":"swift::constraints::ConstraintSystem::matchTypes(swift::Type, swift::Type, swift::constraints::ConstraintKind, swift::optionset::OptionSet, swift::constraints::ConstraintLocatorBuilder)"} -// RUN: not --crash %target-swift-frontend -typecheck %s +// RUN: not --crash %target-swift-frontend -typecheck -parse-as-library %s weak var a : b? a class c class b diff --git a/validation-test/compiler_crashers/MissingConformanceFailure-MissingConformanceFailure-25c9a2.swift b/validation-test/compiler_crashers/MissingConformanceFailure-MissingConformanceFailure-25c9a2.swift new file mode 100644 index 0000000000000..3d7ec829bbac2 --- /dev/null +++ b/validation-test/compiler_crashers/MissingConformanceFailure-MissingConformanceFailure-25c9a2.swift @@ -0,0 +1,6 @@ +// {"kind":"typecheck","original":"d896f132","signature":"swift::constraints::MissingConformanceFailure::MissingConformanceFailure(swift::constraints::Solution const&, swift::constraints::ConstraintLocator*, std::__1::pair)","signatureAssert":"Assertion failed: (getGenericContext() && \"Affected decl not within a generic context?\"), function RequirementFailure"} +// RUN: not --crash %target-swift-frontend -typecheck %s +internal let a = + { + 0 ? [a] : [1&&: <#expression#>] + }[<#expression#>] diff --git a/validation-test/compiler_crashers/SILGenBuilder-createEnum-3f34a0.swift b/validation-test/compiler_crashers/SILGenBuilder-createEnum-3f34a0.swift new file mode 100644 index 0000000000000..3206f96f105d3 --- /dev/null +++ b/validation-test/compiler_crashers/SILGenBuilder-createEnum-3f34a0.swift @@ -0,0 +1,3 @@ +// {"kind":"emit-silgen","original":"7b4a72a9","signature":"swift::Lowering::SILGenBuilder::createEnum(swift::SILLocation, swift::Lowering::ManagedValue, swift::EnumElementDecl*, swift::SILType)","signatureAssert":"Assertion failed: (v->getType().isObject()), function operator()"} +// RUN: not --crash %target-swift-frontend -emit-silgen %s +internal var a: Any = ["": [a]] as [String: [AnyObject?]] diff --git a/validation-test/compiler_crashers/ConnectedComponents-unionSets-7527be.swift b/validation-test/compiler_crashers_fixed/ConnectedComponents-unionSets-7527be.swift similarity index 81% rename from validation-test/compiler_crashers/ConnectedComponents-unionSets-7527be.swift rename to validation-test/compiler_crashers_fixed/ConnectedComponents-unionSets-7527be.swift index c47984a0fcbf3..0ceb27c85ba24 100644 --- a/validation-test/compiler_crashers/ConnectedComponents-unionSets-7527be.swift +++ b/validation-test/compiler_crashers_fixed/ConnectedComponents-unionSets-7527be.swift @@ -1,5 +1,5 @@ // {"kind":"typecheck","signature":"(anonymous namespace)::ConnectedComponents::unionSets(swift::TypeVariableType*, swift::TypeVariableType*)","signatureAssert":"Assertion failed: (validComponentCount > 0), function unionSets"} -// RUN: not --crash %target-swift-frontend -typecheck %s +// RUN: not %target-swift-frontend -typecheck %s let b = (c(), d() a { e diff --git a/validation-test/compiler_crashers/ConstraintGraph-computeConnectedComponents-37d275.swift b/validation-test/compiler_crashers_fixed/ConstraintGraph-computeConnectedComponents-37d275.swift similarity index 83% rename from validation-test/compiler_crashers/ConstraintGraph-computeConnectedComponents-37d275.swift rename to validation-test/compiler_crashers_fixed/ConstraintGraph-computeConnectedComponents-37d275.swift index 0522f80258f99..f39695c2c8bf3 100644 --- a/validation-test/compiler_crashers/ConstraintGraph-computeConnectedComponents-37d275.swift +++ b/validation-test/compiler_crashers_fixed/ConstraintGraph-computeConnectedComponents-37d275.swift @@ -1,3 +1,3 @@ // {"kind":"typecheck","original":"1d97bdbd","signature":"swift::constraints::ConstraintGraph::computeConnectedComponents(llvm::ArrayRef)","signatureAssert":"Assertion failed: (component != components.end()), function operator()"} -// RUN: not --crash %target-swift-frontend -typecheck %s +// RUN: not %target-swift-frontend -typecheck %s let i =... a { " ? \(i Array* )" [ diff --git a/validation-test/compiler_crashers/ConstraintSystem-getCalleeLocator-a6b3bc.swift b/validation-test/compiler_crashers_fixed/ConstraintSystem-getCalleeLocator-a6b3bc.swift similarity index 90% rename from validation-test/compiler_crashers/ConstraintSystem-getCalleeLocator-a6b3bc.swift rename to validation-test/compiler_crashers_fixed/ConstraintSystem-getCalleeLocator-a6b3bc.swift index aef865aadd8ab..07324b495c00b 100644 --- a/validation-test/compiler_crashers/ConstraintSystem-getCalleeLocator-a6b3bc.swift +++ b/validation-test/compiler_crashers_fixed/ConstraintSystem-getCalleeLocator-a6b3bc.swift @@ -1,5 +1,5 @@ // {"kind":"typecheck","original":"901f9c6d","signature":"swift::constraints::ConstraintSystem::getCalleeLocator(swift::constraints::ConstraintLocator*, bool, llvm::function_ref, llvm::function_ref, llvm::function_ref (swift::constraints::ConstraintLocator*)>)","signatureAssert":"Assertion failed: (!fnTy->is()), function operator()"} -// RUN: not --crash %target-swift-frontend -typecheck %s +// RUN: not %target-swift-frontend -typecheck %s let a = [].reduce([]) { 0 && a($1 == a $1 { diff --git a/validation-test/compiler_crashers_fixed/ConstraintSystem-matchTypes-7c8101.swift b/validation-test/compiler_crashers_fixed/ConstraintSystem-matchTypes-7c8101.swift new file mode 100644 index 0000000000000..ca9c002f6946b --- /dev/null +++ b/validation-test/compiler_crashers_fixed/ConstraintSystem-matchTypes-7c8101.swift @@ -0,0 +1,6 @@ +// {"kind":"typecheck","signature":"swift::constraints::ConstraintSystem::matchTypes(swift::Type, swift::Type, swift::constraints::ConstraintKind, swift::optionset::OptionSet, swift::constraints::ConstraintLocatorBuilder)"} +// RUN: not %target-swift-frontend -typecheck %s +weak var a : b? a +class c + class b + weak var a: c? diff --git a/validation-test/compiler_crashers/MissingConformanceFailure-MissingConformanceFailure-da6465.swift b/validation-test/compiler_crashers_fixed/MissingConformanceFailure-MissingConformanceFailure-da6465.swift similarity index 88% rename from validation-test/compiler_crashers/MissingConformanceFailure-MissingConformanceFailure-da6465.swift rename to validation-test/compiler_crashers_fixed/MissingConformanceFailure-MissingConformanceFailure-da6465.swift index 77cffb7cf51bf..1cb3a0f677d41 100644 --- a/validation-test/compiler_crashers/MissingConformanceFailure-MissingConformanceFailure-da6465.swift +++ b/validation-test/compiler_crashers_fixed/MissingConformanceFailure-MissingConformanceFailure-da6465.swift @@ -1,5 +1,5 @@ // {"kind":"typecheck","original":"d896f132","signature":"swift::constraints::MissingConformanceFailure::MissingConformanceFailure(swift::constraints::Solution const&, swift::constraints::ConstraintLocator*, std::__1::pair)","signatureAssert":"Assertion failed: (getGenericContext() && \"Affected decl not within a generic context?\"), function RequirementFailure"} -// RUN: not --crash %target-swift-frontend -typecheck %s +// RUN: not %target-swift-frontend -typecheck %s let a = { 0 ? [a] : [1&&: <#expression#>] diff --git a/validation-test/compiler_crashers/SILGenBuilder-createEnum-845e70.swift b/validation-test/compiler_crashers_fixed/SILGenBuilder-createEnum-845e70.swift similarity index 84% rename from validation-test/compiler_crashers/SILGenBuilder-createEnum-845e70.swift rename to validation-test/compiler_crashers_fixed/SILGenBuilder-createEnum-845e70.swift index 1ea09d57e6603..002f26ce1f3b0 100644 --- a/validation-test/compiler_crashers/SILGenBuilder-createEnum-845e70.swift +++ b/validation-test/compiler_crashers_fixed/SILGenBuilder-createEnum-845e70.swift @@ -1,3 +1,3 @@ // {"kind":"emit-silgen","original":"7b4a72a9","signature":"swift::Lowering::SILGenBuilder::createEnum(swift::SILLocation, swift::Lowering::ManagedValue, swift::EnumElementDecl*, swift::SILType)","signatureAssert":"Assertion failed: (v->getType().isObject()), function operator()"} -// RUN: not --crash %target-swift-frontend -emit-silgen %s +// RUN: not %target-swift-frontend -emit-silgen %s var a: Any = ["": [a]] as [String: [AnyObject?]] diff --git a/validation-test/compiler_crashers/TypeChecker-typeCheckStmtConditionElement-029cff.swift b/validation-test/compiler_crashers_fixed/TypeChecker-typeCheckStmtConditionElement-029cff.swift similarity index 86% rename from validation-test/compiler_crashers/TypeChecker-typeCheckStmtConditionElement-029cff.swift rename to validation-test/compiler_crashers_fixed/TypeChecker-typeCheckStmtConditionElement-029cff.swift index 1850f451acb6f..df213ed2dc3f2 100644 --- a/validation-test/compiler_crashers/TypeChecker-typeCheckStmtConditionElement-029cff.swift +++ b/validation-test/compiler_crashers_fixed/TypeChecker-typeCheckStmtConditionElement-029cff.swift @@ -1,3 +1,3 @@ // {"kind":"typecheck","signature":"swift::TypeChecker::typeCheckStmtConditionElement(swift::StmtConditionElement&, bool&, swift::DeclContext*)","signatureAssert":"Assertion failed: (!elt.getPattern()->hasType() && \"the pattern binding condition is already type checked\"), function typeCheckPatternBindingStmtConditionElement"} -// RUN: not --crash %target-swift-frontend -typecheck %s +// RUN: not %target-swift-frontend -typecheck %s a guard let b let a = b diff --git a/validation-test/compiler_crashers/TypeChecker-typeCheckStmtConditionElement-266df8.swift b/validation-test/compiler_crashers_fixed/TypeChecker-typeCheckStmtConditionElement-266df8.swift similarity index 87% rename from validation-test/compiler_crashers/TypeChecker-typeCheckStmtConditionElement-266df8.swift rename to validation-test/compiler_crashers_fixed/TypeChecker-typeCheckStmtConditionElement-266df8.swift index e76481422b62e..a01423101544a 100644 --- a/validation-test/compiler_crashers/TypeChecker-typeCheckStmtConditionElement-266df8.swift +++ b/validation-test/compiler_crashers_fixed/TypeChecker-typeCheckStmtConditionElement-266df8.swift @@ -1,5 +1,5 @@ // {"kind":"typecheck","signature":"swift::TypeChecker::typeCheckStmtConditionElement(swift::StmtConditionElement&, bool&, swift::DeclContext*)","signatureAssert":"Assertion failed: (!elt.getPattern()->hasType() && \"the pattern binding condition is already type checked\"), function typeCheckPatternBindingStmtConditionElement"} -// RUN: not --crash %target-swift-frontend -typecheck %s +// RUN: not %target-swift-frontend -typecheck %s struct a { func b() {} } diff --git a/validation-test/compiler_crashers/TypeConverter-setCaptureTypeExpansionContext-e72208.swift b/validation-test/compiler_crashers_fixed/TypeConverter-setCaptureTypeExpansionContext-e72208.swift similarity index 88% rename from validation-test/compiler_crashers/TypeConverter-setCaptureTypeExpansionContext-e72208.swift rename to validation-test/compiler_crashers_fixed/TypeConverter-setCaptureTypeExpansionContext-e72208.swift index 0180957614ec0..3f79f5792896e 100644 --- a/validation-test/compiler_crashers/TypeConverter-setCaptureTypeExpansionContext-e72208.swift +++ b/validation-test/compiler_crashers_fixed/TypeConverter-setCaptureTypeExpansionContext-e72208.swift @@ -1,5 +1,5 @@ // {"issueID":85266,"kind":"emit-silgen","signature":"swift::Lowering::TypeConverter::setCaptureTypeExpansionContext(swift::SILDeclRef, swift::SILModule&)","signatureAssert":"Assertion failed: (existing->second == context && \"closure shouldn't be emitted with different capture type expansion contexts\"), function setCaptureTypeExpansionContext"} -// RUN: not --crash %target-swift-frontend -emit-silgen %s +// RUN: not %target-swift-frontend -emit-silgen %s // https://github.com/swiftlang/swift/issues/85266 func a() { func b() -> Any {