kbs 0.2.1 → 0.4.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.
Files changed (134) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +87 -1
  3. data/README.md +66 -25
  4. data/lib/kbs/agenda.rb +301 -0
  5. data/lib/kbs/alpha_memory.rb +80 -9
  6. data/lib/kbs/alpha_network.rb +95 -0
  7. data/lib/kbs/beta_memory.rb +54 -19
  8. data/lib/kbs/blackboard/audit_log.rb +26 -25
  9. data/lib/kbs/blackboard/engine.rb +49 -40
  10. data/lib/kbs/blackboard/fact.rb +17 -21
  11. data/lib/kbs/blackboard/memory.rb +116 -40
  12. data/lib/kbs/blackboard/message_queue.rb +39 -28
  13. data/lib/kbs/blackboard/persistence/hybrid_store.rb +20 -9
  14. data/lib/kbs/blackboard/persistence/redis_store.rb +59 -51
  15. data/lib/kbs/blackboard/persistence/sqlite_store.rb +29 -32
  16. data/lib/kbs/blackboard/persistence/store.rb +11 -1
  17. data/lib/kbs/blackboard/redis_message_queue.rb +16 -7
  18. data/lib/kbs/condition.rb +42 -2
  19. data/lib/kbs/decompiler.rb +300 -124
  20. data/lib/kbs/dsl/condition_helpers.rb +8 -6
  21. data/lib/kbs/dsl/knowledge_base.rb +73 -93
  22. data/lib/kbs/dsl/pattern_evaluator.rb +38 -15
  23. data/lib/kbs/dsl/rule_builder.rb +118 -40
  24. data/lib/kbs/dsl/variable.rb +51 -6
  25. data/lib/kbs/dsl.rb +10 -3
  26. data/lib/kbs/engine.rb +395 -77
  27. data/lib/kbs/errors.rb +38 -0
  28. data/lib/kbs/exists_node.rb +12 -0
  29. data/lib/kbs/fact.rb +5 -19
  30. data/lib/kbs/fact_registry.rb +51 -0
  31. data/lib/kbs/introspection.rb +93 -0
  32. data/lib/kbs/join_indexing.rb +106 -0
  33. data/lib/kbs/join_node.rb +93 -57
  34. data/lib/kbs/join_test_builder.rb +80 -0
  35. data/lib/kbs/join_tests.rb +66 -0
  36. data/lib/kbs/memory_index.rb +104 -0
  37. data/lib/kbs/negation_node.rb +6 -82
  38. data/lib/kbs/network_node.rb +31 -0
  39. data/lib/kbs/pattern_matching.rb +52 -0
  40. data/lib/kbs/production_node.rb +50 -6
  41. data/lib/kbs/quantifier_node.rb +140 -0
  42. data/lib/kbs/rule.rb +26 -13
  43. data/lib/kbs/rule_source.rb +74 -0
  44. data/lib/kbs/rule_step.rb +27 -0
  45. data/lib/kbs/token.rb +76 -10
  46. data/lib/kbs/tracer.rb +80 -0
  47. data/lib/kbs/truth_maintenance.rb +82 -0
  48. data/lib/kbs/version.rb +1 -1
  49. data/lib/kbs/working_memory.rb +25 -3
  50. data/lib/kbs.rb +17 -4
  51. metadata +22 -129
  52. data/.envrc +0 -3
  53. data/.github/workflows/deploy-github-pages.yml +0 -52
  54. data/COMMITS.md +0 -196
  55. data/Rakefile +0 -8
  56. data/docs/advanced/custom-persistence.md +0 -775
  57. data/docs/advanced/debugging.md +0 -726
  58. data/docs/advanced/index.md +0 -8
  59. data/docs/advanced/performance.md +0 -865
  60. data/docs/advanced/testing.md +0 -827
  61. data/docs/api/blackboard.md +0 -1157
  62. data/docs/api/engine.md +0 -1047
  63. data/docs/api/facts.md +0 -1212
  64. data/docs/api/index.md +0 -12
  65. data/docs/api/rules.md +0 -1104
  66. data/docs/architecture/blackboard.md +0 -544
  67. data/docs/architecture/index.md +0 -277
  68. data/docs/architecture/network-structure.md +0 -343
  69. data/docs/architecture/rete-algorithm.md +0 -737
  70. data/docs/assets/css/custom.css +0 -83
  71. data/docs/assets/images/blackboard-architecture.svg +0 -136
  72. data/docs/assets/images/compiled-network.svg +0 -101
  73. data/docs/assets/images/fact-assertion-flow.svg +0 -117
  74. data/docs/assets/images/fact-rule-relationship.svg +0 -65
  75. data/docs/assets/images/fact-structure.svg +0 -42
  76. data/docs/assets/images/inference-cycle.svg +0 -47
  77. data/docs/assets/images/kb-components.svg +0 -43
  78. data/docs/assets/images/kbs.jpg +0 -0
  79. data/docs/assets/images/pattern-matching-trace.svg +0 -136
  80. data/docs/assets/images/rete-network-layers.svg +0 -96
  81. data/docs/assets/images/rule-structure.svg +0 -44
  82. data/docs/assets/images/system-layers.svg +0 -69
  83. data/docs/assets/images/trading-signal-network.svg +0 -139
  84. data/docs/assets/js/mathjax.js +0 -17
  85. data/docs/examples/index.md +0 -223
  86. data/docs/guides/blackboard-memory.md +0 -589
  87. data/docs/guides/dsl.md +0 -1321
  88. data/docs/guides/facts.md +0 -652
  89. data/docs/guides/getting-started.md +0 -385
  90. data/docs/guides/index.md +0 -23
  91. data/docs/guides/negation.md +0 -529
  92. data/docs/guides/pattern-matching.md +0 -561
  93. data/docs/guides/persistence.md +0 -451
  94. data/docs/guides/variable-binding.md +0 -491
  95. data/docs/guides/writing-rules.md +0 -914
  96. data/docs/index.md +0 -155
  97. data/docs/installation.md +0 -156
  98. data/docs/quick-start.md +0 -221
  99. data/docs/what-is-a-fact.md +0 -694
  100. data/docs/what-is-a-knowledge-base.md +0 -350
  101. data/docs/what-is-a-rule.md +0 -833
  102. data/examples/.gitignore +0 -1
  103. data/examples/README.md +0 -531
  104. data/examples/advanced_example.rb +0 -270
  105. data/examples/advanced_example_dsl.rb +0 -224
  106. data/examples/ai_enhanced_kbs.rb +0 -523
  107. data/examples/ai_enhanced_kbs_dsl.rb +0 -538
  108. data/examples/blackboard_demo.rb +0 -50
  109. data/examples/blackboard_demo_dsl.rb +0 -50
  110. data/examples/car_diagnostic.rb +0 -64
  111. data/examples/car_diagnostic_dsl.rb +0 -54
  112. data/examples/concurrent_inference_demo.rb +0 -362
  113. data/examples/concurrent_inference_demo_dsl.rb +0 -362
  114. data/examples/csv_trading_system.rb +0 -559
  115. data/examples/csv_trading_system_dsl.rb +0 -525
  116. data/examples/iot_demo_using_dsl.rb +0 -83
  117. data/examples/portfolio_rebalancing_system.rb +0 -651
  118. data/examples/portfolio_rebalancing_system_dsl.rb +0 -613
  119. data/examples/redis_trading_demo.rb +0 -177
  120. data/examples/redis_trading_demo_dsl.rb +0 -177
  121. data/examples/rule_source_demo.rb +0 -123
  122. data/examples/run_all.rb +0 -50
  123. data/examples/run_all_dsl.rb +0 -49
  124. data/examples/sample_stock_data.csv +0 -46
  125. data/examples/stock_trading_advanced.rb +0 -469
  126. data/examples/stock_trading_advanced_dsl.rb +0 -404
  127. data/examples/temp_dsl.txt +0 -9392
  128. data/examples/timestamped_trading.rb +0 -286
  129. data/examples/timestamped_trading_dsl.rb +0 -258
  130. data/examples/trading_demo.rb +0 -334
  131. data/examples/trading_demo_dsl.rb +0 -322
  132. data/examples/working_demo.rb +0 -176
  133. data/examples/working_demo_dsl.rb +0 -160
  134. data/mkdocs.yml +0 -181
