gdp-wired 0.31.1 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +95 -6
- package/dist/core/c/reader.d.ts +86 -0
- package/dist/core/c/reader.js +860 -0
- package/dist/core/check.js +20 -6
- package/dist/core/cli.d.ts +76 -0
- package/dist/core/cli.js +636 -0
- package/dist/core/dsl.d.ts +6 -4
- package/dist/core/dsl.js +30 -16
- package/dist/core/effect.d.ts +6 -4
- package/dist/core/effect.js +48 -10
- package/dist/core/ex/harness.exs +177 -0
- package/dist/core/ex/json.exs +46 -0
- package/dist/core/ex/reader.exs +462 -0
- package/dist/core/exists.d.ts +3 -0
- package/dist/core/exists.js +19 -5
- package/dist/core/extract-c.d.ts +35 -0
- package/dist/core/extract-c.js +424 -0
- package/dist/core/extract-check.js +27 -6
- package/dist/core/extract-ex.d.ts +16 -0
- package/dist/core/extract-ex.js +33 -0
- package/dist/core/extract-go-check.d.ts +28 -0
- package/dist/core/extract-go-check.js +639 -0
- package/dist/core/extract-go.d.ts +231 -0
- package/dist/core/extract-go.js +1166 -0
- package/dist/core/extract-jvm.d.ts +23 -0
- package/dist/core/extract-jvm.js +220 -0
- package/dist/core/extract-print.js +17 -7
- package/dist/core/extract-py.d.ts +15 -0
- package/dist/core/extract-py.js +31 -0
- package/dist/core/extract-rb.d.ts +17 -0
- package/dist/core/extract-rb.js +31 -0
- package/dist/core/extract-read.d.ts +20 -0
- package/dist/core/extract-read.js +46 -6
- package/dist/core/extract-rs.d.ts +12 -0
- package/dist/core/extract-rs.js +306 -0
- package/dist/core/extract-shapes.d.ts +2 -0
- package/dist/core/extract-shapes.js +6 -5
- package/dist/core/extract-step.d.ts +806 -0
- package/dist/core/extract-step.js +4141 -0
- package/dist/core/extract-swift.d.ts +27 -0
- package/dist/core/extract-swift.js +484 -0
- package/dist/core/extract-xstate.d.ts +10 -3
- package/dist/core/extract-xstate.js +50 -4
- package/dist/core/extract.d.ts +22 -3
- package/dist/core/extract.js +107 -18
- package/dist/core/go/go.mod +3 -0
- package/dist/core/go/reader.go +901 -0
- package/dist/core/infer.d.ts +4 -0
- package/dist/core/infer.js +1838 -69
- package/dist/core/jvm/Harness.java +361 -0
- package/dist/core/jvm/JavaReader.java +825 -0
- package/dist/core/jvm/Jvm.java +332 -0
- package/dist/core/jvm/KtReader.java +960 -0
- package/dist/core/jvm/Rt.java +10 -0
- package/dist/core/laws.d.ts +83 -0
- package/dist/core/laws.js +623 -0
- package/dist/core/machine.d.ts +2 -0
- package/dist/core/machine.js +87 -0
- package/dist/core/py/harness.py +328 -0
- package/dist/core/py/reader.py +447 -0
- package/dist/core/rb/harness.rb +233 -0
- package/dist/core/rb/reader.rb +375 -0
- package/dist/core/relational.d.ts +49 -0
- package/dist/core/relational.js +345 -0
- package/dist/core/rs/Cargo.lock +108 -0
- package/dist/core/rs/Cargo.toml +14 -0
- package/dist/core/rs/src/main.rs +681 -0
- package/dist/core/swift/Harness.swift +124 -0
- package/dist/core/swift/Main.swift +34 -0
- package/dist/core/swift/Package.swift +13 -0
- package/dist/core/swift/Sources/gdp-swiftreader/main.swift +1341 -0
- package/dist/interchange/check.d.ts +16 -0
- package/dist/interchange/check.js +111 -0
- package/dist/interchange/format.d.ts +150 -0
- package/dist/interchange/format.js +678 -0
- package/dist/kernel/epr.d.ts +40 -0
- package/dist/kernel/epr.js +1882 -0
- package/dist/kernel/kernel.d.ts +45 -1
- package/dist/kernel/kernel.js +138 -13
- package/dist/kernel/prove.d.ts +45 -0
- package/dist/kernel/prove.js +658 -51
- package/dist/lean-kernel/emit.d.ts +17 -2
- package/dist/lean-kernel/emit.js +87 -7
- package/package.json +57 -2
|
@@ -0,0 +1,1341 @@
|
|
|
1
|
+
// The extractor's Swift reader (core/extract-swift.ts): a package's sources read through swift-syntax's parser and
|
|
2
|
+
// lowered into the shared step IR (core/extract-step.ts's SModule, as JSON on stdout), which the shared executor runs
|
|
3
|
+
// into the rule. Types are the code's declared ones (a property's annotation or its literal initializer, a parameter's,
|
|
4
|
+
// a result's, a protocol's requirements), never inferred past what the declarations say: a value of no declared type
|
|
5
|
+
// is opaque, refused where a step reads it. Nothing here decides the subset beyond the syntax: a construct the IR has no
|
|
6
|
+
// node for becomes {"e": "no"} / {"s": "no"} with the reason, refused only where a step reaches it. Integer semantics
|
|
7
|
+
// are the IR's own operations: `+ - *` trap past the type's range (Swift's default), `&+ &- &*` wrap, `/ %` truncate,
|
|
8
|
+
// Int32(x) traps where x doesn't fit, Int32(truncatingIfNeeded:) wraps, Int32(clamping:) saturates.
|
|
9
|
+
//
|
|
10
|
+
// gdp-swiftreader <root> <entry file or -> <names,comma-separated or -> <ctor arity or -> <file>...
|
|
11
|
+
import Foundation
|
|
12
|
+
import SwiftOperators
|
|
13
|
+
import SwiftParser
|
|
14
|
+
import SwiftSyntax
|
|
15
|
+
|
|
16
|
+
// --- JSON ----------------------------------------------------------------------------------------------------------
|
|
17
|
+
indirect enum J: ExpressibleByStringLiteral, ExpressibleByIntegerLiteral, ExpressibleByBooleanLiteral, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral, ExpressibleByNilLiteral {
|
|
18
|
+
case null, b(Bool), i(Int), s(String), a([J]), o([(String, J)])
|
|
19
|
+
init(stringLiteral v: String) { self = .s(v) }
|
|
20
|
+
init(integerLiteral v: Int) { self = .i(v) }
|
|
21
|
+
init(booleanLiteral v: Bool) { self = .b(v) }
|
|
22
|
+
init(arrayLiteral xs: J...) { self = .a(xs) }
|
|
23
|
+
init(dictionaryLiteral kv: (String, J)...) { self = .o(kv.filter { if case .null = $0.1 { return false }; return true }) }
|
|
24
|
+
init(nilLiteral: ()) { self = .null }
|
|
25
|
+
subscript(k: String) -> J {
|
|
26
|
+
get { if case .o(let kv) = self { return kv.first { $0.0 == k }?.1 ?? .null }; return .null }
|
|
27
|
+
set {
|
|
28
|
+
guard case .o(var kv) = self else { return }
|
|
29
|
+
if let i = kv.firstIndex(where: { $0.0 == k }) { kv[i].1 = newValue } else { kv.append((k, newValue)) }
|
|
30
|
+
self = .o(kv)
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
var str: String? { if case .s(let s) = self { return s }; return nil }
|
|
34
|
+
var isNull: Bool { if case .null = self { return true }; return false }
|
|
35
|
+
var arr: [J] { if case .a(let xs) = self { return xs }; return [] }
|
|
36
|
+
func write(_ out: inout String) {
|
|
37
|
+
switch self {
|
|
38
|
+
case .null: out += "null"
|
|
39
|
+
case .b(let b): out += b ? "true" : "false"
|
|
40
|
+
case .i(let i): out += String(i)
|
|
41
|
+
case .s(let s):
|
|
42
|
+
out += "\""
|
|
43
|
+
for u in s.unicodeScalars {
|
|
44
|
+
switch u {
|
|
45
|
+
case "\"": out += "\\\""
|
|
46
|
+
case "\\": out += "\\\\"
|
|
47
|
+
case "\n": out += "\\n"
|
|
48
|
+
case "\r": out += "\\r"
|
|
49
|
+
case "\t": out += "\\t"
|
|
50
|
+
default: if u.value < 0x20 { out += String(format: "\\u%04x", u.value) } else { out.unicodeScalars.append(u) }
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
out += "\""
|
|
54
|
+
case .a(let xs): out += "["; for (i, x) in xs.enumerated() { if i > 0 { out += "," }; x.write(&out) }; out += "]"
|
|
55
|
+
case .o(let kv): out += "{"; for (i, (k, v)) in kv.enumerated() { if i > 0 { out += "," }; J.s(k).write(&out); out += ":"; v.write(&out) }; out += "}"
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
func X(_ e: String, _ p: String, _ kv: [(String, J)] = []) -> J { .o([("e", .s(e)), ("p", .s(p))] + kv.filter { !$0.1.isNull }) }
|
|
60
|
+
func S(_ s: String, _ p: String, _ kv: [(String, J)] = []) -> J { .o([("s", .s(s)), ("p", .s(p))] + kv.filter { !$0.1.isNull }) }
|
|
61
|
+
func no(_ p: String, _ why: String) -> J { X("no", p, [("why", .s(why))]) }
|
|
62
|
+
func sno(_ p: String, _ why: String) -> J { S("no", p, [("why", .s(why))]) }
|
|
63
|
+
func v(_ n: String, _ p: String) -> J { X("var", p, [("n", .s(n))]) }
|
|
64
|
+
func isPlace(_ x: J) -> Bool { ["var", "get", "idx"].contains(x["e"].str ?? "") }
|
|
65
|
+
func short(_ t: String) -> String { let s = t.split(whereSeparator: { $0.isWhitespace }).joined(separator: " "); return s.count <= 60 ? s : String(s.prefix(57)) + "..." }
|
|
66
|
+
|
|
67
|
+
// --- types, read from their text (the declared ones only) ---------------------------------------------------------
|
|
68
|
+
indirect enum TT: Equatable {
|
|
69
|
+
case n(String, [TT]), opt(TT), dict(TT, TT), arr(TT), tup([TT]), fn, bad(String)
|
|
70
|
+
var name: String? { if case .n(let n, _) = self { return n }; return nil }
|
|
71
|
+
}
|
|
72
|
+
func parseType(_ text: String) -> TT {
|
|
73
|
+
var toks: [String] = []
|
|
74
|
+
var i = text.startIndex
|
|
75
|
+
while i < text.endIndex {
|
|
76
|
+
let c = text[i]
|
|
77
|
+
if c.isWhitespace { i = text.index(after: i); continue }
|
|
78
|
+
if c.isLetter || c == "_" || c == "@" {
|
|
79
|
+
var j = text.index(after: i)
|
|
80
|
+
while j < text.endIndex, text[j].isLetter || text[j].isNumber || text[j] == "_" || text[j] == "." { j = text.index(after: j) }
|
|
81
|
+
toks.append(String(text[i..<j])); i = j; continue
|
|
82
|
+
}
|
|
83
|
+
if c == "-", text.index(after: i) < text.endIndex, text[text.index(after: i)] == ">" { toks.append("->"); i = text.index(i, offsetBy: 2); continue }
|
|
84
|
+
toks.append(String(c)); i = text.index(after: i)
|
|
85
|
+
}
|
|
86
|
+
var k = 0
|
|
87
|
+
func peek() -> String? { k < toks.count ? toks[k] : nil }
|
|
88
|
+
func type() -> TT {
|
|
89
|
+
while let t = peek(), ["any", "some", "inout", "borrowing", "consuming", "sending", "__owned", "__shared"].contains(t) || t.hasPrefix("@") { k += 1 }
|
|
90
|
+
var out: TT
|
|
91
|
+
guard let t = peek() else { return .bad(text) }
|
|
92
|
+
if t == "[" {
|
|
93
|
+
k += 1
|
|
94
|
+
let a = type()
|
|
95
|
+
if peek() == ":" { k += 1; let b = type(); if peek() == "]" { k += 1 }; out = .dict(a, b) } else { if peek() == "]" { k += 1 }; out = .arr(a) }
|
|
96
|
+
} else if t == "(" {
|
|
97
|
+
k += 1
|
|
98
|
+
var xs: [TT] = []
|
|
99
|
+
while let p = peek(), p != ")" { if p == "," { k += 1; continue }; if k + 1 < toks.count, toks[k + 1] == ":" { k += 2 }; xs.append(type()) }
|
|
100
|
+
k += 1
|
|
101
|
+
if peek() == "->" || peek() == "throws" || peek() == "async" { return .fn }
|
|
102
|
+
out = xs.count == 1 ? xs[0] : .tup(xs)
|
|
103
|
+
} else if t.first?.isLetter == true || t.first == "_" {
|
|
104
|
+
k += 1
|
|
105
|
+
var name = t.hasPrefix("Swift.") ? String(t.dropFirst(6)) : t
|
|
106
|
+
var args: [TT] = []
|
|
107
|
+
if peek() == "<" { k += 1; while let p = peek(), p != ">" { if p == "," { k += 1; continue }; args.append(type()) }; k += 1 }
|
|
108
|
+
if name.hasSuffix(".Type") || name.hasSuffix(".Protocol") { name = "?meta" }
|
|
109
|
+
if name == "Optional", args.count == 1 { out = .opt(args[0]) }
|
|
110
|
+
else if name == "Dictionary", args.count == 2 { out = .dict(args[0], args[1]) }
|
|
111
|
+
else if name == "Array", args.count == 1 { out = .arr(args[0]) }
|
|
112
|
+
else { out = .n(name, args) }
|
|
113
|
+
} else { return .bad(text) }
|
|
114
|
+
while let p = peek(), p == "?" || p == "!" { k += 1; out = .opt(out) }
|
|
115
|
+
if peek() == "->" { return .fn }
|
|
116
|
+
return out
|
|
117
|
+
}
|
|
118
|
+
let t = type()
|
|
119
|
+
return k < toks.count && toks[k] != "throws" ? .bad(text) : t
|
|
120
|
+
}
|
|
121
|
+
let INTS: [String: (Int, Bool)] = ["Int": (64, true), "Int64": (64, true), "Int32": (32, true), "Int16": (16, true), "Int8": (8, true),
|
|
122
|
+
"UInt": (64, false), "UInt64": (64, false), "UInt32": (32, false), "UInt16": (16, false), "UInt8": (8, false)]
|
|
123
|
+
func swiftText(_ t: TT) -> String {
|
|
124
|
+
switch t {
|
|
125
|
+
case .n(let n, let a): return a.isEmpty ? n : "\(n)<\(a.map(swiftText).joined(separator: ", "))>"
|
|
126
|
+
case .opt(let x): return "\(swiftText(x))?"
|
|
127
|
+
case .dict(let a, let b): return "[\(swiftText(a)): \(swiftText(b))]"
|
|
128
|
+
case .arr(let x): return "[\(swiftText(x))]"
|
|
129
|
+
case .tup(let xs): return "(\(xs.map(swiftText).joined(separator: ", ")))"
|
|
130
|
+
case .fn: return "() -> Void"
|
|
131
|
+
case .bad(let s): return s
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// --- the package, indexed ------------------------------------------------------------------------------------------
|
|
136
|
+
struct Case { let name: String; var params: [(label: String?, t: TT)]; var raw: J }
|
|
137
|
+
final class Ty {
|
|
138
|
+
let name: String; var qual: String; var kind: String; var file: String; var line: Int
|
|
139
|
+
var generic = false; var inherits: [String] = []; var priv = false
|
|
140
|
+
var members: [(file: String, decl: DeclSyntax)] = []
|
|
141
|
+
var cases: [Case] = []
|
|
142
|
+
var rawType: TT?
|
|
143
|
+
var outer: Ty?
|
|
144
|
+
init(name: String, qual: String, kind: String, file: String, line: Int) { self.name = name; self.qual = qual; self.kind = kind; self.file = file; self.line = line }
|
|
145
|
+
}
|
|
146
|
+
struct SrcFile { let rel: String; let tree: SourceFileSyntax; let conv: SourceLocationConverter }
|
|
147
|
+
// A stored property: its name, type, initializer, `let`, where its binding keyword is (the check's copy writes `var`).
|
|
148
|
+
struct Prop {
|
|
149
|
+
let name: String; let t: TT; let ttext: String; let initv: ExprSyntax?; let isLet: Bool; let kw: String; let observers: Bool; let priv: Bool
|
|
150
|
+
// (a `var` of an Optional type with no initial value starts nil)
|
|
151
|
+
var nilInit: Bool { initv == nil && !isLet && { if case .opt = t { return true }; return false }() }
|
|
152
|
+
var hasInit: Bool { initv != nil || nilInit }
|
|
153
|
+
}
|
|
154
|
+
// A method: its key (the request's name), its base name, labels, the declaration.
|
|
155
|
+
struct Meth { let key: String; let base: String; let labels: [String]; let decl: DeclSyntax; let file: String; let isStatic: Bool; let priv: Bool }
|
|
156
|
+
|
|
157
|
+
final class Reader {
|
|
158
|
+
let root: String
|
|
159
|
+
var files: [SrcFile] = []
|
|
160
|
+
var types: [String: [Ty]] = [:]
|
|
161
|
+
var allTypes: [Ty] = []
|
|
162
|
+
var aliases: [String: TT] = [:]
|
|
163
|
+
var consts: [String: (J, TT)] = [:]
|
|
164
|
+
var free: [String: (String, FunctionDeclSyntax)] = [:]
|
|
165
|
+
var recs: [(String, J)] = []
|
|
166
|
+
var recSeen: Set<String> = []
|
|
167
|
+
var funcs: [(String, J)] = []
|
|
168
|
+
var funcSeen: Set<String> = []
|
|
169
|
+
var enumsOut: [(String, J)] = []
|
|
170
|
+
var ctorArity: Int?
|
|
171
|
+
var ctorSig: String?
|
|
172
|
+
// per function
|
|
173
|
+
var file = ""
|
|
174
|
+
var conv: SourceLocationConverter?
|
|
175
|
+
var tmp = 0
|
|
176
|
+
var scopes: [[String: TT]] = []
|
|
177
|
+
var selfTy: Ty?
|
|
178
|
+
var inActor = false
|
|
179
|
+
var retT: TT = .tup([])
|
|
180
|
+
|
|
181
|
+
init(root: String) { self.root = root }
|
|
182
|
+
|
|
183
|
+
func at(_ n: some SyntaxProtocol) -> String {
|
|
184
|
+
guard let c = conv else { return "\(file):1:1" }
|
|
185
|
+
let l = n.startLocation(converter: c, afterLeadingTrivia: true)
|
|
186
|
+
return "\(file):\(l.line):\(l.column)"
|
|
187
|
+
}
|
|
188
|
+
func end(_ n: some SyntaxProtocol) -> String {
|
|
189
|
+
guard let c = conv else { return "1:1" }
|
|
190
|
+
let l = n.endLocation(converter: c, afterTrailingTrivia: false)
|
|
191
|
+
return "\(l.line):\(l.column)"
|
|
192
|
+
}
|
|
193
|
+
func with<T>(file f: String, _ body: () -> T) -> T {
|
|
194
|
+
let saved = (file, conv)
|
|
195
|
+
file = f; conv = files.first { $0.rel == f }?.conv
|
|
196
|
+
defer { (file, conv) = saved }
|
|
197
|
+
return body()
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// --- the index: every type of the files read (nested ones too), extensions merged, constants, free functions ----
|
|
201
|
+
func load(_ paths: [String]) {
|
|
202
|
+
for p in paths {
|
|
203
|
+
guard let src = try? String(contentsOfFile: p, encoding: .utf8) else { continue }
|
|
204
|
+
let parsed = Parser.parse(source: src)
|
|
205
|
+
let folded = OperatorTable.standardOperators.foldAll(parsed) { _ in }.as(SourceFileSyntax.self) ?? parsed
|
|
206
|
+
let rel = p.hasPrefix(root + "/") ? String(p.dropFirst(root.count + 1)) : p
|
|
207
|
+
files.append(SrcFile(rel: rel, tree: folded, conv: SourceLocationConverter(fileName: rel, tree: folded)))
|
|
208
|
+
}
|
|
209
|
+
for f in files { with(file: f.rel) { for item in f.tree.statements { if case .decl(let d) = item.item { declare(d, outer: nil) } } } }
|
|
210
|
+
for f in files { with(file: f.rel) { for item in f.tree.statements { if case .decl(let d) = item.item { extend(d) } } } }
|
|
211
|
+
for f in files { with(file: f.rel) { for item in f.tree.statements { if case .decl(let d) = item.item { constant(d, owner: nil) } } } }
|
|
212
|
+
for t in allTypes { for (mf, d) in t.members { with(file: mf) { constant(d, owner: t) } } }
|
|
213
|
+
}
|
|
214
|
+
func line(_ n: some SyntaxProtocol) -> Int { conv.map { n.startLocation(converter: $0, afterLeadingTrivia: true).line } ?? 1 }
|
|
215
|
+
func isPrivate(_ mods: DeclModifierListSyntax) -> Bool { mods.contains { ["private", "fileprivate"].contains($0.name.text) } }
|
|
216
|
+
func declare(_ d: DeclSyntax, outer: Ty?) {
|
|
217
|
+
var made: Ty?
|
|
218
|
+
let mk = { (name: String, kind: String, mods: DeclModifierListSyntax, gen: Bool, inh: InheritanceClauseSyntax?, members: MemberBlockSyntax) in
|
|
219
|
+
let t = Ty(name: name, qual: outer.map { "\($0.qual).\(name)" } ?? name, kind: kind, file: self.file, line: self.line(d))
|
|
220
|
+
t.generic = gen; t.outer = outer; t.priv = self.isPrivate(mods)
|
|
221
|
+
t.inherits = inh?.inheritedTypes.map { $0.type.trimmedDescription } ?? []
|
|
222
|
+
for m in members.members { t.members.append((self.file, m.decl)) }
|
|
223
|
+
self.types[name, default: []].append(t); self.allTypes.append(t)
|
|
224
|
+
made = t
|
|
225
|
+
}
|
|
226
|
+
if let c = d.as(ClassDeclSyntax.self) { mk(c.name.text, "class", c.modifiers, c.genericParameterClause != nil, c.inheritanceClause, c.memberBlock) }
|
|
227
|
+
else if let s = d.as(StructDeclSyntax.self) { mk(s.name.text, "struct", s.modifiers, s.genericParameterClause != nil, s.inheritanceClause, s.memberBlock) }
|
|
228
|
+
else if let a = d.as(ActorDeclSyntax.self) { mk(a.name.text, "actor", a.modifiers, a.genericParameterClause != nil, a.inheritanceClause, a.memberBlock) }
|
|
229
|
+
else if let e = d.as(EnumDeclSyntax.self) { mk(e.name.text, "enum", e.modifiers, e.genericParameterClause != nil, e.inheritanceClause, e.memberBlock) }
|
|
230
|
+
else if let p = d.as(ProtocolDeclSyntax.self) { mk(p.name.text, "protocol", p.modifiers, p.primaryAssociatedTypeClause != nil, p.inheritanceClause, p.memberBlock) }
|
|
231
|
+
else if let ta = d.as(TypeAliasDeclSyntax.self) { aliases[ta.name.text] = parseType(ta.initializer.value.trimmedDescription) }
|
|
232
|
+
else if let f = d.as(FunctionDeclSyntax.self), outer == nil { free[f.name.text] = (file, f) }
|
|
233
|
+
guard let t = made else { return }
|
|
234
|
+
for (_, m) in t.members { declare(m, outer: t) }
|
|
235
|
+
}
|
|
236
|
+
func extend(_ d: DeclSyntax) {
|
|
237
|
+
guard let e = d.as(ExtensionDeclSyntax.self) else { return }
|
|
238
|
+
let name = e.extendedType.trimmedDescription.split(separator: ".").last.map(String.init) ?? ""
|
|
239
|
+
guard let t = types[name]?.first, e.genericWhereClause == nil else { return }
|
|
240
|
+
for m in e.memberBlock.members { t.members.append((file, m.decl)); declare(m.decl, outer: t) }
|
|
241
|
+
t.inherits += e.inheritanceClause?.inheritedTypes.map { $0.type.trimmedDescription } ?? []
|
|
242
|
+
}
|
|
243
|
+
// A constant: a `let` (static, or at the file's top) whose value is a literal integer, boolean or string (or a fixed
|
|
244
|
+
// width's max or min, or arithmetic of those).
|
|
245
|
+
func constant(_ d: DeclSyntax, owner: Ty?) {
|
|
246
|
+
if let ec = d.as(EnumCaseDeclSyntax.self), let t = owner, t.kind == "enum" {
|
|
247
|
+
for el in ec.elements {
|
|
248
|
+
let params = el.parameterClause?.parameters.map { (label: $0.firstName?.text, t: parseType($0.type.trimmedDescription)) } ?? []
|
|
249
|
+
var raw: J = .null
|
|
250
|
+
if let rv = el.rawValue?.value { raw = constValue(rv)?.0 ?? .null }
|
|
251
|
+
t.cases.append(Case(name: el.name.text, params: params, raw: raw))
|
|
252
|
+
}
|
|
253
|
+
return
|
|
254
|
+
}
|
|
255
|
+
if let e = d.as(EnumDeclSyntax.self), let t = types[e.name.text]?.first(where: { $0.file == file }) ?? types[e.name.text]?.first {
|
|
256
|
+
if let first = e.inheritanceClause?.inheritedTypes.first { let r = parseType(first.type.trimmedDescription); if case .n(let n, _) = r, INTS[n] != nil || n == "String" { t.rawType = r } }
|
|
257
|
+
}
|
|
258
|
+
guard let vd = d.as(VariableDeclSyntax.self), vd.bindingSpecifier.text == "let" else { return }
|
|
259
|
+
let isStatic = vd.modifiers.contains { $0.name.text == "static" || $0.name.text == "class" }
|
|
260
|
+
if owner != nil && !isStatic { return }
|
|
261
|
+
for b in vd.bindings {
|
|
262
|
+
guard let id = b.pattern.as(IdentifierPatternSyntax.self), let iv = b.initializer?.value, b.accessorBlock == nil else { continue }
|
|
263
|
+
guard var (val, t) = constValue(iv) else { continue }
|
|
264
|
+
if let ann = b.typeAnnotation?.type { t = parseType(ann.trimmedDescription) }
|
|
265
|
+
if case .n(let n, _) = t, let (bits, signed) = INTS[n] { val["ty"] = ["k": "int", "bits": .i(bits), "signed": .b(signed), "sw": .s(n)] }
|
|
266
|
+
consts[owner.map { "\($0.name).\(id.identifier.text)" } ?? id.identifier.text] = (val, t)
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
func constValue(_ e: ExprSyntax) -> (J, TT)? {
|
|
270
|
+
if let i = e.as(IntegerLiteralExprSyntax.self), let n = intLit(i.literal.text) { return (X("int", "", [("v", .s(String(n)))]), .n("Int", [])) }
|
|
271
|
+
if let b = e.as(BooleanLiteralExprSyntax.self) { return (X("bool", "", [("v", .b(b.literal.text == "true"))]), .n("Bool", [])) }
|
|
272
|
+
if let s = e.as(StringLiteralExprSyntax.self), s.segments.count == 1, case .stringSegment(let seg) = s.segments.first! { return (X("str", "", [("v", .s(seg.content.text))]), .n("String", [])) }
|
|
273
|
+
if let p = e.as(PrefixOperatorExprSyntax.self), p.operator.text == "-", let (x, t) = constValue(p.expression), let n = Int(x["v"].str ?? "") { return (X("int", "", [("v", .s(String(-n)))]), t) }
|
|
274
|
+
if let m = e.as(MemberAccessExprSyntax.self), let base = m.base?.trimmedDescription, let (bits, signed) = INTS[base] {
|
|
275
|
+
let n = m.declName.baseName.text
|
|
276
|
+
let v: Int? = n == "max" ? (bits == 64 ? (signed ? Int.max : nil) : (signed ? (1 << (bits - 1)) - 1 : (1 << bits) - 1)) : n == "min" ? (signed ? (bits == 64 ? Int.min : -(1 << (bits - 1))) : 0) : nil
|
|
277
|
+
if let v { return (X("int", "", [("v", .s(String(v)))]), .n(base, [])) }
|
|
278
|
+
}
|
|
279
|
+
if let c = e.as(FunctionCallExprSyntax.self), let callee = c.calledExpression.as(DeclReferenceExprSyntax.self), INTS[callee.baseName.text] != nil, c.arguments.count == 1, c.arguments.first!.label == nil, let (x, _) = constValue(c.arguments.first!.expression) { return (x, .n(callee.baseName.text, [])) }
|
|
280
|
+
if let inf = e.as(InfixOperatorExprSyntax.self), let op = inf.operator.as(BinaryOperatorExprSyntax.self)?.operator.text, let (a, ta) = constValue(inf.leftOperand), let (b, _) = constValue(inf.rightOperand), let x = Int(a["v"].str ?? ""), let y = Int(b["v"].str ?? "") {
|
|
281
|
+
let r: Int? = op == "+" ? x &+ y : op == "-" ? x &- y : op == "*" ? x &* y : op == "<<" && y < 62 ? x << y : op == "/" && y != 0 ? x / y : nil
|
|
282
|
+
if let r { return (X("int", "", [("v", .s(String(r)))]), ta) }
|
|
283
|
+
}
|
|
284
|
+
if let t = e.as(TupleExprSyntax.self), t.elements.count == 1 { return constValue(t.elements.first!.expression) }
|
|
285
|
+
if let r = e.as(DeclReferenceExprSyntax.self), let c = consts[r.baseName.text] { return c }
|
|
286
|
+
return nil
|
|
287
|
+
}
|
|
288
|
+
func intLit(_ s: String) -> Int? {
|
|
289
|
+
let t = s.replacingOccurrences(of: "_", with: "")
|
|
290
|
+
if t.hasPrefix("0x") { return Int(t.dropFirst(2), radix: 16) }
|
|
291
|
+
if t.hasPrefix("0b") { return Int(t.dropFirst(2), radix: 2) }
|
|
292
|
+
if t.hasPrefix("0o") { return Int(t.dropFirst(2), radix: 8) }
|
|
293
|
+
return Int(t)
|
|
294
|
+
}
|
|
295
|
+
func ty(named n: String, from: Ty? = nil) -> Ty? {
|
|
296
|
+
let last = n.split(separator: ".").last.map(String.init) ?? n
|
|
297
|
+
guard let cands = types[last], !cands.isEmpty else { return nil }
|
|
298
|
+
if cands.count == 1 { return cands[0] }
|
|
299
|
+
if let q = cands.first(where: { $0.qual == n || $0.qual.hasSuffix(".\(n)") }) { return q }
|
|
300
|
+
var o = from
|
|
301
|
+
while let x = o { if let c = cands.first(where: { $0.outer === x }) { return c }; o = x.outer }
|
|
302
|
+
return cands.first { $0.outer == nil } ?? cands[0]
|
|
303
|
+
}
|
|
304
|
+
func resolve(_ t: TT) -> TT { if case .n(let n, let a) = t, a.isEmpty, let x = aliases[n], x != t { return resolve(x) }; return t }
|
|
305
|
+
|
|
306
|
+
// --- the IR's types ---------------------------------------------------------------------------------------------------
|
|
307
|
+
func stype(_ t0: TT) -> J {
|
|
308
|
+
let t = resolve(t0)
|
|
309
|
+
switch t {
|
|
310
|
+
case .opt(let x): return ["k": "opt", "of": stype(x)]
|
|
311
|
+
case .dict(let a, let b): return ["k": "map", "key": stype(a), "val": stype(b)]
|
|
312
|
+
case .arr: return ["k": "opaque", "why": .s("\(swiftText(t)), an Array (lists are outside the Swift subset)")]
|
|
313
|
+
case .tup, .fn, .bad: return ["k": "opaque", "why": .s("\(swiftText(t)), a type outside the subset")]
|
|
314
|
+
case .n(let n, let args):
|
|
315
|
+
if let (bits, signed) = INTS[n] { return ["k": "int", "bits": .i(bits), "signed": .b(signed), "sw": .s(n)] }
|
|
316
|
+
if n == "Bool" { return ["k": "bool"] }
|
|
317
|
+
if n == "String" || n == "Substring" || n == "Character" { return ["k": "str"] }
|
|
318
|
+
if n == "Double" || n == "Float" || n == "CGFloat" || n == "Float80" { return ["k": "opaque", "why": .s("\(n), a float (a binary fraction that rounds; the subset reads integers)")] }
|
|
319
|
+
if n == "Void" { return ["k": "none"] }
|
|
320
|
+
if n == "Self", let s = selfTy { return named(s) }
|
|
321
|
+
if let x = ty(named: n, from: selfTy), args.isEmpty { return named(x) }
|
|
322
|
+
return ["k": "opaque", "why": .s("\(swiftText(t)), a type of other code")]
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
func named(_ x: Ty) -> J {
|
|
326
|
+
switch x.kind {
|
|
327
|
+
case "enum":
|
|
328
|
+
if x.cases.contains(where: { !$0.params.isEmpty }) { return ["k": "opaque", "why": .s("\(x.qual), an enum with associated values")] }
|
|
329
|
+
enumOut(x)
|
|
330
|
+
return ["k": "choice", "values": .a(x.cases.map { .s($0.name) }), "discs": .a(discs(x).map { .i($0) }), "enum": .s(x.qual)]
|
|
331
|
+
case "protocol": rec(x); return ["k": "rec", "name": .s(x.qual)]
|
|
332
|
+
default:
|
|
333
|
+
if x.generic { return ["k": "opaque", "why": .s("\(x.qual), a generic type")] }
|
|
334
|
+
rec(x); return ["k": "rec", "name": .s(x.qual)]
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
func discs(_ x: Ty) -> [Int] {
|
|
338
|
+
var next = 0
|
|
339
|
+
return x.cases.map { c in
|
|
340
|
+
if case .n(let rn, _)? = x.rawType, INTS[rn] != nil, let r = Int(c.raw["v"].str ?? "") { next = r }
|
|
341
|
+
defer { next += 1 }
|
|
342
|
+
return next
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
func enumOut(_ x: Ty) {
|
|
346
|
+
if enumsOut.contains(where: { $0.0 == x.qual }) { return }
|
|
347
|
+
enumsOut.append((x.qual, ["values": .a(x.cases.map { .s($0.name) }), "discs": .a(discs(x).map { .i($0) }), "data": false]))
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// --- a type's members: stored properties, methods (keys unique in the type), computed properties ---------------------
|
|
351
|
+
func props(_ t: Ty) -> [Prop] {
|
|
352
|
+
var out: [Prop] = []
|
|
353
|
+
for (mf, d) in t.members {
|
|
354
|
+
guard let vd = d.as(VariableDeclSyntax.self), !vd.modifiers.contains(where: { ["static", "class"].contains($0.name.text) }) else { continue }
|
|
355
|
+
for b in vd.bindings {
|
|
356
|
+
guard let id = b.pattern.as(IdentifierPatternSyntax.self) else { continue }
|
|
357
|
+
var observers = false
|
|
358
|
+
if let ab = b.accessorBlock {
|
|
359
|
+
guard case .accessors(let acc) = ab.accessors, acc.allSatisfy({ ["willSet", "didSet"].contains($0.accessorSpecifier.text) }) else { continue }
|
|
360
|
+
observers = true
|
|
361
|
+
}
|
|
362
|
+
let tt: TT = b.typeAnnotation.map { parseType($0.type.trimmedDescription) } ?? b.initializer.flatMap { ini in with(file: mf) { literalType(ini.value) } } ?? .bad("no declared type")
|
|
363
|
+
let kw = with(file: mf) { at(vd.bindingSpecifier) }
|
|
364
|
+
out.append(Prop(name: id.identifier.text, t: tt, ttext: b.typeAnnotation?.type.trimmedDescription ?? swiftText(tt), initv: b.initializer?.value, isLet: vd.bindingSpecifier.text == "let", kw: kw, observers: observers, priv: isPrivate(vd.modifiers)))
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
return out
|
|
368
|
+
}
|
|
369
|
+
// The type of an initializer the declaration doesn't annotate: a literal's, a fixed width's conversion, a type's
|
|
370
|
+
// member or init (Swift infers no more than this from a property's initializer without its context).
|
|
371
|
+
func literalType(_ e: ExprSyntax) -> TT? {
|
|
372
|
+
if e.is(IntegerLiteralExprSyntax.self) { return .n("Int", []) }
|
|
373
|
+
if e.is(BooleanLiteralExprSyntax.self) { return .n("Bool", []) }
|
|
374
|
+
if e.is(StringLiteralExprSyntax.self) { return .n("String", []) }
|
|
375
|
+
if let c = e.as(FunctionCallExprSyntax.self), let r = c.calledExpression.as(DeclReferenceExprSyntax.self), r.baseName.text.first?.isUppercase == true { return .n(r.baseName.text, []) }
|
|
376
|
+
if let m = e.as(MemberAccessExprSyntax.self), let b = m.base?.trimmedDescription, b.first?.isUppercase == true { if INTS[b] != nil { return .n(b, []) }; if let x = ty(named: b), x.kind == "enum" { return .n(x.qual, []) } }
|
|
377
|
+
if let p = e.as(PrefixOperatorExprSyntax.self), p.operator.text == "-" { return literalType(p.expression) }
|
|
378
|
+
return nil
|
|
379
|
+
}
|
|
380
|
+
func methods(_ t: Ty) -> [Meth] {
|
|
381
|
+
var raw: [(String, [String], DeclSyntax, String, Bool, Bool)] = []
|
|
382
|
+
for (mf, d) in t.members {
|
|
383
|
+
if let f = d.as(FunctionDeclSyntax.self) {
|
|
384
|
+
let labels = f.signature.parameterClause.parameters.map { $0.firstName.text }
|
|
385
|
+
raw.append((f.name.text, labels, d, mf, f.modifiers.contains { ["static", "class"].contains($0.name.text) }, isPrivate(f.modifiers)))
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
var out: [Meth] = []
|
|
389
|
+
for (base, labels, d, mf, st, pv) in raw {
|
|
390
|
+
let over = raw.filter { $0.0 == base }.count > 1
|
|
391
|
+
var key = over ? ([base] + labels.map { $0 == "_" ? "" : $0 }).joined(separator: "_") : base
|
|
392
|
+
if st { key = "_static_\(key)" } else if pv { key = "_\(key)" }
|
|
393
|
+
out.append(Meth(key: key, base: base, labels: labels, decl: d, file: mf, isStatic: st, priv: pv))
|
|
394
|
+
}
|
|
395
|
+
return out
|
|
396
|
+
}
|
|
397
|
+
func computed(_ t: Ty) -> [(String, TT, CodeBlockItemListSyntax?, ExprSyntax?, String, Bool)] {
|
|
398
|
+
var out: [(String, TT, CodeBlockItemListSyntax?, ExprSyntax?, String, Bool)] = []
|
|
399
|
+
for (mf, d) in t.members {
|
|
400
|
+
guard let vd = d.as(VariableDeclSyntax.self), !vd.modifiers.contains(where: { $0.name.text == "static" }) else { continue }
|
|
401
|
+
for b in vd.bindings {
|
|
402
|
+
guard let id = b.pattern.as(IdentifierPatternSyntax.self), let ab = b.accessorBlock, let ann = b.typeAnnotation?.type else { continue }
|
|
403
|
+
switch ab.accessors {
|
|
404
|
+
case .getter(let items): out.append((id.identifier.text, parseType(ann.trimmedDescription), items, nil, mf, isPrivate(vd.modifiers)))
|
|
405
|
+
case .accessors(let acc):
|
|
406
|
+
if let g = acc.first(where: { $0.accessorSpecifier.text == "get" }), let body = g.body { out.append((id.identifier.text, parseType(ann.trimmedDescription), body.statements, nil, mf, isPrivate(vd.modifiers))) }
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
return out
|
|
411
|
+
}
|
|
412
|
+
func isComputed(_ t: Ty, _ n: String) -> Bool { computed(t).contains { $0.0 == n } }
|
|
413
|
+
func isStored(_ t: Ty, _ n: String) -> Bool { props(t).contains { $0.name == n } }
|
|
414
|
+
func methodKey(_ t: Ty, _ base: String, _ labels: [String]) -> Meth? {
|
|
415
|
+
let ms = methods(t).filter { $0.base == base }
|
|
416
|
+
if ms.count <= 1 { return ms.first }
|
|
417
|
+
return ms.first { $0.labels.map { $0 == "_" ? nil : $0 } == labels.map { $0 == "_" ? nil : $0 } } ?? ms.first { $0.labels.count == labels.count }
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// --- a record: the type read (its fields, its init as __init__, its methods), once -----------------------------------
|
|
421
|
+
func rec(_ t: Ty) {
|
|
422
|
+
if recSeen.contains(t.qual) { return }
|
|
423
|
+
recSeen.insert(t.qual)
|
|
424
|
+
let saved = (selfTy, inActor)
|
|
425
|
+
selfTy = t; inActor = t.kind == "actor"
|
|
426
|
+
defer { (selfTy, inActor) = saved }
|
|
427
|
+
if t.kind == "protocol" {
|
|
428
|
+
// A protocol: its requirements' declared results (an answer's type) and their text (the check's fake conforms).
|
|
429
|
+
var methodsJ: [(String, J)] = [], rets: [(String, J)] = [], reqs: [J] = []
|
|
430
|
+
var assoc = false
|
|
431
|
+
for (mf, d) in t.members {
|
|
432
|
+
if d.is(AssociatedTypeDeclSyntax.self) { assoc = true }
|
|
433
|
+
if let f = d.as(FunctionDeclSyntax.self) {
|
|
434
|
+
let n = f.name.text
|
|
435
|
+
methodsJ.append((n, .null))
|
|
436
|
+
let r = f.signature.returnClause.map { parseType($0.type.trimmedDescription) } ?? .n("Void", [])
|
|
437
|
+
rets.append((n, stype(r)))
|
|
438
|
+
reqs.append(["kind": "func", "name": .s(n), "decl": .s(with(file: mf) { f.with(\.body, nil).with(\.leadingTrivia, []).trimmedDescription }), "ret": .s(swiftText(r)),
|
|
439
|
+
"params": .a(f.signature.parameterClause.parameters.map { ["label": .s($0.firstName.text), "name": .s(($0.secondName ?? $0.firstName).text), "t": .s($0.type.trimmedDescription)] }),
|
|
440
|
+
"throws": .b(f.signature.effectSpecifiers?.trimmedDescription.contains("throws") ?? false), "async": .b(f.signature.effectSpecifiers?.trimmedDescription.contains("async") ?? false),
|
|
441
|
+
"mutating": .b(f.modifiers.contains { $0.name.text == "mutating" }), "static": .b(f.modifiers.contains { $0.name.text == "static" })])
|
|
442
|
+
}
|
|
443
|
+
if let vd = d.as(VariableDeclSyntax.self) {
|
|
444
|
+
for b in vd.bindings { if let id = b.pattern.as(IdentifierPatternSyntax.self), let ann = b.typeAnnotation?.type { reqs.append(["kind": "var", "name": .s(id.identifier.text), "ret": .s(ann.trimmedDescription), "set": .b(b.accessorBlock?.trimmedDescription.contains("set") ?? false)]) } }
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
recs.append((t.qual, ["name": .s(t.qual), "short": .s(t.name), "fields": [], "methods": .o(methodsJ), "kinds": ["protocol"], "own": false, "module": "", "p": .s("\(t.file):\(t.line):1"), "rets": .o(rets),
|
|
448
|
+
"swift": ["kind": "protocol", "qual": .s(t.qual), "reqs": .a(reqs), "assoc": .b(assoc), "inherits": .a(t.inherits.map { .s($0) })]]))
|
|
449
|
+
return
|
|
450
|
+
}
|
|
451
|
+
let ps = props(t)
|
|
452
|
+
var fields: [J] = []
|
|
453
|
+
for p in ps {
|
|
454
|
+
var st = stype(p.t)
|
|
455
|
+
if p.observers { st = ["k": "opaque", "why": .s("\(p.name): a property with observers (willSet, didSet)")] }
|
|
456
|
+
fields.append(["name": .s(p.name), "t": st])
|
|
457
|
+
}
|
|
458
|
+
var methodsJ: [(String, J)] = []
|
|
459
|
+
var sigs: [(String, J)] = []
|
|
460
|
+
// The initializer: the one there is, or the one of the arity asked for (ctor); none: the memberwise one (a struct's)
|
|
461
|
+
// or the default one (a class's whose properties all have initial values).
|
|
462
|
+
var inits: [(InitializerDeclSyntax, String)] = []
|
|
463
|
+
for (mf, d) in t.members { if let i = d.as(InitializerDeclSyntax.self), i.optionalMark == nil { inits.append((i, mf)) } }
|
|
464
|
+
let initId = "\(t.qual).__init__"
|
|
465
|
+
var ctorJ: J = .null
|
|
466
|
+
let bare = { (s: String) in s.filter { !$0.isWhitespace } }
|
|
467
|
+
let pick = ctorSig.map { sig in inits.filter { bare($0.0.signature.parameterClause.trimmedDescription) == bare(sig) } } ?? ctorArity.map { n in inits.filter { $0.0.signature.parameterClause.parameters.count == n } } ?? inits
|
|
468
|
+
if inits.isEmpty {
|
|
469
|
+
let mw = ps.filter { !$0.hasInit }
|
|
470
|
+
if t.kind != "struct" && !mw.isEmpty { funcs.append((initId, stub(initId, "__init__", t, "a class with no init whose properties have no initial values"))) }
|
|
471
|
+
else { funcs.append((initId, memberwise(t, ps, mw))) }
|
|
472
|
+
ctorJ = ["labels": .a(t.kind == "struct" ? mw.map { .s($0.name) } : []), "throws": false, "types": .a(t.kind == "struct" ? mw.map { .s(swiftText($0.t)) } : [])]
|
|
473
|
+
methodsJ.append(("__init__", .s(initId)))
|
|
474
|
+
} else if pick.count != 1 {
|
|
475
|
+
funcs.append((initId, stub(initId, "__init__", t, pick.isEmpty ? "no init of the arity or parameters asked for (ctor)" : "a type with \(pick.count) inits (name one by its arity or its parameters: ctor, e.g. \"(limit: Int)\")")))
|
|
476
|
+
methodsJ.append(("__init__", .s(initId)))
|
|
477
|
+
} else {
|
|
478
|
+
let (i, mf) = pick[0]
|
|
479
|
+
funcs.append((initId, with(file: mf) { initFunc(i, t, ps, initId) }))
|
|
480
|
+
methodsJ.append(("__init__", .s(initId)))
|
|
481
|
+
for (o, of) in inits where o != i {
|
|
482
|
+
let labels = o.signature.parameterClause.parameters.map { $0.firstName.text }
|
|
483
|
+
let oid = "\(t.qual).__init__/\(labels.joined(separator: ":"))"
|
|
484
|
+
funcs.append((oid, with(file: of) { initFunc(o, t, ps, oid) }))
|
|
485
|
+
methodsJ.append(("__init__/\(labels.joined(separator: ":"))", .s(oid)))
|
|
486
|
+
}
|
|
487
|
+
ctorJ = ["labels": .a(i.signature.parameterClause.parameters.map { .s($0.firstName.text) }), "throws": .b(i.signature.effectSpecifiers?.trimmedDescription.contains("throws") ?? false),
|
|
488
|
+
"types": .a(i.signature.parameterClause.parameters.map { .s($0.type.trimmedDescription) })]
|
|
489
|
+
}
|
|
490
|
+
for m in methods(t) {
|
|
491
|
+
guard let f = m.decl.as(FunctionDeclSyntax.self) else { continue }
|
|
492
|
+
let fid = "\(t.qual).\(m.key)"
|
|
493
|
+
methodsJ.append((m.key, .s(fid)))
|
|
494
|
+
funcs.append((fid, with(file: m.file) { function(f, t, fid, m.key, m.isStatic) }))
|
|
495
|
+
sigs.append((m.key, ["name": .s(m.base), "labels": .a(m.labels.map { .s($0) }), "static": .b(m.isStatic), "mutating": .b(f.modifiers.contains { $0.name.text == "mutating" }),
|
|
496
|
+
"throws": .b(f.signature.effectSpecifiers?.trimmedDescription.contains("throws") ?? false), "async": .b(f.signature.effectSpecifiers?.trimmedDescription.contains("async") ?? false),
|
|
497
|
+
"types": .a(f.signature.parameterClause.parameters.map { .s($0.type.trimmedDescription) }), "ret": .s(f.signature.returnClause.map { $0.type.trimmedDescription } ?? "Void")]))
|
|
498
|
+
}
|
|
499
|
+
for (n, tt, items, _, mf, _) in computed(t) {
|
|
500
|
+
let fid = "\(t.qual)._get_\(n)"
|
|
501
|
+
methodsJ.append(("_get_\(n)", .s(fid)))
|
|
502
|
+
funcs.append((fid, with(file: mf) { getter(n, tt, items, t, fid) }))
|
|
503
|
+
}
|
|
504
|
+
var kinds: [J] = []
|
|
505
|
+
if t.kind == "struct" { kinds.append("value") }
|
|
506
|
+
if t.generic { kinds.append(.s("generic:\(t.name)")) }
|
|
507
|
+
let own = t.inherits.compactMap { ty(named: $0, from: t) }.filter { $0.kind == "class" }
|
|
508
|
+
var inits0: J = .null
|
|
509
|
+
if !own.isEmpty { inits0 = .s("a subclass of \(own[0].qual) (the subset reads a class with no superclass of the code's own)") }
|
|
510
|
+
recs.append((t.qual, ["name": .s(t.qual), "short": .s(t.name), "fields": .a(fields), "methods": .o(methodsJ), "kinds": .a(kinds), "own": true, "module": "", "p": .s("\(t.file):\(t.line):1"),
|
|
511
|
+
"swift": ["kind": .s(t.kind), "qual": .s(t.qual), "file": .s(t.file), "priv": .b(t.priv), "ctor": ctorJ, "sigs": .o(sigs), "refused": inits0,
|
|
512
|
+
"props": .a(ps.map { ["name": .s($0.name), "t": .s($0.ttext), "let": .b($0.isLet), "kw": .s($0.kw), "init": .b($0.hasInit)] })]]))
|
|
513
|
+
if !inits0.isNull { funcs.removeAll { $0.0 == initId }; funcs.append((initId, stub(initId, "__init__", t, inits0.str!))) }
|
|
514
|
+
}
|
|
515
|
+
func stub(_ id: String, _ name: String, _ t: Ty, _ why: String) -> J {
|
|
516
|
+
let p = "\(t.file):\(t.line):1"
|
|
517
|
+
return ["id": .s(id), "name": .s(name), "cls": .s(t.qual), "p": .s(p), "span": [.s(t.file), .i(t.line), .i(t.line)], "params": [["name": "self", "t": ["k": "any"], "self": true]], "ret": ["k": "none"], "body": [sno(p, why)], "decorators": []]
|
|
518
|
+
}
|
|
519
|
+
// The properties' initial values, in their order (what every init of the type runs first).
|
|
520
|
+
func propInits(_ t: Ty, _ ps: [Prop]) -> [J] {
|
|
521
|
+
var out: [J] = []
|
|
522
|
+
for p in ps {
|
|
523
|
+
if p.nilInit { let at0 = "\(t.file):\(t.line):1"; out.append(S("set", at0, [("to", X("get", at0, [("x", v("self", at0)), ("f", .s(p.name)), ("text", .s("self.\(p.name)"))])), ("x", X("none", at0))])); continue }
|
|
524
|
+
guard let iv = p.initv else { continue }
|
|
525
|
+
let mf = t.members.first { m in m.decl.as(VariableDeclSyntax.self)?.bindings.contains { $0.pattern.as(IdentifierPatternSyntax.self)?.identifier.text == p.name } ?? false }?.file ?? t.file
|
|
526
|
+
with(file: mf) {
|
|
527
|
+
let (pre, x) = expr(iv, expect: p.t)
|
|
528
|
+
out += pre
|
|
529
|
+
out.append(S("set", at(iv), [("to", X("get", at(iv), [("x", v("self", at(iv))), ("f", .s(p.name)), ("text", .s("self.\(p.name)"))])), ("x", x)]))
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
return out
|
|
533
|
+
}
|
|
534
|
+
func memberwise(_ t: Ty, _ ps: [Prop], _ mw: [Prop]) -> J {
|
|
535
|
+
let p = "\(t.file):\(t.line):1"
|
|
536
|
+
let saved = scopes
|
|
537
|
+
defer { scopes = saved }
|
|
538
|
+
scopes = [Dictionary(uniqueKeysWithValues: mw.map { ($0.name, $0.t) })]
|
|
539
|
+
var body = with(file: t.file) { propInits(t, ps) }
|
|
540
|
+
for m in mw { body.append(S("set", p, [("to", X("get", p, [("x", v("self", p)), ("f", .s(m.name)), ("text", .s("self.\(m.name)"))])), ("x", v(m.name, p))])) }
|
|
541
|
+
return ["id": .s("\(t.qual).__init__"), "name": "__init__", "cls": .s(t.qual), "p": .s(p), "span": [.s(t.file), .i(t.line), .i(t.line)],
|
|
542
|
+
"params": .a([["name": "self", "t": ["k": "any"], "self": true]] + mw.map { ["name": .s($0.name), "t": stype($0.t)] }), "ret": ["k": "none"], "body": .a(body), "decorators": []]
|
|
543
|
+
}
|
|
544
|
+
func params(_ ps: FunctionParameterListSyntax) -> ([J], [String: TT], J?) {
|
|
545
|
+
var out: [J] = [["name": "self", "t": ["k": "any"], "self": true]]
|
|
546
|
+
var names: [String: TT] = [:]
|
|
547
|
+
for (i, pa) in ps.enumerated() {
|
|
548
|
+
let n = (pa.secondName ?? pa.firstName).text == "_" ? "_arg\(i)" : (pa.secondName ?? pa.firstName).text
|
|
549
|
+
let tt = parseType(pa.type.trimmedDescription)
|
|
550
|
+
names[n] = tt
|
|
551
|
+
if pa.type.trimmedDescription.hasPrefix("inout ") { return (out, names, sno(at(pa), "\(pa.trimmedDescription): an inout parameter")) }
|
|
552
|
+
if pa.ellipsis != nil { return (out, names, sno(at(pa), "\(pa.trimmedDescription): a variadic parameter")) }
|
|
553
|
+
var j: J = ["name": .s(n), "t": stype(tt)]
|
|
554
|
+
if let dv = pa.defaultValue?.value { let (pre, x) = expr(dv, expect: tt); if pre.isEmpty { j["dflt"] = x } }
|
|
555
|
+
out.append(j)
|
|
556
|
+
}
|
|
557
|
+
return (out, names, nil)
|
|
558
|
+
}
|
|
559
|
+
func initFunc(_ i: InitializerDeclSyntax, _ t: Ty, _ ps: [Prop], _ id: String) -> J {
|
|
560
|
+
tmp = 0
|
|
561
|
+
scopes = []
|
|
562
|
+
let (pj, names, bad) = params(i.signature.parameterClause.parameters)
|
|
563
|
+
scopes = [names]
|
|
564
|
+
let delegates = i.body.map { b in b.statements.contains { $0.trimmedDescription.hasPrefix("self.init(") } } ?? false
|
|
565
|
+
var body: [J] = delegates ? [] : propInits(t, ps)
|
|
566
|
+
if let bad { body.append(bad) }
|
|
567
|
+
if let b = i.body { body += block(b.statements) } else { body.append(sno(at(i), "an init with no body")) }
|
|
568
|
+
let p = at(i)
|
|
569
|
+
return ["id": .s(id), "name": "__init__", "cls": .s(t.qual), "p": .s(p), "span": [.s(file), .i(line(i)), .i(i.body.map { b in conv.map { c in b.endLocation(converter: c).line } ?? 1 } ?? 1)],
|
|
570
|
+
"params": .a(pj), "ret": ["k": "none"], "body": .a(body), "decorators": []]
|
|
571
|
+
}
|
|
572
|
+
func function(_ f: FunctionDeclSyntax, _ t: Ty?, _ id: String, _ key: String, _ isStatic: Bool) -> J {
|
|
573
|
+
tmp = 0
|
|
574
|
+
let (pj0, names, bad) = params(f.signature.parameterClause.parameters)
|
|
575
|
+
var pj = pj0
|
|
576
|
+
if isStatic || t == nil { pj.removeFirst() }
|
|
577
|
+
scopes = [names]
|
|
578
|
+
retT = f.signature.returnClause.map { parseType($0.type.trimmedDescription) } ?? .tup([])
|
|
579
|
+
var body: [J] = []
|
|
580
|
+
if let bad { body.append(bad) }
|
|
581
|
+
if f.genericParameterClause != nil { body.append(sno(at(f), "\(f.name.text): a generic function")) }
|
|
582
|
+
if let b = f.body { body += block(b.statements) } else { body.append(sno(at(f), "\(f.name.text): no body")) }
|
|
583
|
+
let effects = f.signature.effectSpecifiers?.trimmedDescription ?? ""
|
|
584
|
+
let ret: J = f.signature.returnClause.map { stype(parseType($0.type.trimmedDescription)) } ?? ["k": "none"]
|
|
585
|
+
let endLine = f.body.map { b in conv.map { b.endLocation(converter: $0).line } ?? 1 } ?? line(f)
|
|
586
|
+
return ["id": .s(id), "name": .s(key), "cls": t.map { .s($0.qual) } ?? .null, "p": .s(at(f.name)), "span": [.s(file), .i(line(f)), .i(endLine)], "params": .a(pj), "ret": ret, "body": .a(body),
|
|
587
|
+
"async": .b(effects.contains("async")), "static": .b(isStatic || t == nil), "decorators": [], "generic": .b(f.genericParameterClause != nil)]
|
|
588
|
+
}
|
|
589
|
+
func getter(_ n: String, _ tt: TT, _ items: CodeBlockItemListSyntax?, _ t: Ty, _ id: String) -> J {
|
|
590
|
+
tmp = 0
|
|
591
|
+
scopes = [[:]]
|
|
592
|
+
retT = tt
|
|
593
|
+
var body: [J] = []
|
|
594
|
+
if let items {
|
|
595
|
+
// (a single expression is the getter's result)
|
|
596
|
+
if items.count == 1, case .expr(let e) = items.first!.item, !e.is(IfExprSyntax.self), !e.is(SwitchExprSyntax.self) { let (pre, x) = expr(e, expect: tt); body = pre + [S("ret", at(e), [("x", x)])] }
|
|
597
|
+
else { body = block(items) }
|
|
598
|
+
}
|
|
599
|
+
let p = "\(t.file):\(t.line):1"
|
|
600
|
+
return ["id": .s(id), "name": .s("_get_\(n)"), "cls": .s(t.qual), "p": .s(p), "span": [.s(file), .i(t.line), .i(t.line)], "params": [["name": "self", "t": ["k": "any"], "self": true]], "ret": stype(tt), "body": .a(body), "decorators": []]
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
// --- locals ----------------------------------------------------------------------------------------------------------
|
|
604
|
+
func local(_ n: String) -> TT?? { for s in scopes.reversed() { if let t = s[n] { return .some(t) } }; return nil }
|
|
605
|
+
func bind(_ n: String, _ t: TT?) { if scopes.isEmpty { scopes = [[:]] }; scopes[scopes.count - 1][n] = t ?? .bad("unknown") }
|
|
606
|
+
func temp() -> String { tmp += 1; let n = "$t\(tmp)"; bind(n, nil); return n }
|
|
607
|
+
func scoped<T>(_ body: () -> T) -> T { scopes.append([:]); defer { scopes.removeLast() }; return body() }
|
|
608
|
+
|
|
609
|
+
// --- statements ------------------------------------------------------------------------------------------------------
|
|
610
|
+
func block(_ items: CodeBlockItemListSyntax) -> [J] {
|
|
611
|
+
var out: [J] = []
|
|
612
|
+
for it in items {
|
|
613
|
+
switch it.item {
|
|
614
|
+
case .decl(let d): out += decl(d)
|
|
615
|
+
case .stmt(let s): out += stmt(s)
|
|
616
|
+
case .expr(let e): out += exprStmt(e)
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
return out
|
|
620
|
+
}
|
|
621
|
+
func decl(_ d: DeclSyntax) -> [J] {
|
|
622
|
+
let p = at(d)
|
|
623
|
+
guard let vd = d.as(VariableDeclSyntax.self) else { return [sno(p, "\(short(d.trimmedDescription)): a declaration in a function")] }
|
|
624
|
+
var out: [J] = []
|
|
625
|
+
for b in vd.bindings {
|
|
626
|
+
let ann = b.typeAnnotation.map { parseType($0.type.trimmedDescription) }
|
|
627
|
+
if b.accessorBlock != nil { out.append(sno(p, "a computed local")); continue }
|
|
628
|
+
if let id = b.pattern.as(IdentifierPatternSyntax.self) {
|
|
629
|
+
let n = id.identifier.text
|
|
630
|
+
guard let iv = b.initializer?.value else { bind(n, ann); continue }
|
|
631
|
+
let (pre, x0) = expr(iv, expect: ann)
|
|
632
|
+
out += pre
|
|
633
|
+
bind(n, ann ?? typeOf(iv))
|
|
634
|
+
out.append(S("set", p, [("to", v(n, p)), ("x", copied(x0, iv))]))
|
|
635
|
+
} else if let tp = b.pattern.as(TuplePatternSyntax.self), let iv = b.initializer?.value {
|
|
636
|
+
let (pre, x0) = expr(iv, expect: nil)
|
|
637
|
+
out += pre
|
|
638
|
+
var xs: [J] = []
|
|
639
|
+
for el in tp.elements {
|
|
640
|
+
if let id = el.pattern.as(IdentifierPatternSyntax.self) { bind(id.identifier.text, nil); xs.append(v(id.identifier.text, p)) } else { xs.append(v("_", p)) }
|
|
641
|
+
}
|
|
642
|
+
out.append(S("set", p, [("to", X("tuple", p, [("xs", .a(xs))])), ("x", x0)]))
|
|
643
|
+
} else if b.pattern.is(WildcardPatternSyntax.self), let iv = b.initializer?.value { let (pre, x) = expr(iv, expect: nil); out += pre + [S("expr", p, [("x", x)])] }
|
|
644
|
+
else { out.append(sno(p, "\(short(b.trimmedDescription)): a pattern outside the subset")) }
|
|
645
|
+
}
|
|
646
|
+
return out
|
|
647
|
+
}
|
|
648
|
+
// A value read by value: a struct copied (Swift's value semantics), never one of a class (a reference).
|
|
649
|
+
func copied(_ x: J, _ e: ExprSyntax) -> J {
|
|
650
|
+
guard isPlace(x) else { return x }
|
|
651
|
+
if case .n(let n, _)? = typeOf(e), let t = ty(named: n, from: selfTy), t.kind != "struct" { return x }
|
|
652
|
+
return X("copy", x["p"].str ?? "", [("x", x)])
|
|
653
|
+
}
|
|
654
|
+
func stmt(_ s: StmtSyntax) -> [J] {
|
|
655
|
+
let p = at(s)
|
|
656
|
+
if let r = s.as(ReturnStmtSyntax.self) {
|
|
657
|
+
guard let e = r.expression else { return [S("ret", p)] }
|
|
658
|
+
let (pre, x) = expr(e, expect: retT)
|
|
659
|
+
return pre + [S("ret", p, [("x", copied(x, e))])]
|
|
660
|
+
}
|
|
661
|
+
if let t = s.as(ThrowStmtSyntax.self) { return [S("fail", p, [("why", .s("throw \(short(t.expression.trimmedDescription))"))])] }
|
|
662
|
+
if let g = s.as(GuardStmtSyntax.self) { return guardStmt(g) }
|
|
663
|
+
if let e = s.as(ExpressionStmtSyntax.self) { return exprStmt(e.expression) }
|
|
664
|
+
if s.is(BreakStmtSyntax.self) { return [S("break", p)] }
|
|
665
|
+
if s.is(ForStmtSyntax.self) || s.is(WhileStmtSyntax.self) || s.is(RepeatStmtSyntax.self) { return [sno(p, "a loop")] }
|
|
666
|
+
if s.is(DeferStmtSyntax.self) { return [sno(p, "defer")] }
|
|
667
|
+
if s.is(DoStmtSyntax.self) { return [sno(p, "do ... catch")] }
|
|
668
|
+
if s.is(FallThroughStmtSyntax.self) { return [sno(p, "fallthrough")] }
|
|
669
|
+
if s.is(ContinueStmtSyntax.self) { return [sno(p, "continue")] }
|
|
670
|
+
return [sno(p, "\(short(s.trimmedDescription)): a statement outside the subset")]
|
|
671
|
+
}
|
|
672
|
+
func exprStmt(_ e: ExprSyntax) -> [J] {
|
|
673
|
+
let p = at(e)
|
|
674
|
+
if let i = e.as(IfExprSyntax.self) { return ifStmt(i, into: nil) }
|
|
675
|
+
if let sw = e.as(SwitchExprSyntax.self) { return switchStmt(sw, into: nil) }
|
|
676
|
+
if let inf = e.as(InfixOperatorExprSyntax.self) {
|
|
677
|
+
if inf.operator.is(AssignmentExprSyntax.self) { return assign(inf.leftOperand, inf.rightOperand, p) }
|
|
678
|
+
if let op = inf.operator.as(BinaryOperatorExprSyntax.self)?.operator.text, ["+=", "-=", "*=", "/=", "%=", "&+=", "&-=", "&*="].contains(op) { return compound(inf.leftOperand, String(op.dropLast()), inf.rightOperand, p, e) }
|
|
679
|
+
}
|
|
680
|
+
if let t = e.as(TryExprSyntax.self), t.questionOrExclamationMark?.text != "?" { return exprStmt(t.expression) }
|
|
681
|
+
let (pre, x) = expr(e, expect: nil)
|
|
682
|
+
if ["unit", "none"].contains(x["e"].str ?? "") { return pre }
|
|
683
|
+
return pre + [S("expr", p, [("x", x)])]
|
|
684
|
+
}
|
|
685
|
+
func target(_ l: ExprSyntax) -> ([J], J) {
|
|
686
|
+
let p = at(l)
|
|
687
|
+
if l.is(DiscardAssignmentExprSyntax.self) { return ([], v("_", p)) }
|
|
688
|
+
if let r = l.as(DeclReferenceExprSyntax.self) {
|
|
689
|
+
let n = r.baseName.text
|
|
690
|
+
if local(n) != nil { return ([], v(n, p)) }
|
|
691
|
+
if let st = selfTy, isStored(st, n) { return ([], X("get", p, [("x", v("self", p)), ("f", .s(n)), ("text", .s(n))])) }
|
|
692
|
+
return ([], no(p, "\(n): an assignment to other than a local or a stored property"))
|
|
693
|
+
}
|
|
694
|
+
if let m = l.as(MemberAccessExprSyntax.self), let base = m.base {
|
|
695
|
+
let (pre, b) = expr(base, expect: nil)
|
|
696
|
+
if let bt = typeOf(base), case .n(let bn, _) = bt, let t = ty(named: bn, from: selfTy), isComputed(t, m.declName.baseName.text) { return (pre, no(p, "\(m.trimmedDescription): a computed property set")) }
|
|
697
|
+
return (pre, X("get", p, [("x", b), ("f", .s(m.declName.baseName.text)), ("text", .s(short(m.trimmedDescription)))]))
|
|
698
|
+
}
|
|
699
|
+
if let sc = l.as(SubscriptCallExprSyntax.self), sc.arguments.count == 1, sc.arguments.first!.label == nil {
|
|
700
|
+
let (pre, b) = expr(sc.calledExpression, expect: nil)
|
|
701
|
+
let kt: TT? = { if case .dict(let k, _)? = typeOf(sc.calledExpression) { return k }; return nil }()
|
|
702
|
+
let (kp, k) = expr(sc.arguments.first!.expression, expect: kt)
|
|
703
|
+
return (pre + kp, X("idx", p, [("x", b), ("i", k), ("text", .s(short(l.trimmedDescription)))]))
|
|
704
|
+
}
|
|
705
|
+
return ([], no(p, "\(short(l.trimmedDescription)): an assignment the subset doesn't read"))
|
|
706
|
+
}
|
|
707
|
+
func assign(_ l: ExprSyntax, _ r: ExprSyntax, _ p: String) -> [J] {
|
|
708
|
+
if l.is(DiscardAssignmentExprSyntax.self) { let (pre, x) = expr(r, expect: nil); return pre + [S("expr", p, [("x", x)])] }
|
|
709
|
+
if let t = l.as(TupleExprSyntax.self), t.elements.count > 1 { return [sno(p, "a tuple assigned")] }
|
|
710
|
+
let (tp, to) = target(l)
|
|
711
|
+
if to["e"].str == "no" { return tp + [S("expr", p, [("x", to)])] }
|
|
712
|
+
if to["e"].str == "idx" {
|
|
713
|
+
if r.is(NilLiteralExprSyntax.self) { return tp + [S("del", p, [("x", to)])] }
|
|
714
|
+
if case .opt? = typeOf(r) { return tp + [sno(p, "\(short(r.trimmedDescription)): an Optional set at a key (it sets or removes)")] }
|
|
715
|
+
}
|
|
716
|
+
let (rp, x) = expr(r, expect: typeOf(l))
|
|
717
|
+
return rp + tp + [S("set", p, [("to", to), ("x", copied(x, r))])]
|
|
718
|
+
}
|
|
719
|
+
func compound(_ l: ExprSyntax, _ op: String, _ r: ExprSyntax, _ p: String, _ e: ExprSyntax) -> [J] {
|
|
720
|
+
// d[k, default: v] op= y: the key's value (or v) op y, set at the key
|
|
721
|
+
if let sc = l.as(SubscriptCallExprSyntax.self), sc.arguments.count == 2, sc.arguments.last!.label?.text == "default" {
|
|
722
|
+
let (pre, d) = expr(sc.calledExpression, expect: nil)
|
|
723
|
+
let (kp, k) = expr(sc.arguments.first!.expression, expect: nil)
|
|
724
|
+
let (dp, dv) = expr(sc.arguments.last!.expression, expect: nil)
|
|
725
|
+
let (rp, y) = expr(r, expect: nil)
|
|
726
|
+
let cur = X("call", p, [("f", X("get", p, [("x", d), ("f", "get"), ("text", .s(short(sc.calledExpression.trimmedDescription)))])), ("args", [k, dv]), ("kw", []), ("text", .s(short(l.trimmedDescription)))])
|
|
727
|
+
return pre + kp + dp + rp + [S("set", p, [("to", X("idx", p, [("x", d), ("i", k), ("text", .s(short(l.trimmedDescription)))])), ("x", arith(op, cur, y, p, e.trimmedDescription))])]
|
|
728
|
+
}
|
|
729
|
+
let (tp, to) = target(l)
|
|
730
|
+
if to["e"].str == "no" { return tp + [S("expr", p, [("x", to)])] }
|
|
731
|
+
let (rp, y) = expr(r, expect: typeOf(l))
|
|
732
|
+
return rp + tp + [S("set", p, [("to", to), ("x", arith(op, to, y, p, e.trimmedDescription))])]
|
|
733
|
+
}
|
|
734
|
+
func arith(_ op: String, _ a: J, _ b: J, _ p: String, _ text: String) -> J {
|
|
735
|
+
let wrap = op.hasPrefix("&")
|
|
736
|
+
let o = wrap ? String(op.dropFirst()) : op
|
|
737
|
+
return X("bin", p, [("op", .s(o)), ("x", a), ("y", b), ("ovf", .s(wrap ? "wrap" : "trap")), ("div", "trunc"), ("text", .s(short(text))), ("trap", .s("a crash: \(o == "/" || o == "%" ? "division by zero or overflow" : "arithmetic overflow")")), ("crash", wrap ? .null : true)])
|
|
738
|
+
}
|
|
739
|
+
// A condition list (`if c, let x = o, case .a = e`): each one's test, with the bindings it makes visible to the next.
|
|
740
|
+
enum Cond { case test(J), bind(String, J, TT?), pat(J, [J]) }
|
|
741
|
+
func conds(_ cl: ConditionElementListSyntax) -> ([J], [Cond]) {
|
|
742
|
+
var pre: [J] = [], out: [Cond] = []
|
|
743
|
+
for c in cl {
|
|
744
|
+
let p = at(c)
|
|
745
|
+
switch c.condition {
|
|
746
|
+
case .expression(let e):
|
|
747
|
+
let (ep, x) = expr(e, expect: .n("Bool", []))
|
|
748
|
+
if !ep.isEmpty && !out.isEmpty { out.append(.test(no(p, "a condition with statements after a binding"))); continue }
|
|
749
|
+
pre += ep; out.append(.test(x))
|
|
750
|
+
case .optionalBinding(let ob):
|
|
751
|
+
guard let id = ob.pattern.as(IdentifierPatternSyntax.self) else { out.append(.test(no(p, "an optional binding's pattern"))); continue }
|
|
752
|
+
let n = id.identifier.text
|
|
753
|
+
let src: ExprSyntax = ob.initializer?.value ?? ExprSyntax(DeclReferenceExprSyntax(baseName: .identifier(n)))
|
|
754
|
+
let (ep, x) = ob.initializer == nil ? ([], local(n) != nil ? v(n, p) : expr(src, expect: nil).1) : expr(src, expect: nil)
|
|
755
|
+
if !ep.isEmpty && !out.isEmpty { out.append(.test(no(p, "a binding with statements after another"))); continue }
|
|
756
|
+
pre += ep
|
|
757
|
+
var inner: TT? = nil
|
|
758
|
+
if case .opt(let i)? = (ob.initializer == nil ? (local(n) ?? nil) : typeOf(src)) { inner = i }
|
|
759
|
+
let t = temp()
|
|
760
|
+
pre.append(S("set", p, [("to", v(t, p)), ("x", x)]))
|
|
761
|
+
out.append(.bind(n, v(t, p), inner))
|
|
762
|
+
case .matchingPattern(let mp):
|
|
763
|
+
let (ep, x) = expr(mp.initializer.value, expect: nil)
|
|
764
|
+
if !ep.isEmpty && !out.isEmpty { out.append(.test(no(p, "a pattern with statements after a binding"))); continue }
|
|
765
|
+
pre += ep
|
|
766
|
+
let t = temp()
|
|
767
|
+
pre.append(S("set", p, [("to", v(t, p)), ("x", x)]))
|
|
768
|
+
let (test, binds) = pattern(mp.pattern, v(t, p), typeOf(mp.initializer.value), p)
|
|
769
|
+
out.append(.pat(test, binds))
|
|
770
|
+
default: out.append(.test(no(p, "\(short(c.trimmedDescription)): an availability condition")))
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
return (pre, out)
|
|
774
|
+
}
|
|
775
|
+
func nest(_ cs: [Cond], _ i: Int, _ then: () -> [J], _ els: [J], _ p: String) -> [J] {
|
|
776
|
+
if i == cs.count { return then() }
|
|
777
|
+
switch cs[i] {
|
|
778
|
+
case .test(let c): return [S("if", p, [("c", c), ("then", .a(nest(cs, i + 1, then, els, p))), ("else", .a(els))])]
|
|
779
|
+
case .bind(let n, let src, let t):
|
|
780
|
+
bind(n, t)
|
|
781
|
+
return [S("if", p, [("c", X("is", p, [("x", src), ("k", "some")])), ("then", .a([S("set", p, [("to", v(n, p)), ("x", X("unwrap", p, [("x", src), ("k", "some")]))])] + nest(cs, i + 1, then, els, p))), ("else", .a(els))])]
|
|
782
|
+
case .pat(let test, let binds): return [S("if", p, [("c", test), ("then", .a(binds + nest(cs, i + 1, then, els, p))), ("else", .a(els))])]
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
// An if (a statement, or a value set into `into`): its conditions nested, the else lowered once and shared.
|
|
786
|
+
func ifStmt(_ i: IfExprSyntax, into: String?) -> [J] {
|
|
787
|
+
let p = at(i)
|
|
788
|
+
var els: [J] = []
|
|
789
|
+
switch i.elseBody {
|
|
790
|
+
case .ifExpr(let e)?: els = scoped { ifStmt(e, into: into) }
|
|
791
|
+
case .codeBlock(let b)?: els = scoped { valued(b.statements, into) }
|
|
792
|
+
case nil: els = []
|
|
793
|
+
}
|
|
794
|
+
return scoped {
|
|
795
|
+
let (pre, cs) = conds(i.conditions)
|
|
796
|
+
return pre + nest(cs, 0, { valued(i.body.statements, into) }, els, p)
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
// A block whose last expression is the value (an if or switch used as an expression).
|
|
800
|
+
func valued(_ items: CodeBlockItemListSyntax, _ into: String?) -> [J] {
|
|
801
|
+
guard let into, let last = items.last, case .expr(let e) = last.item else { return block(items) }
|
|
802
|
+
let rest = block(CodeBlockItemListSyntax(items.dropLast()))
|
|
803
|
+
if let ie = e.as(IfExprSyntax.self) { return rest + ifStmt(ie, into: into) }
|
|
804
|
+
if let se = e.as(SwitchExprSyntax.self) { return rest + switchStmt(se, into: into) }
|
|
805
|
+
let (pre, x) = expr(e, expect: nil)
|
|
806
|
+
return rest + pre + [S("set", at(e), [("to", v(into, at(e))), ("x", x)])]
|
|
807
|
+
}
|
|
808
|
+
func guardStmt(_ g: GuardStmtSyntax) -> [J] {
|
|
809
|
+
let p = at(g)
|
|
810
|
+
let els = scoped { block(g.body.statements) }
|
|
811
|
+
let (pre, cs) = conds(g.conditions)
|
|
812
|
+
var out = pre
|
|
813
|
+
for c in cs {
|
|
814
|
+
switch c {
|
|
815
|
+
case .test(let x): out.append(S("if", p, [("c", x), ("then", []), ("else", .a(els))]))
|
|
816
|
+
case .bind(let n, let src, let t):
|
|
817
|
+
out.append(S("if", p, [("c", X("is", p, [("x", src), ("k", "none")])), ("then", .a(els)), ("else", [])]))
|
|
818
|
+
bind(n, t)
|
|
819
|
+
out.append(S("set", p, [("to", v(n, p)), ("x", X("unwrap", p, [("x", src), ("k", "some")]))]))
|
|
820
|
+
case .pat(let test, let binds): out.append(S("if", p, [("c", test), ("then", []), ("else", .a(els))])); out += binds
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
return out
|
|
824
|
+
}
|
|
825
|
+
// A switch: its cases a chain of ifs in order (the last a failure: Swift's switch is exhaustive, so it is unreachable
|
|
826
|
+
// for the code's own values), inside a block a `break` leaves.
|
|
827
|
+
func switchStmt(_ sw: SwitchExprSyntax, into: String?) -> [J] {
|
|
828
|
+
let p = at(sw)
|
|
829
|
+
let (pre, x) = expr(sw.subject, expect: nil)
|
|
830
|
+
let st = typeOf(sw.subject)
|
|
831
|
+
let t = temp()
|
|
832
|
+
var out = pre + [S("set", p, [("to", v(t, p)), ("x", x)])]
|
|
833
|
+
var chain: [J] = [S("fail", p, [("why", "a switch no case takes (unreachable for the code's own values)")])]
|
|
834
|
+
for c in sw.cases.reversed() {
|
|
835
|
+
guard case .switchCase(let sc) = c else { return out + [sno(at(c), "#if in a switch")] }
|
|
836
|
+
let cp = at(sc)
|
|
837
|
+
let r: [J] = scoped {
|
|
838
|
+
switch sc.label {
|
|
839
|
+
case .default: return valued(sc.statements, into)
|
|
840
|
+
case .case(let lab):
|
|
841
|
+
var tests: [J] = []
|
|
842
|
+
var binds: [J] = []
|
|
843
|
+
var guardX: J? = nil
|
|
844
|
+
for item in lab.caseItems {
|
|
845
|
+
let (tt, bs) = pattern(item.pattern, v(t, cp), st, cp)
|
|
846
|
+
if !bs.isEmpty && lab.caseItems.count > 1 { return [sno(cp, "a case of several patterns that bind")] }
|
|
847
|
+
binds += bs; tests.append(tt)
|
|
848
|
+
if let w = item.whereClause {
|
|
849
|
+
if lab.caseItems.count > 1 { return [sno(cp, "a where clause in a case of several patterns")] }
|
|
850
|
+
let (wp, wx) = expr(w.condition, expect: .n("Bool", []))
|
|
851
|
+
if !wp.isEmpty { return [sno(cp, "a where clause with statements")] }
|
|
852
|
+
guardX = wx
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
let body = valued(sc.statements, into)
|
|
856
|
+
let test = tests.count == 1 ? tests[0] : X("or", cp, [("xs", .a(tests)), ("strict", true)])
|
|
857
|
+
if let gx = guardX { return [S("if", cp, [("c", test), ("then", .a(binds + [S("if", cp, [("c", gx), ("then", .a(body)), ("else", .a(chain))])])), ("else", .a(chain))])] }
|
|
858
|
+
if test["e"].str == "bool", case .b(true) = test["v"] { return binds + body }
|
|
859
|
+
return [S("if", cp, [("c", test), ("then", .a(binds + body)), ("else", .a(chain))])]
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
chain = r
|
|
863
|
+
}
|
|
864
|
+
out.append(S("switch", p, [("cases", [["default": true, "b": .a(chain), "p": .s(p)]])]))
|
|
865
|
+
return out
|
|
866
|
+
}
|
|
867
|
+
// A pattern against a value: its test, and the bindings it makes (set where it holds).
|
|
868
|
+
func pattern(_ pat: PatternSyntax, _ val: J, _ vt: TT?, _ p: String, binding: Bool = false) -> (J, [J]) {
|
|
869
|
+
let yes = X("bool", p, [("v", true)])
|
|
870
|
+
if pat.is(WildcardPatternSyntax.self) { return (yes, []) }
|
|
871
|
+
if let vb = pat.as(ValueBindingPatternSyntax.self) { return pattern(vb.pattern, val, vt, p, binding: true) }
|
|
872
|
+
if let id = pat.as(IdentifierPatternSyntax.self) { bind(id.identifier.text, vt); return (yes, [S("set", p, [("to", v(id.identifier.text, p)), ("x", val)])]) }
|
|
873
|
+
if let ep = pat.as(ExpressionPatternSyntax.self) { return exprPattern(ep.expression, val, vt, p, binding: binding) }
|
|
874
|
+
return (no(p, "\(short(pat.trimmedDescription)): a pattern outside the subset"), [])
|
|
875
|
+
}
|
|
876
|
+
func exprPattern(_ e: ExprSyntax, _ val: J, _ vt: TT?, _ p: String, binding: Bool) -> (J, [J]) {
|
|
877
|
+
let yes = X("bool", p, [("v", true)])
|
|
878
|
+
if e.is(DiscardAssignmentExprSyntax.self) { return (yes, []) }
|
|
879
|
+
if let pe = e.as(PatternExprSyntax.self) { return pattern(pe.pattern, val, vt, p, binding: binding) }
|
|
880
|
+
if binding, let r = e.as(DeclReferenceExprSyntax.self) { bind(r.baseName.text, vt); return (yes, [S("set", p, [("to", v(r.baseName.text, p)), ("x", val)])]) }
|
|
881
|
+
if e.is(NilLiteralExprSyntax.self) { return (X("is", p, [("x", val), ("k", "none")]), []) }
|
|
882
|
+
if let oc = e.as(OptionalChainingExprSyntax.self) {
|
|
883
|
+
var inner: TT? = nil
|
|
884
|
+
if case .opt(let i)? = vt { inner = i }
|
|
885
|
+
let (t, b) = exprPattern(oc.expression, X("unwrap", p, [("x", val), ("k", "some")]), inner, p, binding: binding)
|
|
886
|
+
return (X("and", p, [("xs", [X("is", p, [("x", val), ("k", "some")]), t]), ("strict", true)]), b)
|
|
887
|
+
}
|
|
888
|
+
// .some(p) / .none on an Optional
|
|
889
|
+
if case .opt(let inner)? = vt {
|
|
890
|
+
if let m = e.as(MemberAccessExprSyntax.self), m.base == nil, m.declName.baseName.text == "none" { return (X("is", p, [("x", val), ("k", "none")]), []) }
|
|
891
|
+
if let c = e.as(FunctionCallExprSyntax.self), let m = c.calledExpression.as(MemberAccessExprSyntax.self), m.base == nil, m.declName.baseName.text == "some", c.arguments.count == 1 {
|
|
892
|
+
let (t, b) = exprPattern(c.arguments.first!.expression, X("unwrap", p, [("x", val), ("k", "some")]), inner, p, binding: binding)
|
|
893
|
+
return (X("and", p, [("xs", [X("is", p, [("x", val), ("k", "some")]), t]), ("strict", true)]), b)
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
if let c = e.as(FunctionCallExprSyntax.self), c.calledExpression.as(MemberAccessExprSyntax.self) != nil { return (no(p, "\(short(e.trimmedDescription)): a case with associated values (an enum with data)"), []) }
|
|
897
|
+
// a range: lo...hi, lo..<hi
|
|
898
|
+
if let inf = e.as(InfixOperatorExprSyntax.self), let op = inf.operator.as(BinaryOperatorExprSyntax.self)?.operator.text, op == "..." || op == "..<" {
|
|
899
|
+
let (_, lo) = expr(inf.leftOperand, expect: vt), (_, hi) = expr(inf.rightOperand, expect: vt)
|
|
900
|
+
return (X("and", p, [("xs", [X("cmp", p, [("op", "<="), ("x", lo), ("y", val)]), X("cmp", p, [("op", .s(op == "..." ? "<=" : "<")), ("x", val), ("y", hi)])]), ("strict", true)]), [])
|
|
901
|
+
}
|
|
902
|
+
let (pre, x) = expr(e, expect: vt)
|
|
903
|
+
if !pre.isEmpty { return (no(p, "\(short(e.trimmedDescription)): a pattern with statements"), []) }
|
|
904
|
+
return (X("cmp", p, [("op", "=="), ("x", val), ("y", x), ("text", .s(short(e.trimmedDescription)))]), [])
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
// --- expressions: (statements before, the value) ------------------------------------------------------------------
|
|
908
|
+
func expr(_ e: ExprSyntax, expect: TT?) -> ([J], J) {
|
|
909
|
+
let p = at(e)
|
|
910
|
+
let t = short(e.trimmedDescription)
|
|
911
|
+
if let i = e.as(IntegerLiteralExprSyntax.self) {
|
|
912
|
+
guard let n = intLit(i.literal.text) else { return ([], no(p, "\(t): an integer literal past Int")) }
|
|
913
|
+
var x = X("int", p, [("v", .s(String(n)))])
|
|
914
|
+
if case .n(let en, _)? = expect.map(resolve), INTS[en] != nil { x["ty"] = stype(.n(en, [])) }
|
|
915
|
+
if case .opt(.n(let en, _))? = expect.map(resolve), INTS[en] != nil { x["ty"] = stype(.n(en, [])) }
|
|
916
|
+
return ([], x)
|
|
917
|
+
}
|
|
918
|
+
if let b = e.as(BooleanLiteralExprSyntax.self) { return ([], X("bool", p, [("v", .b(b.literal.text == "true"))])) }
|
|
919
|
+
if e.is(NilLiteralExprSyntax.self) { return ([], X("none", p)) }
|
|
920
|
+
if e.is(FloatLiteralExprSyntax.self) { return ([], no(p, "\(t): a float literal")) }
|
|
921
|
+
if let s = e.as(StringLiteralExprSyntax.self) { return stringLit(s, p, t) }
|
|
922
|
+
if let tu = e.as(TupleExprSyntax.self) {
|
|
923
|
+
if tu.elements.count == 1 { return expr(tu.elements.first!.expression, expect: expect) }
|
|
924
|
+
var pre: [J] = [], xs: [J] = []
|
|
925
|
+
for el in tu.elements { let (a, x) = expr(el.expression, expect: nil); pre += a; xs.append(x) }
|
|
926
|
+
return (pre, X("tuple", p, [("xs", .a(xs))]))
|
|
927
|
+
}
|
|
928
|
+
if let r = e.as(DeclReferenceExprSyntax.self) { return ([], name(r.baseName.text, p, t, expect)) }
|
|
929
|
+
if e.is(SuperExprSyntax.self) { return ([], no(p, "super")) }
|
|
930
|
+
if let m = e.as(MemberAccessExprSyntax.self) { return member(m, p, t, expect) }
|
|
931
|
+
if let c = e.as(FunctionCallExprSyntax.self) {
|
|
932
|
+
if c.trailingClosure != nil || c.arguments.contains(where: { $0.expression.is(ClosureExprSyntax.self) }) { return ([], no(p, "\(t): a closure")) }
|
|
933
|
+
var (pre, x) = call(c, p, t, expect)
|
|
934
|
+
if x["e"].str == "call" { x["end"] = .s(end(c)) }
|
|
935
|
+
return (pre, x)
|
|
936
|
+
}
|
|
937
|
+
if let sc = e.as(SubscriptCallExprSyntax.self) {
|
|
938
|
+
let (pre, b) = expr(sc.calledExpression, expect: nil)
|
|
939
|
+
let kt: TT? = { if case .dict(let k, _)? = typeOf(sc.calledExpression) { return k }; return nil }()
|
|
940
|
+
let vt: TT? = { if case .dict(_, let v)? = typeOf(sc.calledExpression) { return v }; return nil }()
|
|
941
|
+
if sc.arguments.count == 1, sc.arguments.first!.label == nil {
|
|
942
|
+
let (kp, k) = expr(sc.arguments.first!.expression, expect: kt)
|
|
943
|
+
return (pre + kp, X("call", p, [("f", X("get", p, [("x", b), ("f", "get"), ("text", .s(short(sc.calledExpression.trimmedDescription)))])), ("args", [k]), ("kw", []), ("text", .s(t))]))
|
|
944
|
+
}
|
|
945
|
+
if sc.arguments.count == 2, sc.arguments.last!.label?.text == "default" {
|
|
946
|
+
let (kp, k) = expr(sc.arguments.first!.expression, expect: kt), (dp, d) = expr(sc.arguments.last!.expression, expect: vt)
|
|
947
|
+
return (pre + kp + dp, X("call", p, [("f", X("get", p, [("x", b), ("f", "get"), ("text", .s(short(sc.calledExpression.trimmedDescription)))])), ("args", [k, d]), ("kw", []), ("text", .s(t))]))
|
|
948
|
+
}
|
|
949
|
+
return (pre, no(p, "\(t): a subscript outside the subset (a dictionary's [key] and [key, default:])"))
|
|
950
|
+
}
|
|
951
|
+
if let inf = e.as(InfixOperatorExprSyntax.self) { return infix(inf, p, t, expect) }
|
|
952
|
+
if let pr = e.as(PrefixOperatorExprSyntax.self) {
|
|
953
|
+
let op = pr.operator.text
|
|
954
|
+
if op == "!" { let (pre, x) = expr(pr.expression, expect: .n("Bool", [])); return (pre, X("not", p, [("x", x), ("strict", true), ("text", .s(t))])) }
|
|
955
|
+
if op == "-" {
|
|
956
|
+
if let i = pr.expression.as(IntegerLiteralExprSyntax.self), let n = intLit(i.literal.text) { var x = X("int", p, [("v", .s(String(-n)))]); if case .n(let en, _)? = expect, INTS[en] != nil { x["ty"] = stype(.n(en, [])) }; return ([], x) }
|
|
957
|
+
let (pre, x) = expr(pr.expression, expect: expect)
|
|
958
|
+
return (pre, arith("-", X("int", p, [("v", "0")]), x, p, t))
|
|
959
|
+
}
|
|
960
|
+
if op == "+" { return expr(pr.expression, expect: expect) }
|
|
961
|
+
return ([], no(p, "\(t): the operator \(op)"))
|
|
962
|
+
}
|
|
963
|
+
if let fu = e.as(ForceUnwrapExprSyntax.self) { let (pre, x) = expr(fu.expression, expect: expect.map { .opt($0) }); return (pre, X("expect", p, [("x", x), ("text", .s("\(t) (a crash: nil force-unwrapped)")), ("crash", true)])) }
|
|
964
|
+
if let tr = e.as(TryExprSyntax.self) {
|
|
965
|
+
if tr.questionOrExclamationMark?.text == "?" { return ([], no(p, "\(t): try? (an error made nil)")) }
|
|
966
|
+
return expr(tr.expression, expect: expect)
|
|
967
|
+
}
|
|
968
|
+
if e.is(AwaitExprSyntax.self) { return ([], no(p, "\(t): an await (a suspension point, where other calls may interleave)")) }
|
|
969
|
+
if let te = e.as(TernaryExprSyntax.self) {
|
|
970
|
+
let (cp, c) = expr(te.condition, expect: .n("Bool", []))
|
|
971
|
+
let (ap, a) = expr(te.thenExpression, expect: expect), (bp, b) = expr(te.elseExpression, expect: expect)
|
|
972
|
+
if ap.isEmpty && bp.isEmpty { return (cp, X("ite", p, [("c", c), ("a", a), ("b", b), ("text", .s(t))])) }
|
|
973
|
+
let r = temp()
|
|
974
|
+
return (cp + [S("if", p, [("c", c), ("then", .a(ap + [S("set", p, [("to", v(r, p)), ("x", a)])])), ("else", .a(bp + [S("set", p, [("to", v(r, p)), ("x", b)])]))])], v(r, p))
|
|
975
|
+
}
|
|
976
|
+
if let ie = e.as(IfExprSyntax.self) { let r = temp(); return (ifStmt(ie, into: r), v(r, p)) }
|
|
977
|
+
if let se = e.as(SwitchExprSyntax.self) { let r = temp(); return (switchStmt(se, into: r), v(r, p)) }
|
|
978
|
+
if let d = e.as(DictionaryExprSyntax.self) {
|
|
979
|
+
if case .colon = d.content { return ([], X("dict", p, [("keys", []), ("vals", []), ("text", .s(t))])) }
|
|
980
|
+
return ([], no(p, "\(t): a dictionary literal with items"))
|
|
981
|
+
}
|
|
982
|
+
if e.is(ArrayExprSyntax.self) { return ([], no(p, "\(t): an array")) }
|
|
983
|
+
if e.is(ClosureExprSyntax.self) { return ([], no(p, "\(t): a closure")) }
|
|
984
|
+
if e.is(IsExprSyntax.self) || e.is(AsExprSyntax.self) { return ([], no(p, "\(t): a dynamic type test or cast")) }
|
|
985
|
+
if e.is(OptionalChainingExprSyntax.self) { return ([], no(p, "\(t): optional chaining")) }
|
|
986
|
+
if e.is(InOutExprSyntax.self) { return ([], no(p, "\(t): an inout argument")) }
|
|
987
|
+
return ([], no(p, "\(t): an expression outside the subset"))
|
|
988
|
+
}
|
|
989
|
+
func stringLit(_ s: StringLiteralExprSyntax, _ p: String, _ t: String) -> ([J], J) {
|
|
990
|
+
var parts: [J] = [], pre: [J] = []
|
|
991
|
+
var plain = true
|
|
992
|
+
for seg in s.segments {
|
|
993
|
+
switch seg {
|
|
994
|
+
case .stringSegment(let ss): parts.append(.s(ss.content.text))
|
|
995
|
+
case .expressionSegment(let es):
|
|
996
|
+
guard es.expressions.count == 1, es.expressions.first!.label == nil else { plain = false; continue }
|
|
997
|
+
let (a, x) = expr(es.expressions.first!.expression, expect: nil)
|
|
998
|
+
pre += a
|
|
999
|
+
parts.append(["x": x, "plain": true])
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
if !plain { return (pre, X("opaque", p, [("why", .s("\(t): a formatted string"))])) }
|
|
1003
|
+
if parts.count == 1, case .s(let str) = parts[0] { return (pre, X("str", p, [("v", .s(str))])) }
|
|
1004
|
+
if parts.isEmpty { return (pre, X("str", p, [("v", "")])) }
|
|
1005
|
+
return (pre, X("fstr", p, [("parts", .a(parts)), ("text", .s(t))]))
|
|
1006
|
+
}
|
|
1007
|
+
// A name: a local, a stored property of self, a computed one (its getter called), a constant, a function.
|
|
1008
|
+
func name(_ n: String, _ p: String, _ t: String, _ expect: TT?) -> J {
|
|
1009
|
+
if n == "self" { return v("self", p) }
|
|
1010
|
+
if local(n) != nil { return v(n, p) }
|
|
1011
|
+
if let st = selfTy {
|
|
1012
|
+
if isStored(st, n) { return X("get", p, [("x", v("self", p)), ("f", .s(n)), ("text", .s(n))]) }
|
|
1013
|
+
if isComputed(st, n) { return X("call", p, [("f", X("get", p, [("x", v("self", p)), ("f", .s("_get_\(n)")), ("text", .s(n))])), ("args", []), ("kw", []), ("text", .s(n))]) }
|
|
1014
|
+
var o: Ty? = st
|
|
1015
|
+
while let x = o { if let c = consts["\(x.name).\(n)"] { var j = c.0; j["p"] = .s(p); return j }; o = x.outer }
|
|
1016
|
+
}
|
|
1017
|
+
if let c = consts[n] { var j = c.0; j["p"] = .s(p); return j }
|
|
1018
|
+
if let f = free[n] { _ = f; return X("fn", p, [("id", .s(n))]) }
|
|
1019
|
+
return X("ext", p, [("q", .s(n)), ("text", .s(t))])
|
|
1020
|
+
}
|
|
1021
|
+
func enumCase(_ en: Ty, _ c: String, _ p: String) -> J? {
|
|
1022
|
+
guard en.kind == "enum", en.cases.contains(where: { $0.name == c }) else { return nil }
|
|
1023
|
+
if en.cases.contains(where: { !$0.params.isEmpty }) { return no(p, "\(en.qual).\(c): a case of an enum with associated values") }
|
|
1024
|
+
enumOut(en)
|
|
1025
|
+
return X("variant", p, [("enum", .s(en.qual)), ("v", .s(c)), ("values", .a(en.cases.map { .s($0.name) })), ("discs", .a(discs(en).map { .i($0) }))])
|
|
1026
|
+
}
|
|
1027
|
+
func member(_ m: MemberAccessExprSyntax, _ p: String, _ t: String, _ expect: TT?) -> ([J], J) {
|
|
1028
|
+
let n = m.declName.baseName.text
|
|
1029
|
+
guard let base = m.base else {
|
|
1030
|
+
// .case: of the type the context expects (an Optional's .none), else the one own enum that has it
|
|
1031
|
+
if case .opt? = expect, n == "none" { return ([], X("none", p)) }
|
|
1032
|
+
var et = expect.map(resolve)
|
|
1033
|
+
if case .opt(let i)? = et { et = i }
|
|
1034
|
+
if case .n(let en, _)? = et, let x = ty(named: en, from: selfTy), let c = enumCase(x, n, p) { return ([], c) }
|
|
1035
|
+
if INTS[et?.name ?? ""] != nil, n == "max" || n == "min", let c = constValue(ExprSyntax(MemberAccessExprSyntax(base: ExprSyntax(DeclReferenceExprSyntax(baseName: .identifier(et!.name!))), name: .identifier(n)))) { var j = c.0; j["p"] = .s(p); return ([], j) }
|
|
1036
|
+
let owners = allTypes.filter { $0.kind == "enum" && $0.cases.contains { $0.name == n } }
|
|
1037
|
+
if owners.count == 1, let c = enumCase(owners[0], n, p) { return ([], c) }
|
|
1038
|
+
return ([], no(p, "\(t): a member of a type the context doesn't state"))
|
|
1039
|
+
}
|
|
1040
|
+
let bt = base.trimmedDescription
|
|
1041
|
+
// a type's member: a fixed width's max or min, a constant, an enum's case
|
|
1042
|
+
if bt.first?.isUppercase == true, base.is(DeclReferenceExprSyntax.self) || base.is(MemberAccessExprSyntax.self), local(bt) == nil {
|
|
1043
|
+
if let c = constValue(ExprSyntax(m)) { var j = c.0; j["p"] = .s(p); return ([], j) }
|
|
1044
|
+
let tn = bt == "Self" ? selfTy?.name ?? bt : bt
|
|
1045
|
+
if let x = ty(named: tn, from: selfTy) {
|
|
1046
|
+
if let c = enumCase(x, n, p) { return ([], c) }
|
|
1047
|
+
if let c = consts["\(x.name).\(n)"] { var j = c.0; j["p"] = .s(p); return ([], j) }
|
|
1048
|
+
return ([], no(p, "\(t): a static member"))
|
|
1049
|
+
}
|
|
1050
|
+
if INTS[bt] == nil && !["Bool", "String"].contains(bt) { return ([], X("ext", p, [("q", .s(bt + "." + n)), ("text", .s(t))])) }
|
|
1051
|
+
}
|
|
1052
|
+
let bty = typeOf(base).map(resolve)
|
|
1053
|
+
let (pre, b) = expr(base, expect: nil)
|
|
1054
|
+
if n == "rawValue", case .n(let en, _)? = bty, let x = ty(named: en, from: selfTy), x.kind == "enum" {
|
|
1055
|
+
guard case .n(let rn, _)? = x.rawType, INTS[rn] != nil else { return (pre, no(p, "\(t): a raw value that isn't an integer")) }
|
|
1056
|
+
return (pre, X("cast", p, [("x", b), ("ty", stype(.n(rn, []))), ("text", .s(t))]))
|
|
1057
|
+
}
|
|
1058
|
+
if case .n(let bn, _)? = bty, let x = ty(named: bn, from: selfTy), isComputed(x, n) {
|
|
1059
|
+
return (pre, X("call", p, [("f", X("get", p, [("x", b), ("f", .s("_get_\(n)")), ("text", .s(t))])), ("args", []), ("kw", []), ("text", .s(t))]))
|
|
1060
|
+
}
|
|
1061
|
+
if case .dict? = bty { return (pre, no(p, "\(t): a dictionary's \(n) (the subset reads [key], [key, default:], updateValue and removeValue)")) }
|
|
1062
|
+
return (pre, X("get", p, [("x", b), ("f", .s(n)), ("text", .s(t))]))
|
|
1063
|
+
}
|
|
1064
|
+
func args(_ list: LabeledExprListSyntax, _ types: [TT?] = []) -> ([J], [J]) {
|
|
1065
|
+
var pre: [J] = [], out: [J] = []
|
|
1066
|
+
for (i, a) in list.enumerated() { let (s, x) = expr(a.expression, expect: i < types.count ? types[i] : nil); pre += s; out.append(copied(x, a.expression)) }
|
|
1067
|
+
return (pre, out)
|
|
1068
|
+
}
|
|
1069
|
+
func call(_ c: FunctionCallExprSyntax, _ p: String, _ t: String, _ expect: TT?) -> ([J], J) {
|
|
1070
|
+
let labels = c.arguments.map { $0.label?.text ?? "_" }
|
|
1071
|
+
let a0 = c.arguments.first?.expression
|
|
1072
|
+
let failS = { (why: String, crash: Bool) -> J in S("fail", p, [("why", .s(why)), ("crash", crash ? true : .null)]) }
|
|
1073
|
+
if let r = c.calledExpression.as(DeclReferenceExprSyntax.self), local(r.baseName.text) == nil {
|
|
1074
|
+
let n = r.baseName.text
|
|
1075
|
+
// A fixed width made from a value: trapping where it doesn't fit, or wrapping, clamping, exactly (an Optional).
|
|
1076
|
+
if INTS[n] != nil, c.arguments.count == 1, let a0 {
|
|
1077
|
+
let (pre, x) = expr(a0, expect: nil)
|
|
1078
|
+
let ity: J = { var j = stype(.n(n, [])); j["k"] = .null; return ["bits": j["bits"], "signed": j["signed"], "name": .s(n)] }()
|
|
1079
|
+
let at0 = X("as", p, [("x", x), ("ity", ity)])
|
|
1080
|
+
let zero = X("int", p, [("v", "0"), ("ity", ity)])
|
|
1081
|
+
switch labels[0] {
|
|
1082
|
+
case "_": return (pre, X("bin", p, [("op", "+"), ("x", at0), ("y", zero), ("ovf", "trap"), ("text", .s(t)), ("trap", .s("a crash: \(n)(_:) of a value past its range")), ("crash", true)]))
|
|
1083
|
+
case "truncatingIfNeeded", "bitPattern": return (pre, X("conv", p, [("x", x), ("ity", ity), ("why", .s("\(t): a conversion of other than an integer")), ("text", .s(t))]))
|
|
1084
|
+
case "clamping": return (pre, X("bin", p, [("op", "+"), ("x", at0), ("y", zero), ("ovf", "sat"), ("text", .s(t))]))
|
|
1085
|
+
case "exactly": return (pre, X("bin", p, [("op", "+"), ("x", at0), ("y", zero), ("ovf", "checked"), ("text", .s(t))]))
|
|
1086
|
+
default: return (pre, no(p, "\(t): \(n)(\(labels[0]):)"))
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
if (n == "min" || n == "max") && c.arguments.count >= 2 {
|
|
1090
|
+
let (pre, xs) = args(c.arguments, Array(repeating: expect, count: c.arguments.count))
|
|
1091
|
+
var acc = xs[0]
|
|
1092
|
+
for x in xs.dropFirst() { acc = X("call", p, [("f", X("builtin", p, [("n", .s(n))])), ("args", [acc, x]), ("kw", []), ("text", .s(t))]) }
|
|
1093
|
+
return (pre, acc)
|
|
1094
|
+
}
|
|
1095
|
+
if n == "abs" && c.arguments.count == 1 { let (pre, xs) = args(c.arguments); return (pre, X("call", p, [("f", X("builtin", p, [("n", "abs")])), ("args", .a(xs)), ("kw", []), ("text", .s(t))])) }
|
|
1096
|
+
if ["precondition", "assert"].contains(n), let a0 {
|
|
1097
|
+
let (pre, x) = expr(a0, expect: .n("Bool", []))
|
|
1098
|
+
return (pre + [S("if", p, [("c", x), ("then", []), ("else", [failS("\(n)(\(short(a0.trimmedDescription))) (a crash)", true)])])], X("unit", p))
|
|
1099
|
+
}
|
|
1100
|
+
if ["preconditionFailure", "fatalError", "assertionFailure"].contains(n) { return ([failS("\(n)() (a crash)", true)], X("unit", p)) }
|
|
1101
|
+
if let x = ty(named: n, from: selfTy) { return construct(x, c, p, t) }
|
|
1102
|
+
if n == "Self", let x = selfTy { return construct(x, c, p, t) }
|
|
1103
|
+
// the type's own method (implicit self), or a free function of the code's own
|
|
1104
|
+
if let st = selfTy, let m = methodKey(st, n, labels) {
|
|
1105
|
+
if m.isStatic { return ownCall(X("fn", p, [("id", .s("\(st.qual).\(m.key)"))]), m, c, p, t) }
|
|
1106
|
+
return ownCall(X("get", p, [("x", v("self", p)), ("f", .s(m.key)), ("text", .s(n))]), m, c, p, t)
|
|
1107
|
+
}
|
|
1108
|
+
if let (_, f) = free[n] { return freeCall(f, c, p, t) }
|
|
1109
|
+
}
|
|
1110
|
+
if let m = c.calledExpression.as(MemberAccessExprSyntax.self) {
|
|
1111
|
+
let n = m.declName.baseName.text
|
|
1112
|
+
guard let base = m.base else {
|
|
1113
|
+
if case .opt(let i)? = expect, n == "some", let a0 { let (pre, x) = expr(a0, expect: i); return (pre, X("some", p, [("x", x)])) }
|
|
1114
|
+
return ([], no(p, "\(t): a case with associated values, or a static member the context doesn't state"))
|
|
1115
|
+
}
|
|
1116
|
+
let bt = base.trimmedDescription
|
|
1117
|
+
if bt == "self", n == "init" { let (pre, xs) = args(c.arguments); return (pre, X("call", p, [("f", X("get", p, [("x", v("self", p)), ("f", .s("__init__/\(labels.joined(separator: ":"))")), ("text", "self.init")])), ("args", .a(xs)), ("kw", []), ("text", .s(t))])) }
|
|
1118
|
+
if bt.first?.isUppercase == true, local(bt) == nil, base.is(DeclReferenceExprSyntax.self) || base.is(MemberAccessExprSyntax.self) {
|
|
1119
|
+
let tn = bt == "Self" ? selfTy?.name ?? bt : bt
|
|
1120
|
+
if let x = ty(named: tn, from: selfTy) {
|
|
1121
|
+
if n == "init" { return construct(x, c, p, t) }
|
|
1122
|
+
if let me = methodKey(x, n, labels), me.isStatic { return ownCall(X("fn", p, [("id", .s("\(x.qual).\(me.key)"))]), me, c, p, t) }
|
|
1123
|
+
return ([], no(p, "\(t): a case with associated values, or a static member outside the subset"))
|
|
1124
|
+
}
|
|
1125
|
+
// other code's static function: at the boundary
|
|
1126
|
+
let (pre, xs) = args(c.arguments)
|
|
1127
|
+
return (pre, X("call", p, [("f", X("ext", p, [("q", .s("\(bt).\(n)")), ("text", .s("\(bt).\(n)"))])), ("args", .a(xs)), ("kw", []), ("text", .s(t))]))
|
|
1128
|
+
}
|
|
1129
|
+
let bty = typeOf(base).map(resolve)
|
|
1130
|
+
let (pre, b) = expr(base, expect: nil)
|
|
1131
|
+
// a dictionary's
|
|
1132
|
+
if case .dict(let kt, let vt)? = bty {
|
|
1133
|
+
if n == "removeValue", labels == ["forKey"], let a0 { let (kp, k) = expr(a0, expect: kt); return (pre + kp, X("call", p, [("f", X("get", p, [("x", b), ("f", "remove"), ("text", .s(bt))])), ("args", [k]), ("kw", []), ("text", .s(t))])) }
|
|
1134
|
+
if n == "updateValue", labels == ["_", "forKey"] {
|
|
1135
|
+
let (vp, vv) = expr(c.arguments.first!.expression, expect: vt), (kp, k) = expr(c.arguments.last!.expression, expect: kt)
|
|
1136
|
+
return (pre + vp + kp, X("call", p, [("f", X("get", p, [("x", b), ("f", "insert"), ("text", .s(bt))])), ("args", [k, vv]), ("kw", []), ("text", .s(t))]))
|
|
1137
|
+
}
|
|
1138
|
+
return (pre, no(p, "\(t): a dictionary's \(n) (the subset reads [key], [key, default:], updateValue and removeValue)"))
|
|
1139
|
+
}
|
|
1140
|
+
// an integer's reporting-overflow arithmetic: (partialValue: the wrapped result, overflow: whether it wrapped)
|
|
1141
|
+
if ["addingReportingOverflow", "subtractingReportingOverflow", "multipliedReportingOverflow"].contains(n), let a0 {
|
|
1142
|
+
let op = n.hasPrefix("adding") ? "+" : n.hasPrefix("subtracting") ? "-" : "*"
|
|
1143
|
+
let (ap, y) = expr(a0, expect: bty)
|
|
1144
|
+
let ta = temp(), tb = temp()
|
|
1145
|
+
let setA = S("set", p, [("to", v(ta, p)), ("x", b)]), setB = S("set", p, [("to", v(tb, p)), ("x", y)])
|
|
1146
|
+
let wrapped = X("bin", p, [("op", .s(op)), ("x", v(ta, p)), ("y", v(tb, p)), ("ovf", "wrap"), ("text", .s(t))])
|
|
1147
|
+
let checked = X("bin", p, [("op", .s(op)), ("x", v(ta, p)), ("y", v(tb, p)), ("ovf", "checked"), ("text", .s(t))])
|
|
1148
|
+
return (pre + ap + [setA, setB], X("tuple", p, [("xs", [wrapped, X("is", p, [("x", checked), ("k", "none")])])]))
|
|
1149
|
+
}
|
|
1150
|
+
// a method of the code's own type, by its labels; else a method of other code (an injected dependency's)
|
|
1151
|
+
if case .n(let bn, _)? = bty, let x = ty(named: bn, from: selfTy), x.kind != "protocol", let me = methodKey(x, n, labels) {
|
|
1152
|
+
let (cp, cx) = ownCall(X("get", p, [("x", b), ("f", .s(me.key)), ("text", .s(short(m.trimmedDescription)))]), me, c, p, t)
|
|
1153
|
+
return (pre + cp, cx)
|
|
1154
|
+
}
|
|
1155
|
+
var types: [TT?] = []
|
|
1156
|
+
if case .n(let bn, _)? = bty, let x = ty(named: bn, from: selfTy), x.kind == "protocol", let f = x.members.compactMap({ $0.decl.as(FunctionDeclSyntax.self) }).first(where: { $0.name.text == n }) {
|
|
1157
|
+
types = f.signature.parameterClause.parameters.map { parseType($0.type.trimmedDescription) }
|
|
1158
|
+
}
|
|
1159
|
+
let (ap, xs) = args(c.arguments, types)
|
|
1160
|
+
return (pre + ap, X("call", p, [("f", X("get", p, [("x", b), ("f", .s(n)), ("text", .s(short(m.trimmedDescription)))])), ("args", .a(xs)), ("kw", []), ("text", .s(t))]))
|
|
1161
|
+
}
|
|
1162
|
+
if let r = c.calledExpression.as(DeclReferenceExprSyntax.self) {
|
|
1163
|
+
let (pre, xs) = args(c.arguments)
|
|
1164
|
+
if local(r.baseName.text) != nil { return (pre, no(p, "\(t): a call of a local closure")) }
|
|
1165
|
+
return (pre, X("call", p, [("f", X("ext", p, [("q", .s(r.baseName.text)), ("text", .s(r.baseName.text))])), ("args", .a(xs)), ("kw", []), ("text", .s(t))]))
|
|
1166
|
+
}
|
|
1167
|
+
return ([], no(p, "\(t): a call outside the subset"))
|
|
1168
|
+
}
|
|
1169
|
+
// A call of the code's own function or method: its arguments matched to its parameters by their labels (a default
|
|
1170
|
+
// where one is left out), given by the parameters' names.
|
|
1171
|
+
func ownCall(_ f: J, _ m: Meth, _ c: FunctionCallExprSyntax, _ p: String, _ t: String) -> ([J], J) {
|
|
1172
|
+
guard let fd = m.decl.as(FunctionDeclSyntax.self) else { return ([], no(p, t)) }
|
|
1173
|
+
return matched(f, fd.signature.parameterClause.parameters, c, p, t)
|
|
1174
|
+
}
|
|
1175
|
+
func freeCall(_ fd: FunctionDeclSyntax, _ c: FunctionCallExprSyntax, _ p: String, _ t: String) -> ([J], J) {
|
|
1176
|
+
matched(X("fn", p, [("id", .s(fd.name.text))]), fd.signature.parameterClause.parameters, c, p, t)
|
|
1177
|
+
}
|
|
1178
|
+
func matched(_ f: J, _ ps: FunctionParameterListSyntax, _ c: FunctionCallExprSyntax, _ p: String, _ t: String) -> ([J], J) {
|
|
1179
|
+
var pre: [J] = [], kw: [J] = []
|
|
1180
|
+
var args = Array(c.arguments)
|
|
1181
|
+
for (i, pa) in ps.enumerated() {
|
|
1182
|
+
let label = pa.firstName.text
|
|
1183
|
+
let n = (pa.secondName ?? pa.firstName).text == "_" ? "_arg\(i)" : (pa.secondName ?? pa.firstName).text
|
|
1184
|
+
if let a = args.first, (a.label?.text ?? "_") == label {
|
|
1185
|
+
args.removeFirst()
|
|
1186
|
+
let (s, x) = expr(a.expression, expect: parseType(pa.type.trimmedDescription))
|
|
1187
|
+
pre += s; kw.append([.s(n), copied(x, a.expression)])
|
|
1188
|
+
} else if pa.defaultValue == nil { return ([], no(p, "\(t): an argument not matched to its parameter (\(label))")) }
|
|
1189
|
+
}
|
|
1190
|
+
if !args.isEmpty { return ([], no(p, "\(t): arguments past the parameters")) }
|
|
1191
|
+
return (pre, X("call", p, [("f", f), ("args", []), ("kw", .a(kw)), ("text", .s(t))]))
|
|
1192
|
+
}
|
|
1193
|
+
// A value of the code's own type made: a struct by its memberwise init (a record: its fields given), else refused.
|
|
1194
|
+
func construct(_ x: Ty, _ c: FunctionCallExprSyntax, _ p: String, _ t: String) -> ([J], J) {
|
|
1195
|
+
if x.kind == "enum" { return ([], no(p, "\(t): an enum made from a raw value")) }
|
|
1196
|
+
if x.kind != "struct" || x.members.contains(where: { $0.decl.is(InitializerDeclSyntax.self) }) { return ([], no(p, "\(t): an object made by its init (the subset makes a struct by its memberwise init)")) }
|
|
1197
|
+
let ps = props(x)
|
|
1198
|
+
var pre: [J] = [], fields: [J] = []
|
|
1199
|
+
var given = Array(c.arguments)
|
|
1200
|
+
for pr in ps {
|
|
1201
|
+
if let a = given.first, a.label?.text == pr.name, !(pr.isLet && pr.initv != nil) {
|
|
1202
|
+
given.removeFirst()
|
|
1203
|
+
let (s, v0) = expr(a.expression, expect: pr.t)
|
|
1204
|
+
pre += s; fields.append([.s(pr.name), copied(v0, a.expression)])
|
|
1205
|
+
} else if let iv = pr.initv { let (s, v0) = with(file: x.file) { scoped { expr(iv, expect: pr.t) } }; pre += s; fields.append([.s(pr.name), v0]) }
|
|
1206
|
+
else if pr.nilInit { fields.append([.s(pr.name), X("none", p)]) }
|
|
1207
|
+
else { return ([], no(p, "\(t): \(pr.name) not given")) }
|
|
1208
|
+
}
|
|
1209
|
+
if !given.isEmpty { return ([], no(p, "\(t): arguments the memberwise init doesn't take")) }
|
|
1210
|
+
rec(x)
|
|
1211
|
+
return (pre, X("new", p, [("rec", .s(x.qual)), ("fields", .a(fields)), ("text", .s(t))]))
|
|
1212
|
+
}
|
|
1213
|
+
func infix(_ inf: InfixOperatorExprSyntax, _ p: String, _ t: String, _ expect: TT?) -> ([J], J) {
|
|
1214
|
+
if inf.operator.is(AssignmentExprSyntax.self) { return (assign(inf.leftOperand, inf.rightOperand, p), X("unit", p)) }
|
|
1215
|
+
guard let op = inf.operator.as(BinaryOperatorExprSyntax.self)?.operator.text else { return ([], no(p, "\(t): an operator outside the subset")) }
|
|
1216
|
+
let l = inf.leftOperand, r = inf.rightOperand
|
|
1217
|
+
if ["+=", "-=", "*=", "/=", "%=", "&+=", "&-=", "&*="].contains(op) { return (compound(l, String(op.dropLast()), r, p, ExprSyntax(inf)), X("unit", p)) }
|
|
1218
|
+
if op == "&&" || op == "||" {
|
|
1219
|
+
let (lp, a) = expr(l, expect: .n("Bool", [])), (rp, b) = expr(r, expect: .n("Bool", []))
|
|
1220
|
+
if rp.isEmpty { return (lp, X(op == "&&" ? "and" : "or", p, [("xs", [a, b]), ("strict", true), ("text", .s(t))])) }
|
|
1221
|
+
let tv = temp()
|
|
1222
|
+
let then = rp + [S("set", p, [("to", v(tv, p)), ("x", b)])], short = [S("set", p, [("to", v(tv, p)), ("x", X("bool", p, [("v", .b(op == "||"))]))])]
|
|
1223
|
+
return (lp + [S("if", p, [("c", a), ("then", .a(op == "&&" ? then : short)), ("else", .a(op == "&&" ? short : then))])], v(tv, p))
|
|
1224
|
+
}
|
|
1225
|
+
if op == "??" {
|
|
1226
|
+
let lt = typeOf(l)
|
|
1227
|
+
var inner: TT? = expect
|
|
1228
|
+
if case .opt(let i)? = lt { inner = i }
|
|
1229
|
+
let (lp, a) = expr(l, expect: lt), (rp, b) = expr(r, expect: inner)
|
|
1230
|
+
if rp.isEmpty { return (lp, X("opt_or", p, [("x", a), ("d", b), ("text", .s(t))])) }
|
|
1231
|
+
let ta = temp(), tv = temp()
|
|
1232
|
+
return (lp + [S("set", p, [("to", v(ta, p)), ("x", a)]), S("if", p, [("c", X("is", p, [("x", v(ta, p)), ("k", "some")])), ("then", [S("set", p, [("to", v(tv, p)), ("x", X("unwrap", p, [("x", v(ta, p)), ("k", "some")]))])]), ("else", .a(rp + [S("set", p, [("to", v(tv, p)), ("x", b)])]))])], v(tv, p))
|
|
1233
|
+
}
|
|
1234
|
+
if ["==", "!="].contains(op), r.is(NilLiteralExprSyntax.self) || l.is(NilLiteralExprSyntax.self) {
|
|
1235
|
+
let (pre, x) = expr(r.is(NilLiteralExprSyntax.self) ? l : r, expect: nil)
|
|
1236
|
+
return (pre, X("is", p, [("x", x), ("k", .s(op == "==" ? "none" : "some")), ("text", .s(t))]))
|
|
1237
|
+
}
|
|
1238
|
+
let lt = typeOf(l), rt = typeOf(r)
|
|
1239
|
+
let (lp, a) = expr(l, expect: isShorthand(l) ? rt : (lt ?? rt ?? expect)), (rp, b) = expr(r, expect: isShorthand(r) ? lt : (rt ?? lt ?? expect))
|
|
1240
|
+
let pre = lp + rp
|
|
1241
|
+
if ["==", "!=", "<", "<=", ">", ">="].contains(op) { return (pre, X("cmp", p, [("op", .s(op)), ("x", a), ("y", b), ("text", .s(t))])) }
|
|
1242
|
+
if ["+", "-", "*", "/", "%", "&+", "&-", "&*"].contains(op) { return (pre, arith(op, a, b, p, t)) }
|
|
1243
|
+
if ["<<", ">>", "&<<", "&>>"].contains(op) { return (pre, X("binop", p, [("op", .s(op.hasPrefix("&") ? String(op.dropFirst()) : op)), ("x", a), ("y", b), ("text", .s(t))])) }
|
|
1244
|
+
return (pre, no(p, "\(t): the operator \(op)"))
|
|
1245
|
+
}
|
|
1246
|
+
func isShorthand(_ e: ExprSyntax) -> Bool { if let m = e.as(MemberAccessExprSyntax.self) { return m.base == nil }; return false }
|
|
1247
|
+
|
|
1248
|
+
// --- the declared type of an expression, where the declarations say it (else nil) ------------------------------------
|
|
1249
|
+
func typeOf(_ e: ExprSyntax) -> TT? {
|
|
1250
|
+
if e.is(IntegerLiteralExprSyntax.self) { return nil }
|
|
1251
|
+
if e.is(BooleanLiteralExprSyntax.self) { return .n("Bool", []) }
|
|
1252
|
+
if e.is(StringLiteralExprSyntax.self) { return .n("String", []) }
|
|
1253
|
+
if let tu = e.as(TupleExprSyntax.self), tu.elements.count == 1 { return typeOf(tu.elements.first!.expression) }
|
|
1254
|
+
if let r = e.as(DeclReferenceExprSyntax.self) {
|
|
1255
|
+
let n = r.baseName.text
|
|
1256
|
+
if n == "self", let s = selfTy { return .n(s.qual, []) }
|
|
1257
|
+
if let l = local(n) { if case .bad? = l { return nil }; return l }
|
|
1258
|
+
if let st = selfTy {
|
|
1259
|
+
if let pr = props(st).first(where: { $0.name == n }) { return pr.t }
|
|
1260
|
+
if let c = computed(st).first(where: { $0.0 == n }) { return c.1 }
|
|
1261
|
+
if let c = consts["\(st.name).\(n)"] { return c.1 }
|
|
1262
|
+
}
|
|
1263
|
+
return consts[n]?.1
|
|
1264
|
+
}
|
|
1265
|
+
if let m = e.as(MemberAccessExprSyntax.self) {
|
|
1266
|
+
let n = m.declName.baseName.text
|
|
1267
|
+
guard let base = m.base else { return nil }
|
|
1268
|
+
let bt = base.trimmedDescription
|
|
1269
|
+
if INTS[bt] != nil { return .n(bt, []) }
|
|
1270
|
+
if bt.first?.isUppercase == true, local(bt) == nil, let x = ty(named: bt == "Self" ? selfTy?.name ?? bt : bt, from: selfTy) {
|
|
1271
|
+
if x.kind == "enum" && x.cases.contains(where: { $0.name == n }) { return .n(x.qual, []) }
|
|
1272
|
+
return consts["\(x.name).\(n)"]?.1
|
|
1273
|
+
}
|
|
1274
|
+
guard case .n(let bn, _)? = typeOf(base).map(resolve), let x = ty(named: bn, from: selfTy) else { return nil }
|
|
1275
|
+
if n == "rawValue" { return x.rawType }
|
|
1276
|
+
if let pr = props(x).first(where: { $0.name == n }) { return pr.t }
|
|
1277
|
+
if let c = computed(x).first(where: { $0.0 == n }) { return c.1 }
|
|
1278
|
+
return nil
|
|
1279
|
+
}
|
|
1280
|
+
if let c = e.as(FunctionCallExprSyntax.self) {
|
|
1281
|
+
if let r = c.calledExpression.as(DeclReferenceExprSyntax.self) {
|
|
1282
|
+
let n = r.baseName.text
|
|
1283
|
+
if INTS[n] != nil { return c.arguments.first?.label?.text == "exactly" ? .opt(.n(n, [])) : .n(n, []) }
|
|
1284
|
+
if n == "min" || n == "max" || n == "abs" { return c.arguments.compactMap { typeOf($0.expression) }.first }
|
|
1285
|
+
if let x = ty(named: n, from: selfTy) { return .n(x.qual, []) }
|
|
1286
|
+
if let st = selfTy, let m = methodKey(st, n, c.arguments.map { $0.label?.text ?? "_" }), let f = m.decl.as(FunctionDeclSyntax.self) { return f.signature.returnClause.map { parseType($0.type.trimmedDescription) } }
|
|
1287
|
+
if let (_, f) = free[n] { return f.signature.returnClause.map { parseType($0.type.trimmedDescription) } }
|
|
1288
|
+
return nil
|
|
1289
|
+
}
|
|
1290
|
+
if let m = c.calledExpression.as(MemberAccessExprSyntax.self), let base = m.base {
|
|
1291
|
+
let n = m.declName.baseName.text
|
|
1292
|
+
if case .n(let bn, _)? = typeOf(base).map(resolve), let x = ty(named: bn, from: selfTy) {
|
|
1293
|
+
if let me = methodKey(x, n, c.arguments.map { $0.label?.text ?? "_" }), let f = me.decl.as(FunctionDeclSyntax.self) { return f.signature.returnClause.map { parseType($0.type.trimmedDescription) } }
|
|
1294
|
+
if x.kind == "protocol", let f = x.members.compactMap({ $0.decl.as(FunctionDeclSyntax.self) }).first(where: { $0.name.text == n }) { return f.signature.returnClause.map { parseType($0.type.trimmedDescription) } }
|
|
1295
|
+
}
|
|
1296
|
+
if case .dict(_, let vt)? = typeOf(base).map(resolve), n == "removeValue" || n == "updateValue" { return .opt(vt) }
|
|
1297
|
+
}
|
|
1298
|
+
return nil
|
|
1299
|
+
}
|
|
1300
|
+
if let sc = e.as(SubscriptCallExprSyntax.self), case .dict(_, let vt)? = typeOf(sc.calledExpression).map(resolve) { return sc.arguments.count == 2 ? vt : .opt(vt) }
|
|
1301
|
+
if let fu = e.as(ForceUnwrapExprSyntax.self), case .opt(let i)? = typeOf(fu.expression) { return i }
|
|
1302
|
+
if let tr = e.as(TryExprSyntax.self) { return typeOf(tr.expression) }
|
|
1303
|
+
if let pr = e.as(PrefixOperatorExprSyntax.self) { return pr.operator.text == "!" ? .n("Bool", []) : typeOf(pr.expression) }
|
|
1304
|
+
if let inf = e.as(InfixOperatorExprSyntax.self), let op = inf.operator.as(BinaryOperatorExprSyntax.self)?.operator.text {
|
|
1305
|
+
if ["==", "!=", "<", "<=", ">", ">=", "&&", "||"].contains(op) { return .n("Bool", []) }
|
|
1306
|
+
if op == "??" { if case .opt(let i)? = typeOf(inf.leftOperand) { return i }; return typeOf(inf.rightOperand) }
|
|
1307
|
+
return typeOf(inf.leftOperand) ?? typeOf(inf.rightOperand)
|
|
1308
|
+
}
|
|
1309
|
+
if let te = e.as(TernaryExprSyntax.self) { return typeOf(te.thenExpression) ?? typeOf(te.elseExpression) }
|
|
1310
|
+
return nil
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
// --- the module ------------------------------------------------------------------------------------------------------
|
|
1314
|
+
func output(entryFile: String?, names: [String]) -> J {
|
|
1315
|
+
var entries: [J] = []
|
|
1316
|
+
let rel = entryFile.map { $0.hasPrefix(root + "/") ? String($0.dropFirst(root.count + 1)) : $0 }
|
|
1317
|
+
let pool = allTypes.filter { ["class", "struct", "actor"].contains($0.kind) && (rel == nil || $0.file == rel) }
|
|
1318
|
+
var efile = rel ?? files.first?.rel ?? ""
|
|
1319
|
+
for n in names.isEmpty ? pool.map(\.qual) : names {
|
|
1320
|
+
if let t = ty(named: n), ["class", "struct", "actor"].contains(t.kind) { rec(t); entries.append(["k": "class", "rec": .s(t.qual)]); efile = t.file }
|
|
1321
|
+
else if let (f, fd) = free[n] { efile = f; let j = with(file: f) { function(fd, nil, n, n, true) }; funcs.append((n, j)); entries.append(["k": "func", "id": .s(n)]) }
|
|
1322
|
+
else { entries.append(["k": "missing", "name": .s(n)]) }
|
|
1323
|
+
}
|
|
1324
|
+
// (the code's free functions, for the calls the entries make)
|
|
1325
|
+
for (n, (f, fd)) in free.sorted(by: { $0.key < $1.key }) where !funcs.contains(where: { $0.0 == n }) { funcs.append((n, with(file: f) { function(fd, nil, n, n, true) })) }
|
|
1326
|
+
var seen = Set<String>()
|
|
1327
|
+
let fs: [(String, J)] = funcs.reversed().filter { seen.insert($0.0).inserted }.reversed()
|
|
1328
|
+
return ["lang": "swift", "file": .s((efile as NSString).lastPathComponent), "path": .s(root + "/" + efile), "module": "", "root": .s(root), "entries": .a(entries),
|
|
1329
|
+
"recs": .o(recs), "funcs": .o(fs), "enums": .o(enumsOut)]
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
// --- main ----------------------------------------------------------------------------------------------------------
|
|
1334
|
+
let argv = CommandLine.arguments
|
|
1335
|
+
guard argv.count >= 5 else { print("{\"error\": \"usage: gdp-swiftreader <root> <file|-> <names|-> <ctor|-> <file>...\"}"); exit(0) }
|
|
1336
|
+
let reader = Reader(root: argv[1])
|
|
1337
|
+
reader.ctorArity = Int(argv[4]); if argv[4] != "-" && reader.ctorArity == nil { reader.ctorSig = argv[4] }
|
|
1338
|
+
reader.load(Array(argv.dropFirst(5)))
|
|
1339
|
+
var out = ""
|
|
1340
|
+
reader.output(entryFile: argv[2] == "-" ? nil : argv[2], names: argv[3] == "-" ? [] : argv[3].split(separator: ",").map(String.init)).write(&out)
|
|
1341
|
+
print(out)
|