Skip to content

Commit 5898df0

Browse files
authored
[ModuleInterface] Trap when trying to print a null type (swiftlang#19596)
We want to catch these bugs sooner rather than later, like the one Harlan fixed in eb75ad8. Trapping deterministically is the best way to do so, and it's better than generating nonsense.
1 parent bf84b29 commit 5898df0

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

include/swift/AST/PrintOptions.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,10 @@ struct PrintOptions {
189189
/// ([] and ?), even if there are no sugar type nodes.
190190
bool SynthesizeSugarOnTypes = false;
191191

192+
/// \brief If true, null types in the AST will be printed as "<null>". If
193+
/// false, the compiler will trap.
194+
bool AllowNullTypes = true;
195+
192196
/// \brief If true, the printer will explode a pattern like this:
193197
/// \code
194198
/// var (a, b) = f()

lib/AST/ASTPrinter.cpp

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ PrintOptions PrintOptions::printTextualInterfaceFile() {
8585
result.TypeDefinitions = true;
8686
result.PrintIfConfig = false;
8787
result.FullyQualifiedTypes = true;
88+
result.AllowNullTypes = false;
8889
result.SkipImports = true;
8990
result.OmitNameOfInaccessibleProperties = true;
9091
result.FunctionDefinitions = true;
@@ -4020,10 +4021,15 @@ void Type::print(raw_ostream &OS, const PrintOptions &PO) const {
40204021
print(Printer, PO);
40214022
}
40224023
void Type::print(ASTPrinter &Printer, const PrintOptions &PO) const {
4023-
if (isNull())
4024+
if (isNull()) {
4025+
if (!PO.AllowNullTypes) {
4026+
// Use report_fatal_error instead of assert to trap in release builds too.
4027+
llvm::report_fatal_error("Cannot pretty-print a null type");
4028+
}
40244029
Printer << "<null>";
4025-
else
4026-
TypePrinter(Printer, PO).visit(*this);
4030+
return;
4031+
}
4032+
TypePrinter(Printer, PO).visit(*this);
40274033
}
40284034

40294035
void AnyFunctionType::printParams(raw_ostream &OS, const

0 commit comments

Comments
 (0)