@@ -12,6 +12,12 @@ module KBS
12
12
  # KBS::Decompiler.new(some_proc).decompile_block # => "{ |x| x + 1 }"
13
13
  #
14
14
  class Decompiler
15
+ # Classes whose #inspect is Ruby source for an equal value.
16
+ LITERAL_CLASSES = [Integer, Symbol, NilClass, TrueClass, FalseClass].freeze
17
+
18
+ # Marks a lookup that has not been tried yet; its result may be nil.
19
+ UNRESOLVED = Object.new.freeze
20
+
15
21
  def initialize(proc_obj)
16
22
  @iseq = RubyVM::InstructionSequence.of(proc_obj)
17
23
  @arr = @iseq.to_a
@@ -21,13 +27,15 @@ module KBS
21
27
  @children = []
22
28
  @iseq.each_child { |c| @children << c }
23
29
  @child_index = 0
24
- @lambda = proc_obj.lambda?
30
+ @proc = proc_obj
31
+ @outer_locals = [] # local tables of enclosing blocks
32
+ @creator_locals = UNRESOLVED
25
33
  end
26
34
 
27
35
  def decompile
28
36
  expr = decompile_body(@body)
29
37
  params = build_params
30
- if @lambda
38
+ if @proc.lambda?
31
39
  "->(#{params}) { #{expr} }"
