Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 47 lines (35 sloc) 1.137 kb
ef7dc56 Kaspar Schiess + A few ways of making parlset parsers modular.
authored
1 $:.unshift File.dirname(__FILE__) + "/../lib"
2
3 require 'pp'
4 require "parslet"
5
6 # Demonstrates modular parsers, split out over many classes. Please look at
7 # ip_address.rb as well.
8
9 module ALanguage
10 include Parslet
11
12 # Parslet rules are really a special kind of method. Mix them into your
13 # classes!
14 rule(:a_language) { str('aaa') }
15 end
16
17 # Parslet parsers are parslet atoms as well. Create an instance and chain them
18 # to your other rules.
19 #
20 class BLanguage < Parslet::Parser
21 root :blang
22
23 rule(:blang) { str('bbb') }
24 end
25
26 # Parslet atoms are really Ruby values, pass them around.
27 c_language = Parslet.str('ccc')
28
29 class Language < Parslet::Parser
30 def initialize(c_language)
31 @c_language = c_language
32 super()
33 end
34
35 root :root
36
37 include ALanguage
38
39 rule(:root) { str('a(') >> a_language >> str(')') >> space |
40 str('b(') >> BLanguage.new >> str(')') >> space |
41 str('c(') >> @c_language >> str(')') >> space }
42 rule(:space) { str(' ').maybe }
43 end
44
45 Language.new(c_language).parse('a(aaa)')
46 Language.new(c_language).parse('b(bbb)')
47 Language.new(c_language).parse('c(ccc)')
Something went wrong with that request. Please try again.