ruby-anything 0.2.2 → 0.2.3

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.
@@ -1,133 +1,133 @@
1
- """Kotlin (JVM) support for the polyglot adapter.
2
-
3
- Analysis: public top-level `fun` declarations (no generics, no extension receivers, no vararg).
4
- Driver: all .kt files are compiled with kotlinc into `work/classes`; the generated Java `PpDriver`
5
- (shared with lang_java.py) calls the facade class (`<File>Kt`) directly, decoding args by the
6
- Kotlin parameter type mapped to its Java signature.
7
- """
8
- import os
9
- import re
10
- import subprocess
11
-
12
- from harness import match_brace, unit_record
13
- from lang_java import JVM_FLAGS, blank, compile_driver, driver_source, runtime as java_runtime, source_files, split_top
14
-
15
- EXTS = {".kt"}
16
- THROW = r"\bthrow\b|\brequire\(|\bcheck\(|\berror\(|\brequireNotNull\(|\bcheckNotNull\("
17
- FUN_RE = re.compile(r"^((?:(?:public|inline|tailrec|operator|infix)\s+)*)fun\s+(<[^>]*>\s*)?(\w+(?:<[^>]*>)?\.)?(\w+)\s*\(", re.M)
18
- ARRAYS = {"IntArray": "Int", "LongArray": "Long", "DoubleArray": "Double", "FloatArray": "Float", "ShortArray": "Short",
19
- "ByteArray": "Byte", "BooleanArray": "Boolean", "CharArray": "Char"}
20
- JAVA = {"Int": "int", "Long": "long", "Short": "short", "Byte": "byte", "Float": "float", "Double": "double",
21
- "Boolean": "boolean", "Char": "char", "String": "String"}
22
- BOX = {"int": "Integer", "long": "Long", "short": "Short", "byte": "Byte", "float": "Float", "double": "Double",
23
- "boolean": "Boolean", "char": "Character", "String": "String"}
24
-
25
-
26
- def runtime():
27
- return "kotlinc 1.3 on " + java_runtime()
28
-
29
-
30
- def kt_annotation(t):
31
- """Declared type, with the primitive array classes spelled Array<X> so the harness generates lists for them."""
32
- t = t.strip()
33
- return f"Array<{ARRAYS[t.rstrip('?')]}>" if t.rstrip("?") in ARRAYS else t
34
-
35
-
36
- def kt2java(t, boxed=False):
37
- t = re.sub(r"\s+", "", t)
38
- nullable = t.endswith("?")
39
- t = t.rstrip("?")
40
- if t in ARRAYS:
41
- return JAVA[ARRAYS[t]] + "[]"
42
- m = re.fullmatch(r"Array<(.+)>", t)
43
- if m:
44
- return kt2java(m.group(1), True) + "[]"
45
- m = re.fullmatch(r"(?:Mutable)?(?:List|Collection)<(.+)>", t)
46
- if m:
47
- return f"java.util.List<{kt2java(m.group(1), True)}>"
48
- if t in JAVA:
49
- return BOX[JAVA[t]] if boxed or nullable else JAVA[t]
50
- raise SystemExit(f"unsupported Kotlin parameter type {t!r}: only primitives, String, arrays and lists of those can be recorded")
51
-
52
-
53
- def parse_params(raw, normalize=True):
54
- params = []
55
- for part in split_top(raw):
56
- part = re.sub(r"@\w+\s*", "", part)
57
- m = re.match(r"((?:vararg|noinline|crossinline)\s+)?(?:val\s+|var\s+)?(\w+)\s*:\s*(.+?)(?:\s*=\s*(.+))?$", part, re.S)
58
- if m:
59
- params.append({"name": m.group(2), "annotation": kt_annotation(m.group(3)) if normalize else m.group(3).strip(), "default": (m.group(4) or "").strip() or None,
60
- "kind": "varargs" if m.group(1) else "positional"})
61
- return params
62
-
63
-
64
- def paren_end(clean, open_index):
65
- depth = 0
66
- for i in range(open_index, len(clean)):
67
- depth += clean[i] == "("
68
- depth -= clean[i] == ")"
69
- if depth == 0:
70
- return i
71
- return len(clean) - 1
72
-
73
-
74
- def expr_end(clean, start):
75
- """End of an expression body: first newline at bracket depth 0 followed by a line that is not indented."""
76
- depth = 0
77
- for i in range(start, len(clean)):
78
- c = clean[i]
79
- depth += c in "({["
80
- depth -= c in ")}]"
81
- if c == "\n" and depth <= 0 and not re.match(r"[ \t]+\S", clean[i + 1:i + 1 + 200]):
82
- return i - 1
83
- return len(clean) - 1
84
-
85
-
86
- def analyze_file(rel, text):
87
- clean = blank(text)
88
- pkg = (re.search(r"^package\s+([\w.]+)", clean, re.M) or [None, ""])[1]
89
- module = pkg or os.path.splitext(os.path.basename(rel))[0]
90
- units = []
91
- for m in FUN_RE.finditer(clean):
92
- if m.group(2) or m.group(3): # generic or extension functions are not recordable
93
- continue
94
- close = paren_end(clean, m.end() - 1)
95
- tail = re.match(r"\s*(?::\s*([^={\n]+?))?\s*([{=])", clean[close + 1:])
96
- if not tail:
97
- continue
98
- params = parse_params(text[m.end():close])
99
- if any(p["kind"] == "varargs" for p in params):
100
- continue
101
- body_at = close + 1 + tail.end() - 1
102
- end = match_brace(text, body_at) if tail.group(2) == "{" else expr_end(clean, body_at)
103
- units.append(unit_record(rel, module, m.group(4), m.start(), end, text, params,
104
- (tail.group(1) or "").strip() or None, THROW))
105
- return units
106
-
107
-
108
- def stdlib():
109
- lib = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath("/usr/bin/kotlinc"))), "lib")
110
- for name in ("kotlin-stdlib.jar", "kotlin-stdlib-minimal-for-test.jar"):
111
- if os.path.exists(os.path.join(lib, name)):
112
- return os.path.join(lib, name)
113
- raise SystemExit("kotlin-stdlib.jar not found next to kotlinc")
114
-
115
-
116
- def prepare(src, rel, unit, work):
117
- text = open(os.path.join(src, rel), encoding="utf-8", errors="replace").read()
118
- pkg = re.search(r"^package\s+([\w.]+)", text, re.M)
119
- jvm_name = re.search(r'@file:JvmName\(\s*"(\w+)"\s*\)', text)
120
- stem = re.sub(r"\W", "_", os.path.splitext(os.path.basename(rel))[0])
121
- facade = jvm_name.group(1) if jvm_name else stem[:1].upper() + stem[1:] + "Kt"
122
- cls = (pkg.group(1) + "." if pkg else "") + facade
123
- args = ", ".join(f"a{i}" for i in range(len(unit["params"])))
124
- src_text = unit["source"] # re-read the signature: unit annotations spell IntArray as Array<Int>
125
- declared = parse_params(src_text[src_text.index("(") + 1:paren_end(src_text, src_text.index("("))], normalize=False)
126
- driver = driver_source([kt2java(p["annotation"]) for p in declared], f"{cls}.{unit['name']}({args})",
127
- unit["returns"] == "Unit", os.path.basename(rel))
128
- classes = os.path.join(work, "classes")
129
- os.makedirs(classes, exist_ok=True)
130
- lib = stdlib()
131
- subprocess.run(["kotlinc", "-nowarn", "-d", classes] + source_files(src, ".kt"), check=True, capture_output=True, cwd=work,
132
- env=dict(os.environ, HOME=work, JAVA_OPTS="-Xmx512m -XX:+UseSerialGC -Xshare:off"))
133
- return compile_driver(work, driver, lib, [])
1
+ """Kotlin (JVM) support for the polyglot adapter.
2
+
3
+ Analysis: public top-level `fun` declarations (no generics, no extension receivers, no vararg).
4
+ Driver: all .kt files are compiled with kotlinc into `work/classes`; the generated Java `PpDriver`
5
+ (shared with lang_java.py) calls the facade class (`<File>Kt`) directly, decoding args by the
6
+ Kotlin parameter type mapped to its Java signature.
7
+ """
8
+ import os
9
+ import re
10
+ import subprocess
11
+
12
+ from harness import match_brace, unit_record
13
+ from lang_java import JVM_FLAGS, blank, compile_driver, driver_source, runtime as java_runtime, source_files, split_top
14
+
15
+ EXTS = {".kt"}
16
+ THROW = r"\bthrow\b|\brequire\(|\bcheck\(|\berror\(|\brequireNotNull\(|\bcheckNotNull\("
17
+ FUN_RE = re.compile(r"^((?:(?:public|inline|tailrec|operator|infix)\s+)*)fun\s+(<[^>]*>\s*)?(\w+(?:<[^>]*>)?\.)?(\w+)\s*\(", re.M)
18
+ ARRAYS = {"IntArray": "Int", "LongArray": "Long", "DoubleArray": "Double", "FloatArray": "Float", "ShortArray": "Short",
19
+ "ByteArray": "Byte", "BooleanArray": "Boolean", "CharArray": "Char"}
20
+ JAVA = {"Int": "int", "Long": "long", "Short": "short", "Byte": "byte", "Float": "float", "Double": "double",
21
+ "Boolean": "boolean", "Char": "char", "String": "String"}
22
+ BOX = {"int": "Integer", "long": "Long", "short": "Short", "byte": "Byte", "float": "Float", "double": "Double",
23
+ "boolean": "Boolean", "char": "Character", "String": "String"}
24
+
25
+
26
+ def runtime():
27
+ return "kotlinc 1.3 on " + java_runtime()
28
+
29
+
30
+ def kt_annotation(t):
31
+ """Declared type, with the primitive array classes spelled Array<X> so the harness generates lists for them."""
32
+ t = t.strip()
33
+ return f"Array<{ARRAYS[t.rstrip('?')]}>" if t.rstrip("?") in ARRAYS else t
34
+
35
+
36
+ def kt2java(t, boxed=False):
37
+ t = re.sub(r"\s+", "", t)
38
+ nullable = t.endswith("?")
39
+ t = t.rstrip("?")
40
+ if t in ARRAYS:
41
+ return JAVA[ARRAYS[t]] + "[]"
42
+ m = re.fullmatch(r"Array<(.+)>", t)
43
+ if m:
44
+ return kt2java(m.group(1), True) + "[]"
45
+ m = re.fullmatch(r"(?:Mutable)?(?:List|Collection)<(.+)>", t)
46
+ if m:
47
+ return f"java.util.List<{kt2java(m.group(1), True)}>"
48
+ if t in JAVA:
49
+ return BOX[JAVA[t]] if boxed or nullable else JAVA[t]
50
+ raise SystemExit(f"unsupported Kotlin parameter type {t!r}: only primitives, String, arrays and lists of those can be recorded")
51
+
52
+
53
+ def parse_params(raw, normalize=True):
54
+ params = []
55
+ for part in split_top(raw):
56
+ part = re.sub(r"@\w+\s*", "", part)
57
+ m = re.match(r"((?:vararg|noinline|crossinline)\s+)?(?:val\s+|var\s+)?(\w+)\s*:\s*(.+?)(?:\s*=\s*(.+))?$", part, re.S)
58
+ if m:
59
+ params.append({"name": m.group(2), "annotation": kt_annotation(m.group(3)) if normalize else m.group(3).strip(), "default": (m.group(4) or "").strip() or None,
60
+ "kind": "varargs" if m.group(1) else "positional"})
61
+ return params
62
+
63
+
64
+ def paren_end(clean, open_index):
65
+ depth = 0
66
+ for i in range(open_index, len(clean)):
67
+ depth += clean[i] == "("
68
+ depth -= clean[i] == ")"
69
+ if depth == 0:
70
+ return i
71
+ return len(clean) - 1
72
+
73
+
74
+ def expr_end(clean, start):
75
+ """End of an expression body: first newline at bracket depth 0 followed by a line that is not indented."""
76
+ depth = 0
77
+ for i in range(start, len(clean)):
78
+ c = clean[i]
79
+ depth += c in "({["
80
+ depth -= c in ")}]"
81
+ if c == "\n" and depth <= 0 and not re.match(r"[ \t]+\S", clean[i + 1:i + 1 + 200]):
82
+ return i - 1
83
+ return len(clean) - 1
84
+
85
+
86
+ def analyze_file(rel, text):
87
+ clean = blank(text)
88
+ pkg = (re.search(r"^package\s+([\w.]+)", clean, re.M) or [None, ""])[1]
89
+ module = pkg or os.path.splitext(os.path.basename(rel))[0]
90
+ units = []
91
+ for m in FUN_RE.finditer(clean):
92
+ if m.group(2) or m.group(3): # generic or extension functions are not recordable
93
+ continue
94
+ close = paren_end(clean, m.end() - 1)
95
+ tail = re.match(r"\s*(?::\s*([^={\n]+?))?\s*([{=])", clean[close + 1:])
96
+ if not tail:
97
+ continue
98
+ params = parse_params(text[m.end():close])
99
+ if any(p["kind"] == "varargs" for p in params):
100
+ continue
101
+ body_at = close + 1 + tail.end() - 1
102
+ end = match_brace(text, body_at) if tail.group(2) == "{" else expr_end(clean, body_at)
103
+ units.append(unit_record(rel, module, m.group(4), m.start(), end, text, params,
104
+ (tail.group(1) or "").strip() or None, THROW))
105
+ return units
106
+
107
+
108
+ def stdlib():
109
+ lib = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath("/usr/bin/kotlinc"))), "lib")
110
+ for name in ("kotlin-stdlib.jar", "kotlin-stdlib-minimal-for-test.jar"):
111
+ if os.path.exists(os.path.join(lib, name)):
112
+ return os.path.join(lib, name)
113
+ raise SystemExit("kotlin-stdlib.jar not found next to kotlinc")
114
+
115
+
116
+ def prepare(src, rel, unit, work):
117
+ text = open(os.path.join(src, rel), encoding="utf-8", errors="replace").read()
118
+ pkg = re.search(r"^package\s+([\w.]+)", text, re.M)
119
+ jvm_name = re.search(r'@file:JvmName\(\s*"(\w+)"\s*\)', text)
120
+ stem = re.sub(r"\W", "_", os.path.splitext(os.path.basename(rel))[0])
121
+ facade = jvm_name.group(1) if jvm_name else stem[:1].upper() + stem[1:] + "Kt"
122
+ cls = (pkg.group(1) + "." if pkg else "") + facade
123
+ args = ", ".join(f"a{i}" for i in range(len(unit["params"])))
124
+ src_text = unit["source"] # re-read the signature: unit annotations spell IntArray as Array<Int>
125
+ declared = parse_params(src_text[src_text.index("(") + 1:paren_end(src_text, src_text.index("("))], normalize=False)
126
+ driver = driver_source([kt2java(p["annotation"]) for p in declared], f"{cls}.{unit['name']}({args})",
127
+ unit["returns"] == "Unit", os.path.basename(rel))
128
+ classes = os.path.join(work, "classes")
129
+ os.makedirs(classes, exist_ok=True)
130
+ lib = stdlib()
131
+ subprocess.run(["kotlinc", "-nowarn", "-d", classes] + source_files(src, ".kt"), check=True, capture_output=True, cwd=work,
132
+ env=dict(os.environ, HOME=work, JAVA_OPTS="-Xmx512m -XX:+UseSerialGC -Xshare:off"))
133
+ return compile_driver(work, driver, lib, [])
@@ -1,156 +1,156 @@
1
- """PHP support for the polyglot adapter.
2
-
3
- Analysis: top-level `function` declarations (methods inside classes are skipped).
4
- Driver: nothing compiles; prepare writes pp_driver.php, which requires the target file, decodes JSON args
5
- (with $float tags), calls the function, maps thrown Throwables to raise outcomes and encodes the result
6
- (floats stay floats via json_encode's serialize_precision=-1).
7
- """
8
- import json
9
- import os
10
- import re
11
- import subprocess
12
-
13
- from harness import match_brace, unit_record
14
-
15
- EXTS = {".php"}
16
- THROW = r"\bthrow\b"
17
- FUNC_RE = re.compile(r"^function\s+&?([A-Za-z_]\w*)\s*\(([^)]*)\)\s*(?::\s*([?\w|\x5c]+))?\s*\{", re.M)
18
- PARAM_RE = re.compile(r"^(?:([?\w|\x5c]+)\s+)?(&)?(\.\.\.)?\$(\w+)\s*(?:=\s*(.+))?$", re.S)
19
-
20
-
21
- def runtime():
22
- out = subprocess.run(["php", "-r", "echo PHP_VERSION;"], capture_output=True, text=True).stdout.strip()
23
- return "php " + out
24
-
25
-
26
- def imports(text):
27
- return sorted(set(re.findall(r"(?:require|include)(?:_once)?\s*\(?\s*['\"]([^'\"]+)['\"]", text)) |
28
- set(re.findall(r"^use\s+([\w\x5c]+)", text, re.M)))
29
-
30
-
31
- def split_params(raw):
32
- parts, depth, cur = [], 0, ""
33
- for c in raw:
34
- depth += c in "([" and 1 or (c in ")]" and -1 or 0)
35
- if c == "," and depth == 0:
36
- parts.append(cur)
37
- cur = ""
38
- else:
39
- cur += c
40
- return parts + [cur]
41
-
42
-
43
- def parse_params(raw):
44
- params = []
45
- for part in [p.strip() for p in split_params(raw) if p.strip()]:
46
- m = PARAM_RE.match(part)
47
- if m:
48
- params.append({"name": m.group(4), "annotation": m.group(1), "default": (m.group(5) or "").strip() or None,
49
- "kind": "varargs" if m.group(3) else "positional"})
50
- return params
51
-
52
-
53
- def analyze_file(rel, text):
54
- ns = (re.search(r"^namespace\s+([\w\x5c]+)\s*;", text, re.M) or [None, ""])[1]
55
- module = ns.replace("\\", ".") or os.path.splitext(rel)[0].replace("/", ".")
56
- units = []
57
- for m in FUNC_RE.finditer(text):
58
- end = match_brace(text, m.end() - 1)
59
- units.append(unit_record(rel, module, m.group(1), m.start(), end, text, parse_params(m.group(2)), m.group(3), THROW))
60
- return units
61
-
62
-
63
- DRIVER = r'''<?php
64
- error_reporting(E_ALL & ~E_DEPRECATED);
65
- $ppTarget = realpath(__TARGET__);
66
- $ppFn = __FN__;
67
-
68
- function ppSpecial($s) {
69
- switch ($s) {
70
- case "nan": return NAN;
71
- case "inf": return INF;
72
- case "-inf": return -INF;
73
- case "-0.0": return -0.0;
74
- }
75
- return (float)$s;
76
- }
77
-
78
- function ppDec($v) {
79
- if (is_array($v)) {
80
- if (count($v) === 1 && isset($v['$float']) && is_string($v['$float'])) {
81
- return ppSpecial($v['$float']);
82
- }
83
- return array_map('ppDec', $v);
84
- }
85
- return $v;
86
- }
87
-
88
- function ppEnc($v) {
89
- if (is_float($v)) {
90
- if (is_nan($v)) return ['$float' => 'nan'];
91
- if (is_infinite($v)) return ['$float' => $v > 0 ? 'inf' : '-inf'];
92
- if ($v == 0 && fdiv(1, $v) < 0) return ['$float' => '-0.0'];
93
- if ($v == floor($v) && abs($v) > 9007199254740992) return ['$float' => json_encode($v)];
94
- return $v;
95
- }
96
- if (is_array($v)) {
97
- if ($v === []) return [];
98
- $out = array_map('ppEnc', $v);
99
- return array_is_list($v) ? $out : (object)$out;
100
- }
101
- if (is_object($v)) return ppEnc(get_object_vars($v));
102
- return $v;
103
- }
104
-
105
- function ppWrite($v) {
106
- ini_set('serialize_precision', '-1');
107
- file_put_contents(getenv('PP_RESULT'), json_encode($v, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION | JSON_INVALID_UTF8_SUBSTITUTE));
108
- }
109
-
110
- function ppLine($e, $target) {
111
- if (realpath($e->getFile()) === $target) return $e->getLine();
112
- foreach ($e->getTrace() as $f) {
113
- if (isset($f['file']) && realpath($f['file']) === $target) return $f['line'];
114
- }
115
- return null;
116
- }
117
-
118
- function ppCall($fn, $args, $target) {
119
- try {
120
- return ['kind' => 'return', 'value' => ppEnc($fn(...$args))];
121
- } catch (Throwable $e) {
122
- $o = ['kind' => 'raise', 'type' => get_class($e), 'message' => $e->getMessage()];
123
- $line = ppLine($e, $target);
124
- if ($line) $o['raise_line'] = $line;
125
- return $o;
126
- }
127
- }
128
-
129
- require_once $ppTarget;
130
- $req = json_decode(stream_get_contents(STDIN), true);
131
- $args = ppDec($req['args'] ?? []);
132
- if (($req['mode'] ?? 'call') === 'bench') {
133
- $samples = [];
134
- for ($i = 0; $i < ($req['iterations'] ?? 1); $i++) {
135
- $t = hrtime(true);
136
- ob_start();
137
- ppCall($ppFn, $args, $ppTarget);
138
- ob_end_clean();
139
- $samples[] = hrtime(true) - $t;
140
- }
141
- ppWrite(['samples_ns' => $samples]);
142
- } else {
143
- ppWrite(['outcome' => ppCall($ppFn, $args, $ppTarget)]);
144
- }
145
- '''
146
-
147
-
148
- def prepare(src, rel, unit, work):
149
- if unit["kind"] != "function":
150
- raise SystemExit("only top-level PHP functions can be recorded")
151
- ns = (re.search(r"^namespace\s+([\w\x5c]+)\s*;", open(os.path.join(src, rel), encoding="utf-8", errors="replace").read(), re.M) or [None, ""])[1]
152
- fn = ("\\" + ns + "\\" if ns else "") + unit["name"]
153
- code = DRIVER.replace("__TARGET__", json.dumps(os.path.join(src, rel))).replace("__FN__", json.dumps(fn))
154
- path = os.path.join(work, "pp_driver.php")
155
- open(path, "w", encoding="utf-8").write(code)
156
- return ["php", "-d", "display_errors=stderr", "-d", "serialize_precision=-1", path]
1
+ """PHP support for the polyglot adapter.
2
+
3
+ Analysis: top-level `function` declarations (methods inside classes are skipped).
4
+ Driver: nothing compiles; prepare writes pp_driver.php, which requires the target file, decodes JSON args
5
+ (with $float tags), calls the function, maps thrown Throwables to raise outcomes and encodes the result
6
+ (floats stay floats via json_encode's serialize_precision=-1).
7
+ """
8
+ import json
9
+ import os
10
+ import re
11
+ import subprocess
12
+
13
+ from harness import match_brace, unit_record
14
+
15
+ EXTS = {".php"}
16
+ THROW = r"\bthrow\b"
17
+ FUNC_RE = re.compile(r"^function\s+&?([A-Za-z_]\w*)\s*\(([^)]*)\)\s*(?::\s*([?\w|\x5c]+))?\s*\{", re.M)
18
+ PARAM_RE = re.compile(r"^(?:([?\w|\x5c]+)\s+)?(&)?(\.\.\.)?\$(\w+)\s*(?:=\s*(.+))?$", re.S)
19
+
20
+
21
+ def runtime():
22
+ out = subprocess.run(["php", "-r", "echo PHP_VERSION;"], capture_output=True, text=True).stdout.strip()
23
+ return "php " + out
24
+
25
+
26
+ def imports(text):
27
+ return sorted(set(re.findall(r"(?:require|include)(?:_once)?\s*\(?\s*['\"]([^'\"]+)['\"]", text)) |
28
+ set(re.findall(r"^use\s+([\w\x5c]+)", text, re.M)))
29
+
30
+
31
+ def split_params(raw):
32
+ parts, depth, cur = [], 0, ""
33
+ for c in raw:
34
+ depth += c in "([" and 1 or (c in ")]" and -1 or 0)
35
+ if c == "," and depth == 0:
36
+ parts.append(cur)
37
+ cur = ""
38
+ else:
39
+ cur += c
40
+ return parts + [cur]
41
+
42
+
43
+ def parse_params(raw):
44
+ params = []
45
+ for part in [p.strip() for p in split_params(raw) if p.strip()]:
46
+ m = PARAM_RE.match(part)
47
+ if m:
48
+ params.append({"name": m.group(4), "annotation": m.group(1), "default": (m.group(5) or "").strip() or None,
49
+ "kind": "varargs" if m.group(3) else "positional"})
50
+ return params
51
+
52
+
53
+ def analyze_file(rel, text):
54
+ ns = (re.search(r"^namespace\s+([\w\x5c]+)\s*;", text, re.M) or [None, ""])[1]
55
+ module = ns.replace("\\", ".") or os.path.splitext(rel)[0].replace("/", ".")
56
+ units = []
57
+ for m in FUNC_RE.finditer(text):
58
+ end = match_brace(text, m.end() - 1)
59
+ units.append(unit_record(rel, module, m.group(1), m.start(), end, text, parse_params(m.group(2)), m.group(3), THROW))
60
+ return units
61
+
62
+
63
+ DRIVER = r'''<?php
64
+ error_reporting(E_ALL & ~E_DEPRECATED);
65
+ $ppTarget = realpath(__TARGET__);
66
+ $ppFn = __FN__;
67
+
68
+ function ppSpecial($s) {
69
+ switch ($s) {
70
+ case "nan": return NAN;
71
+ case "inf": return INF;
72
+ case "-inf": return -INF;
73
+ case "-0.0": return -0.0;
74
+ }
75
+ return (float)$s;
76
+ }
77
+
78
+ function ppDec($v) {
79
+ if (is_array($v)) {
80
+ if (count($v) === 1 && isset($v['$float']) && is_string($v['$float'])) {
81
+ return ppSpecial($v['$float']);
82
+ }
83
+ return array_map('ppDec', $v);
84
+ }
85
+ return $v;
86
+ }
87
+
88
+ function ppEnc($v) {
89
+ if (is_float($v)) {
90
+ if (is_nan($v)) return ['$float' => 'nan'];
91
+ if (is_infinite($v)) return ['$float' => $v > 0 ? 'inf' : '-inf'];
92
+ if ($v == 0 && fdiv(1, $v) < 0) return ['$float' => '-0.0'];
93
+ if ($v == floor($v) && abs($v) > 9007199254740992) return ['$float' => json_encode($v)];
94
+ return $v;
95
+ }
96
+ if (is_array($v)) {
97
+ if ($v === []) return [];
98
+ $out = array_map('ppEnc', $v);
99
+ return array_is_list($v) ? $out : (object)$out;
100
+ }
101
+ if (is_object($v)) return ppEnc(get_object_vars($v));
102
+ return $v;
103
+ }
104
+
105
+ function ppWrite($v) {
106
+ ini_set('serialize_precision', '-1');
107
+ file_put_contents(getenv('PP_RESULT'), json_encode($v, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION | JSON_INVALID_UTF8_SUBSTITUTE));
108
+ }
109
+
110
+ function ppLine($e, $target) {
111
+ if (realpath($e->getFile()) === $target) return $e->getLine();
112
+ foreach ($e->getTrace() as $f) {
113
+ if (isset($f['file']) && realpath($f['file']) === $target) return $f['line'];
114
+ }
115
+ return null;
116
+ }
117
+
118
+ function ppCall($fn, $args, $target) {
119
+ try {
120
+ return ['kind' => 'return', 'value' => ppEnc($fn(...$args))];
121
+ } catch (Throwable $e) {
122
+ $o = ['kind' => 'raise', 'type' => get_class($e), 'message' => $e->getMessage()];
123
+ $line = ppLine($e, $target);
124
+ if ($line) $o['raise_line'] = $line;
125
+ return $o;
126
+ }
127
+ }
128
+
129
+ require_once $ppTarget;
130
+ $req = json_decode(stream_get_contents(STDIN), true);
131
+ $args = ppDec($req['args'] ?? []);
132
+ if (($req['mode'] ?? 'call') === 'bench') {
133
+ $samples = [];
134
+ for ($i = 0; $i < ($req['iterations'] ?? 1); $i++) {
135
+ $t = hrtime(true);
136
+ ob_start();
137
+ ppCall($ppFn, $args, $ppTarget);
138
+ ob_end_clean();
139
+ $samples[] = hrtime(true) - $t;
140
+ }
141
+ ppWrite(['samples_ns' => $samples]);
142
+ } else {
143
+ ppWrite(['outcome' => ppCall($ppFn, $args, $ppTarget)]);
144
+ }
145
+ '''
146
+
147
+
148
+ def prepare(src, rel, unit, work):
149
+ if unit["kind"] != "function":
150
+ raise SystemExit("only top-level PHP functions can be recorded")
151
+ ns = (re.search(r"^namespace\s+([\w\x5c]+)\s*;", open(os.path.join(src, rel), encoding="utf-8", errors="replace").read(), re.M) or [None, ""])[1]
152
+ fn = ("\\" + ns + "\\" if ns else "") + unit["name"]
153
+ code = DRIVER.replace("__TARGET__", json.dumps(os.path.join(src, rel))).replace("__FN__", json.dumps(fn))
154
+ path = os.path.join(work, "pp_driver.php")
155
+ open(path, "w", encoding="utf-8").write(code)
156
+ return ["php", "-d", "display_errors=stderr", "-d", "serialize_precision=-1", path]