32
40
  else
33
41
  "proc { |#{params}| #{expr} }"
@@ -54,113 +62,214 @@ module KBS
54
62
  @locals.first(count).join(", ")
55
63
  end
56
64
 
65
+ # The state of one pass over a body: the simulated stack, the
66
+ # statements finished so far, the && / || operators still waiting
67
+ # for their label, the || expressions built (to parenthesize them
68
+ # inside &&), how many steps to skip, and whether the pass is over.
69
+ Pass = Struct.new(:steps, :stack, :statements, :pending, :or_exprs, :skip, :done)
70
+
71
+ # Instructions that push a fixed piece of source.
72
+ FIXED_SOURCES = {
73
+ putobject_INT2FIX_0_: "0",
74
+ putobject_INT2FIX_1_: "1",
75
+ putself: "self",
76
+ putnil: "nil"
77
+ }.freeze
78
+
79
+ BINARY_OPERATIONS = %i[
80
+ opt_plus opt_minus opt_mult opt_div opt_mod
81
+ opt_eq opt_neq opt_lt opt_le opt_gt opt_ge opt_ltlt
82
+ ].freeze
83
+
84
+ # Instruction => the method that translates it.
85
+ HANDLERS = {
86
+ dup: :translate_dup,
87
+ getlocal_WC_0: :translate_getlocal,
88
+ getlocal_WC_1: :translate_outer_getlocal,
89
+ setlocal_WC_0: :translate_setlocal,
90
+ putobject: :translate_literal,
91
+ putchilledstring: :translate_literal,
92
+ dupchilledstring: :translate_literal,
93
+ putstring: :translate_literal,
94
+ opt_send_without_block: :translate_call,
95
+ send: :translate_call_with_block,
96
+ newarray: :translate_newarray,
97
+ newhash: :translate_newhash,
98
+ branchunless: :translate_branchunless,
99
+ pop: :translate_pop,
100
+ leave: :translate_nothing,
101
+ nop: :translate_nothing # Ruby 3.x starts a block with nop
102
+ }.merge(BINARY_OPERATIONS.to_h { |op| [op, :translate_binary] }).freeze
103
+
104
+ private_constant :Pass, :FIXED_SOURCES, :BINARY_OPERATIONS, :HANDLERS
105
+
57
106
  def decompile_body(body)
