Class: MOSAIK::Syntax::Tree

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/mosaik/syntax/tree.rb

Overview

Tree of constants in the codebase

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTree

Returns a new instance of Tree.



13
14
15
16
# File 'lib/mosaik/syntax/tree.rb', line 13

def initialize
  # Create a top-level constant to represent the root of the hierarchy
  @top = Constant.new("main")
end

Instance Attribute Details

#topObject (readonly)

Returns the value of attribute top.



11
12
13
# File 'lib/mosaik/syntax/tree.rb', line 11

def top
  @top
end

Instance Method Details

#[](constant_path) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/mosaik/syntax/tree.rb', line 18

def [](constant_path)
  current_constant = top

  # Split constant path by ::
  constant_path.split("::").inject(nil) do |fully_qualified_constant_name, constant_name|
    # Generate fully qualified constant name
    fully_qualified_constant_name = [fully_qualified_constant_name, constant_name].compact.join("::")

    # Look up or create constant
    next_constant = current_constant.descendants.find { |c| c.name == fully_qualified_constant_name }
    next_constant ||= Constant.new(fully_qualified_constant_name, current_constant)

    # Add constant to hierarchy
    current_constant.descendants << next_constant

    # Descend into the next constant
    current_constant = next_constant

    fully_qualified_constant_name
  end

  current_constant
end

#dfs(constant, &block) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/mosaik/syntax/tree.rb', line 46

def dfs(constant, &block)
  constant.descendants.each do |descendant|
    yield descendant

    dfs(descendant, &block)
  end
end

#eachObject



42
43
44
# File 'lib/mosaik/syntax/tree.rb', line 42

def each(&)
  dfs(top, &)
end