Class: Skeem::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/skeem/parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeParser

Returns a new instance of Parser.



11
12
13
14
15
16
17
18
19
20
# File 'lib/skeem/parser.rb', line 11

def initialize
  # Create a Rley facade object
  @engine = Rley::Engine.new do |cfg|
    cfg.diagnose = true
    cfg.repr_builder = SkmBuilder
  end

  # Step 1. Load Skeem grammar
  @engine.use_grammar(Skeem::Grammar)
end

Instance Attribute Details

#engineObject (readonly)

Returns the value of attribute engine.



9
10
11
# File 'lib/skeem/parser.rb', line 9

def engine
  @engine
end

Instance Method Details

#parse(source) ⇒ ParseTree

Parse the given Skeem expression into a parse tree.

Examples:

Defining a function that computes the area of a circle

source = "(define circle-area (lambda (r) (* pi (* r r))))"
regex = Skeem::parse(source)

Parameters:

  • source (String)

    Skeem expression to parse

Returns:

  • (ParseTree)

    A regexp object equivalent to the Skeem expression.



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/skeem/parser.rb', line 28

def parse(source)
  lexer = Skeem::Tokenizer.new(source)
  result = engine.parse(lexer.tokens)

  unless result.success?
    # Stop if the parse failed...
    line1 = "Parsing failed\n"
    line2 = "Reason: #{result.failure_reason.message}"
    raise StandardError, line1 + line2
  end

  engine.to_ptree(result)
end