58
- stack = []
59
- statements = []
60
- instructions = body.select { |i| i.is_a?(Array) }
61
-
62
- instructions.each do |inst|
63
- op = inst[0]
64
- case op
65
- when :getlocal_WC_0
66
- idx = inst[1]
67
- name = slot_to_name(idx)
68
- stack.push(name.to_s)
69
-
70
- when :setlocal_WC_0
71
- idx = inst[1]
72
- name = slot_to_name(idx)
73
- val = stack.pop
74
- statements << "#{name} = #{val}"
75
-
76
- when :putobject
77
- stack.push(inst[1].inspect)
78
-
79
- when :putobject_INT2FIX_0_
80
- stack.push("0")
81
-
82
- when :putobject_INT2FIX_1_
83
- stack.push("1")
84
-
85
- when :putself
86
- stack.push("self")
87
-
88
- when :putnil
89
- stack.push("nil")
90
-
91
- when :putchilledstring, :putstring
92
- stack.push(inst[1].inspect)
93
-
94
- when :opt_plus, :opt_minus, :opt_mult, :opt_div, :opt_mod,
95
- :opt_eq, :opt_neq, :opt_lt, :opt_le, :opt_gt, :opt_ge,
96
- :opt_ltlt
97
- op_sym = inst[1][:mid]
98
- b = stack.pop
99
- a = stack.pop
100
- stack.push("#{a} #{op_sym} #{b}")
101
-
102
- when :opt_send_without_block
103
- calldata = inst[1]
104
- method = calldata[:mid]
105
- argc = calldata[:orig_argc]
106
- args = stack.pop(argc)
107
- receiver = stack.pop
108
- call_str = format_call(receiver, method, args)
109
- stack.push(call_str)
110
-
111
- when :send
112
- calldata = inst[1]
113
- method = calldata[:mid]
114
- argc = calldata[:orig_argc]
115
- args = stack.pop(argc)
116
- receiver = stack.pop
117
-
118
- child_iseq = @children[@child_index]
119
- @child_index += 1
120
- child_src = decompile_child(child_iseq)
121
-
122
- base = format_call(receiver, method, args)
123
- stack.push("#{base} { #{child_src} }")
124
-
125
- when :newarray
126
- count = inst[1]
127
- items = stack.pop(count)
128
- stack.push("[#{items.join(', ')}]")
129
-
130
- when :newhash
131
- count = inst[1]
132
- pairs = stack.pop(count)
133
- entries = pairs.each_slice(2).map { |k, v| "#{k} => #{v}" }
134
- stack.push("{ #{entries.join(', ')} }")
135
-
136
- when :branchunless
137
- condition = stack.pop
138
- remaining = instructions[instructions.index(inst) + 1..]
139
- true_val = extract_value(remaining, 0)
140
- false_val = extract_value(remaining, 1)
141
- if true_val && false_val
142
- stack.push("#{condition} ? #{true_val} : #{false_val}")
143
- break
144
- end
145
-
146
- when :leave
147
- # ignore
148
-
149
- when :pop
150
- val = stack.pop
151
- statements << val if val
152
-
153
- else
154
- stack.push("/* #{op} */")
155
- end
107
+ pass = new_pass(body)
108
+ pass.steps.each_with_index do |inst, index|
109
+ break if pass.done
110
+
111
+ translate_step(pass, inst, index)
112
+ end
113
+ body_source(pass)
114
+ end
115
+
116
+ def new_pass(body)
117
+ steps = body.select { |item| item.is_a?(Array) || label?(item) }
118
+ Pass.new(steps, [], [], [], {}.compare_by_identity, 0, false)
119
+ end
120
+
121
+ # Translates one step, unless an earlier step already consumed it.
122
+ def translate_step(pass, inst, index)
123
+ if pass.skip.positive?
124
+ pass.skip -= 1
125
+ elsif label?(inst)
126
+ close_logical_ops(inst, pass.pending, pass.stack, pass.or_exprs)
127
+ else
128
+ translate_instruction(pass, inst, index)
129
+ end
130
+ end
131
+
132
+ def translate_instruction(pass, inst, index)
133
+ op = inst[0]
134
+ fixed = FIXED_SOURCES[op]
135
+ handler = HANDLERS[op]
136
+ if fixed
137
+ pass.stack.push(fixed)
138
+ elsif handler
139
+ send(handler, pass, inst, index)
140
+ else
141
+ pass.stack.push("/* #{op} */")
142
+ end
143
+ end
144
+
145
+ # The source of a finished pass: its statements, then the value left
146
+ # on the stack. An operator whose label lies outside the steps never
147
+ # closed, and becomes a placeholder.
148
+ def body_source(pass)
149
+ pending = pass.pending
150
+ return "/* #{pending.last[0]} */" if pending.any?
151
+
152
+ (pass.statements + [pass.stack.last].compact).join("; ")
153
+ end
154
+
155
+ def translate_dup(pass, _inst, index)
156
+ steps = pass.steps
157
+ stack = pass.stack
158
+ logical = logical_op_at(steps, index)
159
+ if logical
160
+ pass.pending.push([logical, stack.pop, steps[index + 1][1]])
161
+ pass.skip = 2
162
+ else
163
+ stack.push("/* dup */")
164
+ end
165
+ end
166
+
167
+ def translate_getlocal(pass, inst, _index)
168
+ pass.stack.push(slot_to_name(inst[1]).to_s)
169
+ end
170
+
171
+ def translate_outer_getlocal(pass, inst, _index)
172
+ slot = inst[1]
173
+ name = if @outer_locals.empty?
174
+ captured_value(slot)
175
+ else
176
+ slot_to_name(slot, @outer_locals.last).to_s
177
+ end
178
+ pass.stack.push(name || '/* getlocal_WC_1 */')
179
+ end
180
+
181
+ def translate_setlocal(pass, inst, _index)
182
+ pass.statements << "#{slot_to_name(inst[1])} = #{pass.stack.pop}"
183
+ end
184
+
185
+ def translate_literal(pass, inst, _index)
186
+ pass.stack.push(inst[1].inspect)
187
+ end
188
+
189
+ def translate_binary(pass, inst, _index)
190
+ stack = pass.stack
191
+ right = stack.pop
192
+ left = stack.pop
193
+ stack.push("#{left} #{inst.last[:mid]} #{right}") # opt_neq carries == then !=
194
+ end
195
+
196
+ def translate_call(pass, inst, _index)
197
+ pass.stack.push(pop_call(pass.stack, inst[1]))
198
+ end
199
+
200
+ def translate_call_with_block(pass, inst, _index)
201
+ call = pop_call(pass.stack, inst[1])
202
+ child_iseq = @children[@child_index]
203
+ @child_index += 1
204
+ pass.stack.push("#{call} { #{decompile_child(child_iseq)} }")
205
+ end
206
+
207
+ # Takes a call's arguments and receiver off the stack and returns the
208
+ # call as source.
209
+ def pop_call(stack, calldata)
210
+ args = stack.pop(calldata[:orig_argc])
211
+ format_call(stack.pop, calldata[:mid], args)
212
+ end
213
+
214
+ def translate_newarray(pass, inst, _index)
215
+ stack = pass.stack
216
+ stack.push("[#{stack.pop(inst[1]).join(', ')}]")
217
+ end
218
+
219
+ def translate_newhash(pass, inst, _index)
220
+ stack = pass.stack
221
+ entries = stack.pop(inst[1]).each_slice(2).map { |key, value| "#{key} => #{value}" }
222
+ stack.push("{ #{entries.join(', ')} }")
223
+ end
224
+
225
+ # Ends the pass: what follows is the two branches of a ternary.
226
+ # Anything else on the stack, such as from a bare branchif, would be
227
+ # lost, so that case becomes a placeholder.
228
+ def translate_branchunless(pass, inst, index)
229
+ stack = pass.stack
230
+ lone = stack.size == 1
231
+ stack.push(lone ? ternary(stack.pop, pass.steps[(index + 1)..], inst[1]) : '/* branchunless */')
232
+ pass.done = true
233
+ end
234
+
235
+ def translate_pop(pass, _inst, _index)
236
+ value = pass.stack.pop
237
+ pass.statements << value if value
238
+ end
239
+
240
+ def translate_nothing(_pass, _inst, _index); end
241
+
242
+ # Ruby compiles `a && b` as `a; dup; branchunless L; pop; b; L:`, and
243
+ # `a || b` the same way with branchif. Returns "&&" or "||" when the
244
+ # dup at index starts that sequence, else nil.
245
+ def logical_op_at(steps, index)
246
+ branch = steps[index + 1]
247
+ pop = steps[index + 2]
248
+ return unless pop.is_a?(Array) && pop[0] == :pop && branch.is_a?(Array)
249
+
250
+ { branchunless: "&&", branchif: "||" }[branch[0]]
251
+ end
252
+
253
+ # At a jump target, joins each pending operator whose branch goes
254
+ # there with the expression on top of the stack, innermost first.
255
+ # An || result used as either side of && is parenthesized.
256
+ def close_logical_ops(label, pending, stack, or_exprs)
257
+ while pending.any? && pending.last[2] == label
258
+ op, left, _label = pending.pop
259
+ right = stack.pop
260
+ left, right = [left, right].map { |side| or_exprs.key?(side) ? "(#{side})" : side } if op == "&&"
261
+ expr = "#{left} #{op} #{right}"
262
+ or_exprs[expr] = true if op == "||"
263
+ stack.push(expr)
156
264
  end
