Class: AST::Node

Inherits:
Object
  • Object
show all
Includes:
AST
Defined in:
lib/ast_ext/node.rb

Overview

redefining in order to allow type itself to be any type e.g. String, Symbol, Fixnum, etc.

Instance Method Summary collapse

Methods included from AST

#new_ast

Constructor Details

#initialize(type, children = [], properties = {}) ⇒ Node

The ‘properties` hash is passed to #assign_properties.



10
11
12
13
14
15
16
17
18
# File 'lib/ast_ext/node.rb', line 10

def initialize(type, children=[], properties={})
  @type, @children = type, children.to_a.freeze

  assign_properties(properties)

  @hash = [@type.object_id, @children, self.class].hash

  freeze
end

Instance Method Details

Returns string reconstituted from polish-notation into notation normally required by each operator.

Parameters:

  • logic (Hash) (defaults to: nil)

    hash of operators allowed in this AST containing each operator’s print properties

Returns:

  • (String)

    string reconstituted from polish-notation into notation normally required by each operator



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/ast_ext/node.rb', line 22

def print(logic=nil)
  return type.to_s if children.empty?
  str = ''
  op = type.respond_to?(:text) ? type : logic[type.to_s]
  return str unless op
  case op.position
    when :prefix
      str << op.symbol
      children.each do |c| str << c.print(logic) end
    when :postfix
      children.each do |c| str << c.print(logic) end
      str << op.symbol
    when :infix
      if op.arity > 2
        str << children.first.print(logic) << op.symbol << children[1].print(logic) << op.pair.symbol << children.last.print
      else
        str << (children.first.respond_to?(:print) ? children.first.print(logic) : children.first.symbol) << op.symbol << children.last.print
      end
    else # should not happen
  end
  str
end