Skip to content

Commit aa70ac7

Browse files
committed
[Compile Time Constant Extraction] Extract explicit cast property init values
For some types which are e.g. ExpressibleByStringLiteral, we may encounter a coerce expression with a compile-time-knowable parameter/sub-expression.
1 parent e851856 commit aa70ac7

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

Diff for: lib/ConstExtract/ConstExtract.cpp

+5
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,11 @@ static std::shared_ptr<CompileTimeValue> extractCompileTimeValue(Expr *expr) {
294294
placeholderExpr->getOriginalWrappedValue());
295295
}
296296

297+
case ExprKind::Coerce: {
298+
auto coerceExpr = cast<CoerceExpr>(expr);
299+
return extractCompileTimeValue(coerceExpr->getSubExpr());
300+
}
301+
297302
default: {
298303
break;
299304
}

Diff for: test/ConstExtraction/ExtractCoerce.swift

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// RUN: %empty-directory(%t)
2+
// RUN: echo "[MyProto]" > %t/protocols.json
3+
4+
// RUN: %target-swift-frontend -typecheck -emit-const-values-path %t/ExtractLiterals.swiftconstvalues -const-gather-protocols-file %t/protocols.json -primary-file %s
5+
// RUN: cat %t/ExtractLiterals.swiftconstvalues 2>&1 | %FileCheck %s
6+
7+
struct CoercableThing : ExpressibleByStringLiteral {
8+
let thing: String
9+
public init(unicodeScalarLiteral value: String) {
10+
self.init(stringLiteral: value)
11+
}
12+
13+
init(stringLiteral: String) {
14+
self.thing = stringLiteral
15+
}
16+
}
17+
18+
protocol MyProto {}
19+
public struct TestStruct : MyProto {
20+
let foo: CoercableThing = "foo"
21+
let bar: CoercableThing = CoercableThing("bar")
22+
}
23+
24+
// CHECK: "label": "foo",
25+
// CHECK: "valueKind": "RawLiteral",
26+
// CHECK: "value": "foo"
27+
// CHECK: "label": "bar",
28+
// CHECK: "valueKind": "RawLiteral",
29+
// CHECK: "value": "bar"

0 commit comments

Comments
 (0)