265
+ end
157
266
 
158
- all = statements + [stack.last].compact
159
- all.join("; ")
267
+ def label?(item)
268
+ item.is_a?(Symbol) && item.start_with?("label_")
160
269
  end
161
270
 
162
271
  def format_call(receiver, method, args)
163
- prefix = (receiver == "self") ? "" : "#{receiver}."
272
+ prefix = receiver == "self" ? "" : "#{receiver}."
164
273
  if args.empty?
165
274
  "#{prefix}#{method}"
166
275
  else
@@ -169,36 +278,103 @@ module KBS
169
278
  end
170
279
 
171
280
  def decompile_child(child_iseq)
172
- child_arr = child_iseq.to_a
173
- child_locals = child_arr[10]
174
- child_params = child_arr[11]
175
- child_body = child_arr[13]
176
- count = child_params[:lead_num] || 0
177
- param_names = child_locals.first(count).join(", ")
281
+ child = child_iseq.to_a
282
+ locals = child[10]
283
+ params = child[11]
284
+ count = params[:lead_num] || 0
285
+ expr = in_scope(locals, params, child[13]) { decompile_body(@body) }
286
+
287
+ count.positive? ? "|#{locals.first(count).join(', ')}| #{expr}" : expr
288
+ end
178
289
 
290
+ # Runs the block with a nested block's locals, parameters and body in
291
+ # place of the current ones.
292
+ def in_scope(locals, params, body)
179
293
  saved = [@locals, @params, @body]
