File: capture.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 (38 lines) | stat: -rw-r--r-- 960 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

# Stores the result of matching an atom against input in the #captures in 
# parse context. Doing so will allow you to pull parts of the ongoing parse
# out later and use them to match other pieces of input. 
#
# Example: 
#   # After this, context.captures[:an_a] returns 'a'
#   str('a').capture(:an_a)
#
#   # Capture and use of the capture: (matches either 'aa' or 'bb')
#   match['ab'].capture(:first) >> 
#     dynamic { |src, ctx| str(ctx.captures[:first]) }
#   
class Parslet::Atoms::Capture < Parslet::Atoms::Base
  attr_reader :parslet, :name

  def initialize(parslet, name)
    super()

    @parslet, @name = parslet, name
  end

  def apply(source, context, consume_all)
    success, value = result = parslet.apply(source, context, consume_all)

    if success
      context.captures[name.to_sym] = 
        flatten(value)
    end
    
    return result
  end
  
  def to_s_inner(prec)
    "(#{name.inspect} = #{parslet.to_s(prec)})"
  end
end