ruby-anything 0.2.1 → 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,148 +1,148 @@
1
- """Plain-Ruby (non-Rails source) support for the polyglot adapter.
2
-
3
- Analysis: top-level `def name` and `def self.name` (module/class functions). Ruby has no types, so
4
- annotations come from YARD `# @param x [Type]` comments, else from a literal default value.
5
- Driver: pp_driver.rb loads the target file, decodes JSON args (with $float tags), finds the function on
6
- the module(s) declared in the file (or Object for top-level defs), and maps exceptions to raise outcomes.
7
- Run with `ruby --disable-gems`; only stdlib `json` is required.
8
- """
9
- import json
10
- import os
11
- import re
12
- import subprocess
13
-
14
- from harness import unit_record
15
-
16
- EXTS = {".rb"}
17
- THROW = r"\b(raise|fail)\b"
18
- DEF_RE = re.compile(r"^([ \t]*)def\s+(?:self\.)?([A-Za-z_]\w*[?!]?)\s*(\(([^)]*)\))?([^\n]*)", re.M)
19
- LITERAL_TYPES = [(r"^-?\d+$", "Integer"), (r"^-?\d+\.\d+$", "Float"), (r"^[\"']", "String"), (r"^(true|false)$", "bool"), (r"^\[", "Array")]
20
-
21
-
22
- def runtime():
23
- return "ruby " + subprocess.run(["ruby", "-e", "print RUBY_VERSION"], capture_output=True, text=True).stdout.strip()
24
-
25
-
26
- def imports(text):
27
- return sorted(set(re.findall(r"^\s*require(?:_relative)?\s+['\"]([^'\"]+)['\"]", text, re.M)))
28
-
29
-
30
- def parse_params(raw, comment):
31
- types = dict(re.findall(r"@param\s+(\w+)\s+\[([^\]]+)\]", comment or ""))
32
- params = []
33
- for part in [p.strip() for p in (raw or "").split(",") if p.strip()]:
34
- kind, default = "positional", None
35
- if part.startswith("&"):
36
- continue
37
- if part.startswith("**"):
38
- kind, name = "kwargs", part[2:]
39
- elif part.startswith("*"):
40
- kind, name = "varargs", part[1:]
41
- else:
42
- m = re.match(r"(\w+)(:)?\s*(.*)$", part)
43
- name, default = m.group(1), m.group(3).lstrip("=").strip() or None
44
- if m.group(2):
45
- kind = "keyword"
46
- ann = types.get(name)
47
- if not ann and default:
48
- ann = next((t for rx, t in LITERAL_TYPES if re.match(rx, default)), None)
49
- params.append({"name": name, "annotation": ann, "default": default, "kind": kind})
50
- return params
51
-
52
-
53
- def analyze_file(rel, text):
54
- module = os.path.splitext(rel)[0].replace("/", ".")
55
- units = []
56
- for m in DEF_RE.finditer(text):
57
- indent, name, _paren, raw, rest = m.groups()
58
- if re.match(r"^\s*=", rest) or re.match(r"^\s*\(?.*\)\s*=", rest): # endless def: one line
59
- end = m.end() - 1
60
- else:
61
- em = re.compile(r"^" + indent + r"end\b", re.M).search(text, m.end())
62
- end = em.end() - 1 if em else len(text) - 1
63
- before = text[:m.start()].rstrip().split("\n")
64
- comment = "\n".join(l for l in before[-6:] if l.strip().startswith("#"))
65
- units.append(unit_record(rel, module, name, m.start(), end, text, parse_params(raw, comment), None, THROW))
66
- return units
67
-
68
-
69
- DRIVER = r'''require "json"
70
- TARGET = File.realpath(__TARGET__)
71
- FN = __FN__
72
- MODS = __MODS__
73
-
74
- def pp_special(s)
75
- case s
76
- when "nan" then Float::NAN
77
- when "inf" then Float::INFINITY
78
- when "-inf" then -Float::INFINITY
79
- when "-0.0" then -0.0
80
- else s.to_f
81
- end
82
- end
83
-
84
- def pp_dec(v)
85
- case v
86
- when Hash then v.size == 1 && v["$float"].is_a?(String) ? pp_special(v["$float"]) : v.transform_values { |x| pp_dec(x) }
87
- when Array then v.map { |x| pp_dec(x) }
88
- else v
89
- end
90
- end
91
-
92
- def pp_enc(v)
93
- case v
94
- when Float
95
- return { "$float" => "nan" } if v.nan?
96
- return { "$float" => v > 0 ? "inf" : "-inf" } if v.infinite?
97
- return { "$float" => "-0.0" } if v.zero? && 1.0 / v < 0
98
- return { "$float" => v.to_s } if v == v.floor && v.abs > 2**53
99
- v
100
- when Array then v.map { |x| pp_enc(x) }
101
- when Hash then v.to_h { |k, x| [k.to_s, pp_enc(x)] }
102
- when Symbol then v.to_s
103
- when nil, true, false, Integer, String then v
104
- else v.to_s
105
- end
106
- end
107
-
108
- def pp_line(e)
109
- loc = (e.backtrace_locations || []).find { |l| File.realpath(l.absolute_path || l.path) == TARGET rescue false }
110
- loc&.lineno
111
- end
112
-
113
- def pp_call(recv, args)
114
- { "kind" => "return", "value" => pp_enc(recv.send(FN, *args)) }
115
- rescue Exception => e # rubocop:disable Lint/RescueException
116
- o = { "kind" => "raise", "type" => e.class.name, "message" => e.message }
117
- line = pp_line(e)
118
- o["raise_line"] = line if line
119
- o
120
- end
121
-
122
- load TARGET
123
- recv = MODS.map { |m| Object.const_get(m) rescue nil }.compact.find { |m| m.respond_to?(FN) } || self
124
- req = JSON.parse($stdin.read)
125
- args = pp_dec(req["args"] || [])
126
- if req["mode"] == "bench"
127
- samples = Array.new(req["iterations"] || 1) do
128
- t = Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)
129
- pp_call(recv, args)
130
- Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond) - t
131
- end
132
- File.write(ENV["PP_RESULT"], JSON.generate("samples_ns" => samples))
133
- else
134
- File.write(ENV["PP_RESULT"], JSON.generate("outcome" => pp_call(recv, args)))
135
- end
136
- '''
137
-
138
-
139
- def prepare(src, rel, unit, work):
140
- if unit["kind"] != "function":
141
- raise SystemExit("only top-level Ruby functions can be recorded")
142
- text = open(os.path.join(src, rel), encoding="utf-8", errors="replace").read()
143
- mods = re.findall(r"^\s*(?:module|class)\s+([A-Z]\w*(?:::[A-Z]\w*)*)", text, re.M)
144
- code = DRIVER.replace("__TARGET__", json.dumps(os.path.join(src, rel))).replace("__FN__", json.dumps(unit["name"])) \
145
- .replace("__MODS__", json.dumps(mods))
146
- path = os.path.join(work, "pp_driver.rb")
147
- open(path, "w", encoding="utf-8").write(code)
148
- return ["ruby", "--disable-gems", path]
1
+ """Plain-Ruby (non-Rails source) support for the polyglot adapter.
2
+
3
+ Analysis: top-level `def name` and `def self.name` (module/class functions). Ruby has no types, so
4
+ annotations come from YARD `# @param x [Type]` comments, else from a literal default value.
5
+ Driver: pp_driver.rb loads the target file, decodes JSON args (with $float tags), finds the function on
6
+ the module(s) declared in the file (or Object for top-level defs), and maps exceptions to raise outcomes.
7
+ Run with `ruby --disable-gems`; only stdlib `json` is required.
8
+ """
9
+ import json
10
+ import os
11
+ import re
12
+ import subprocess
13
+
14
+ from harness import unit_record
15
+
16
+ EXTS = {".rb"}
17
+ THROW = r"\b(raise|fail)\b"
18
+ DEF_RE = re.compile(r"^([ \t]*)def\s+(?:self\.)?([A-Za-z_]\w*[?!]?)\s*(\(([^)]*)\))?([^\n]*)", re.M)
19
+ LITERAL_TYPES = [(r"^-?\d+$", "Integer"), (r"^-?\d+\.\d+$", "Float"), (r"^[\"']", "String"), (r"^(true|false)$", "bool"), (r"^\[", "Array")]
20
+
21
+
22
+ def runtime():
23
+ return "ruby " + subprocess.run(["ruby", "-e", "print RUBY_VERSION"], capture_output=True, text=True).stdout.strip()
24
+
25
+
26
+ def imports(text):
27
+ return sorted(set(re.findall(r"^\s*require(?:_relative)?\s+['\"]([^'\"]+)['\"]", text, re.M)))
28
+
29
+
30
+ def parse_params(raw, comment):
31
+ types = dict(re.findall(r"@param\s+(\w+)\s+\[([^\]]+)\]", comment or ""))
32
+ params = []
33
+ for part in [p.strip() for p in (raw or "").split(",") if p.strip()]:
34
+ kind, default = "positional", None
35
+ if part.startswith("&"):
36
+ continue
37
+ if part.startswith("**"):
38
+ kind, name = "kwargs", part[2:]
39
+ elif part.startswith("*"):
40
+ kind, name = "varargs", part[1:]
41
+ else:
42
+ m = re.match(r"(\w+)(:)?\s*(.*)$", part)
43
+ name, default = m.group(1), m.group(3).lstrip("=").strip() or None
44
+ if m.group(2):
45
+ kind = "keyword"
46
+ ann = types.get(name)
47
+ if not ann and default:
48
+ ann = next((t for rx, t in LITERAL_TYPES if re.match(rx, default)), None)
49
+ params.append({"name": name, "annotation": ann, "default": default, "kind": kind})
50
+ return params
51
+
52
+
53
+ def analyze_file(rel, text):
54
+ module = os.path.splitext(rel)[0].replace("/", ".")
55
+ units = []
56
+ for m in DEF_RE.finditer(text):
57
+ indent, name, _paren, raw, rest = m.groups()
58
+ if re.match(r"^\s*=", rest) or re.match(r"^\s*\(?.*\)\s*=", rest): # endless def: one line
59
+ end = m.end() - 1
60
+ else:
61
+ em = re.compile(r"^" + indent + r"end\b", re.M).search(text, m.end())
62
+ end = em.end() - 1 if em else len(text) - 1
63
+ before = text[:m.start()].rstrip().split("\n")
64
+ comment = "\n".join(l for l in before[-6:] if l.strip().startswith("#"))
65
+ units.append(unit_record(rel, module, name, m.start(), end, text, parse_params(raw, comment), None, THROW))
66
+ return units
67
+
68
+
69
+ DRIVER = r'''require "json"
70
+ TARGET = File.realpath(__TARGET__)
71
+ FN = __FN__
72
+ MODS = __MODS__
73
+
74
+ def pp_special(s)
75
+ case s
76
+ when "nan" then Float::NAN
77
+ when "inf" then Float::INFINITY
78
+ when "-inf" then -Float::INFINITY
79
+ when "-0.0" then -0.0
80
+ else s.to_f
81
+ end
82
+ end
83
+
84
+ def pp_dec(v)
85
+ case v
86
+ when Hash then v.size == 1 && v["$float"].is_a?(String) ? pp_special(v["$float"]) : v.transform_values { |x| pp_dec(x) }
87
+ when Array then v.map { |x| pp_dec(x) }
88
+ else v
89
+ end
90
+ end
91
+
92
+ def pp_enc(v)
93
+ case v
94
+ when Float
95
+ return { "$float" => "nan" } if v.nan?
96
+ return { "$float" => v > 0 ? "inf" : "-inf" } if v.infinite?
97
+ return { "$float" => "-0.0" } if v.zero? && 1.0 / v < 0
98
+ return { "$float" => v.to_s } if v == v.floor && v.abs > 2**53
99
+ v
100
+ when Array then v.map { |x| pp_enc(x) }
101
+ when Hash then v.to_h { |k, x| [k.to_s, pp_enc(x)] }
102
+ when Symbol then v.to_s
103
+ when nil, true, false, Integer, String then v
104
+ else v.to_s
105
+ end
106
+ end
107
+
108
+ def pp_line(e)
109
+ loc = (e.backtrace_locations || []).find { |l| File.realpath(l.absolute_path || l.path) == TARGET rescue false }
110
+ loc&.lineno
111
+ end
112
+
113
+ def pp_call(recv, args)
114
+ { "kind" => "return", "value" => pp_enc(recv.send(FN, *args)) }
115
+ rescue Exception => e # rubocop:disable Lint/RescueException
116
+ o = { "kind" => "raise", "type" => e.class.name, "message" => e.message }
117
+ line = pp_line(e)
118
+ o["raise_line"] = line if line
119
+ o
120
+ end
121
+
122
+ load TARGET
123
+ recv = MODS.map { |m| Object.const_get(m) rescue nil }.compact.find { |m| m.respond_to?(FN) } || self
124
+ req = JSON.parse($stdin.read)
125
+ args = pp_dec(req["args"] || [])
126
+ if req["mode"] == "bench"
127
+ samples = Array.new(req["iterations"] || 1) do
128
+ t = Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)
129
+ pp_call(recv, args)
130
+ Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond) - t
131
+ end
132
+ File.write(ENV["PP_RESULT"], JSON.generate("samples_ns" => samples))
133
+ else
134
+ File.write(ENV["PP_RESULT"], JSON.generate("outcome" => pp_call(recv, args)))
135
+ end
136
+ '''
137
+
138
+
139
+ def prepare(src, rel, unit, work):
140
+ if unit["kind"] != "function":
141
+ raise SystemExit("only top-level Ruby functions can be recorded")
142
+ text = open(os.path.join(src, rel), encoding="utf-8", errors="replace").read()
143
+ mods = re.findall(r"^\s*(?:module|class)\s+([A-Z]\w*(?:::[A-Z]\w*)*)", text, re.M)
144
+ code = DRIVER.replace("__TARGET__", json.dumps(os.path.join(src, rel))).replace("__FN__", json.dumps(unit["name"])) \
145
+ .replace("__MODS__", json.dumps(mods))
146
+ path = os.path.join(work, "pp_driver.rb")
147
+ open(path, "w", encoding="utf-8").write(code)
148
+ return ["ruby", "--disable-gems", path]