dentaku 4.0.2 → 4.2.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 (41) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/rspec.yml +1 -1
  3. data/.github/workflows/rubocop.yml +1 -1
  4. data/CHANGELOG.md +87 -0
  5. data/README.md +176 -11
  6. data/lib/dentaku/ast/access.rb +14 -11
  7. data/lib/dentaku/ast/array.rb +2 -0
  8. data/lib/dentaku/ast/combinators.rb +105 -4
  9. data/lib/dentaku/ast/functions/duration.rb +3 -3
  10. data/lib/dentaku/ast/functions/rounddown.rb +8 -2
  11. data/lib/dentaku/ast/functions/roundup.rb +8 -2
  12. data/lib/dentaku/ast/functions/xor.rb +6 -6
  13. data/lib/dentaku/ast/member_access.rb +56 -0
  14. data/lib/dentaku/ast/negation.rb +4 -0
  15. data/lib/dentaku/ast/operation.rb +6 -0
  16. data/lib/dentaku/ast.rb +2 -0
  17. data/lib/dentaku/bulk_expression_solver.rb +48 -7
  18. data/lib/dentaku/calculator.rb +26 -3
  19. data/lib/dentaku/dependency_resolver.rb +12 -0
  20. data/lib/dentaku/humanize_visitor.rb +276 -0
  21. data/lib/dentaku/numeric_parser.rb +7 -6
  22. data/lib/dentaku/parser.rb +15 -2
  23. data/lib/dentaku/print_visitor.rb +38 -2
  24. data/lib/dentaku/token_scanner.rb +37 -19
  25. data/lib/dentaku/tokenizer.rb +6 -2
  26. data/lib/dentaku/version.rb +1 -1
  27. data/lib/dentaku/visitor/infix.rb +4 -0
  28. data/mise.toml +2 -0
  29. data/spec/ast/member_access_spec.rb +124 -0
  30. data/spec/ast/xor_spec.rb +16 -3
  31. data/spec/builtin_functions_spec.rb +26 -0
  32. data/spec/bulk_expression_solver_spec.rb +88 -0
  33. data/spec/calculator_spec.rb +181 -1
  34. data/spec/case_sensitivity_spec.rb +54 -0
  35. data/spec/humanize_visitor_spec.rb +217 -0
  36. data/spec/parser_spec.rb +8 -0
  37. data/spec/print_visitor_spec.rb +66 -0
  38. data/spec/tokenizer_spec.rb +19 -0
  39. data/spec/visitor_spec.rb +7 -0
  40. metadata +9 -3
  41. data/lib/dentaku/token_matchers.rb +0 -29
@@ -32,6 +32,10 @@ module Dentaku
32
32
  true
33
33
  end
34
34
 
35
+ def self.prefix?
36
+ true
37
+ end
38
+
35
39
  def self.precedence
36
40
  40
37
41
  end
@@ -26,6 +26,12 @@ module Dentaku
26
26
  false
27
27
  end
28
28
 
29
+ # a prefix operator has no left operand, so it never folds the
30
+ # operators before it
31
+ def self.prefix?
32
+ false
33
+ end
34
+
29
35
  def accept(visitor)
30
36
  visitor.visit_operation(self)
31
37
  end
data/lib/dentaku/ast.rb CHANGED
@@ -11,6 +11,7 @@ require_relative './ast/negation'
11
11
  require_relative './ast/comparators'
12
12
  require_relative './ast/combinators'
13
13
  require_relative './ast/access'
14
+ require_relative './ast/member_access'
14
15
  require_relative './ast/array'
15
16
  require_relative './ast/grouping'
16
17
  require_relative './ast/case'
@@ -28,6 +29,7 @@ require_relative './ast/functions/intercept'
28
29
  require_relative './ast/functions/map'
29
30
  require_relative './ast/functions/max'
30
31
  require_relative './ast/functions/min'
32
+ require_relative './ast/functions/mul'
31
33
  require_relative './ast/functions/not'
32
34
  require_relative './ast/functions/or'
33
35
  require_relative './ast/functions/pluck'
@@ -90,7 +90,7 @@ module Dentaku
90
90
 
91
91
  evaluated_facts = facts.to_h.each_with_object({}) do |(var_name, ast), h|
92
92
  with_rescues(var_name, h, block) do
93
- h[var_name] = ast.is_a?(Array) ? ast.map(&:value) : ast.value
93
+ h[var_name] = fact_value(ast)
94
94
  end
