Class: Resyma::Evaluator

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

Overview

Evaluator for Resyma::Core::ParseTree

Instance Method Summary collapse

Constructor Details

#initializeEvaluator

Returns a new instance of Evaluator.



61
62
63
# File 'lib/resyma/parsetree.rb', line 61

def initialize
  @rules = {}
end

Instance Method Details

#def_rule(type) {|AST, The, filename, lino| ... } ⇒ nil

Define a evaluation rule

Parameters:

  • type (Symbol, Array<Symbol>)

    Type(s) assocating to the rule

Yield Parameters:

  • AST (Parser::AST::Node)

    of the node

  • The (Binding)

    environment surrounding the DSL

  • filename (String)

    Source location

  • lino (Integer)

    Source location

Returns:

  • (nil)

    Nothing



76
77
78
79
80
# File 'lib/resyma/parsetree.rb', line 76

def def_rule(type, &block)
  types = type.is_a?(Array) ? type : [type]
  types.each { |sym| @rules[sym] = block }
  nil
end

#evaluate(parsetree, bd, filename, lino) ⇒ Object

Evaluate AST of the parse tree

Parameters:

  • parsetree (Resyma::Core::ParseTree)

    A parse tree whose ast is not nil

  • bd (Binding)

    Environment

  • filename (String)

    Source location

  • lino (Integer)

    Source location

Returns:

  • (Object)

    Reterning value of corresponding evaluating rule



93
94
95
96
97
98
99
100
# File 'lib/resyma/parsetree.rb', line 93

def evaluate(parsetree, bd, filename, lino)
  if parsetree.ast.nil?
    raise NoASTError,
          "AST of parse trees is necessary for evaluation"
  end

  evaluate_ast(parsetree.ast, bd, filename, lino)
end

#evaluate_ast(ast, bd, filename, lino) ⇒ Object

Evaluate the AST by defined rules

Parameters:

  • ast (Parser::AST::Node)

    An abstract syntax tree

  • bd (Binding)

    Environment

  • filename (String)

    Source location

  • lino (Integer)

    Source location

Returns:

  • (Object)

    Returning value of corresponding evaluating rule



112
113
114
115
116
117
118
119
# File 'lib/resyma/parsetree.rb', line 112

def evaluate_ast(ast, bd, filename, lino)
  evaluator = @rules[ast.type]
  if evaluator.nil?
    fallback ast, bd, filename, lino
  else
    evaluator.call(ast, bd, filename, lino)
  end
end

#fallback(ast, bd, filename, lino) ⇒ Object

Fallback evaluating method. AST whose type is not defined by current evaluator will be passed to this method. The default action is unparse the AST by unparser and evaluate the string by eval

Parameters:

  • ast (Parser::AST::Node)

    An abstract syntax tree

  • bd (Binding)

    The environment

  • filename (String)

    Source location

  • lino (Integer)

    Source location

Returns:

  • (Object)

    Evaluating result



133
134
135
136
# File 'lib/resyma/parsetree.rb', line 133

def fallback(ast, bd, filename, lino)
  string = Unparser.unparse(ast)
  eval(string, bd, filename, lino)
end