Class: Calc

Inherits:
Object
  • Object
show all
Includes:
EBNF::PEG::Parser
Defined in:
examples/calc/calc.rb

Instance Attribute Summary collapse

Attributes included from EBNF::PEG::Parser

#packrat, #scanner, #whitespace

Instance Method Summary collapse

Methods included from EBNF::PEG::Parser

#clear_packrat, #debug, #depth, #error, #find_rule, #onFinish, #onStart, #onTerminal, #parse, #prod_data, #progress, #terminal_options, #terminal_regexp, #update_furthest_failure, #warn

Constructor Details

#initialize(**options) ⇒ Calc

Instantiate the calculator using the EBNF grammar.

Parameters:

  • options (Hash{Symbol => Object})

Options Hash (**options):

  • :trace (Boolean)

    Trace level. 0(debug), 1(info), 2(warn), 3(error).



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'examples/calc/calc.rb', line 131

def initialize(**options)
  # Intantiate grammar from ebnf.ebnf
  ebnf = File.expand_path("../calc.ebnf", __FILE__)

  # Perform PEG-specific transformation to the associated rules, which will be passed directly to the parser.
  @rules = EBNF.parse(File.open(ebnf)).make_peg.ast

  @options = options.dup

  # If the `trace` option is set, instantiate a logger for collecting trace information.
  if @options.has_key?(:trace)
    @options[:logger] = Logger.new(STDERR)
    @options[:logger].level = @options[:trace]
    @options[:logger].formatter = lambda {|severity, datetime, progname, msg| "#{severity} #{msg}\n"}
  end
end

Instance Attribute Details

#astArray<EBNF::Rule> (readonly)

Abstract syntax tree from parse

Returns:



16
17
18
# File 'examples/calc/calc.rb', line 16

def ast
  @ast
end

Instance Method Details

#evaluate(input) ⇒ Object

Evaluate an expression

Evaluates each line of input.

Parameters:

  • input (String)


153
154
155
156
157
# File 'examples/calc/calc.rb', line 153

def evaluate(input)
  result = parse(input, :Expr, @rules, **@options)
    # This is called for each Expr
  puts result
end