Class: Macros::Expander

Inherits:
Object
  • Object
show all
Includes:
Sexp
Defined in:
lib/macros/expander.rb

Instance Method Summary collapse

Methods included from Sexp

#node?, #s, #seval, #sfind, #smatch?, #treefilter, #treemap

Constructor Details

#initialize(macros) ⇒ Expander

Returns a new instance of Expander.



6
7
8
# File 'lib/macros/expander.rb', line 6

def initialize(macros)
  @macros = macros
end

Instance Method Details

#macro_block?(node) ⇒ Boolean

foo(1,2) { some_more_code }

>> (block >> (send nil :foo >> (int 1) >> (int 2)) >> (args) >> (send nil :some_more_code)))

Returns:

  • (Boolean)


29
30
31
32
33
34
35
36
# File 'lib/macros/expander.rb', line 29

def macro_block?(node)
  # send with block
  node.type == :block &&
    # target is implicit self
    sfind(node, [:block, 0, :send, 0]).nil? &&
    # known macro
    @macros.key?(sfind(node, [:block, 0, :send, 1]))
end

#macroexpand(sexp) ⇒ Object



10
11
12
# File 'lib/macros/expander.rb', line 10

def macroexpand(sexp)
  treemap(sexp, &method(:macroexpand_1))
end

#macroexpand_1(node) ⇒ Object



14
15
16
17
18
19
# File 'lib/macros/expander.rb', line 14

def macroexpand_1(node)
  return node unless macro_block?(node)
  macro = seval @macros[sfind(node, [:block, 0, :send, 1])]
  body = sfind(node, [:block, 2])
  macro.call(body)
end