treetop 1.4.14 → 1.4.15

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,278 +0,0 @@
1
- <html><head><link href="./screen.css" rel="stylesheet" type="text/css" />
2
- <script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
3
- </script>
4
- <script type="text/javascript">
5
- _uacct = "UA-3418876-1";
6
- urchinTracker();
7
- </script>
8
- </head><body><div id="top"><div id="main_navigation"><ul><li>Documentation</li><li><a href="contribute.html">Contribute</a></li><li><a href="index.html">Home</a></li></ul></div></div><div id="middle"><div id="main_content"><div id="secondary_navigation"><ul><li>Syntax</li><li><a href="semantic_interpretation.html">Semantics</a></li><li><a href="using_in_ruby.html">Using In Ruby</a></li><li><a href="pitfalls_and_advanced_techniques.html">Advanced Techniques</a></li></ul></div><div id="documentation_content"><h1>Syntactic Recognition</h1>
9
-
10
- <p>Treetop grammars are written in a custom language based on parsing expression grammars. Literature on the subject of <a href="http://en.wikipedia.org/wiki/Parsing_expression_grammar">parsing expression grammars</a> (PEGs) is useful in writing Treetop grammars.</p>
11
-
12
- <p>PEGs have no separate lexical analyser (since the algorithm has the same time-complexity guarantees as the best lexical analysers) so all whitespace and other lexical niceties (like comments) must be explicitly handled in the grammar. A further benefit is that multiple PEG grammars may be seamlessly composed into a single parser.</p>
13
-
14
- <h1>Grammar Structure</h1>
15
-
16
- <p>Treetop grammars look like this:</p>
17
-
18
- <pre><code>require "my_stuff"
19
-
20
- grammar GrammarName
21
- include Module::Submodule
22
-
23
- rule rule_name
24
- ...
25
- end
26
-
27
- rule rule_name
28
- ...
29
- end
30
-
31
- ...
32
- end
33
- </code></pre>
34
-
35
- <p>The main keywords are:</p>
36
-
37
- <ul>
38
- <li><p><code>grammar</code> : This introduces a new grammar. It is followed by a constant name to which the grammar will be bound when it is loaded.</p></li>
39
- <li><p><code>include</code>: This causes the generated parser to include the referenced Ruby module (which may be another parser)</p></li>
40
- <li><p><code>require</code>: This must be at the start of the file, and is passed through to the emitted Ruby grammar</p></li>
41
- <li><p><code>rule</code> : This defines a parsing rule within the grammar. It is followed by a name by which this rule can be referenced within other rules. It is then followed by a parsing expression defining the rule.</p></li>
42
- </ul>
43
-
44
-
45
- <p>A grammar may be surrounded by one or more nested <code>module</code> statements, which provides a namespace for the generated Ruby parser.</p>
46
-
47
- <p>Treetop will emit a module called <code>GrammarName</code> and a parser class called <code>GrammarNameParser</code> (in the module namespace, if specified).</p>
48
-
49
- <h1>Parsing Expressions</h1>
50
-
51
- <p>Each rule associates a name with a <em>parsing expression</em>. Parsing expressions are a generalization of vanilla regular expressions. Their key feature is the ability to reference other expressions in the grammar by name.</p>
52
-
53
- <h2>Terminal Symbols</h2>
54
-
55
- <h3>Strings</h3>
56
-
57
- <p>Strings are surrounded in double or single quotes and must be matched exactly.</p>
58
-
59
- <ul>
60
- <li><code>"foo"</code></li>
61
- <li><code>'foo'</code></li>
62
- </ul>
63
-
64
-
65
- <h3>Character Classes</h3>
66
-
67
- <p>Character classes are surrounded by brackets. Their semantics are identical to those used in Ruby's regular expressions.</p>
68
-
69
- <ul>
70
- <li><code>[a-zA-Z]</code></li>
71
- <li><code>[0-9]</code></li>
72
- </ul>
73
-
74
-
75
- <h3>The Anything Symbol</h3>
76
-
77
- <p>The anything symbol is represented by a dot (<code>.</code>) and matches any single character.</p>
78
-
79
- <h3>Ellipsis</h3>
80
-
81
- <p>An empty string matches at any position and consumes no input. It's useful when you wish to treat a single symbol as part of a sequence, for example when an alternate rule will be processed using shared code.</p>
82
-
83
- <pre>
84
- rule alts
85
- ( foo bar / baz '' )
86
- {
87
- def value
88
- elements.map{|e| e.text_value }
89
- end
90
- }
91
- end
92
- </pre>
93
-
94
-
95
- <h2>Nonterminal Symbols</h2>
96
-
97
- <p>Nonterminal symbols are unquoted references to other named rules. They are equivalent to an inline substitution of the named expression.</p>
98
-
99
- <pre><code>rule foo
100
- "the dog " bar
101
- end
102
-
103
- rule bar
104
- "jumped"
105
- end
106
- </code></pre>
107
-
108
- <p>The above grammar is equivalent to:</p>
109
-
110
- <pre><code>rule foo
111
- "the dog jumped"
112
- end
113
- </code></pre>
114
-
115
- <h2>Ordered Choice</h2>
116
-
117
- <p>Parsers attempt to match ordered choices in left-to-right order, and stop after the first successful match.</p>
118
-
119
- <pre><code>"foobar" / "foo" / "bar"
120
- </code></pre>
121
-
122
- <p>Note that if <code>"foo"</code> in the above expression came first, <code>"foobar"</code> would never be matched.
123
- Note also that the above rule will match <code>"bar"</code> as a prefix of <code>"barbie"</code>.
124
- Care is required when it's desired to match language keywords exactly.</p>
125
-
126
- <h2>Sequences</h2>
127
-
128
- <p>Sequences are a space-separated list of parsing expressions. They have higher precedence than choices, so choices must be parenthesized to be used as the elements of a sequence.</p>
129
-
130
- <pre><code>"foo" "bar" ("baz" / "bop")
131
- </code></pre>
132
-
133
- <h2>Zero or More</h2>
134
-
135
- <p>Parsers will greedily match an expression zero or more times if it is followed by the star (<code>*</code>) symbol.</p>
136
-
137
- <ul>
138
- <li><code>'foo'*</code> matches the empty string, <code>"foo"</code>, <code>"foofoo"</code>, etc.</li>
139
- </ul>
140
-
141
-
142
- <h2>One or More</h2>
143
-
144
- <p>Parsers will greedily match an expression one or more times if it is followed by the plus (<code>+</code>) symbol.</p>
145
-
146
- <ul>
147
- <li><code>'foo'+</code> does not match the empty string, but matches <code>"foo"</code>, <code>"foofoo"</code>, etc.</li>
148
- </ul>
149
-
150
-
151
- <h2>Optional Expressions</h2>
152
-
153
- <p>An expression can be declared optional by following it with a question mark (<code>?</code>).</p>
154
-
155
- <ul>
156
- <li><code>'foo'?</code> matches <code>"foo"</code> or the empty string.</li>
157
- </ul>
158
-
159
-
160
- <h2>Repetition count</h2>
161
-
162
- <p>A generalised repetition count (minimum, maximum) is also available.</p>
163
-
164
- <ul>
165
- <li><code>'foo' 2..</code> matches <code>'foo'</code> two or more times</li>
166
- <li><code>'foo' 3..5</code> matches <code>'foo'</code> from three to five times</li>
167
- <li><code>'foo' ..4</code> matches <code>'foo'</code> from zero to four times</li>
168
- </ul>
169
-
170
-
171
- <h2>Lookahead Assertions</h2>
172
-
173
- <p>Lookahead assertions can be used to make parsing expressions context-sensitive.
174
- The parser will look ahead into the buffer and attempt to match an expression without consuming input.</p>
175
-
176
- <h3>Positive Lookahead Assertion</h3>
177
-
178
- <p>Preceding an expression with an ampersand <code>(&amp;)</code> indicates that it must match, but no input will be consumed in the process of determining whether this is true.</p>
179
-
180
- <ul>
181
- <li><code>"foo" &amp;"bar"</code> matches <code>"foobar"</code> but only consumes up to the end <code>"foo"</code>. It will not match <code>"foobaz"</code>.</li>
182
- </ul>
183
-
184
-
185
- <h3>Negative Lookahead Assertion</h3>
186
-
187
- <p>Preceding an expression with a bang <code>(!)</code> indicates that the expression must not match, but no input will be consumed in the process of determining whether this is true.</p>
188
-
189
- <ul>
190
- <li><code>"foo" !"bar"</code> matches <code>"foobaz"</code> but only consumes up to the end <code>"foo"</code>. It will not match <code>"foobar"</code>.</li>
191
- </ul>
192
-
193
-
194
- <p>Note that a lookahead assertion may be used on any rule, not just a string terminal.</p>
195
-
196
- <pre><code>rule things
197
- thing (!(disallowed / ',') following)*
198
- end
199
- </code></pre>
200
-
201
- <p>Here's a common use case:</p>
202
-
203
- <pre><code>rule word
204
- [a-zA-Z]+
205
- end
206
-
207
- rule conjunction
208
- primitive ('and' ' '+ primitive)*
209
- end
210
-
211
- rule primitive
212
- (!'and' word ' '+)*
213
- end
214
- </code></pre>
215
-
216
- <p>Here's the easiest way to handle C-style comments:</p>
217
-
218
- <pre><code>rule c_comment
219
- '/*'
220
- (
221
- !'*/'
222
- (. / "\n")
223
- )*
224
- '*/'
225
- end
226
- </code></pre>
227
-
228
- <h2>Semantic predicates (positive and negative)</h2>
229
-
230
- <p>Sometimes you must execute Ruby code during parsing in order to decide how to proceed.
231
- This is an advanced feature, and must be used with great care, because it can change the
232
- way a Treetop parser backtracks in a way that breaks the parsing algorithm. See the
233
- notes below on how to use this feature safely.</p>
234
-
235
- <p>The code block is the body of a Ruby lambda block, and should return true or false, to cause this
236
- parse rule to continue or fail (for positive sempreds), fail or continue (for negative sempreds).</p>
237
-
238
- <ul>
239
- <li><code>&amp;{ ... }</code> Evaluate the block and fail this rule if the result is false or nil</li>
240
- <li><code>!{ ... }</code> Evaluate the block and fail this rule if the result is not false or nil</li>
241
- </ul>
242
-
243
-
244
- <p>The lambda is passed a single argument which is the array of syntax nodes matched so far in the
245
- current sequence. Note that because the current rule has not yet succeeded, no syntax node has
246
- yet been constructed, and so the lambda block is being run in a context where the <code>names</code> of the
247
- preceding rules (or as assigned by labels) are not available to access the sub-rules.</p>
248
-
249
- <pre><code>rule id
250
- [a-zA-Z][a-zA-Z0-9]*
251
- {
252
- def is_reserved
253
- ReservedSymbols.include? text_value
254
- end
255
- }
256
- end
257
-
258
- rule foo_rule
259
- foo id &amp;{|seq| seq[1].is_reserved } baz
260
- end
261
- </code></pre>
262
-
263
- <p>Match "foo id baz" only if <code>id.is_reserved</code>. Note that <code>id</code> cannot be referenced by name from <code>foo_rule</code>,
264
- since that rule has not yet succeeded, but <code>id</code> has completed and so its added methods are available.</p>
265
-
266
- <pre><code>rule test_it
267
- foo bar &amp;{|s| debugger; true } baz
268
- end
269
- </code></pre>
270
-
271
- <p>Match <code>foo</code> then <code>bar</code>, stop to enter the debugger (make sure you have said <code>require "ruby-debug"</code> somewhere),
272
- then continue by trying to match <code>baz</code>.</p>
273
-
274
- <p>Treetop, like other PEG parsers, achieves its performance guarantee by remembering which rules it has
275
- tried at which locations in the input, and what the result was. This process, called memoization,
276
- requires that the rule would produce the same result (if run again) as it produced the first time when
277
- the result was remembered. If you violate this principle in your semantic predicates, be prepared to
278
- fight Cerberus before you're allowed out of Hades again.</p></div></div></div><div id="bottom"></div></body></html>
@@ -1,123 +0,0 @@
1
- <html><head><link href="./screen.css" rel="stylesheet" type="text/css" />
2
- <script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
3
- </script>
4
- <script type="text/javascript">
5
- _uacct = "UA-3418876-1";
6
- urchinTracker();
7
- </script>
8
- </head><body><div id="top"><div id="main_navigation"><ul><li>Documentation</li><li><a href="contribute.html">Contribute</a></li><li><a href="index.html">Home</a></li></ul></div></div><div id="middle"><div id="main_content"><div id="secondary_navigation"><ul><li><a href="syntactic_recognition.html">Syntax</a></li><li><a href="semantic_interpretation.html">Semantics</a></li><li>Using In Ruby</li><li><a href="pitfalls_and_advanced_techniques.html">Advanced Techniques</a></li></ul></div><div id="documentation_content"><h1>Using Treetop Grammars in Ruby</h1>
9
-
10
- <h2>Using the Command Line Compiler</h2>
11
-
12
- <p>You can compile <code>.treetop</code> files into Ruby source code with the <code>tt</code> command line script. <code>tt</code> takes an list of files with a <code>.treetop</code> extension and compiles them into <code>.rb</code> files of the same name. You can then <code>require</code> these files like any other Ruby script. Alternately, you can supply just one <code>.treetop</code> file and a <code>-o</code> flag to name specify the name of the output file. Improvements to this compilation script are welcome.</p>
13
-
14
- <pre><code>tt foo.treetop bar.treetop
15
- tt foo.treetop -o foogrammar.rb
16
- </code></pre>
17
-
18
- <h2>Loading A Grammar Directly</h2>
19
-
20
- <p>The Polyglot gem makes it possible to load <code>.treetop</code> or <code>.tt</code> files directly with <code>require</code>. This will invoke <code>Treetop.load</code>, which automatically compiles the grammar to Ruby and then evaluates the Ruby source. If you are getting errors in methods you define on the syntax tree, try using the command line compiler for better stack trace feedback. A better solution to this issue is in the works.</p>
21
-
22
- <p>In order to use Polyglot dynamic loading of <code>.treetop</code> or <code>.tt</code> files though, you need to require the Polyglot gem before you require the Treetop gem as Treetop will only create hooks into Polyglot for the treetop files if Polyglot is already loaded. So you need to use:</p>
23
-
24
- <pre><code>require 'polyglot'
25
- require 'treetop'
26
- </code></pre>
27
-
28
- <p>in order to use Polyglot auto loading with Treetop in Ruby.</p>
29
-
30
- <h2>Instantiating and Using Parsers</h2>
31
-
32
- <p>If a grammar by the name of <code>Foo</code> is defined, the compiled Ruby source will define a <code>FooParser</code> class.
33
- To parse input, create an instance and call its <code>parse</code> method with a string.
34
- The parser will return the syntax tree of the match or <code>nil</code> if there is a failure.
35
- Note that by default, the parser will fail unless <em>all</em> input is consumed.</p>
36
-
37
- <pre><code>Treetop.load "arithmetic"
38
-
39
- parser = ArithmeticParser.new
40
- if parser.parse('1+1')
41
- puts 'success'
42
- else
43
- puts 'failure'
44
- end
45
- </code></pre>
46
-
47
- <h2>Parser Options</h2>
48
-
49
- <p>A Treetop parser has several options you may set.
50
- Some are settable permanently by methods on the parser, but all may be passed in as options to the <code>parse</code> method.</p>
51
-
52
- <pre><code>parser = ArithmeticParser.new
53
- input = 'x = 2; y = x+3;'
54
-
55
- # Temporarily override an option:
56
- result1 = parser.parse(input, :consume_all_input =&gt; false)
57
- puts "consumed #{parser.index} characters"
58
-
59
- parser.consume_all_input = false
60
- result1 = parser.parse(input)
61
- puts "consumed #{parser.index} characters"
62
-
63
- # Continue the parse with the next character:
64
- result2 = parser.parse(input, :index =&gt; parser.index)
65
-
66
- # Parse, but match rule `variable` instead of the normal root rule:
67
- parser.parse(input, :root =&gt; :variable)
68
- parser.root = :variable # Permanent setting
69
- </code></pre>
70
-
71
- <p>If you have a statement-oriented language, you can save memory by parsing just one statement at a time,
72
- and discarding the parse tree after each statement.</p>
73
-
74
- <h2>Learning From Failure</h2>
75
-
76
- <p>If a parse fails, it returns nil. In this case, you can ask the parser for an explanation.
77
- The failure reasons include the terminal nodes which were tried at the furthermost point the parse reached.</p>
78
-
79
- <pre><code>parser = ArithmeticParser.new
80
- result = parser.parse('4+=3')
81
-
82
- if !result
83
- puts parser.failure_reason
84
- puts parser.failure_line
85
- puts parser.failure_column
86
- end
87
-
88
- =&gt;
89
- Expected one of (, - at line 1, column 3 (byte 3) after +
90
- 1
91
- 3
92
- </code></pre>
93
-
94
- <h2>Using Parse Results</h2>
95
-
96
- <p>Please don't try to walk down the syntax tree yourself, and please don't use the tree as your own convenient data structure.
97
- It contains many more nodes than your application needs, often even more than one for every character of input.</p>
98
-
99
- <pre><code>parser = ArithmeticParser.new
100
- p parser.parse('2+3')
101
-
102
- =&gt;
103
- SyntaxNode+Additive1 offset=0, "2+3" (multitive):
104
- SyntaxNode+Multitive1 offset=0, "2" (primary):
105
- SyntaxNode+Number0 offset=0, "2":
106
- SyntaxNode offset=0, ""
107
- SyntaxNode offset=0, "2"
108
- SyntaxNode offset=1, ""
109
- SyntaxNode offset=1, ""
110
- SyntaxNode offset=1, "+3":
111
- SyntaxNode+Additive0 offset=1, "+3" (multitive):
112
- SyntaxNode offset=1, "+"
113
- SyntaxNode+Multitive1 offset=2, "3" (primary):
114
- SyntaxNode+Number0 offset=2, "3":
115
- SyntaxNode offset=2, ""
116
- SyntaxNode offset=2, "3"
117
- SyntaxNode offset=3, ""
118
- SyntaxNode offset=3, ""
119
- </code></pre>
120
-
121
- <p>Instead, add methods to the root rule which return the information you require in a sensible form.
122
- Each rule can call its sub-rules, and this method of walking the syntax tree is much preferable to
123
- attempting to walk it from the outside.</p></div></div></div><div id="bottom"></div></body></html>