ruby-anything 0.2.0 → 0.2.1
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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +9 -2
- package/README.md +15 -1
- package/adapters/node/harness.mjs +3 -1
- package/adapters/node/package-lock.json +26 -26
- package/adapters/node/package.json +7 -7
- package/adapters/polyglot/harness.py +350 -350
- package/adapters/polyglot/lang_csharp.py +222 -222
- package/adapters/polyglot/lang_java.py +510 -510
- package/adapters/polyglot/lang_rust.py +430 -430
- package/adapters/polyglot/lang_swift.py +337 -337
- package/adapters/ruby/harness.rb +134 -0
- package/package.json +3 -3
- package/src/adapters.js +60 -63
|
@@ -1,337 +1,337 @@
|
|
|
1
|
-
"""Swift support for the polyglot adapter.
|
|
2
|
-
|
|
3
|
-
Analysis: top-level `func` declarations (column 0). Parameter labels are kept so calls are generated correctly.
|
|
4
|
-
Driver: all sibling .swift files are compiled with a generated `main.swift` (swiftc -Onone) that decodes the JSON
|
|
5
|
-
args per declared type (Int/Int64/Double/Float/Bool/String and arrays of those), calls the function with `try`,
|
|
6
|
-
and maps a thrown Error to a raise outcome (type = the Error's type name, message = String(describing: error)).
|
|
7
|
-
Offline: only Foundation / stdlib. Value JSON is hand-encoded so Doubles stay floats (2.0 not 2).
|
|
8
|
-
"""
|
|
9
|
-
import os
|
|
10
|
-
import re
|
|
11
|
-
import subprocess
|
|
12
|
-
|
|
13
|
-
from harness import match_brace, unit_record
|
|
14
|
-
|
|
15
|
-
EXTS = {".swift"}
|
|
16
|
-
SKIP_DIRS = ("Tests",)
|
|
17
|
-
THROW = r"\bthrow\s"
|
|
18
|
-
FUNC_RE = re.compile(
|
|
19
|
-
r"^(?:@\w+\s+)*(?:(?:public|internal|private|fileprivate|open|nonisolated)\s+)*func\s+([A-Za-z_]\w*)\s*(<[^>]*>)?\s*"
|
|
20
|
-
r"\(([^)]*)\)\s*(throws|rethrows)?\s*(?:->\s*([^{\n]+?))?\s*\{", re.M)
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
def runtime():
|
|
24
|
-
return subprocess.run(["swiftc", "--version"], capture_output=True, text=True).stdout.split("\n")[0].strip()
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
def imports(text):
|
|
28
|
-
return sorted(set(re.findall(r"^import\s+(\w+)", text, re.M)))
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
def split_top(raw):
|
|
32
|
-
parts, depth, cur = [], 0, ""
|
|
33
|
-
for c in raw:
|
|
34
|
-
depth += c in "[(<"
|
|
35
|
-
depth -= c in "])>"
|
|
36
|
-
if c == "," and depth == 0:
|
|
37
|
-
parts.append(cur)
|
|
38
|
-
cur = ""
|
|
39
|
-
else:
|
|
40
|
-
cur += c
|
|
41
|
-
return parts + [cur] if cur.strip() else parts
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
def parse_params(raw):
|
|
45
|
-
"""-> list of {name, annotation, default, kind, label}; label is None for `_`."""
|
|
46
|
-
params = []
|
|
47
|
-
for part in split_top(raw):
|
|
48
|
-
head, _, typ = part.partition(":")
|
|
49
|
-
typ, _, default = typ.partition("=")
|
|
50
|
-
names = head.split()
|
|
51
|
-
label, name = (names[0], names[-1]) if names else ("", "")
|
|
52
|
-
params.append({"name": name, "annotation": typ.strip(), "default": default.strip() or None,
|
|
53
|
-
"kind": "varargs" if typ.strip().endswith("...") else "positional",
|
|
54
|
-
"label": None if label == "_" else label})
|
|
55
|
-
return params
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
def analyze_file(rel, text):
|
|
59
|
-
if rel.endswith("Tests.swift") or os.path.basename(rel) in ("main.swift", "Package.swift"):
|
|
60
|
-
return []
|
|
61
|
-
module = os.path.splitext(os.path.basename(rel))[0]
|
|
62
|
-
units = []
|
|
63
|
-
for m in FUNC_RE.finditer(text):
|
|
64
|
-
if m.group(2): # generic functions are not recordable
|
|
65
|
-
continue
|
|
66
|
-
end = match_brace(text, m.end() - 1)
|
|
67
|
-
params = [{k: v for k, v in p.items() if k != "label"} for p in parse_params(m.group(3))]
|
|
68
|
-
units.append(unit_record(rel, module, m.group(1), m.start(), end, text, params, (m.group(5) or "").strip() or None, THROW))
|
|
69
|
-
return units
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
def dec(typ, expr, depth=0):
|
|
73
|
-
t = typ.strip()
|
|
74
|
-
simple = {"Int": "ppInt({})", "Int64": "Int64(ppInt({}))", "Double": "ppDouble({})", "Float": "Float(ppDouble({}))",
|
|
75
|
-
"Bool": "ppBool({})", "String": "ppString({})"}
|
|
76
|
-
if t in simple:
|
|
77
|
-
return "try " + simple[t].format(expr)
|
|
78
|
-
if t.startswith("[") and t.endswith("]"):
|
|
79
|
-
return f"try ppArray({expr}).map {{ e{depth} in {dec(t[1:-1], f'e{depth}', depth + 1)} }}"
|
|
80
|
-
raise SystemExit(f"unsupported Swift parameter type {typ!r}")
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
DRIVER = r'''import Foundation
|
|
84
|
-
|
|
85
|
-
struct PPDecodeError: Error { let message: String }
|
|
86
|
-
|
|
87
|
-
func ppDouble(_ v: Any) throws -> Double {
|
|
88
|
-
if let d = v as? [String: Any], let s = d["$float"] as? String {
|
|
89
|
-
switch s {
|
|
90
|
-
case "nan": return Double.nan
|
|
91
|
-
case "inf": return Double.infinity
|
|
92
|
-
case "-inf": return -Double.infinity
|
|
93
|
-
case "-0.0": return Double(sign: .minus, exponent: 0, significand: 0)
|
|
94
|
-
default:
|
|
95
|
-
if let f = Double(s) { return f }
|
|
96
|
-
throw PPDecodeError(message: "bad $float \(s)")
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
if let d = v as? Double { return d }
|
|
100
|
-
if let i = v as? Int { return Double(i) }
|
|
101
|
-
throw PPDecodeError(message: "cannot use \(v) as Double")
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
func ppInt(_ v: Any) throws -> Int {
|
|
105
|
-
if let i = v as? Int { return i }
|
|
106
|
-
if let d = v as? Double, d == d.rounded(), abs(d) < 9.2e18 { return Int(d) }
|
|
107
|
-
throw PPDecodeError(message: "cannot use \(v) as Int")
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
func ppBool(_ v: Any) throws -> Bool {
|
|
111
|
-
if let b = v as? Bool { return b }
|
|
112
|
-
throw PPDecodeError(message: "cannot use \(v) as Bool")
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
func ppString(_ v: Any) throws -> String {
|
|
116
|
-
if let s = v as? String { return s }
|
|
117
|
-
throw PPDecodeError(message: "cannot use \(v) as String")
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
func ppArray(_ v: Any) throws -> [Any] {
|
|
121
|
-
if let a = v as? [Any] { return a }
|
|
122
|
-
throw PPDecodeError(message: "cannot use \(v) as Array")
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
// Foundation's JSONSerialization does not round numbers exactly, so args are parsed here (Double(String) is exact).
|
|
126
|
-
struct PPParser {
|
|
127
|
-
let s: [UInt8]
|
|
128
|
-
var i = 0
|
|
129
|
-
|
|
130
|
-
mutating func ws() {
|
|
131
|
-
while i < s.count, s[i] == 32 || s[i] == 10 || s[i] == 13 || s[i] == 9 { i += 1 }
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
mutating func expect(_ c: Character) throws {
|
|
135
|
-
ws()
|
|
136
|
-
guard i < s.count, s[i] == c.asciiValue! else { throw PPDecodeError(message: "bad JSON, expected \(c)") }
|
|
137
|
-
i += 1
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
mutating func value() throws -> Any {
|
|
141
|
-
ws()
|
|
142
|
-
guard i < s.count else { throw PPDecodeError(message: "bad JSON: unexpected end") }
|
|
143
|
-
switch s[i] {
|
|
144
|
-
case UInt8(ascii: "{"):
|
|
145
|
-
i += 1
|
|
146
|
-
var d: [String: Any] = [:]
|
|
147
|
-
ws()
|
|
148
|
-
if i < s.count, s[i] == UInt8(ascii: "}") { i += 1; return d }
|
|
149
|
-
while true {
|
|
150
|
-
ws()
|
|
151
|
-
let k = try string()
|
|
152
|
-
try expect(":")
|
|
153
|
-
d[k] = try value()
|
|
154
|
-
ws()
|
|
155
|
-
if i < s.count, s[i] == UInt8(ascii: ",") { i += 1; continue }
|
|
156
|
-
try expect("}")
|
|
157
|
-
return d
|
|
158
|
-
}
|
|
159
|
-
case UInt8(ascii: "["):
|
|
160
|
-
i += 1
|
|
161
|
-
var a: [Any] = []
|
|
162
|
-
ws()
|
|
163
|
-
if i < s.count, s[i] == UInt8(ascii: "]") { i += 1; return a }
|
|
164
|
-
while true {
|
|
165
|
-
a.append(try value())
|
|
166
|
-
ws()
|
|
167
|
-
if i < s.count, s[i] == UInt8(ascii: ",") { i += 1; continue }
|
|
168
|
-
try expect("]")
|
|
169
|
-
return a
|
|
170
|
-
}
|
|
171
|
-
case UInt8(ascii: "\""): return try string()
|
|
172
|
-
case UInt8(ascii: "t"): i += 4; return true
|
|
173
|
-
case UInt8(ascii: "f"): i += 5; return false
|
|
174
|
-
case UInt8(ascii: "n"): i += 4; return NSNull()
|
|
175
|
-
default:
|
|
176
|
-
let start = i
|
|
177
|
-
while i < s.count, "+-0123456789.eE".utf8.contains(s[i]) { i += 1 }
|
|
178
|
-
let text = String(decoding: s[start..<i], as: UTF8.self)
|
|
179
|
-
if let n = Int(text) { return n }
|
|
180
|
-
if let d = Double(text) { return d }
|
|
181
|
-
throw PPDecodeError(message: "bad JSON number \(text)")
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
mutating func hex4() throws -> UInt32 {
|
|
186
|
-
guard i + 4 <= s.count, let h = UInt32(String(decoding: s[i..<i + 4], as: UTF8.self), radix: 16) else {
|
|
187
|
-
throw PPDecodeError(message: "bad JSON unicode escape")
|
|
188
|
-
}
|
|
189
|
-
i += 4
|
|
190
|
-
return h
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
mutating func string() throws -> String {
|
|
194
|
-
guard i < s.count, s[i] == UInt8(ascii: "\"") else { throw PPDecodeError(message: "bad JSON string") }
|
|
195
|
-
i += 1
|
|
196
|
-
var out: [UInt8] = []
|
|
197
|
-
while i < s.count, s[i] != UInt8(ascii: "\"") {
|
|
198
|
-
if s[i] != UInt8(ascii: "\\") { out.append(s[i]); i += 1; continue }
|
|
199
|
-
i += 1
|
|
200
|
-
guard i < s.count else { break }
|
|
201
|
-
let c = s[i]
|
|
202
|
-
i += 1
|
|
203
|
-
switch c {
|
|
204
|
-
case UInt8(ascii: "n"): out.append(10)
|
|
205
|
-
case UInt8(ascii: "t"): out.append(9)
|
|
206
|
-
case UInt8(ascii: "r"): out.append(13)
|
|
207
|
-
case UInt8(ascii: "b"): out.append(8)
|
|
208
|
-
case UInt8(ascii: "f"): out.append(12)
|
|
209
|
-
case UInt8(ascii: "u"):
|
|
210
|
-
var cp = try hex4()
|
|
211
|
-
if cp >= 0xD800 && cp < 0xDC00, i + 6 <= s.count, s[i] == UInt8(ascii: "\\") {
|
|
212
|
-
i += 2
|
|
213
|
-
cp = 0x10000 + ((cp - 0xD800) << 10) + (try hex4() - 0xDC00)
|
|
214
|
-
}
|
|
215
|
-
out += Array(String(Unicode.Scalar(cp) ?? "\u{FFFD}").utf8)
|
|
216
|
-
default: out.append(c)
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
i += 1
|
|
220
|
-
return String(decoding: out, as: UTF8.self)
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
func ppQuote(_ s: String) -> String {
|
|
225
|
-
var out = "\""
|
|
226
|
-
for u in s.unicodeScalars {
|
|
227
|
-
switch u {
|
|
228
|
-
case "\"": out += "\\\""
|
|
229
|
-
case "\\": out += "\\\\"
|
|
230
|
-
case "\n": out += "\\n"
|
|
231
|
-
case "\r": out += "\\r"
|
|
232
|
-
case "\t": out += "\\t"
|
|
233
|
-
default:
|
|
234
|
-
if u.value < 0x20 { out += String(format: "\\u%04x", u.value) } else { out.unicodeScalars.append(u) }
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
return out + "\""
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
func ppDbl(_ d: Double) -> String {
|
|
241
|
-
if d.isNaN { return "{\"$float\":\"nan\"}" }
|
|
242
|
-
if d.isInfinite { return d > 0 ? "{\"$float\":\"inf\"}" : "{\"$float\":\"-inf\"}" }
|
|
243
|
-
if d == 0 && d.sign == .minus { return "{\"$float\":\"-0.0\"}" }
|
|
244
|
-
if d == d.rounded() && abs(d) > 9007199254740992 { return "{\"$float\":\"\(d)\"}" } // like the Go adapter
|
|
245
|
-
return "\(d)"
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
func ppEnc(_ v: Any) -> String {
|
|
249
|
-
switch v {
|
|
250
|
-
case let b as Bool: return b ? "true" : "false"
|
|
251
|
-
case let i as any BinaryInteger: return "\(i)"
|
|
252
|
-
case let d as Double: return ppDbl(d)
|
|
253
|
-
case let f as Float: return f.isFinite ? "\(f)" : ppDbl(Double(f))
|
|
254
|
-
case let s as String: return ppQuote(s)
|
|
255
|
-
case let a as [Any]: return "[" + a.map(ppEnc).joined(separator: ",") + "]"
|
|
256
|
-
case is NSNull: return "null"
|
|
257
|
-
default: return ppQuote(String(describing: v))
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
func ppRaise(_ type: String, _ message: String) -> String {
|
|
262
|
-
return "{\"kind\":\"raise\",\"type\":" + ppQuote(type) + ",\"message\":" + ppQuote(message) + "}"
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
func ppInvoke(_ args: [Any]) throws -> Any {
|
|
266
|
-
func arg(_ i: Int) throws -> Any {
|
|
267
|
-
if i < args.count { return args[i] }
|
|
268
|
-
throw PPDecodeError(message: "missing argument \(i)")
|
|
269
|
-
}
|
|
270
|
-
__DECODE__
|
|
271
|
-
__CALL__
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
func ppOutcome(_ args: [Any]) -> String {
|
|
275
|
-
do {
|
|
276
|
-
let r = try ppInvoke(args)
|
|
277
|
-
return "{\"kind\":\"return\",\"value\":" + ppEnc(r) + "}"
|
|
278
|
-
} catch let e as PPDecodeError {
|
|
279
|
-
return ppRaise("TypeError", e.message)
|
|
280
|
-
} catch {
|
|
281
|
-
return ppRaise(String(describing: type(of: error)), String(describing: error))
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
setvbuf(stdout, nil, _IOLBF, 0)
|
|
286
|
-
let ppInput = FileHandle.standardInput.readDataToEndOfFile()
|
|
287
|
-
var ppParser = PPParser(s: [UInt8](ppInput))
|
|
288
|
-
let ppReq = (try? ppParser.value()) as? [String: Any] ?? [:]
|
|
289
|
-
let ppArgs = ppReq["args"] as? [Any] ?? []
|
|
290
|
-
let ppOut: String
|
|
291
|
-
if (ppReq["mode"] as? String) == "bench" {
|
|
292
|
-
let n = max((ppReq["iterations"] as? Int) ?? 1, 1)
|
|
293
|
-
var samples: [String] = []
|
|
294
|
-
for _ in 0..<n {
|
|
295
|
-
let t0 = DispatchTime.now().uptimeNanoseconds
|
|
296
|
-
_ = try? ppInvoke(ppArgs)
|
|
297
|
-
samples.append(String(DispatchTime.now().uptimeNanoseconds - t0))
|
|
298
|
-
}
|
|
299
|
-
ppOut = "{\"samples_ns\":[" + samples.joined(separator: ",") + "]}"
|
|
300
|
-
} else {
|
|
301
|
-
ppOut = "{\"outcome\":" + ppOutcome(ppArgs) + "}"
|
|
302
|
-
}
|
|
303
|
-
fflush(stdout)
|
|
304
|
-
if let path = ProcessInfo.processInfo.environment["PP_RESULT"] {
|
|
305
|
-
try? ppOut.write(toFile: path, atomically: false, encoding: .utf8)
|
|
306
|
-
}
|
|
307
|
-
'''
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
def prepare(src, rel, unit, work):
|
|
311
|
-
if unit["kind"] != "function":
|
|
312
|
-
raise SystemExit("only top-level Swift functions can be recorded")
|
|
313
|
-
pkg_dir = os.path.join(src, os.path.dirname(rel))
|
|
314
|
-
sig = FUNC_RE.search(unit["source"])
|
|
315
|
-
decode, args = [], []
|
|
316
|
-
for i, p in enumerate(parse_params(sig.group(3))):
|
|
317
|
-
if p["kind"] != "positional":
|
|
318
|
-
raise SystemExit("variadic Swift parameters are not supported")
|
|
319
|
-
decode.append(f" let a{i}: {p['annotation']} = {dec(p['annotation'], f'(arg({i}))')}")
|
|
320
|
-
args.append(f"{p['label'] + ': ' if p['label'] else ''}a{i}")
|
|
321
|
-
call = f"{unit['name']}({', '.join(args)})"
|
|
322
|
-
is_void = not sig.group(5) or sig.group(5).strip() in ("Void", "()")
|
|
323
|
-
body = f" try {call}\n return NSNull()" if is_void else f" return try {call}"
|
|
324
|
-
files = []
|
|
325
|
-
for name in sorted(os.listdir(pkg_dir)): # `private` would hide functions from the driver file
|
|
326
|
-
if name.endswith(".swift") and name not in ("main.swift", "Package.swift") and not name.endswith("Tests.swift"):
|
|
327
|
-
p = os.path.join(pkg_dir, name)
|
|
328
|
-
code = re.sub(r"^(?:private|fileprivate)\s+", "", open(p, encoding="utf-8").read(), flags=re.M)
|
|
329
|
-
open(p, "w", encoding="utf-8").write(code)
|
|
330
|
-
files.append(name)
|
|
331
|
-
open(os.path.join(pkg_dir, "main.swift"), "w", encoding="utf-8").write(
|
|
332
|
-
DRIVER.replace("__DECODE__", "\n".join(decode)).replace("__CALL__", body))
|
|
333
|
-
out = os.path.join(work, "ppdrv")
|
|
334
|
-
env = dict(os.environ, HOME=work, TMPDIR=work)
|
|
335
|
-
subprocess.run(["swiftc", "-Onone", "-module-cache-path", os.path.join(work, "mc"), "-o", out, *files, "main.swift"],
|
|
336
|
-
cwd=pkg_dir, env=env, check=True, capture_output=True)
|
|
337
|
-
return [out]
|
|
1
|
+
"""Swift support for the polyglot adapter.
|
|
2
|
+
|
|
3
|
+
Analysis: top-level `func` declarations (column 0). Parameter labels are kept so calls are generated correctly.
|
|
4
|
+
Driver: all sibling .swift files are compiled with a generated `main.swift` (swiftc -Onone) that decodes the JSON
|
|
5
|
+
args per declared type (Int/Int64/Double/Float/Bool/String and arrays of those), calls the function with `try`,
|
|
6
|
+
and maps a thrown Error to a raise outcome (type = the Error's type name, message = String(describing: error)).
|
|
7
|
+
Offline: only Foundation / stdlib. Value JSON is hand-encoded so Doubles stay floats (2.0 not 2).
|
|
8
|
+
"""
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import subprocess
|
|
12
|
+
|
|
13
|
+
from harness import match_brace, unit_record
|
|
14
|
+
|
|
15
|
+
EXTS = {".swift"}
|
|
16
|
+
SKIP_DIRS = ("Tests",)
|
|
17
|
+
THROW = r"\bthrow\s"
|
|
18
|
+
FUNC_RE = re.compile(
|
|
19
|
+
r"^(?:@\w+\s+)*(?:(?:public|internal|private|fileprivate|open|nonisolated)\s+)*func\s+([A-Za-z_]\w*)\s*(<[^>]*>)?\s*"
|
|
20
|
+
r"\(([^)]*)\)\s*(throws|rethrows)?\s*(?:->\s*([^{\n]+?))?\s*\{", re.M)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def runtime():
|
|
24
|
+
return subprocess.run(["swiftc", "--version"], capture_output=True, text=True).stdout.split("\n")[0].strip()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def imports(text):
|
|
28
|
+
return sorted(set(re.findall(r"^import\s+(\w+)", text, re.M)))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def split_top(raw):
|
|
32
|
+
parts, depth, cur = [], 0, ""
|
|
33
|
+
for c in raw:
|
|
34
|
+
depth += c in "[(<"
|
|
35
|
+
depth -= c in "])>"
|
|
36
|
+
if c == "," and depth == 0:
|
|
37
|
+
parts.append(cur)
|
|
38
|
+
cur = ""
|
|
39
|
+
else:
|
|
40
|
+
cur += c
|
|
41
|
+
return parts + [cur] if cur.strip() else parts
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def parse_params(raw):
|
|
45
|
+
"""-> list of {name, annotation, default, kind, label}; label is None for `_`."""
|
|
46
|
+
params = []
|
|
47
|
+
for part in split_top(raw):
|
|
48
|
+
head, _, typ = part.partition(":")
|
|
49
|
+
typ, _, default = typ.partition("=")
|
|
50
|
+
names = head.split()
|
|
51
|
+
label, name = (names[0], names[-1]) if names else ("", "")
|
|
52
|
+
params.append({"name": name, "annotation": typ.strip(), "default": default.strip() or None,
|
|
53
|
+
"kind": "varargs" if typ.strip().endswith("...") else "positional",
|
|
54
|
+
"label": None if label == "_" else label})
|
|
55
|
+
return params
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def analyze_file(rel, text):
|
|
59
|
+
if rel.endswith("Tests.swift") or os.path.basename(rel) in ("main.swift", "Package.swift"):
|
|
60
|
+
return []
|
|
61
|
+
module = os.path.splitext(os.path.basename(rel))[0]
|
|
62
|
+
units = []
|
|
63
|
+
for m in FUNC_RE.finditer(text):
|
|
64
|
+
if m.group(2): # generic functions are not recordable
|
|
65
|
+
continue
|
|
66
|
+
end = match_brace(text, m.end() - 1)
|
|
67
|
+
params = [{k: v for k, v in p.items() if k != "label"} for p in parse_params(m.group(3))]
|
|
68
|
+
units.append(unit_record(rel, module, m.group(1), m.start(), end, text, params, (m.group(5) or "").strip() or None, THROW))
|
|
69
|
+
return units
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def dec(typ, expr, depth=0):
|
|
73
|
+
t = typ.strip()
|
|
74
|
+
simple = {"Int": "ppInt({})", "Int64": "Int64(ppInt({}))", "Double": "ppDouble({})", "Float": "Float(ppDouble({}))",
|
|
75
|
+
"Bool": "ppBool({})", "String": "ppString({})"}
|
|
76
|
+
if t in simple:
|
|
77
|
+
return "try " + simple[t].format(expr)
|
|
78
|
+
if t.startswith("[") and t.endswith("]"):
|
|
79
|
+
return f"try ppArray({expr}).map {{ e{depth} in {dec(t[1:-1], f'e{depth}', depth + 1)} }}"
|
|
80
|
+
raise SystemExit(f"unsupported Swift parameter type {typ!r}")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
DRIVER = r'''import Foundation
|
|
84
|
+
|
|
85
|
+
struct PPDecodeError: Error { let message: String }
|
|
86
|
+
|
|
87
|
+
func ppDouble(_ v: Any) throws -> Double {
|
|
88
|
+
if let d = v as? [String: Any], let s = d["$float"] as? String {
|
|
89
|
+
switch s {
|
|
90
|
+
case "nan": return Double.nan
|
|
91
|
+
case "inf": return Double.infinity
|
|
92
|
+
case "-inf": return -Double.infinity
|
|
93
|
+
case "-0.0": return Double(sign: .minus, exponent: 0, significand: 0)
|
|
94
|
+
default:
|
|
95
|
+
if let f = Double(s) { return f }
|
|
96
|
+
throw PPDecodeError(message: "bad $float \(s)")
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if let d = v as? Double { return d }
|
|
100
|
+
if let i = v as? Int { return Double(i) }
|
|
101
|
+
throw PPDecodeError(message: "cannot use \(v) as Double")
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
func ppInt(_ v: Any) throws -> Int {
|
|
105
|
+
if let i = v as? Int { return i }
|
|
106
|
+
if let d = v as? Double, d == d.rounded(), abs(d) < 9.2e18 { return Int(d) }
|
|
107
|
+
throw PPDecodeError(message: "cannot use \(v) as Int")
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
func ppBool(_ v: Any) throws -> Bool {
|
|
111
|
+
if let b = v as? Bool { return b }
|
|
112
|
+
throw PPDecodeError(message: "cannot use \(v) as Bool")
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
func ppString(_ v: Any) throws -> String {
|
|
116
|
+
if let s = v as? String { return s }
|
|
117
|
+
throw PPDecodeError(message: "cannot use \(v) as String")
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
func ppArray(_ v: Any) throws -> [Any] {
|
|
121
|
+
if let a = v as? [Any] { return a }
|
|
122
|
+
throw PPDecodeError(message: "cannot use \(v) as Array")
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Foundation's JSONSerialization does not round numbers exactly, so args are parsed here (Double(String) is exact).
|
|
126
|
+
struct PPParser {
|
|
127
|
+
let s: [UInt8]
|
|
128
|
+
var i = 0
|
|
129
|
+
|
|
130
|
+
mutating func ws() {
|
|
131
|
+
while i < s.count, s[i] == 32 || s[i] == 10 || s[i] == 13 || s[i] == 9 { i += 1 }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
mutating func expect(_ c: Character) throws {
|
|
135
|
+
ws()
|
|
136
|
+
guard i < s.count, s[i] == c.asciiValue! else { throw PPDecodeError(message: "bad JSON, expected \(c)") }
|
|
137
|
+
i += 1
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
mutating func value() throws -> Any {
|
|
141
|
+
ws()
|
|
142
|
+
guard i < s.count else { throw PPDecodeError(message: "bad JSON: unexpected end") }
|
|
143
|
+
switch s[i] {
|
|
144
|
+
case UInt8(ascii: "{"):
|
|
145
|
+
i += 1
|
|
146
|
+
var d: [String: Any] = [:]
|
|
147
|
+
ws()
|
|
148
|
+
if i < s.count, s[i] == UInt8(ascii: "}") { i += 1; return d }
|
|
149
|
+
while true {
|
|
150
|
+
ws()
|
|
151
|
+
let k = try string()
|
|
152
|
+
try expect(":")
|
|
153
|
+
d[k] = try value()
|
|
154
|
+
ws()
|
|
155
|
+
if i < s.count, s[i] == UInt8(ascii: ",") { i += 1; continue }
|
|
156
|
+
try expect("}")
|
|
157
|
+
return d
|
|
158
|
+
}
|
|
159
|
+
case UInt8(ascii: "["):
|
|
160
|
+
i += 1
|
|
161
|
+
var a: [Any] = []
|
|
162
|
+
ws()
|
|
163
|
+
if i < s.count, s[i] == UInt8(ascii: "]") { i += 1; return a }
|
|
164
|
+
while true {
|
|
165
|
+
a.append(try value())
|
|
166
|
+
ws()
|
|
167
|
+
if i < s.count, s[i] == UInt8(ascii: ",") { i += 1; continue }
|
|
168
|
+
try expect("]")
|
|
169
|
+
return a
|
|
170
|
+
}
|
|
171
|
+
case UInt8(ascii: "\""): return try string()
|
|
172
|
+
case UInt8(ascii: "t"): i += 4; return true
|
|
173
|
+
case UInt8(ascii: "f"): i += 5; return false
|
|
174
|
+
case UInt8(ascii: "n"): i += 4; return NSNull()
|
|
175
|
+
default:
|
|
176
|
+
let start = i
|
|
177
|
+
while i < s.count, "+-0123456789.eE".utf8.contains(s[i]) { i += 1 }
|
|
178
|
+
let text = String(decoding: s[start..<i], as: UTF8.self)
|
|
179
|
+
if let n = Int(text) { return n }
|
|
180
|
+
if let d = Double(text) { return d }
|
|
181
|
+
throw PPDecodeError(message: "bad JSON number \(text)")
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
mutating func hex4() throws -> UInt32 {
|
|
186
|
+
guard i + 4 <= s.count, let h = UInt32(String(decoding: s[i..<i + 4], as: UTF8.self), radix: 16) else {
|
|
187
|
+
throw PPDecodeError(message: "bad JSON unicode escape")
|
|
188
|
+
}
|
|
189
|
+
i += 4
|
|
190
|
+
return h
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
mutating func string() throws -> String {
|
|
194
|
+
guard i < s.count, s[i] == UInt8(ascii: "\"") else { throw PPDecodeError(message: "bad JSON string") }
|
|
195
|
+
i += 1
|
|
196
|
+
var out: [UInt8] = []
|
|
197
|
+
while i < s.count, s[i] != UInt8(ascii: "\"") {
|
|
198
|
+
if s[i] != UInt8(ascii: "\\") { out.append(s[i]); i += 1; continue }
|
|
199
|
+
i += 1
|
|
200
|
+
guard i < s.count else { break }
|
|
201
|
+
let c = s[i]
|
|
202
|
+
i += 1
|
|
203
|
+
switch c {
|
|
204
|
+
case UInt8(ascii: "n"): out.append(10)
|
|
205
|
+
case UInt8(ascii: "t"): out.append(9)
|
|
206
|
+
case UInt8(ascii: "r"): out.append(13)
|
|
207
|
+
case UInt8(ascii: "b"): out.append(8)
|
|
208
|
+
case UInt8(ascii: "f"): out.append(12)
|
|
209
|
+
case UInt8(ascii: "u"):
|
|
210
|
+
var cp = try hex4()
|
|
211
|
+
if cp >= 0xD800 && cp < 0xDC00, i + 6 <= s.count, s[i] == UInt8(ascii: "\\") {
|
|
212
|
+
i += 2
|
|
213
|
+
cp = 0x10000 + ((cp - 0xD800) << 10) + (try hex4() - 0xDC00)
|
|
214
|
+
}
|
|
215
|
+
out += Array(String(Unicode.Scalar(cp) ?? "\u{FFFD}").utf8)
|
|
216
|
+
default: out.append(c)
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
i += 1
|
|
220
|
+
return String(decoding: out, as: UTF8.self)
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
func ppQuote(_ s: String) -> String {
|
|
225
|
+
var out = "\""
|
|
226
|
+
for u in s.unicodeScalars {
|
|
227
|
+
switch u {
|
|
228
|
+
case "\"": out += "\\\""
|
|
229
|
+
case "\\": out += "\\\\"
|
|
230
|
+
case "\n": out += "\\n"
|
|
231
|
+
case "\r": out += "\\r"
|
|
232
|
+
case "\t": out += "\\t"
|
|
233
|
+
default:
|
|
234
|
+
if u.value < 0x20 { out += String(format: "\\u%04x", u.value) } else { out.unicodeScalars.append(u) }
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return out + "\""
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
func ppDbl(_ d: Double) -> String {
|
|
241
|
+
if d.isNaN { return "{\"$float\":\"nan\"}" }
|
|
242
|
+
if d.isInfinite { return d > 0 ? "{\"$float\":\"inf\"}" : "{\"$float\":\"-inf\"}" }
|
|
243
|
+
if d == 0 && d.sign == .minus { return "{\"$float\":\"-0.0\"}" }
|
|
244
|
+
if d == d.rounded() && abs(d) > 9007199254740992 { return "{\"$float\":\"\(d)\"}" } // like the Go adapter
|
|
245
|
+
return "\(d)"
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
func ppEnc(_ v: Any) -> String {
|
|
249
|
+
switch v {
|
|
250
|
+
case let b as Bool: return b ? "true" : "false"
|
|
251
|
+
case let i as any BinaryInteger: return "\(i)"
|
|
252
|
+
case let d as Double: return ppDbl(d)
|
|
253
|
+
case let f as Float: return f.isFinite ? "\(f)" : ppDbl(Double(f))
|
|
254
|
+
case let s as String: return ppQuote(s)
|
|
255
|
+
case let a as [Any]: return "[" + a.map(ppEnc).joined(separator: ",") + "]"
|
|
256
|
+
case is NSNull: return "null"
|
|
257
|
+
default: return ppQuote(String(describing: v))
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
func ppRaise(_ type: String, _ message: String) -> String {
|
|
262
|
+
return "{\"kind\":\"raise\",\"type\":" + ppQuote(type) + ",\"message\":" + ppQuote(message) + "}"
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
func ppInvoke(_ args: [Any]) throws -> Any {
|
|
266
|
+
func arg(_ i: Int) throws -> Any {
|
|
267
|
+
if i < args.count { return args[i] }
|
|
268
|
+
throw PPDecodeError(message: "missing argument \(i)")
|
|
269
|
+
}
|
|
270
|
+
__DECODE__
|
|
271
|
+
__CALL__
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
func ppOutcome(_ args: [Any]) -> String {
|
|
275
|
+
do {
|
|
276
|
+
let r = try ppInvoke(args)
|
|
277
|
+
return "{\"kind\":\"return\",\"value\":" + ppEnc(r) + "}"
|
|
278
|
+
} catch let e as PPDecodeError {
|
|
279
|
+
return ppRaise("TypeError", e.message)
|
|
280
|
+
} catch {
|
|
281
|
+
return ppRaise(String(describing: type(of: error)), String(describing: error))
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
setvbuf(stdout, nil, _IOLBF, 0)
|
|
286
|
+
let ppInput = FileHandle.standardInput.readDataToEndOfFile()
|
|
287
|
+
var ppParser = PPParser(s: [UInt8](ppInput))
|
|
288
|
+
let ppReq = (try? ppParser.value()) as? [String: Any] ?? [:]
|
|
289
|
+
let ppArgs = ppReq["args"] as? [Any] ?? []
|
|
290
|
+
let ppOut: String
|
|
291
|
+
if (ppReq["mode"] as? String) == "bench" {
|
|
292
|
+
let n = max((ppReq["iterations"] as? Int) ?? 1, 1)
|
|
293
|
+
var samples: [String] = []
|
|
294
|
+
for _ in 0..<n {
|
|
295
|
+
let t0 = DispatchTime.now().uptimeNanoseconds
|
|
296
|
+
_ = try? ppInvoke(ppArgs)
|
|
297
|
+
samples.append(String(DispatchTime.now().uptimeNanoseconds - t0))
|
|
298
|
+
}
|
|
299
|
+
ppOut = "{\"samples_ns\":[" + samples.joined(separator: ",") + "]}"
|
|
300
|
+
} else {
|
|
301
|
+
ppOut = "{\"outcome\":" + ppOutcome(ppArgs) + "}"
|
|
302
|
+
}
|
|
303
|
+
fflush(stdout)
|
|
304
|
+
if let path = ProcessInfo.processInfo.environment["PP_RESULT"] {
|
|
305
|
+
try? ppOut.write(toFile: path, atomically: false, encoding: .utf8)
|
|
306
|
+
}
|
|
307
|
+
'''
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def prepare(src, rel, unit, work):
|
|
311
|
+
if unit["kind"] != "function":
|
|
312
|
+
raise SystemExit("only top-level Swift functions can be recorded")
|
|
313
|
+
pkg_dir = os.path.join(src, os.path.dirname(rel))
|
|
314
|
+
sig = FUNC_RE.search(unit["source"])
|
|
315
|
+
decode, args = [], []
|
|
316
|
+
for i, p in enumerate(parse_params(sig.group(3))):
|
|
317
|
+
if p["kind"] != "positional":
|
|
318
|
+
raise SystemExit("variadic Swift parameters are not supported")
|
|
319
|
+
decode.append(f" let a{i}: {p['annotation']} = {dec(p['annotation'], f'(arg({i}))')}")
|
|
320
|
+
args.append(f"{p['label'] + ': ' if p['label'] else ''}a{i}")
|
|
321
|
+
call = f"{unit['name']}({', '.join(args)})"
|
|
322
|
+
is_void = not sig.group(5) or sig.group(5).strip() in ("Void", "()")
|
|
323
|
+
body = f" try {call}\n return NSNull()" if is_void else f" return try {call}"
|
|
324
|
+
files = []
|
|
325
|
+
for name in sorted(os.listdir(pkg_dir)): # `private` would hide functions from the driver file
|
|
326
|
+
if name.endswith(".swift") and name not in ("main.swift", "Package.swift") and not name.endswith("Tests.swift"):
|
|
327
|
+
p = os.path.join(pkg_dir, name)
|
|
328
|
+
code = re.sub(r"^(?:private|fileprivate)\s+", "", open(p, encoding="utf-8").read(), flags=re.M)
|
|
329
|
+
open(p, "w", encoding="utf-8").write(code)
|
|
330
|
+
files.append(name)
|
|
331
|
+
open(os.path.join(pkg_dir, "main.swift"), "w", encoding="utf-8").write(
|
|
332
|
+
DRIVER.replace("__DECODE__", "\n".join(decode)).replace("__CALL__", body))
|
|
333
|
+
out = os.path.join(work, "ppdrv")
|
|
334
|
+
env = dict(os.environ, HOME=work, TMPDIR=work)
|
|
335
|
+
subprocess.run(["swiftc", "-Onone", "-module-cache-path", os.path.join(work, "mc"), "-o", out, *files, "main.swift"],
|
|
336
|
+
cwd=pkg_dir, env=env, check=True, capture_output=True)
|
|
337
|
+
return [out]
|