95
95
  end
96
96
 
@@ -116,6 +116,15 @@ module Dentaku
116
116
  {}
117
117
  end
118
118
 
119
+ # facts can be arrays and hashes nested to any depth, e.g. [{ a: 1 }]
120
+ def fact_value(ast)
121
+ case ast
122
+ when Array then ast.map { |a| fact_value(a) }
123
+ when Hash then ast.transform_values { |a| fact_value(a) }
124
+ else ast.value
125
+ end
126
+ end
127
+
119
128
  def with_rescues(var_name, results, block)
120
129
  yield
121
130
  rescue Dentaku::UnboundVariableError, Dentaku::ZeroDivisionError, Dentaku::ArgumentError => ex
@@ -152,13 +161,45 @@ module Dentaku
152
161
  end
153
162
  end
154
163
 
164
+ # Stored memory can satisfy a formula's reference to another key being
165
+ # solved, which hides that edge from `dependencies`. Order those keys first
166
+ # anyway so the formula sees the solved value rather than the stored one,
167
+ # unless the edge would close a cycle -- then the stored value is what
168
+ # breaks it, as for self-referential formulas.
169
+ def resolve_order_graph
170
+ graph = dependencies
171
+ keys = expressions.keys.map { |k| normalized_name(k) }
172
+
173
+ hidden = expressions.to_h do |var, expr|
174
+ own = normalized_name(var)
175
+ visible = graph.fetch(var, []).map { |d| normalized_name(d) }
176
+ all = Array(calculator.dependencies(expr, nil)).map { |d| normalized_name(d) }
177
+ [var, (all & keys) - visible - [own]]
178
+ end
179
+ return graph if hidden.values.all?(&:empty?)
180
+
181
+ with_hidden = graph.merge(hidden) { |_, deps, extra| deps + extra }
182
+ cycle_of = {}
183
+ DependencyResolver.cycles(with_hidden, calculator.case_sensitive).each_with_index do |cycle, i|
184
+ cycle.each { |name| cycle_of[name] = i }
185
+ end
186
+
187
+ graph.merge(hidden) do |var, deps, extra|
188
+ cycle = cycle_of[normalized_name(var)]
189
+ deps + extra.reject { |e| cycle && cycle_of[e] == cycle }
190
+ end
191
+ end
192
+
155
193
  def variables_in_resolve_order
156
- cache_key = "#{!!calculator.case_sensitive}|#{expressions.keys.map(&:to_s).sort.join("|")}"
157
- @ordered_deps ||= self.class.dependency_cache.fetch(cache_key) {
158
- DependencyResolver.find_resolve_order(dependencies, calculator.case_sensitive).tap do |d|
159
- self.class.dependency_cache[cache_key] = d if calculator.cache_dependency_order?
160
- end
161
- }
194
+ @ordered_deps ||= begin
195
+ dependency_graph = resolve_order_graph
196
+ cache_key = [!!calculator.case_sensitive, dependency_graph]
197
+ self.class.dependency_cache.fetch(cache_key) {
198
+ DependencyResolver.find_resolve_order(dependency_graph, calculator.case_sensitive).tap do |d|
199
+ self.class.dependency_cache[cache_key] = d if calculator.cache_dependency_order?
200
+ end
201
+ }
202
+ end
162
203
  end
163
204
  end
164
205
  end
@@ -5,6 +5,7 @@ require 'dentaku/flat_hash'
5
5
  require 'dentaku/parser'
6
6
  require 'dentaku/string_casing'
7
7
  require 'dentaku/token'
8
+ require 'dentaku/humanize_visitor'
8
9
 
9
10
  module Dentaku
10
11
  class Calculator
@@ -62,6 +63,7 @@ module Dentaku
62
63
  def evaluate(expression, data = {}, &block)
63
64
  context = evaluation_context(data, :permissive)
64
65
  return evaluate_array(expression, context, &block) if expression.is_a?(Array)
66
+ return expression.transform_values { |e| evaluate(e, context, &block) } if expression.is_a?(Hash)
65
67
 
66
68
  evaluate!(expression, context)
67
69
  rescue Dentaku::Error => ex
@@ -75,6 +77,7 @@ module Dentaku
75
77
  def evaluate!(expression, data = {}, &block)
76
78
  context = evaluation_context(data, :strict)
77
79
  return evaluate_array!(expression, context, &block) if expression.is_a? Array
