Class: ASTNode

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

Overview

Abstract Syntax Tree Node

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(figure) ⇒ ASTNode

Returns a new instance of ASTNode.



36
37
38
39
# File 'lib/ast.rb', line 36

def initialize(figure)
  @name = figure.name
  @children = get_children(figure)
end

Instance Attribute Details

#childrenObject (readonly)

Returns the value of attribute children.



34
35
36
# File 'lib/ast.rb', line 34

def children
  @children
end

#nameObject (readonly)

Returns the value of attribute name.



34
35
36
# File 'lib/ast.rb', line 34

def name
  @name
end

Instance Method Details

#get_children(figure) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/ast.rb', line 41

def get_children(figure)
  children = []
  # read each class attribute of the figure
  figure.instance_variables.each do |var|
    # if the attribute is a list
    if figure.instance_variable_get(var).instance_of?(Array)
      # for each element of the list
      figure.instance_variable_get(var).each do |elem|
        # if the element is a point
        if elem.instance_of?(Point)
          # add it to the children
          children << ASTNode.new(elem)
        end
      end
    else
      # the attribute has a single value
      children << ASTLeaf.new(var.to_s)
    end
  end
  children
end

#to_sObject



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/ast.rb', line 63

def to_s
  # print as a tree (indentation) with the name of the node and its children
  res = "#{@name}\n"
  @children.each do |child|
    if child.instance_of?(ASTNode)
      # print all information of the node
      res += "  #{child.name}\n"
      child.children.each do |grandchild|
        res += "    #{grandchild}\n"
      end
    else
      # print only the name of the leaf
      res += "  #{child}\n"
    end
  end
  res
end