Permalink
Browse files

+ A few ways of making parlset parsers modular.

  • Loading branch information...
1 parent 90ac079 commit ef7dc560f9eedfd5ac4095d00a15e83be0f33e03 @kschiess committed Mar 25, 2012
Showing with 47 additions and 0 deletions.
  1. +47 −0 example/modularity.rb
  2. 0 example/output/modularity.out
View
@@ -0,0 +1,47 @@
+$:.unshift File.dirname(__FILE__) + "/../lib"
+
+require 'pp'
+require "parslet"
+
+# Demonstrates modular parsers, split out over many classes. Please look at
+# ip_address.rb as well.
+
+module ALanguage
+ include Parslet
+
+ # Parslet rules are really a special kind of method. Mix them into your
+ # classes!
+ rule(:a_language) { str('aaa') }
+end
+
+# Parslet parsers are parslet atoms as well. Create an instance and chain them
+# to your other rules.
+#
+class BLanguage < Parslet::Parser
+ root :blang
+
+ rule(:blang) { str('bbb') }
+end
+
+# Parslet atoms are really Ruby values, pass them around.
+c_language = Parslet.str('ccc')
+
+class Language < Parslet::Parser
+ def initialize(c_language)
+ @c_language = c_language
+ super()
+ end
+
+ root :root
+
+ include ALanguage
+
+ rule(:root) { str('a(') >> a_language >> str(')') >> space |
+ str('b(') >> BLanguage.new >> str(')') >> space |
+ str('c(') >> @c_language >> str(')') >> space }
+ rule(:space) { str(' ').maybe }
+end
+
+Language.new(c_language).parse('a(aaa)')
@floere
floere Mar 26, 2012 collaborator

It might be a good idea to add the expected output as well, in a comment. Even though the idea is to run the example, with a comment I can also view the examples online and get what it is about.

@kschiess
kschiess Mar 27, 2012 owner

The idea in this example is not to run it, but to study it. It produces no output.

@floere
floere Mar 27, 2012 collaborator

Output of the lines I am specifically commenting on - this usually helps me when studying code.

@floere
floere Mar 27, 2012 collaborator

some statement # => some result is what I meant.

@kschiess
kschiess Mar 27, 2012 owner

And what is it that you're proposing? The three lines here have only very unspectacular results... The real result is that they consume input and don't raise.

@kschiess
kschiess Mar 27, 2012 owner

Also, for more explanation see the mailing list.

@floere
floere Mar 27, 2012 collaborator

I simply proposed this:
Language.new(c_language).parse('a(aaa)') # => '"a(aaa)"@0'

This is spectacular enough for me, especially in this example – it tells me that it works! (Where exactly is your information about the "real result" encoded anyway? ;) )

+Language.new(c_language).parse('b(bbb)')
+Language.new(c_language).parse('c(ccc)')
No changes.

0 comments on commit ef7dc56

Please sign in to comment.