80
+ return expression.transform_values { |e| evaluate!(e, context, &block) } if expression.is_a? Hash
78
81
 
79
82
  store(context) do
80
83
  node = ast(expression)
@@ -111,6 +114,8 @@ module Dentaku
111
114
  expression.dependencies(test_context)
112
115
  when Array
113
116
  expression.flat_map { |e| dependencies(e, context) }
117
+ when Hash
118
+ expression.values.flat_map { |e| dependencies(e, context) }
114
119
  else
115
120
  ast(expression).dependencies(test_context)
116
121
  end
@@ -125,14 +130,21 @@ module Dentaku
125
130
  expression.dependencies(AST::Node::STATIC_CONTEXT).uniq
126
131
  when Array
127
132
  expression.flat_map { |e| identifiers(e) }.uniq
133
+ when Hash
134
+ expression.values.flat_map { |e| identifiers(e) }.uniq
128
135
  else
129
136
  ast(expression).dependencies(AST::Node::STATIC_CONTEXT).uniq
130
137
  end
131
138
  end
132
139
 
140
+ def humanize(expression, data = {})
141
+ HumanizeVisitor.new(ast(expression), data).to_s
142
+ end
143
+
133
144
  def ast(expression)
134
145
  return expression if expression.is_a?(AST::Node)
135
146
  return expression.map { |e| ast(e) } if expression.is_a? Array
147
+ return expression.transform_values { |e| ast(e) } if expression.is_a? Hash
136
148
 
