kbs 0.2.0 → 0.3.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 +86 -0
  3. data/README.md +52 -25
  4. data/lib/kbs/agenda.rb +208 -0
  5. data/lib/kbs/alpha_memory.rb +55 -7
  6. data/lib/kbs/alpha_network.rb +83 -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 +39 -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 +104 -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 +75 -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 +27 -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 +60 -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
@@ -2,19 +2,29 @@
2
2
 
3
3
  module KBS
4
4
  module DSL
5
+ # The object the DSL block runs in: defines rules, asserts and retracts
6
+ # facts, and runs the engine.
5
7
  class KnowledgeBase
8
+ include ConditionHelpers
9
+
6
10
  attr_reader :engine, :rules
7
11
 
8
- def initialize
9
- @engine = Engine.new
12
+ # @param engine [KBS::Engine, nil] engine to run on; a new KBS::Engine when nil
13
+ # Drawn above and below the listings.
14
+ SEPARATOR = ("-" * 40).freeze
15
+
16
+ def initialize(engine: nil)
17
+ @engine = engine || Engine.new
10
18
  @rules = {}
11
19
  @rule_builders = {}
12
20
  @rule_source_locations = {}
13
21
  end
14
22
 
15
- def rule(name, &block)
23
+ # @param priority [Integer, nil] rule priority; a `priority` call in the block wins
24
+ def rule(name, priority: nil, &block)
16
25
  @rule_source_locations[name] = block.source_location if block
17
- builder = RuleBuilder.new(name)
26
+ builder = RuleBuilder.new(name, knowledge_base: self)
27
+ builder.priority(priority) unless priority.nil?
18
28
  builder.instance_eval(&block) if block_given?
19
29
  @rule_builders[name] = builder
20
30
  rule = builder.build
@@ -23,8 +33,8 @@ module KBS
23
33
  builder
24
34
  end
25
35
 
26
- def defrule(name, &block)
27
- rule(name, &block)
36
+ def defrule(name, priority: nil, &)
37
+ rule(name, priority: priority, &)
28
38
  end
29
39
 
30
40
  def fact(type, attributes = {})
@@ -39,32 +49,58 @@ module KBS
39
49
  @engine.remove_fact(fact)
40
50
  end
41
51
 
42
- def run
43
- @engine.run
52
+ # Changes a fact's attributes and matches it against the rules again.
53
+ # See KBS::Engine#modify.
54
+ def modify(fact, changes)
55
+ @engine.modify(fact, changes)
56
+ end
57
+
58
+ # @param limit [Integer, nil] stop after this many rule firings
59
+ # @return [Integer] the number of rules fired
60
+ def run(limit = nil)
61
+ @engine.run(limit)
62
+ end
63
+
64
+ def halt
65
+ @engine.halt
66
+ end
67
+
68
+ # See KBS::Engine#watch.
69
+ def watch(*items)
70
+ @engine.watch(*items)
71
+ self
72
+ end
73
+
74
+ def unwatch(*items)
75
+ @engine.unwatch(*items)
76
+ self
77
+ end
78
+
79
+ # See KBS::Engine#matches.
80
+ def matches(rule_name)
81
+ @engine.matches(rule_name)
44
82
  end
45
83
 
46
84
  def reset
47
85
  @engine.reset
48
86
  end
49
87
 
88
+ def close
89
+ @engine.close
90
+ end
91
+
50
92
  def facts
51
93
  @engine.working_memory.facts
52
94
  end
53
95
 
54
96
  def query(type, pattern = {})
55
- @engine.working_memory.facts.select do |fact|
56
- next false unless fact.type == type
57
- pattern.all? { |key, value| fact.attributes[key] == value }
58
- end
97
+ typed = pattern.merge(type: type)
98
+ @engine.working_memory.facts.select { |fact| fact.matches?(typed) }
59
99
  end
60
100
 
61
101
  def print_facts
