File: expression.rb

package info (click to toggle)
ruby-parslet 1.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 908 kB
  • ctags: 473
  • sloc: ruby: 5,220; makefile: 2
file content (51 lines) | stat: -rw-r--r-- 1,177 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

# Allows specifying rules as strings using the exact same grammar that treetop
# does, minus the actions. This is on one hand a good example of a fully
# fledged parser and on the other hand might even turn out really useful. 
#
# This can be viewed as an extension to parslet and might even be hosted in
# its own gem one fine day. 
# 
class Parslet::Expression
  include Parslet
  
  autoload :Treetop, 'parslet/expression/treetop'
  
  # Creates a parslet from a foreign language expression. 
  #
  # Example: 
  #   
  #   Parslet::Expression.new("'a' 'b'")
  #
  def initialize(str, opts={}, context=self)
    @type = opts[:type] || :treetop
    @exp = str
    @parslet = transform(
      parse(str))
  end
  
  # Transforms the parse tree into a parslet expression. 
  #
  def transform(tree)
    transform = Treetop::Transform.new
    
    # pp tree
    transform.apply(tree)
  rescue 
    warn "Could not transform: " + tree.inspect
    raise
  end
  
  # Parses the string and returns a parse tree.
  #
  def parse(str)
    parser = Treetop::Parser.new
    parser.parse(str)
  end

  # Turns this expression into a parslet.
  #
  def to_parslet
    @parslet
  end
end