Class: Rattler::Parsers::ActionCode

Inherits:
Object
  • Object
show all
Defined in:
lib/rattler/parsers/action_code.rb

Overview

ActionCode defines abstract ruby code with variables that can be bound to captured parse results to produce concrete ruby code for semantic actions.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(code) ⇒ ActionCode

Returns a new instance of ActionCode.

Parameters:

  • code (String)

    ruby code with optional block parameters and free variables and block parameters that can bound to captured parse results



12
13
14
15
16
17
18
19
20
# File 'lib/rattler/parsers/action_code.rb', line 12

def initialize(code)
  if md = /\A\s*\|([^|]*)\|(.*)\Z/.match(code)
    @param_names = md[1].split(',').map {|_| _.strip }
    @body = md[2].strip
  else
    @param_names = []
    @body = code.strip
  end
end

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body.



22
23
24
# File 'lib/rattler/parsers/action_code.rb', line 22

def body
  @body
end

#param_namesObject (readonly)

Returns the value of attribute param_names.



22
23
24
# File 'lib/rattler/parsers/action_code.rb', line 22

def param_names
  @param_names
end

Instance Method Details

#arg_bindings(args) ⇒ Hash

Returns matchers for parameters in the ruby code associated with args as replacements values.

Parameters:

  • args (Array)

    captured parse results as arguments to the ruby code

Returns:

  • (Hash)

    matchers for parameters in the ruby code associated with args as replacements values



43
44
45
46
47
48
# File 'lib/rattler/parsers/action_code.rb', line 43

def arg_bindings(args)
  if param_names.count > args.count
    raise ArgumentError, 'more parameter names than arguments'
  end
  to_bindings param_names.zip(args)
end

#bind(scope) ⇒ String

Bind parameters and variables in the code to parse results in scope

Parameters:

  • scope (ParserScope)

    the scope of captured parse results

Returns:

  • (String)

    concrete ruby code with the parameters and variables bound to the captured parse results



29
30
31
# File 'lib/rattler/parsers/action_code.rb', line 29

def bind(scope)
  bind_in body, scope
end

#scoped_bindings(scope) ⇒ Hash

Returns matchers for variables in the ruby code associated with replacement values.

Parameters:

  • scope (ParserScope)

    the scope of captured parse results

Returns:

  • (Hash)

    matchers for variables in the ruby code associated with replacement values



36
37
38
# File 'lib/rattler/parsers/action_code.rb', line 36

def scoped_bindings(scope)
  to_bindings(scope.bindings).merge(arg_bindings(scope.captures))
end