Module: Ibex::Frontend::AST::Node

Overview

Adds deterministic, recursively serializable hashes to Struct nodes.

Instance Method Summary collapse

Instance Method Details

#serialize(value) ⇒ Object

Parameters:

  • value (Object)

Returns:

  • (Object)


61
62
63
64
65
66
67
68
69
# File 'lib/ibex/frontend/ast.rb', line 61

def serialize(value)
  return value if value.nil?

  case value
  when Array then value.map { |item| serialize(item) }
  when Hash then value.to_h { |key, item| [key, serialize(item)] }
  else value.respond_to?(:to_h) ? value.to_h : value
  end
end

#to_hObject

Returns:

  • (Object)


48
49
50
51
52
53
54
55
56
57
# File 'lib/ibex/frontend/ast.rb', line 48

def to_h
  fields = each_pair.to_h { |name, value| [name, serialize(value)] }
  fields.delete(:aliases) if self.class.name.end_with?("::Tokens") && !fields[:aliases]
  if self.class.name.end_with?("::Root")
    fields.delete(:extended) unless fields[:extended]
    fields.delete(:cst) unless fields[:cst]
  end
  fields.delete(:node_annotation) if self.class.name.end_with?("::Alternative") && !fields[:node_annotation]
  { node: self.class.name.split("::").last }.merge(fields)
end