180
- @locals, @params, @body = child_locals, child_params, child_body
181
- expr = decompile_body(child_body)
294
+ @outer_locals.push(@locals)
295
+ @locals = locals
296
+ @params = params
297
+ @body = body
298
+ yield
299
+ ensure
182
300
  @locals, @params, @body = saved
301
+ @outer_locals.pop
302
+ end
183
303
 
184
- if count > 0
185
- "|#{param_names}| #{expr}"
186
- else
187
- expr
304
+ # `cond ? a : b` compiles to `branchunless L; a; leave; L: b; leave`.
305
+ # Any other shape becomes a placeholder, so the condition is never
306
+ # silently dropped.
307
+ def ternary(condition, rest, else_label)
308
+ split = rest.index(else_label)
309
+ sources = split && [rest[0...split], rest[(split + 1)..]].map { |steps| branch_source(steps) }
310
+ return '/* branchunless */' unless sources&.all?
311
+
312
+ "#{condition} ? #{sources.join(' : ')}"
313
+ end
314
+
315
+ # Source of a ternary branch that ends the block with one
316
+ # expression, else nil.
317
+ def branch_source(steps)
318
+ return unless steps.last.is_a?(Array) && steps.last[0] == :leave
319
+
320
+ src = decompile_body(steps)
321
+ src unless src.empty? || src.include?(';')
322
+ end
323
+
324
+ # The value of a variable the proc captured from the method that
325
+ # created it, as Ruby source, or nil when it can't be resolved or has
326
+ # no literal form.
327
+ def captured_value(slot_idx)
328
+ table = creator_locals or return nil
329
+ value = @proc.binding.local_variable_get(slot_to_name(slot_idx, table))
330
+ value.inspect if literal?(value)
331
+ rescue NameError, TypeError
332
+ nil
333
+ end
334
+
335
+ def literal?(value)
336
+ case value
337
+ when Float then value.finite?
338
+ when String
339
+ value.instance_of?(String) && value.encoding == Encoding::UTF_8 && value.valid_encoding?
340
+ else LITERAL_CLASSES.include?(value.class)
341
+ end
342
+ end
343
+
344
+ # Local table of the method whose body created the proc, or nil when
345
+ # the proc was made anywhere else (a nested block, a class body, the
346
+ # top level), where the slot would index some other scope.
347
+ def creator_locals
348
+ return @creator_locals unless @creator_locals.equal?(UNRESOLVED)
349
+
350
+ @creator_locals = begin
351
+ scope = @proc.binding
352
+ name = scope.eval('__method__')
353
+ method = name && Kernel.instance_method(:method).bind_call(scope.receiver, name)
354
+ creating_iseq(method)&.to_a&.[](10)
355
+ rescue NameError, TypeError, ArgumentError
356
+ nil
357
+ end
358
+ end
359
+
360
+ # Walks the method's super chain for the definition whose body holds
361
+ # the proc as a direct child.
362
+ def creating_iseq(method)
363
+ while method
364
+ iseq = RubyVM::InstructionSequence.of(method)
365
+ return iseq if iseq && direct_child?(iseq)
366
+
367
+ method = method.super_method
188
368
  end
