/
processor.rb
448 lines (394 loc) · 13.4 KB
/
processor.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
require 'rubygems'
require 'ruby_parser'
require 'sexp_processor'
module RubyLess
class RubyLessProcessor < SexpProcessor
attr_reader :ruby
INFIX_OPERATOR = ['<=>', '==', '<', '>', '<=', '>=', '-', '+', '*', '/', '%']
PREFIX_OPERATOR = ['-@']
def self.translate(receiver, string)
if sexp = RubyParser.new.parse(string)
res = self.new(receiver).process(sexp)
if res.klass.kind_of?(Hash)
res.opts[:class] = Hash
end
res
elsif string.size == 0
''
else
raise RubyLess::SyntaxError.new("Syntax error")
end
rescue Racc::ParseError => err
raise RubyLess::SyntaxError.new(err.message)
end
def initialize(helper)
super()
@helper = helper
@indent = " "
self.auto_shift_type = true
self.strict = true
self.expected = TypedString
end
def process(exp)
super
rescue UnknownNodeError => err
if err.message =~ /Unknown node-type :(.*?) /
raise RubyLess::SyntaxError.new("'#{$1}' not available in RubyLess.")
else
raise RubyLess::SyntaxError.new(err.message)
end
# return nil if exp.nil?
# method = exp.shift
# send("process_#{method}", exp)
end
def process_const(exp)
const_name = exp.pop.to_s
if opts = @helper.respond_to?(:safe_const_type) ? @helper.safe_const_type(const_name) : nil
t opts[:method], opts
else
raise RubyLess::Error.new("Unknown constant '#{const_name}'.")
end
end
def process_true(*args)
t 'true', {:class => Boolean, :literal => true}
end
def process_false(*args)
t 'false', {:class => Boolean, :literal => false}
end
def process_and(exp)
t "(#{process(exp.shift)} and #{process(exp.shift)})", Boolean
end
def process_or(exp)
left, right = process(exp.shift), process(exp.shift)
if left.klass == right.klass
t "(#{left} or #{right})", :class => right.klass, :nil => right.could_be_nil?
else
t "(#{left} or #{right})", Boolean
end
end
def process_not(exp)
t "not #{process(exp.shift)}", Boolean
end
def process_if(exp)
cond = process(exp.shift)
true_res = process(exp.shift)
false_res = process(exp.shift)
if true_res && false_res && true_res.klass != false_res.klass
raise RubyLess::SyntaxError.new("Error in conditional expression: '#{true_res}' and '#{false_res}' do not return results of same type (#{true_res.klass} != #{false_res.klass}).")
end
raise RubyLess::SyntaxError.new("Error in conditional expression.") unless true_res || false_res
opts = {}
opts[:nil] = true_res.nil? || true_res.could_be_nil? || false_res.nil? || false_res.could_be_nil?
opts[:class] = true_res ? true_res.klass : false_res.klass
t "#{cond} ? #{true_res || 'nil'} : #{false_res || 'nil'}", opts
end
def process_call(exp)
unless receiver = process(exp.shift)
receiver = @helper.kind_of?(TypedString) ? @helper : nil
end
method_call(receiver, exp)
end
def process_fcall(exp)
method_call(@helper.kind_of?(TypedString) ? @helper : nil, exp)
end
def process_arglist(exp)
code = t("")
until exp.empty? do
code.append_argument(process(exp.shift))
end
code
end
def process_array(exp)
literal = true
list = []
classes = []
while !exp.empty?
res = process(exp.shift)
content_class ||= res.opts[:class]
unless res.opts[:class] <= content_class
classes = list.map { content_class.name } + [res.opts[:class].name]
raise RubyLess::Error.new("Mixed Array not supported ([#{classes * ','}]).")
end
list << res
end
res.opts[:class] = [content_class] # Array
res.opts[:elem] = content_class
t "[#{list * ','}]", res.opts.merge(:literal => nil)
end
# Is this used ?
def process_vcall(exp)
var_name = exp.shift
unless opts = get_method(nil, [var_name])
raise RubyLess::Error.new("Unknown variable or method '#{var_name}'.")
end
method = opts[:method]
if args = opts[:prepend_args]
method = "#{method}(#{args.raw})"
end
t method, opts
end
def process_lit(exp)
lit = exp.shift
t lit.inspect, get_lit_class(lit)
end
def process_str(exp)
lit = exp.shift
t lit.inspect, :class => String, :literal => lit
end
def process_dstr(exp)
t "\"#{parse_dstr(exp)}\"", String
end
def process_evstr(exp)
exp.empty? ? t('', String) : process(exp.shift)
end
def process_hash(exp)
result = t "", String
until exp.empty?
key = exp.shift
if [:lit, :str].include?(key.first)
key = key[1]
rhs = exp.shift
type = rhs.first
rhs = process rhs
#rhs = "(#{rhs})" unless [:lit, :str].include? type # TODO: verify better!
result.set_hash(key, rhs)
else
# ERROR: invalid key
raise RubyLess::SyntaxError.new("Invalid key type for hash (should be a literal value, was #{key.first.inspect})")
end
end
result.rebuild_hash
result
end
def process_ivar(exp)
method_call(nil, exp)
end
private
def t(content, opts = nil)
if opts.nil?
opts = {:class => String}
elsif !opts.kind_of?(Hash)
opts = {:class => opts}
end
TypedString.new(content, opts)
end
def t_if(cond, true_res, opts)
if cond != []
if cond.size > 1
condition = "(#{cond.join(' && ')})"
else
condition = cond.join('')
end
# we can append to 'raw'
if opts[:nil]
# applied method could produce a nil value (so we cannot concat method on top of 'raw' and only check previous condition)
t "(#{condition} ? #{true_res} : nil)", opts
else
# we can keep on checking only 'condition' and appending methods to 'raw'
t "(#{condition} ? #{true_res} : nil)", opts.merge(:nil => true, :cond => cond, :raw => true_res)
end
else
t true_res, opts
end
end
def method_call(receiver, exp)
method = exp.shift.to_s
arg_sexp = args = exp.shift # rescue nil
if arg_sexp
args = process(arg_sexp)
if args == ''
args = nil
signature = [method]
else
signature = [method] + [args.klass].flatten
end
# execution conditional
cond = args ? (args.cond || []) : []
else
args = nil
signature = [method]
cond = []
end
if receiver && receiver.klass.kind_of?(Hash)
# resolve now
if signature.first == '[]' && klass = receiver.klass[args.literal]
return receiver.hash[args.literal]
else
# safe_method_type on Hash... ?
receiver = TypedString.new(receiver, Hash)
opts = get_method(receiver, signature)
end
else
opts = get_method(receiver, signature)
end
# method type can rewrite receiver
if opts[:receiver]
if receiver
receiver = "#{receiver}.#{opts[:receiver]}"
else
receiver = opts[:receiver]
end
end
if receiver
method_call_with_receiver(receiver, args, opts, cond, signature)
else
method = opts[:method]
args = args_with_prepend(args, opts)
if (proc = opts[:pre_processor]) && !args.list.detect {|a| !a.literal}
if proc.kind_of?(Proc)
res = proc.call(*([receiver] + args.list.map(&:literal)))
else
res = @helper.send(proc, *args.list.map(&:literal))
end
return res.kind_of?(TypedString) ? res : t(res.inspect, :class => String, :literal => res)
end
if opts[:accept_nil]
method_call_accepting_nil(method, args, opts)
else
args = "(#{args.raw})" if args
t_if cond, "#{method}#{args}", opts
end
end
end
def method_call_accepting_nil(method, args, opts)
if args
args = args.list.map do |arg|
if !arg.could_be_nil? || arg.raw == arg.cond.to_s
arg.raw
else
"(#{arg.cond} ? #{arg.raw} : nil)"
end
end.join(', ')
t "#{method}(#{args})", opts
else
t method, opts
end
end
def method_call_with_receiver(receiver, args, opts, cond, signature)
method = opts[:method]
arg_list = args ? args.list : []
if receiver.could_be_nil? &&
!(opts == SafeClass.safe_method_type_for(NilClass, signature) && receiver.cond == [receiver])
# Do not add a condition if the method applies on nil
cond += receiver.cond
if (proc = opts[:pre_processor]) && !arg_list.detect {|a| !a.literal}
# pre-processor on element that can be nil
if proc.kind_of?(Proc)
res = proc.call([receiver] + arg_list.map(&:literal))
return t_if cond, res, res.opts
end
end
elsif (proc = opts[:pre_processor]) && !arg_list.detect {|a| !a.literal}
if proc.kind_of?(Proc)
res = proc.call([receiver] + arg_list.map(&:literal))
elsif receiver.literal
res = receiver.literal.send(*([method] + arg_list.map(&:literal)))
end
if res
if res.kind_of?(TypedString)
# This can happen if we use native methods on TypedString (like gsub) that return a new
# typedstring without calling initialize....
if res.opts.nil?
res.instance_variable_set(:@opts, :class => String, :literal => res)
end
return res
else
return t(res.inspect, :class => String, :literal => res)
end
end
end
if method == '/'
t_if cond, "(#{receiver.raw}#{method}#{args.raw} rescue nil)", opts.merge(:nil => true)
elsif INFIX_OPERATOR.include?(method)
t_if cond, "(#{receiver.raw}#{method}#{args.raw})", opts
elsif PREFIX_OPERATOR.include?(method)
t_if cond, "#{method.to_s[0..0]}#{receiver.raw}", opts
elsif method == '[]'
t_if cond, "#{receiver.raw}[#{args.raw}]", opts
else
args = args_with_prepend(args, opts)
args = "(#{args.raw})" if args
t_if cond, "#{receiver.raw}.#{method}#{args}", opts
end
end
def parse_dstr(exp, in_regex = false)
res = escape_str(exp.shift, in_regex)
while part = exp.shift
case part.first
when :str then
res << escape_str(part.last, in_regex)
else
res << '#{' << process(part) << '}'
end
end
res
end
def escape_str(str, in_regex = false)
res = str.gsub(/"/, '\"').gsub(/\n/, '\n')
res.gsub!(/\//, '\/') if in_regex
res
end
def get_method(receiver, signature)
klass = receiver ? receiver.klass : @helper
if klass.respond_to?(:safe_method_type)
type = klass.safe_method_type(signature, receiver)
elsif klass.kind_of?(Array)
unless type = SafeClass.safe_method_type_for(Array, signature)
raise RubyLess::NoMethodError.new(receiver, "[#{klass}]", signature)
end
elsif type = SafeClass.safe_method_type_for(klass, signature)
end
raise RubyLess::NoMethodError.new(receiver, klass, signature) if !type || type[:class].kind_of?(Symbol) # we cannot send: no object.
type[:class].kind_of?(Proc) ? type[:class].call(@helper, receiver ? receiver.klass : @helper, signature) : type
end
def get_lit_class(lit)
unless lit_class = RubyLess::SafeClass.literal_class_for(lit.class)
raise RubyLess::SyntaxError.new("#{klass} literal not supported by RubyLess.")
end
{:class => lit_class, :literal => lit}
end
def args_with_prepend(args, opts)
if prepend_args = opts[:prepend_args]
if prepend_args.kind_of?(Array)
prepend_args = array_to_arguments(prepend_args)
end
if args
prepend_args.append_argument(args)
args = prepend_args
else
args = prepend_args
end
end
if append_args = opts[:append_args]
if append_args.kind_of?(Array)
append_args = array_to_arguments(append_args)
end
if args
args.append_argument(append_args)
else
args = append_args
end
end
if append_hash = opts[:append_hash]
last_arg = args.list.last
unless last_arg.klass.kind_of?(Hash)
last_arg = t "", String
args.append_argument(last_arg)
end
append_hash.each do |key, value|
last_arg.set_hash(key, value)
end
last_arg.rebuild_hash
args.rebuild_arguments
end
args
end
def array_to_arguments(args)
code = t('')
args.each do |arg|
code.append_argument(arg)
end
code
end
end
end