62
- puts "Working Memory Contents:"
63
- puts "-" * 40
64
- facts.each_with_index do |fact, i|
65
- puts "#{i + 1}. #{fact}"
66
- end
67
- puts "-" * 40
102
+ numbered = facts.each_with_index.map { |fact, index| "#{index + 1}. #{fact}" }
103
+ puts ["Working Memory Contents:", SEPARATOR, *numbered, SEPARATOR]
68
104
  end
69
105
 
70
106
  def rule_source(name)
@@ -92,93 +128,37 @@ module KBS
92
128
  end
93
129
 
94
130
  def print_rules
95
- puts "Knowledge Base Rules:"
96
- puts "-" * 40
97
- @rule_builders.each do |name, builder|
98
- puts "Rule: #{name}"
99
- puts " Description: #{builder.description}" if builder.description
100
- puts " Priority: #{builder.priority}"
101
- puts " Conditions: #{builder.conditions.size}"
102
- builder.conditions.each_with_index do |cond, i|
103
- negated = cond.negated ? "NOT " : ""
104
- puts " #{i + 1}. #{negated}#{cond.type}(#{cond.pattern})"
105
- end
106
- puts ""
107
- end
108
- puts "-" * 40
131
+ puts ["Knowledge Base Rules:", SEPARATOR, *@rule_builders.each_value.flat_map(&:summary_lines), SEPARATOR]
109
132
  end
110
133
 
111
134
  private
112
135
 
113
136
  def reconstruct_rule_source(name)
114
- builder = @rule_builders[name]
115
- return nil unless builder
116
-
117
- lines = []
118
- lines << "rule #{name.inspect} do"
119
- lines << " desc #{builder.description.inspect}" if builder.description
120
- lines << " priority #{builder.priority}" if builder.priority != 0
121
-
122
- builder.conditions.each do |cond|
123
- keyword = cond.negated ? "without" : "on"
124
- pattern_str = reconstruct_pattern(cond.pattern)
125
- if pattern_str.empty?
126
- lines << " #{keyword} #{cond.type.inspect}"
127
- else
128
- lines << " #{keyword} #{cond.type.inspect}, #{pattern_str}"
129
- end
130
- end
131
-
132
- if builder.action_block
133
- block_str = decompile_proc_block(builder.action_block)
134
- lines << " perform #{block_str}"
135
- end
136
-
137
- lines << "end"
138
- lines.join("\n")
137
+ @rule_builders[name]&.source
139
138
  end
140
139
 
141
- def reconstruct_pattern(pattern)
142
- return "" if pattern.empty?
140
+ def extract_rule_source(file, start_line)
141
+ lines = File.readlines(file)
142
+ start_idx = start_line - 1
143
+ return nil unless start_idx.between?(0, lines.length - 1)
143
144
 
144
- pattern.map do |key, value|
145
- val_str = if value.is_a?(Proc)
146
- Decompiler.new(value).decompile
147
- else
148
- value.inspect
149
- end
150
- "#{key}: #{val_str}"
151
- end.join(", ")
145
+ rule_lines(lines.drop(rule_line_index(lines, start_idx))).join.chomp
152
146
  end
153
147
 
154
- def decompile_proc_block(proc_obj)
155
- Decompiler.new(proc_obj).decompile_block
156
- rescue => e
157
- "{ <decompilation failed: #{e.message}> }"
148
+ # source_location points to the block's `do` line, which is normally
149
+ # the same line as the `rule` call. Walks back up to 2 lines in case
150
+ # they are on separate lines.
151
+ def rule_line_index(lines, start_idx)
152
+ earliest = [start_idx - 2, 0].max
153
+ start_idx.downto(earliest).find { |index| lines[index].match?(/\b(?:rule|defrule)\b/) } || start_idx
158
154
  end
159
155
 