189
369
  end
190
370
 
191
- def extract_value(instructions, index)
192
- values = instructions.select { |i|
193
- i.is_a?(Array) && (i[0] == :putchilledstring || i[0] == :putstring || i[0] == :putobject)
194
- }
195
- val = values[index]
196
- val[1].inspect if val
371
+ def direct_child?(iseq)
372
+ iseq.each_child { |child| return true if child.to_a == @arr }
373
+ false
197
374
  end
198
375
 
199
- def slot_to_name(slot_idx)
200
- name_idx = @locals.size + 2 - slot_idx
201
- @locals[name_idx] || "?local_#{slot_idx}"
376
+ def slot_to_name(slot_idx, locals = @locals)
377
+ locals[locals.size + 2 - slot_idx] || "?local_#{slot_idx}"
202
378
  end
203
379
  end
204
380
  end
@@ -2,13 +2,15 @@
2
2
 
3
3
  module KBS
4
4
  module DSL
5
+ # Predicates for use as pattern values in the DSL, such as
6
+ # greater_than(90) and between(1, 9).
5
7
  module ConditionHelpers
6
8
  def less_than(value)
7
- ->(v) { v < value }
9
+ ->(v) { v < value rescue false }
8
10
  end
9
11
 
10
12
  def greater_than(value)
11
- ->(v) { v > value }
13
+ ->(v) { v > value rescue false }
12
14
  end
13
15
 
14
16
  def equals(value)
@@ -25,9 +27,9 @@ module KBS
25
27
 
26
28
  def range(min_or_range, max = nil)
27
29
  if min_or_range.is_a?(Range)
28
- ->(v) { min_or_range.include?(v) }
30
+ ->(v) { min_or_range.include?(v) rescue false }
29
31
  else
30
- ->(v) { v >= min_or_range && v <= max }
32
+ ->(v) { v.between?(min_or_range, max) rescue false }
31
33
  end
32
34
  end
33
35
 
@@ -38,7 +40,7 @@ module KBS
38
40
  def any(*values)
39
41
  if values.empty?
40
42
  # Match anything
41
- ->(v) { true }
43
+ ->(_v) { true }
42
44
  else
43
45
  # Match one of the values
44
46
  one_of(*values)
@@ -46,7 +48,7 @@ module KBS
46
48
  end
47
49
 
48
50
  def matches(pattern)
49
- ->(v) { v.match?(pattern) }
51
+ ->(v) { v.match?(pattern) rescue false }
50
52
  end
51
53
 
52
54
  def satisfies(&block)