Class: Delorean::Engine

Inherits:
Object
  • Object
show all
Defined in:
lib/delorean/engine.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(module_name, sset = nil) ⇒ Engine

Returns a new instance of Engine.


13
14
15
16
17
18
# File 'lib/delorean/engine.rb', line 13

def initialize(module_name, sset = nil)
  # name of current module
  @module_name = module_name
  @sset = sset
  reset
end

Instance Attribute Details

#comp_setObject (readonly)

Returns the value of attribute comp_set


10
11
12
# File 'lib/delorean/engine.rb', line 10

def comp_set
  @comp_set
end

#importsObject (readonly)

Returns the value of attribute imports


10
11
12
# File 'lib/delorean/engine.rb', line 10

def imports
  @imports
end

#last_nodeObject (readonly)

Returns the value of attribute last_node


10
11
12
# File 'lib/delorean/engine.rb', line 10

def last_node
  @last_node
end

#line_noObject (readonly)

Returns the value of attribute line_no


10
11
12
# File 'lib/delorean/engine.rb', line 10

def line_no
  @line_no
end

#mObject (readonly)

Returns the value of attribute m


10
11
12
# File 'lib/delorean/engine.rb', line 10

def m
  @m
end

#module_nameObject (readonly)

Returns the value of attribute module_name


10
11
12
# File 'lib/delorean/engine.rb', line 10

def module_name
  @module_name
end

#pmObject (readonly)

Returns the value of attribute pm


10
11
12
# File 'lib/delorean/engine.rb', line 10

def pm
  @pm
end

#ssetObject (readonly)

Returns the value of attribute sset


10
11
12
# File 'lib/delorean/engine.rb', line 10

def sset
  @sset
end

Class Method Details

.grok_runtime_exception(exc) ⇒ Object


456
457
458
459
460
461
462
463
464
# File 'lib/delorean/engine.rb', line 456