160
- def extract_rule_source(file, start_line)
161
- lines = File.readlines(file)
162
- start_idx = start_line - 1
163
- return nil if start_idx < 0 || start_idx >= lines.length
164
-
165
- # source_location points to the block's `do` line, which is
166
- # normally the same line as the `rule` call. Walk back up to
167
- # 2 lines in case they are on separate lines.
168
- rule_idx = start_idx.downto([start_idx - 2, 0].max).find do |i|
169
- lines[i].match?(/\b(?:rule|defrule)\b/)
170
- end || start_idx
171
-
172
- base_indent = lines[rule_idx][/^\s*/].length
173
- end_pattern = /^\s{#{base_indent}}end\b/
174
-
175
- result = []
176
- (rule_idx...lines.length).each do |i|
177
- result << lines[i]
178
- break if i > rule_idx && lines[i].match?(end_pattern)
179
- end
180
-
181
- result.join.chomp
156
+ # The rule's first line through the `end` at the same indentation,
157
+ # or every line when there is no such `end`.
158
+ def rule_lines(lines)
159
+ end_pattern = /^\s{#{lines.first[/^\s*/].length}}end\b/
160
+ last = lines.drop(1).index { |line| line.match?(end_pattern) }
161
+ last ? lines.first(last + 2) : lines
182
162
  end
183
163
  end
184
164
  end
@@ -2,18 +2,29 @@
2
2
 
3
3
  module KBS
4
4
  module DSL
5
+ # Evaluates the block form of a condition, where each method call names
6
+ # a pattern key and a bare name is a variable.
5
7
  class PatternEvaluator
8
+ # The block form of `on` runs here, so helpers such as greater_than
9
+ # must resolve to the helper, not fall into method_missing as keys.
10
+ # Methods this class defines itself (between, matches, any, all)
11
+ # still take precedence over the module's.
12
+ include ConditionHelpers
13
+
6
14
  attr_reader :pattern
7
15
 
8
16
  def initialize
9
17
  @pattern = {}
10
18
  end
11
19
 
20
+ # Every name is a variable or a pattern key.
21
+ def respond_to_missing?(_method, _include_private = false) = true
22
+
12
23
  def method_missing(method, *args, &block)
13
24
  if args.empty? && !block_given?
14
- Variable.new(method)
25
+ Variable.new(method, self)
15
26
  elsif args.length == 1 && !block_given?
16
- @pattern[method] = args.first
27
+ @pattern[method] = pattern_value(args.first)
17
28
  elsif block_given?
18
29
  @pattern[method] = block
19
30
  else
@@ -21,32 +32,44 @@ module KBS
21
32
  end
22
33
  end
23
34
 
24
- def >(value)
25
- ->(v) { v > value }
35
+ # Sets the pattern value of `attribute`, as `value > 80` does.
36
+ # @return the value
37
+ def constrain(attribute, value)
38
+ @pattern[attribute] = value
39
+ end
40
+
41
+ # A Variable given as a value (`location loc`) is its ?variable
42
+ # symbol; any other value is used as is.
43
+ def pattern_value(value)
44
+ value.is_a?(Variable) ? value.to_sym : value
45
+ end
46
+
47
+ def >(other)
48
+ ->(v) { v > other }
26
49
  end
27
50
 
28
- def <(value)
29
- ->(v) { v < value }
51
+ def <(other)
52
+ ->(v) { v < other }
30
53
  end
31
54
 
32
- def >=(value)
33
- ->(v) { v >= value }
55
+ def >=(other)
56
+ ->(v) { v >= other }
34
57
  end
35
58
 
36
- def <=(value)
37
- ->(v) { v <= value }
59
+ def <=(other)
60
+ ->(v) { v <= other }
38
61
  end
39
62
 
40
- def ==(value)
41
- value
63
+ def ==(other)
64
+ other
42
65
  end
43
66
 
44
- def !=(value)
45
- ->(v) { v != value }
67
+ def !=(other)
68
+ ->(v) { v != other }
46
69
  end
47
70
 
48
71
  def between(min, max)
49
- ->(v) { v >= min && v <= max }
72
+ ->(v) { v.between?(min, max) }
50
73
  end
51
74
 
52
75
  def in(collection)
@@ -2,19 +2,32 @@
2
2
 
3
3
  module KBS
4
4
  module DSL
5
+ # Collects the conditions and action written inside a `rule do ... end`
6
+ # block and builds the KBS::Rule.
7
+ #
8
+ # The rule's `perform` block runs with the builder as self, so the
9
+ # builder forwards working-memory calls (assert, retract, modify,
10
+ # query, facts, halt, engine) to the knowledge base that owns the
11
+ # rule. `fact` adds a condition while the rule is being defined and
12
+ # asserts a fact once it is built. Condition keywords called after
13
+ # the build raise KBS::RuleBuiltError.
5
14
  class RuleBuilder
6
15
  include ConditionHelpers
7
16
 
8
17
  attr_reader :name, :description, :conditions, :action_block
9
18
 
10
- def initialize(name)
19
+ # @param knowledge_base [KBS::DSL::KnowledgeBase, nil] where working-memory
20
+ # calls made on the builder, such as those in a perform block, go
21
+ def initialize(name, knowledge_base: nil)
11
22
  @name = name
23
+ @knowledge_base = knowledge_base
24
+ @built = false
12
25
  @description = nil
13
26
  @priority = 0
14
27
  @conditions = []
15
28
  @action_block = nil
16
- @current_condition_group = []
17
29
  @negated = false
30
+ @logical = false
18
31
  end
19
32
 
20
33
  def desc(description)
@@ -29,85 +42,150 @@ module KBS
29
42
  end
30
43
 
31
44
  # Primary DSL keywords (avoid Ruby reserved words)
32
- def on(type, pattern = {}, &block)
45
+ def on(type, pattern = {}, &)
46
+ ensure_building!(:on)
33
47
  if block_given?
34
- pattern = pattern.merge(evaluate_block(&block))
48
+ pattern = pattern.merge(evaluate_block(&))
35
49
  end
36
- @conditions << Condition.new(type, pattern, negated: @negated)
50
+ @conditions << Condition.new(type, pattern, negated: @negated, logical: @logical)
37
51
  @negated = false
38
52
  self
39
53
  end
40
54
 
41
- def without(type = nil, pattern = {}, &block)
42
- if type
43
- # Direct negation: without(:problem)
44
- @negated = true
45
- on(type, pattern, &block)
46
- else
47
- # Chaining: without.on(:problem)
48
- @negated = true
49
- self
50
- end
55
+ def without(type = nil, pattern = {}, &)
56
+ ensure_building!(:without)
57
+ @negated = true
58
+ # Direct negation: without(:problem). Chaining: without.on(:problem).
59
+ type ? on(type, pattern, &) : self
60
+ end
61
+
62
+ # Marks the conditions in the block as logical: every fact the
63
+ # rule's action asserts stays only while those conditions are
64
+ # matched, and is retracted when they stop matching. The block has
65
+ # to come before the rule's other conditions.
66
+ #
67
+ # rule "overheating" do
68
+ # logical do
69
+ # on :sensor, temp: greater_than(90)
70
+ # end
71
+ # perform { assert :overheating }
72
+ # end
73
+ def logical(&)
74
+ ensure_building!(:logical)
75
+ @logical = true
76
+ instance_eval(&)
77
+ self
78
+ ensure
79
+ @logical = false
51
80
  end
52
81
 
53
82
  def perform(&block)
83
+ ensure_building!(:perform)
54
84
  @action_block = block
55
85
  self
56
86
  end
57
87
 
58
88
  # Aliases for readability
59
- def given(type, pattern = {}, &block)
60
- on(type, pattern, &block)
89
+ def given(type, pattern = {}, &)
90
+ on(type, pattern, &)
91
+ end
92
+
93
+ def matches(type, pattern = {}, &)
94
+ on(type, pattern, &)
95
+ end
96
+
97
+ # A condition while the rule is being defined; once it is built, as
98
+ # in a perform block, asserts a fact through the knowledge base.
99
+ def fact(type, pattern = {}, &)
100
+ return knowledge_base!(:fact).fact(type, pattern) if built?
101
+
102
+ on(type, pattern, &)
103
+ end
104
+
105
+ # Matches once when at least one fact fits the pattern, however many
106
+ # do. The rule's action receives no fact for this condition, and a
107
+ # variable first used here is not bound for later conditions.
108
+ def exists(type, pattern = {}, &)
109
+ ensure_building!(:exists)
110
+ pattern = pattern.merge(evaluate_block(&)) if block_given?
111
+ @conditions << Condition.new(type, pattern, exists: true, logical: @logical)
112
+ @negated = false
113
+ self
61
114
  end
62
115
 
63
- def matches(type, pattern = {}, &block)
64
- on(type, pattern, &block)
116
+ def absent(type, pattern = {}, &)
117
+ without.on(type, pattern, &)
65
118
  end
66
119
 
67
- def fact(type, pattern = {}, &block)
68
- on(type, pattern, &block)
120
+ def missing(type, pattern = {}, &)
121
+ without.on(type, pattern, &)
69
122
  end
70
123
 
71
- def exists(type, pattern = {}, &block)
72
- on(type, pattern, &block)
124
+ def lacks(type, pattern = {}, &)
125
+ without.on(type, pattern, &)
73
126
  end
74
127
 
75
- def absent(type, pattern = {}, &block)
76
- without.on(type, pattern, &block)
128
+ def action(&)
129
+ perform(&)
77
130
  end
78
131
 
79
- def missing(type, pattern = {}, &block)
80
- without.on(type, pattern, &block)
132
+ def execute(&)
133
+ perform(&)
81
134
  end
82
135
 
83
- def lacks(type, pattern = {}, &block)
84
- without.on(type, pattern, &block)
136
+ def then(&)
137
+ perform(&)
85
138
  end
86
139
 
87
- def action(&block)
88
- perform(&block)
140
+ # The rule as DSL source, rebuilt from what was collected.
141
+ def source
142
+ RuleSource.new(name: @name, conditions: @conditions, action: @action_block,
143
+ priority: @priority, description: @description).to_s
89
144
  end
90
145
 
91
- def execute(&block)
92
- perform(&block)
146
+ # The lines print_rules shows for this rule.
147
+ def summary_lines
148
+ conditions = @conditions.each_with_index.map { |condition, index| " #{index + 1}. #{condition.summary}" }
149
+ ["Rule: #{@name}", *(" Description: #{@description}" if @description), " Priority: #{@priority}",
150
+ " Conditions: #{@conditions.size}", *conditions, ""]
93
151
  end
94
152
 
95
- def then(&block)
96
- perform(&block)
153
+ # Working-memory calls, forwarded to the knowledge base so that a
154
+ # perform block can make them bare.
155
+ def assert(type, attributes = {}) = knowledge_base!(:assert).assert(type, attributes)
156
+ def retract(fact) = knowledge_base!(:retract).retract(fact)
157
+ def modify(fact, changes) = knowledge_base!(:modify).modify(fact, changes)
158
+ def query(type, pattern = {}) = knowledge_base!(:query).query(type, pattern)
159
+ def facts = knowledge_base!(:facts).facts
160
+ def halt = knowledge_base!(:halt).halt
161
+ def engine = knowledge_base!(:engine).engine
162
+
163
+ # Whether #build has run. After that, condition keywords raise.
164
+ def built?
165
+ @built
97
166
  end
98
167
 
99
168
  def build
169
+ @built = true
100
170
  Rule.new(@name,
101
- conditions: @conditions,
102
- action: @action_block,
103
- priority: @priority)
171
+ conditions: @conditions,
172
+ action: @action_block,
173
+ priority: @priority)
104
174
  end
105
175
 
106
176
  private
107
177
 
108
- def evaluate_block(&block)
178
+ def ensure_building!(keyword)
179
+ raise RuleBuiltError.new(@name, keyword) if built?
180
+ end
181
+
182
+ def knowledge_base!(method)
183
+ @knowledge_base || raise(NoKnowledgeBaseError.new(@name, method))
184
+ end
185
+
186
+ def evaluate_block(&)
109
187
  evaluator = PatternEvaluator.new
110
- evaluator.instance_eval(&block)
188
+ evaluator.instance_eval(&)
111
189
  evaluator.pattern
112
190
  end
113
191
  end
@@ -2,12 +2,22 @@
2
2
 
3
3
  module KBS
4
4
  module DSL
5
+ # A bare name written in a pattern block. Used as a value
6
+ # (`location loc`) it is the ?variable `:loc?`. Compared with a value
7
+ # (`value > 80`) it stands for the attribute of that name, and the
8
+ # comparison becomes that attribute's predicate in the block's pattern.
5
9
  class Variable
10
+ # Operators that turn `name <op> operand` into a predicate on the
11
+ # attribute `name`, built by PatternEvaluator's operator of the same name.
12
+ COMPARISONS = %i[> < >= <=].freeze
13
+
6
14
  attr_reader :name
7
15
 
8
- def initialize(name)
9
- name_str = name.to_s
10
- @name = name_str.end_with?('?') ? name_str.to_sym : "#{name_str}?".to_sym
16
+ # @param evaluator [PatternEvaluator, nil] the pattern block this name
17
+ # was written in; comparisons need it to record their predicate
18
+ def initialize(name, evaluator = nil)
19
+ @name = :"#{name.to_s.delete_suffix('?')}?"
20
+ @evaluator = evaluator
11
21
  end
12
22
 
13
23
  def to_sym
@@ -18,18 +28,53 @@ module KBS
18
28
  @name.to_s
19
29
  end
20
30
 
31
+ # The attribute this name stands for in a comparison.
32
+ def attribute
33
+ @name.to_s.delete_suffix('?').to_sym
34
+ end
35
+
36
+ COMPARISONS.each do |operator|
37
+ define_method(operator) do |operand|
38
+ constrain(operator, operand) do
39
+ raise KBS::Error, "`#{attribute} #{operator} ...` only works inside a pattern block"
40
+ end
41
+ end
42
+ end
43
+
44
+ # Another Variable: whether both are the same variable. Any other
45
+ # value in a pattern block: `value == 80` requires that value.
21
46
  def ==(other)
22
- return false unless other.is_a?(Variable)
23
- @name == other.name
47
+ return @name == other.name if other.is_a?(Variable)
48
+
49
+ constrain(:==, other) { false }
50
+ end
51
+
52
+ # Another Variable: whether they differ. Any other value in a
53
+ # pattern block: `code != 3` requires a value other than that.
54
+ def !=(other)
55
+ return @name != other.name if other.is_a?(Variable)
56
+
57
+ constrain(:!=, other) { true }
24
58
  end
25
59
 
26
60
  def eql?(other)
27
- self == other
61
+ other.is_a?(Variable) && @name == other.name
28
62
  end
29
63
 
30
64
  def hash
31
65
  @name.hash
32
66
  end
67
+
68
+ private
69
+
70
+ # Records `attribute <operator> operand` as the attribute's pattern
71
+ # value in the evaluator and returns that value. Outside a pattern
72
+ # block there is no evaluator, and the block's result is returned.
73
+ def constrain(operator, operand)
74
+ return yield unless @evaluator
75
+
76
+ @evaluator.constrain(attribute, @evaluator.public_send(operator, operand))
77
+ end
33
78
  end
34
79
  end
35
80
  end
data/lib/kbs/dsl.rb CHANGED
@@ -11,10 +11,17 @@ require_relative 'dsl/pattern_evaluator'
11
11
  require_relative 'dsl/rule_builder'
12
12
  require_relative 'dsl/knowledge_base'
13
13
 
14
+ # Knowledge-based systems for Ruby: a RETE rule engine, a blackboard and
15
+ # the DSL to write rules in.
14
16
  module KBS
15
- def self.knowledge_base(&block)
16
- kb = DSL::KnowledgeBase.new
17
- kb.instance_eval(&block) if block_given?
17
+ # Builds a knowledge base and evaluates the block in its context.
18
+ #
19
+ # @param engine [KBS::Engine, nil] engine to run on, such as a
20
+ # KBS::Blackboard::Engine for persistence; a new KBS::Engine when nil
21
+ # @return [KBS::DSL::KnowledgeBase]
22
+ def self.knowledge_base(engine: nil, &)
23
+ kb = DSL::KnowledgeBase.new(engine: engine)
24
+ kb.instance_eval(&) if block_given?
18
25
  kb
19
26
  end
20
27
  end