137
149
  @ast_cache.fetch(expression) {
138
150
  options = {
@@ -209,13 +221,24 @@ module Dentaku
209
221
 
210
222
  private def pairs_to_store(key_or_hash, value)
211
223
  if value.nil?
212
- key_or_hash = FlatHash.from_hash_with_intermediates(key_or_hash) if nested_data_support
213
- key_or_hash.map { |key, val| [standardize_case(key.to_s), val] }
224
+ key_or_hash = FlatHash.from_hash_with_intermediates(key_or_hash) if nested_data_support && nested?(key_or_hash)
225
+ key_or_hash.map { |key, val| [memory_key(key), val] }
214
226
  else
215
- [[standardize_case(key_or_hash.to_s), value]]
227
+ [[memory_key(key_or_hash), value]]
216
228
  end
217
229
  end
218
230
 
231
+ private def nested?(hash)
232
+ hash.each_value { |v| return true if v.is_a?(Hash) }
233
+ false
234
+ end
235
+
236
+ # Symbol#name returns the symbol's interned string, so symbol keys skip
237
+ # the extra String that to_s would allocate
238
+ private def memory_key(key)
239
+ key.is_a?(Symbol) ? standardize_case(key).name : standardize_case(key.to_s)
240
+ end
241
+
219
242
  def store_formula(key, formula)
220
243
  store(key, ast(formula))
221
244
  end
@@ -8,6 +8,14 @@ module Dentaku
8
8
  self.new(vars_to_dependencies_hash, case_sensitive).sort
9
9
  end
10
10
 
11
+ # normalized names of the variables that sit on a cycle, grouped by cycle
12
+ def self.cycles(vars_to_dependencies_hash, case_sensitive = false)
13
+ resolver = self.new(vars_to_dependencies_hash, case_sensitive)
14
+ resolver.strongly_connected_components.select do |component|
15
+ component.size > 1 || resolver.depends_on_itself?(component.first)
16
+ end
17
+ end
18
+
11
19
  def initialize(vars_to_dependencies_hash, case_sensitive = false)
12
20
  @case_sensitive = case_sensitive
13
21
  @key_mapping = Hash[vars_to_dependencies_hash.keys.map { |k| [normalized_name(k), k] }]
@@ -27,6 +35,10 @@ module Dentaku
27
35
  @vars_to_deps.fetch(node.to_s, []).each(&block)
28
36
  end
29
37
 
38
+ def depends_on_itself?(node)
39
+ @vars_to_deps.fetch(node.to_s, []).include?(node.to_s)
40
+ end
41
+
30
42
  private
31
43
 
32
44
  def normalized_name(variable_name)
@@ -0,0 +1,276 @@
1
+ require 'dentaku/print_visitor'
2
+
3
+ module Dentaku
4
+ class HumanizeVisitor < PrintVisitor
5
+ OPERATOR_PHRASES = {
6
+ Dentaku::AST::Addition => 'plus',
7
+ Dentaku::AST::Subtraction => 'minus',
8
+ Dentaku::AST::Multiplication => 'times',
9
+ Dentaku::AST::Division => 'divided by',
10
+ Dentaku::AST::Modulo => 'modulo',
11
+ Dentaku::AST::Exponentiation => 'to the power of',
12
+ Dentaku::AST::Equal => 'equals',
13
+ Dentaku::AST::NotEqual => 'does not equal',
14
+ Dentaku::AST::LessThan => 'is less than',
15
+ Dentaku::AST::LessThanOrEqual => 'is less than or equal to',
16
+ Dentaku::AST::GreaterThan => 'is greater than',
17
+ Dentaku::AST::GreaterThanOrEqual => 'is greater than or equal to',
18
+ Dentaku::AST::And => 'and',
19
+ Dentaku::AST::Or => 'or',
20
+ Dentaku::AST::ExclusiveOr => 'exclusive-or',
21
+ Dentaku::AST::Not => 'not',
22
+ Dentaku::AST::BitwiseAnd => 'bitwise and',
23
+ Dentaku::AST::BitwiseOr => 'bitwise or',
24
+ Dentaku::AST::BitwiseShiftLeft => 'shifted left by',
25
+ Dentaku::AST::BitwiseShiftRight => 'shifted right by',
26
+ }.freeze
27
+
28
+ MATH_PHRASES = {
29
+ 'SIN' => [:unary, 'sine of'],
30
+ 'COS' => [:unary, 'cosine of'],
31
+ 'TAN' => [:unary, 'tangent of'],
32
+ 'ASIN' => [:unary, 'arcsine of'],
33
+ 'ACOS' => [:unary, 'arccosine of'],
34
+ 'ATAN' => [:unary, 'arctangent of'],
35
+ 'SINH' => [:unary, 'hyperbolic sine of'],
36
+ 'COSH' => [:unary, 'hyperbolic cosine of'],
37
+ 'TANH' => [:unary, 'hyperbolic tangent of'],
38
+ 'ASINH' => [:unary, 'inverse hyperbolic sine of'],
39
+ 'ACOSH' => [:unary, 'inverse hyperbolic cosine of'],
40
+ 'ATANH' => [:unary, 'inverse hyperbolic tangent of'],
41
+ 'EXP' => [:unary, 'e to the power of'],
42
+ 'LOG2' => [:unary, 'log base 2 of'],
43
+ 'LOG10' => [:unary, 'log base 10 of'],
44
+ 'SQRT' => [:unary, 'square root of'],
45
+ 'CBRT' => [:unary, 'cube root of'],
46
+ 'ERF' => [:unary, 'error function of'],
47
+ 'ERFC' => [:unary, 'complementary error function of'],
48
+ 'GAMMA' => [:unary, 'gamma function of'],
49
+ 'LGAMMA' => [:unary, 'log-gamma of'],
50
+ 'FREXP' => [:unary, 'mantissa and exponent of'],
51
+ 'ATAN2' => [:binary_and, 'arctangent of'],
52
+ 'HYPOT' => [:binary_and, 'hypotenuse of'],
53
+ 'LDEXP' => [:binary_infix, 'times 2 to the power of'],
54
+ 'LOG' => [:log, 'logarithm of'],
55
+ }.freeze
56
+
57
+ def initialize(node, values = {})
58
+ @values = values.each_with_object({}) { |(k, v), h| h[k.to_s] = v }
59
+ super(node)
60
+ end
61
+
62
+ def visit_operation(node)
63
+ phrase = OPERATOR_PHRASES[node.class]
64
+ return super unless phrase
65
+
66
+ visit_operand(node.left, node.class.precedence, suffix: ' ', dir: :left) if node.left
67
+ @output << phrase
68
+ visit_operand(node.right, node.class.precedence, prefix: ' ', dir: :right) if node.right
69
+ end
70
+
71
+ def visit_function(node)
72
+ case node.name.to_s.upcase
73
+ when 'IF' then humanize_if(node)
74
+ when 'AND' then humanize_join(node.args, 'and')
75
+ when 'OR' then humanize_join(node.args, 'or')
76
+ when 'XOR' then humanize_join(node.args, 'exclusive-or')
77
+ when 'NOT' then @output << 'not '; node.args[0].accept(self)
78
+ when 'SWITCH' then humanize_switch(node)
79
+ when 'MIN' then humanize_aggregate(node.args, 'minimum of')
80
+ when 'MAX' then humanize_aggregate(node.args, 'maximum of')
81
+ when 'SUM' then humanize_aggregate(node.args, 'sum of')
82
+ when 'AVG' then humanize_aggregate(node.args, 'average of')
83
+ when 'COUNT' then humanize_aggregate(node.args, 'count of')
84
+ when 'ABS' then @output << 'absolute value of '; node.args[0].accept(self)
85
+ when 'ROUND' then humanize_round(node, 'rounded')
86
+ when 'ROUNDUP' then humanize_round(node, 'rounded up')
87
+ when 'ROUNDDOWN' then humanize_round(node, 'rounded down')
88
+ when 'INTERCEPT'
89
+ @output << 'linear intercept of '
90
+ node.args[0].accept(self); @output << ' and '; node.args[1].accept(self)
91
+ when 'LEFT'
92
+ @output << 'first '; node.args[1].accept(self)
93
+ @output << ' characters of '; node.args[0].accept(self)
94
+ when 'RIGHT'
95
+ @output << 'last '; node.args[1].accept(self)
96
+ @output << ' characters of '; node.args[0].accept(self)
97
+ when 'MID'
98
+ node.args[2].accept(self)
99
+ @output << ' characters of '; node.args[0].accept(self)
100
+ @output << ' starting at position '; node.args[1].accept(self)
101
+ when 'LEN'
102
+ @output << 'length of '; node.args[0].accept(self)
103
+ when 'FIND'
104
+ @output << 'position of '; node.args[0].accept(self)
105
+ @output << ' in '; node.args[1].accept(self)
106
+ when 'SUBSTITUTE'
107
+ node.args[0].accept(self)
108
+ @output << ' with '; node.args[1].accept(self)
109
+ @output << ' replaced by '; node.args[2].accept(self)
110
+ when 'CONCAT' then humanize_concat(node.args)
111
+ when 'CONTAINS'
112
+ node.args[1].accept(self); @output << ' contains '; node.args[0].accept(self)
113
+ when 'MAP' then humanize_enum(node, 'for each', 'in', ': ')
114
+ when 'FILTER' then humanize_enum(node, 'filter', 'in', ' where ')
115
+ when 'ALL' then humanize_enum(node, 'all', 'in', ' satisfy ')
116
+ when 'ANY' then humanize_enum(node, 'any', 'in', ' satisfies ')
117
+ when 'PLUCK' then humanize_pluck(node)
118
+ else
119
+ humanize_math(node) || super
120
+ end
121
+ end
122
+
123
+ def visit_case(node)
124
+ node.switch.accept(self)
125
+ @output << ' case:'
126
+ node.conditions.each { |c| c.accept(self) }
127
+ node.else&.accept(self)
128
+ end
129
+
130
+ def visit_switch(node)
131
+ node.node.accept(self)
132
+ end
133
+
134
+ def visit_case_conditional(node)
135
+ @output << ' when '
136
+ node.when.node.accept(self)
137
+ @output << ' then '
138
+ node.then.node.accept(self)
139
+ end
140
+
141
+ def visit_else(node)
142
+ @output << '; otherwise '
143
+ node.node.accept(self)
144
+ end
145
+
146
+ def visit_negation(node)
147
+ @output << 'negative '
148
+ node.node.accept(self)
149
+ end
150
+
151
+ def visit_nil(_node)
152
+ @output << 'null'
153
+ end
154
+
155
+ # in English a function call loses its brackets, so `IF(a, b, c).d` would
156
+ # read as `if a then b else c.d`; group calls before `[...]` and `.name`
157
+ def group_access_structure?(node)
158
+ super || node.is_a?(Dentaku::AST::Function)
159
+ end
160
+
161
+ def group_member_structure?(node)
162
+ super || node.is_a?(Dentaku::AST::Function)
163
+ end
164
+
165
+ def visit_identifier(node)
166
+ if @values.key?(node.identifier)
167
+ value = @values[node.identifier]
168
+ @output << (value.is_a?(::String) ? value.inspect : value.to_s)
169
+ else
170
+ super
171
+ end
172
+ end
173
+
174
+ private
175
+
176
+ def humanize_if(node)
177
+ @output << 'if '
178
+ node.predicate.accept(self)
179
+ @output << ' then '
180
+ node.left.accept(self)
181
+ @output << ' else '
182
+ node.right.accept(self)
183
+ end
184
+
185
+ def humanize_join(args, conjunction)
186
+ args.each_with_index do |arg, i|
187
+ @output << " #{conjunction} " if i > 0
188
+ arg.accept(self)
189
+ end
190
+ end
191
+
192
+ def humanize_aggregate(args, prefix)
193
+ @output << prefix
194
+ args.each_with_index do |arg, i|
195
+ @output << (i == 0 ? ' ' : ', ')
196
+ arg.accept(self)
197
+ end
198
+ end
199
+
200
+ def humanize_round(node, word)
201
+ node.args[0].accept(self)
202
+ @output << " #{word} to "
203
+ node.args[1] ? node.args[1].accept(self) : (@output << '0')
204
+ @output << ' decimal places'
205
+ end
206
+
207
+ def humanize_concat(args)
208
+ args.each_with_index do |arg, i|
209
+ @output << (i == args.length - 1 && i > 0 ? ' and ' : ', ') if i > 0
210
+ arg.accept(self)
211
+ end
212
+ @output << ' joined'
213
+ end
214
+
215
+ def humanize_enum(node, verb, preposition, separator)
216
+ collection, item, expr = node.args
217
+ @output << "#{verb} "
218
+ item.accept(self)
219
+ @output << " #{preposition} "
220
+ collection.accept(self)
221
+ @output << separator
222
+ expr.accept(self)
223
+ end
224
+
225
+ def humanize_pluck(node)
226
+ @output << 'values of '
227
+ node.args[1].accept(self)
228
+ @output << ' from '
229
+ node.args[0].accept(self)
230
+ if node.args[2]
231
+ @output << ' (default: '; node.args[2].accept(self); @output << ')'
232
+ end
233
+ end
234
+
235
+ def humanize_switch(node)
236
+ args = node.args
237
+ rest = args[1..]
238
+ has_default = rest.length.odd?
239
+ pairs = has_default ? rest[0..-2] : rest
240
+ pair_count = pairs.length / 2
241
+
242
+ args[0].accept(self)
243
+ @output << ' switch:'
244
+ pairs.each_slice(2).with_index do |(match, result), idx|
245
+ @output << ' when '; match.accept(self)
246
+ @output << ' use '; result.accept(self)
247
+ @output << ';' if has_default || idx < pair_count - 1
248
+ end
249
+ if has_default
250
+ @output << ' otherwise '; rest.last.accept(self)
251
+ end
252
+ end
253
+
254
+ def humanize_math(node)
255
+ style, phrase = MATH_PHRASES[node.name.to_s.upcase]
256
+ return nil unless phrase
257
+
258
+ case style
259
+ when :unary
260
+ @output << "#{phrase} "; node.args[0].accept(self)
261
+ when :binary_and
262
+ @output << "#{phrase} "
263
+ node.args[0].accept(self); @output << ' and '; node.args[1].accept(self)
264
+ when :binary_infix
265
+ node.args[0].accept(self); @output << " #{phrase} "; node.args[1].accept(self)
266
+ when :log
267
+ @output << "#{phrase} "
268
+ node.args[0].accept(self)
269
+ if node.args[1]
270
+ @output << ' in base '; node.args[1].accept(self)
271
+ end
272
+ end
273
+ true
274
+ end
275
+ end
276
+ end
@@ -5,20 +5,21 @@ module Dentaku
5
5
  HEXADECIMAL_PATTERN = '(0x[0-9a-f]+)\b'.freeze
6
6
  # e.g: [0x1A3F]
7
7
 
8
+ NUMERIC_OR_HEXADECIMAL_REGEX = %r{\A(-?(#{ NUMERIC_PATTERN }|#{ HEXADECIMAL_PATTERN }))\z}i
9
+ NUMERIC_REGEX = %r{\A(#{ NUMERIC_PATTERN })\z}i
10
+ HEXADECIMAL_REGEX = %r{\A(#{ HEXADECIMAL_PATTERN })\z}i
11
+
8
12
  class << self
9
13
  def match(string)
10
- regex = %r{\A(-?(#{ NUMERIC_PATTERN }|#{ HEXADECIMAL_PATTERN }))\z}i
11
- string.match(regex)
14
+ string.match(NUMERIC_OR_HEXADECIMAL_REGEX)
12
15
  end
13
16
 
14
17
  def match_numeric(string)
15
- regex = %r{\A(#{ NUMERIC_PATTERN })\z}i
16
- string.match(regex)
18
+ string.match(NUMERIC_REGEX)
17
19
  end
18
20
 
19
21
  def match_hexadecimal(string)
20
- regex = %r{\A(#{ HEXADECIMAL_PATTERN })\z}i
21
- string.match(regex)
22
+ string.match(HEXADECIMAL_REGEX)
22
23
  end
23
24
 
24
25
  def parse_numeric_string(raw)
@@ -25,7 +25,8 @@ module Dentaku
25
25
 
26
26
  and: AST::And,
27
27
  or: AST::Or,
28
- xor: AST::Xor,
28
+ xor: AST::ExclusiveOr,
29
+ not: AST::Not,
29
30
  }.freeze
30
31
 
31
32
  attr_reader :input, :output, :operations, :arities, :case_sensitive
@@ -133,6 +134,8 @@ module Dentaku
133
134
  handle_case(token)
134
135
  when :access
135
136
  handle_access(token)
137
+ when :member_access
138
+ handle_member_access(token)
136
139
  when :array
137
140
  handle_array(token)
138
141
  when :grouping
@@ -144,7 +147,9 @@ module Dentaku
144
147
 
145
148
  def handle_operator(token, lookahead)
146
149
  op_class = operation(token).resolve_class(lookahead)
147
- if op_class.right_associative?
150
+ if op_class.prefix?
151
+ # nothing to fold: the operand comes after
152
+ elsif op_class.right_associative?
148
153
  consume while operations.last && operations.last < AST::Operation && op_class.precedence < operations.last.precedence
149
154
  else
150
155
  consume while operations.last && operations.last < AST::Operation && op_class.precedence <= operations.last.precedence
@@ -243,6 +248,14 @@ module Dentaku
243
248
  end
244
249
  end
245
250
 
251
+ # the tokenizer only emits a member access after a complete operand, so
252
+ # the operand it applies to is on top of the output stack
253
+ def handle_member_access(token)
254
+ fail! :invalid_statement if output.empty?
255
+
256
+ output << AST::MemberAccess.new(output.pop, token.value, case_sensitive: case_sensitive)
257
+ end
258
+
246
259
  def handle_array(token)
247
260
  case token.value
248
261
  when :array_start
@@ -84,12 +84,29 @@ module Dentaku
84
84
  end
85
85
 
86
86
  def visit_access(node)
87
- node.structure.accept(self)
87
+ visit_accessed(node.structure, group_access_structure?(node.structure))
88
88
  @output << "["
89
89
  node.index.accept(self)
90
90
  @output << "]"
91
91
  end
92
92
 
93
+ def visit_member_access(node)
94
+ visit_accessed(node.structure, group_member_structure?(node.structure))
95
+ @output << "." << node.member
96
+ end
97
+
98
+ # `[...]` can directly follow a variable, an array literal, another
99
+ # access or a function call; anything else is grouped, e.g. `(a + b)[0]`
100
+ def group_access_structure?(node)
101
+ !(node.is_a?(Dentaku::AST::Identifier) || node.is_a?(Dentaku::AST::Array) || chainable?(node))
102
+ end
103
+
104
+ # anything else would re-parse differently, e.g. `(user).name` as the
105
+ # variable `user.name`
106
+ def group_member_structure?(node)
107
+ !chainable?(node)
108
+ end
109
+
93
110
  def visit_literal(node)
94
111
  @output << node.quoted
95
112
  end
@@ -103,11 +120,30 @@ module Dentaku
103
120
  end
104
121
 
105
122
  def visit_array(node)
106
- @output << node.value.to_s
123
+ @output << "{"
124
+ element_count = node.elements.length
125
+ node.elements.each_with_index do |element, index|
126
+ element.accept(self)
127
+ @output << ", " unless index >= element_count - 1
128
+ end
129
+ @output << "}"
107
130
  end
108
131
 
109
132
  def to_s
110
133
  @output
111
134
  end
135
+
136
+ private
137
+
138
+ def visit_accessed(node, grouped)
139
+ @output << "(" if grouped
140
+ node.accept(self)
141
+ @output << ")" if grouped
142
+ end
143
+
144
+ # `[...]` and `.name` can follow these without grouping
145
+ def chainable?(node)
146
+ node.is_a?(Dentaku::AST::Access) || node.is_a?(Dentaku::AST::Function)
147
+ end
112
148
  end
113
149
  end