def self.grok_runtime_exception(exc)
  # parse out the delorean-related backtrace records
  bt = exc.backtrace.map do |x|
    x =~ /^#{MOD}(.+?):(\d+)(|:in `(.+)')$/
    $1 && [$1, $2.to_i, $4.sub(/#{POST}$/, '')]
  end.reject(&:!)

  { 'error' => exc.message, 'backtrace' => bt }
end

Instance Method Details

#_evaluate_attr_with_cache(klass, attr, params) ⇒ Object


438
439
440
441
442
443
444
445
446
447
448
449
# File 'lib/delorean/engine.rb', line 438

def _evaluate_attr_with_cache(klass, attr, params)
  params_without_engine = params.reject { |k, _| k == :_engine }

  ::Delorean::Cache.with_cache(
    klass: klass,
    method: attr,
    mutable_params: params,
    params: params_without_engine
  ) do
    klass.send("#{attr}#{POST}".to_sym, params)
  end
end

#_evaluate_with_cache(klass, attrs, params) ⇒ Object


420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'lib/delorean/engine.rb', line 420

def _evaluate_with_cache(klass, attrs, params)
  if attrs.is_a?(Array)
    attrs.map do |attr|
      unless /^[_a-z][A-Za-z0-9_]*$/.match?(attr)
        raise "bad attribute '#{attr}'"
      end

      _evaluate_attr_with_cache(klass, attr, params)
    end
  else
    unless /^[_a-z][A-Za-z0-9_]*$/.match?(attrs)
      raise "bad attribute '#{attrs}'"
    end

    _evaluate_attr_with_cache(klass, attrs, params)
  end
end

#closing_bracket?(line) ⇒ Boolean

Returns:

  • (Boolean)

223
224
225
226
227
228
229
230
231
# File 'lib/delorean/engine.rb', line 223

def closing_bracket?(line)
  stripped = line.strip

  return true if stripped == ']'
  return true if stripped == ')'
  return true if stripped == '}'

  false
end

#curr_lineObject


44
45
46
# File 'lib/delorean/engine.rb', line 44

def curr_line
  @multi_no || @line_no
end

#enumerate_attrsObject

enumerate qualified list of all attrs


341
342
343
344
345
# File 'lib/delorean/engine.rb', line 341

def enumerate_attrs
  @node_attrs.keys.each_with_object({}) do |node, h|
    h[node] = enumerate_attrs_by_node(node)
  end
end

#enumerate_attrs_by_node(node) ⇒ Object

enumerate qualified list of attrs by node


348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# File 'lib/delorean/engine.rb', line 348

def enumerate_attrs_by_node(node)
  raise 'bad node' unless node

  begin
    klass = node.is_a?(String) ? @m.module_eval(node) : node
  rescue NameError
    # FIXME: a little hacky.  Should raise an exception.
    return []
  end

  raise "bad node class #{klass}" unless klass.is_a?(Class)

  klass.methods.map(&:to_s).select do |x|
    x.end_with?(POST)
  end.map do |x|
    x.sub(/#{POST}$/, '')
  end
end

#enumerate_nodesObject

enumerate all nodes


336
337
338
# File 'lib/delorean/engine.rb', line 336

def enumerate_nodes
  SortedSet[* @node_attrs.keys]
end

#enumerate_paramsObject

enumerate all params


368
369
370
# File 'lib/delorean/engine.rb', line 368

def enumerate_params
  @param_set
end

#enumerate_params_by_node(node) ⇒ Object

enumerate params by a single node


373
374
375
376
# File 'lib/delorean/engine.rb', line 373

def enumerate_params_by_node(node)
  attrs = enumerate_attrs_by_node(node)
  Set.new(attrs.select { |a| @param_set.include?(a) })
end

#err(exc, msg) ⇒ Object

Raises:

  • (exc)

201
202
203
# File 'lib/delorean/engine.rb', line 201

def err(exc, msg)
  raise exc.new(msg, @module_name, curr_line)
end

#eval_to_hash(node, attrs, params = {}) ⇒ Object


451
452
453
454
# File 'lib/delorean/engine.rb', line 451

def eval_to_hash(node, attrs, params = {})
  res = evaluate(node, attrs, params)
  Hash[* attrs.zip(res).flatten(1)]
end

#evaluate(node, attrs, params = {}) ⇒ Object

Runtime


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
# File 'lib/delorean/engine.rb', line 382

def evaluate(node, attrs, params = {})
  raise 'bad params' unless params.is_a?(Hash)

  if node.is_a?(Class)
    klass = node
  else
    raise "bad node '#{node}'" unless /^[A-Z][a-zA-Z0-9_]*$/.match?(node)

    begin
      klass = @m.const_get(node)
    rescue NameError
      err(UndefinedNodeError, "node #{node} is undefined")
    end
  end

  params[:_engine] = self

  if klass.respond_to?(NODE_CACHE_ARG) && klass.send(NODE_CACHE_ARG, params)
    return _evaluate_with_cache(klass, attrs, params)
  end

  if attrs.is_a?(Array)
    attrs.map do |attr|
      unless /^[_a-z][A-Za-z0-9_]*$/.match?(attr)
        raise "bad attribute '#{attr}'"
      end

      klass.send("#{attr}#{POST}".to_sym, params)
    end
  else
    unless /^[_a-z][A-Za-z0-9_]*$/.match?(attrs)
      raise "bad attribute '#{attrs}'"
    end

    klass.send("#{attrs}#{POST}".to_sym, params)
  end
end

#gen_import(name) ⇒ Object


63
64
65
66
67
# File 'lib/delorean/engine.rb', line 63

def gen_import(name)
  @imports.merge!(@imports[name].imports)

  @m.const_set("#{MOD}#{name.gsub('::', '__')}", @imports[name].m)
end

#generate(t) ⇒ Object


233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/delorean/engine.rb', line 233

def generate(t)
  t.check(self)

  begin
    # generate ruby code
    gen = t.rewrite(self)
  rescue RuntimeError => exc
    err(ParseError, 'codegen error: ' + exc.message)
  end

  # puts gen

  begin
    # evaluate generated code in @m
    @m.module_eval(gen, "#{MOD}#{module_name}", curr_line)
  rescue StandardError => exc
    # bad ruby code generated, shoudn't happen
    err(ParseError, 'codegen error: ' + exc.message)
  end
end

#get_import_engine(name) ⇒ Object


69
70
71
72
# File 'lib/delorean/engine.rb', line 69

def get_import_engine(name)
  err(ParseError, "#{name} not imported") unless @imports[name]
  @imports[name]
end

#hcountObject

used in counting literal hashes


40
41
42
# File 'lib/delorean/engine.rb', line 40

def hcount
  @hcount += 1
end

#node_defined?(name) ⇒ Boolean

Returns:

  • (Boolean)

74
75
76
# File 'lib/delorean/engine.rb', line 74

def node_defined?(name)
  @pm.constants.member? name.to_sym
end

#parse(source) ⇒ Object


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
# File 'lib/delorean/engine.rb', line 254

def parse(source)
  raise "can't call parse again without reset" if @pm

  # @m module is used at runtime for code evaluation.  @pm module
  # is only used during parsing to check for errors.
  @m = BaseModule.clone
  @pm = Module.new

  multi_line = nil
  @multi_no = nil

  lines = source.each_line.to_a

  lines.each_with_index do |line, index|
    @line_no += 1

    # skip comments
    next if /^\s*\#/.match?(line)

    # remove trailing blanks
    line.rstrip!

    next if line.empty?

    if multi_line
      # if line starts with >4 spaces, assume it's a multline
      # continuation.
      if /\A {5}/.match?(line) || closing_bracket?(line)
        multi_line += line
        next
      else
        t = parser.parse(multi_line)
        err(ParseError, 'syntax error') unless t

        generate(t)
        multi_line = nil
        @multi_no = nil
      end
    end

    # Initially Delorean code is parsed by single line.
    # If line can not be parsed as valid Delorean expressions, parser
    # would combine it with the following lines that are indented by more
    # than 4 spaces and attempt to parse it again.

    # However the first line of method with block can be parsed as a valid
    # method or attribute call. In order to avoid that, we had to add this
    # lookahead hack, that treats any expressions as multiline when
    # the following line is indented by more that 4 spaces.
    next_line = lines[index + 1] || ''

    if /\A {5}/.match?(next_line)
      multi_line ||= ''
      multi_line += line
      @multi_no ||= @line_no
      next
    end

    t = parser.parse(line)

    if !t
      err(ParseError, 'syntax error') unless /^\s+/.match?(line)

      multi_line = line
      @multi_no = @line_no
    else
      generate(t)
    end
  end

  if multi_line
    t = parser.parse(multi_line)
    err(ParseError, 'syntax error') unless t
    generate(t)
  end
end

#parse_call_attr(node_name, attr_name) ⇒ Object

Parse-time check to see if attr is available. If not, error is raised.


118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/delorean/engine.rb', line 118

def parse_call_attr(node_name, attr_name)
  return [] if comp_set.member?(attr_name)

  # get the class associated with node
  klass = @pm.module_eval(node_name)

  # puts attr_name, "#{attr_name}#{POST}".to_sym, klass.methods.inspect

  begin
    klass.send("#{attr_name}#{POST}".to_sym, [])
  rescue NoMethodError
    err(UndefinedError, "'#{attr_name}' not defined in #{node_name}")
  end
end

#parse_call_last_node_attr(attr_name) ⇒ Object

Parse-time check to see if attr is available on current node.


134
135
136
137
# File 'lib/delorean/engine.rb', line 134

def parse_call_last_node_attr(attr_name)
  err(ParseError, 'Not inside a node') unless @last_node
  parse_call_attr(@last_node, attr_name)
end

#parse_check_call_fn(fn, _argcount, class_name = nil) ⇒ Object


205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/delorean/engine.rb', line 205

def parse_check_call_fn(fn, _argcount, class_name = nil)
  klass = case class_name
          when nil
            @m::BaseClass
          when String
            parse_class(class_name)
          else
            class_name
          end

  err(UndefinedFunctionError, "Function #{fn} not found") unless
    klass.methods.member? fn.to_sym
end

#parse_check_defined_mod_node(pname, mname) ⇒ Object


94
95
96
97
# File 'lib/delorean/engine.rb', line 94

def parse_check_defined_mod_node(pname, mname)
  engine = mname ? get_import_engine(mname) : self
  engine.parse_check_defined_node(pname, true)
end

#parse_check_defined_node(name, flag) ⇒ Object

Check to see if node with given name is defined. flag tells the method about our expectation. flag=true means that we make sure that name is defined. flag=false is the opposite.


81
82
83
84
85
86
87
88
# File 'lib/delorean/engine.rb', line 81

def parse_check_defined_node(name, flag)
  isdef = node_defined?(name)

  if isdef != flag
    isdef ? err(RedefinedError, "#{name} already defined") :
      err(UndefinedError, "#{name} not defined yet")
  end
end

#parse_class(class_name) ⇒ Object


187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/delorean/engine.rb', line 187

def parse_class(class_name)
  begin
    # need the runtime module here (@m) since we need to
    # introspect methods/attrs.
    klass = @m.module_eval(class_name)
  rescue NoMethodError, NameError
    err(UndefinedError, "Can't find class: #{class_name}")
  end

  return klass if klass.instance_of?(Class) || klass.instance_of?(Module)

  err(UndefinedError, "Access to non-class/module: #{class_name}")
end

#parse_define_attr(name, spec) ⇒ Object

parse-time attr definition


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
# File 'lib/delorean/engine.rb', line 154

def parse_define_attr(name, spec)
  err(ParseError, "Can't define '#{name}' outside a node") unless
    @last_node

  err(RedefinedError, "Can't redefine '#{name}' in node #{@last_node}") if
    @node_attrs[@last_node].member? name

  @node_attrs[@last_node] << name

  checks = spec.map do |a|
    n = a.index('.') ? a : "#{@last_node}.#{a}"
    "_x.member?('#{n}') ? raise('#{n}') : #{a}#{POST}(_x + ['#{n}'])"
  end.join(';')

  code =
    "class #{@last_node}; def self.#{name}#{POST}(_x); #{checks}; end; end"

  # pp code

  @pm.module_eval(code)

  begin
    parse_call_attr(@last_node, name)
  rescue RuntimeError
    err(RecursionError, "'#{name}' is recursive")
  end
end

#parse_define_node(name, pname, mname = nil) ⇒ Object


99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/delorean/engine.rb', line 99

def parse_define_node(name, pname, mname = nil)
  parse_check_defined_node(name, false)
  parse_check_defined_mod_node(pname, mname) if pname

  sname = pname ? super_name(pname, mname) : 'Object'

  @pm.module_eval <<-RUBY, __FILE__, __LINE__ + 1
    class #{name} < #{sname}; end
  RUBY

  # latest defined node
  @last_node = name

  # mapping of node name to list of attrs it defines
  @node_attrs[name] = []
end

#parse_define_param(name, spec) ⇒ Object


182
183
184
185
# File 'lib/delorean/engine.rb', line 182

def parse_define_param(name, spec)
  parse_define_attr(name, spec)
  @param_set.add(name)
end

#parse_define_var(var_name) ⇒ Object


139
140
141
142
143
144
145
146
# File 'lib/delorean/engine.rb', line 139

def parse_define_var(var_name)
  if comp_set.member? var_name
    err(RedefinedError,
        "List comprehension can't redefine variable '#{var_name}'")
  end

  comp_set.add var_name
end

#parse_import(name) ⇒ Object


48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/delorean/engine.rb', line 48

def parse_import(name)
  err(ParseError, 'No script set') unless sset

  err(ParseError, "Module #{name} importing itself") if
    name == module_name

  begin
    @imports[name] = sset.get_engine(name)
  rescue StandardError => exc
    err(ImportError, exc.to_s)
  end

  @pm.const_set("#{MOD}#{name.gsub('::', '__')}", @imports[name].pm)
end

#parse_undef_var(var_name) ⇒ Object


148
149
150
151
# File 'lib/delorean/engine.rb', line 148

def parse_undef_var(var_name)
  err(ParseError, 'internal error') unless comp_set.member? var_name
  comp_set.delete var_name
end

#parserObject


219
220
221
# File 'lib/delorean/engine.rb', line 219

def parser
  @@parser ||= DeloreanParser.new
end

#resetObject


20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/delorean/engine.rb', line 20

def reset
  @m = nil
  @pm = nil
  @last_node = nil
  @node_attrs = {}
  @line_no = 0
  @multi_no = nil

  # set of comprehension vars
  @comp_set = Set.new

  # set of all params
  @param_set = Set.new

  @imports = {}

  @hcount = 0
end

#super_name(pname, mname) ⇒ Object


90
91
92
# File 'lib/delorean/engine.rb', line 90

def super_name(pname, mname)
  mname ? "#{MOD}#{mname.gsub('::', '__')}::#{pname}" : pname
end