diff --git a/lib/AST/Expr.cpp b/lib/AST/Expr.cpp index 62edfd18b4fa3..666975cc22926 100644 --- a/lib/AST/Expr.cpp +++ b/lib/AST/Expr.cpp @@ -1934,11 +1934,13 @@ unsigned AbstractClosureExpr::getDiscriminator() const { // If we don't have a discriminator, and either // 1. We have ill-formed code and we're able to assign a discriminator, or // 2. We are in a macro expansion buffer + // 3. We are within top-level code where there's nothing to anchor to // // then assign the next discriminator now. if (getRawDiscriminator() == InvalidDiscriminator && (ctx.Diags.hadAnyError() || - getParentSourceFile()->getFulfilledMacroRole() != std::nullopt)) { + getParentSourceFile()->getFulfilledMacroRole() != std::nullopt || + getParent()->isModuleScopeContext())) { auto discriminator = ctx.getNextDiscriminator(getParent()); ctx.setMaxAssignedDiscriminator(getParent(), discriminator + 1); const_cast(this)-> diff --git a/test/Macros/fine_grained_dependencies.swift b/test/Macros/fine_grained_dependencies.swift new file mode 100644 index 0000000000000..8ba199590272a --- /dev/null +++ b/test/Macros/fine_grained_dependencies.swift @@ -0,0 +1,19 @@ +// REQUIRES: swift_swift_parser, executable_test + +// RUN: %empty-directory(%t) +// RUN: %host-build-swift -swift-version 5 -emit-library -o %t/%target-library-name(MacroDefinition) -module-name=MacroDefinition %S/Inputs/syntax_macro_definitions.swift + +// RUN: %target-swift-frontend -typecheck -swift-version 5 -load-plugin-library %t/%target-library-name(MacroDefinition) -module-name MacroUser -parse-as-library -emit-reference-dependencies-path %t/MacroUser.swiftdeps -primary-file %s + +// Note: this test ensures that we don't crash when trying to mangle a symbol +// within a closure passed to a macro. + +@freestanding(declaration) +macro Empty(_ x: T) = #externalMacro(module: "MacroDefinition", type: "EmptyDeclarationMacro") + +#Empty { + struct S { + static var foo: Int { 0 } + } + _ = S.foo +}