Debian Codegraph @

docs/parser.html

raw
1 <!DOCTYPE html>
2 <title>Using a parser - nearley.js - JS Parsing Toolkit</title>
3 <meta charset="utf-8"/>
4 <meta name="viewport" content="width=device-width, initial-scale=1">
5 <meta name="description" content="nearley.js is a simple, fast, and powerful parser toolkit for JavaScript." />
6 <style>
7 body {
8 font-family: BlinkMacSystemFont, -apple-system, Helvetica Neue, Open Sans, Ubuntu, Arial, Helvetica, sans-serif;
9 font-weight: 300;
10 font-size: 15pt;
11 margin: 0px;
12 padding: 0px;
13 }
14
15 #main a {
16 color: #55a;
17 }
18 #main a:visited {
19 color: #55a;
20 }
21 #main a:hover {
22 color: #259;
23 }
24
25 h1 {
26 font-size: 1.2em;
27 font-weight: normal;
28 letter-spacing: 0.2em;
29 text-align: center;
30 margin: 0em;
31 padding: 1em;
32 }
33
34 h1 a {
35 color: #559;
36 text-decoration: none;
37 }
38
39 h1 a:hover {
40 color: orange;
41 cursor: pointer;
42 }
43
44 #version {
45 background: orange;
46 border-radius: 50%;
47 font-weight: bold;
48 color: white;
49 width: 3em;
50 height: 3em;
51 display: inline-block;
52 text-align: center;
53 line-height: 3em;
54 letter-spacing: 0em;
55 }
56
57 h2 {
58 font-size: 1.5em;
59 margin-top: 2em;
60 }
61 h3 {
62 margin-top: 3em;
63 }
64 h4 {
65 margin-top: 3em;
66 }
67
68 .center {
69 padding-left: 2em;
70 padding-right: 2em;
71 margin-left: auto;
72 margin-right: auto;
73 }
74 #main {
75 max-width: 35em;
76 }
77
78 #main p, ul, ol {
79 line-height: 1.5em;
80 margin-bottom: 1em;
81 }
82
83 #main li {
84 margin-top: 1em;
85 margin-bottom: 1em;
86 }
87
88 #main ul li {
89 list-style: none;
90 min-width: 10em;
91 }
92 #main ul li:before {
93 display: inline-block;
94 content: "\2014";
95 margin-left: -1.5em;
96 width: 1.5em;
97 position: absolute;
98 }
99
100 #main textarea {
101 width: 100%;
102 height: 20em;
103 resize: none;
104 margin-top: 5px;
105 margin-bottom: 5px;
106
107 font-family: menlo, monaco, monospace;
108 font-size: 10pt;
109 padding: 5px;
110
111 border: none;
112 border-left: solid 1px #aaa;
113 }
114 #main textarea:focus {
115 outline: none;
116 }
117
118 #main img {
119 display: block;
120 margin-left: auto;
121 margin-right: auto;
122 max-width: 100%;
123 }
124 img + .caption {
125 text-align: center;
126 font-size: 0.7em;
127 color: #aaa;
128 }
129
130 #footer {
131 margin-top: 10em;
132 color: #aaa;
133 font-size: 0.7em;
134 padding: 5em;
135 }
136
137 code {
138 margin-left: 0.2em;
139 margin-right: 0.2em;
140 padding: 0.2em;
141 border-radius: 0.2em;
142 background-color: #eee;
143 }
144
145 pre code {
146 border-radius: 0.5em;
147 padding: 0.5em;
148 display: block;
149 overflow: auto;
150 }
151
152
153 ol {
154 counter-reset: tutorial-counter;
155 position: relative;
156 }
157
158 ol li {
159 list-style: none;
160 }
161
162 ol li:before {
163 content: counter(tutorial-counter);
164 counter-increment: tutorial-counter;
165
166 font-weight: bold;
167 border-radius: 50%;
168 background-color: #559;
169 width: 2em;
170 height: 2em;
171 display: inline-block;
172 text-align: center;
173 line-height: 2em;
174 color: white;
175
176 margin-left: -2em;
177
178 position: absolute;
179 left: 1em;
180 }
181
182 input[type="text"] {
183 border: none;
184 font-family: monospace;
185 font-size: 1em;
186 color: #559;
187 }
188
189 input[type="text"]:focus {
190 outline: none;
191 }
192
193
194 nav {
195 border-bottom: 2px solid #559;
196 background: #fafafa;
197 }
198 nav ul {
199 padding: 0;
200 margin: 0;
201 }
202 nav ul a {
203 text-decoration: none;
204 color: #334;
205 display: block;
206 overflow: hidden;
207 text-overflow: ellipsis;
208 padding: 0.25em 0.5em; */
209 }
210 .page {
211 display: block;
212 }
213
214 .page-title-active,
215 .page-heading-active a {
216 color: #66f;
217 }
218
219 .page-heading {
220 display: block;
221 padding-left: 1.5em;
222 }
223
224
225 @media screen and (min-width: 36rem) {
226 nav {
227 position: fixed;
228 width: 16rem;
229 left: 0;
230 top: 0;
231 bottom: 0;
232 white-space: nowrap;
233 overflow-y: auto;
234 font-size: 1rem;
235 border-bottom: none;
236 border-right: 2px solid #559;
237 }
238 body.docs-page {
239 margin-left: 16rem;
240 }
241 }
242
243 /* highlight.js */
244
245 .hljs{display:block;overflow-x:auto;padding:0.5em;background:#F0F0F0}.hljs,.hljs-subst{color:#444}.hljs-comment{color:#888888}.hljs-keyword,.hljs-attribute,.hljs-selector-tag,.hljs-meta-keyword,.hljs-doctag,.hljs-name{font-weight:bold}.hljs-type,.hljs-string,.hljs-number,.hljs-selector-id,.hljs-selector-class,.hljs-quote,.hljs-template-tag,.hljs-deletion{color:#880000}.hljs-title,.hljs-section{color:#880000;font-weight:bold}.hljs-regexp,.hljs-symbol,.hljs-variable,.hljs-template-variable,.hljs-link,.hljs-selector-attr,.hljs-selector-pseudo{color:#BC6060}.hljs-literal{color:#78A960}.hljs-built_in,.hljs-bullet,.hljs-code,.hljs-addition{color:#397300}.hljs-meta{color:#1f7199}.hljs-meta-string{color:#4d99bf}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:bold}
246
247
248 </style>
249
250 <body class="docs-page">
251
252 <a href="https://github.com/kach/nearley" class="github-corner"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
253 <nav id="nav">
254 <h1><a href="/">nearley<span style="color: #559;">.js</span><span id="version">2.20.0</span></a></h1>
255 <ul>
256 <li class="page"><a href="/docs/index">Home</a>
257 <li class="page"><a href="/docs/getting-started">Getting started</a>
258 <li class="page"><a href="/docs/grammar">Writing a parser</a>
259 <li class="page">
260 <a href="#" class="page-title-active">Using a parser</a>
261 <ul>
262 <li class="page-heading"><a href="#a-note-on-ambiguity">A note on ambiguity</a>
263 <li class="page-heading"><a href="#catching-errors">Catching errors</a>
264 <li class="page-heading"><a href="#accessing-the-parse-table">Accessing the parse table</a>
265 <li class="page-heading"><a href="#using-preprocessors">Using preprocessors</a>
266 <li class="page-heading"><a href="#whats-next">What’s next?</a>
267 </ul>
268 </li>
269 <li class="page"><a href="/docs/tokenizers">Tokenizers</a>
270 <li class="page"><a href="/docs/tooling">Tooling</a>
271 <li class="page"><a href="/docs/how-to-grammar-good">How to grammar good</a>
272 <li class="page"><a href="/docs/using-in-frontend">Compiling in browsers</a>
273 <li class="page"><a href="/docs/glossary">Glossary</a>
274 </ul>
275 </nav>
276
277 <div id="main" class="center">
278
279 <h2>Using a parser</h2>
280 <p>This section describes nearley’s parser API.</p>
281 <p>Once you have compiled a <code>grammar.ne</code> file to a <code>grammar.js</code> module, you can
282 then use nearley to instantiate a <code>Parser</code> object.</p>
283 <p>First, import nearley and your grammar.</p>
284 <pre><code class="language-js">const nearley = require(&quot;nearley&quot;);
285 const grammar = require(&quot;./grammar.js&quot;);</code></pre>
286 <p>Note that if you are parsing in the browser, you can simply include
287 <code>nearley.js</code> and <code>grammar.js</code> in <code>&lt;script&gt;</code> tags.</p>
288 <p>Next, use the grammar to create a new <code>nearley.Parser</code> object.</p>
289 <pre><code class="language-js">// Create a Parser object from our grammar.
290 const parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar));</code></pre>
291 <p>Once you have a <code>Parser</code>, you can <code>.feed</code> it a string to parse. Since nearley
292 is a <em>streaming</em> parser, you can feed strings more than once. For example, a
293 REPL might feed the parser lines of code as the user enters them:</p>
294 <pre><code class="language-js">// Parse something!
295 parser.feed(&quot;if (true) {&quot;);
296 parser.feed(&quot;x = 1&quot;);
297 parser.feed(&quot;}&quot;);
298 // or, parser.feed(&quot;if (true) {x=1}&quot;);</code></pre>
299 <p>Finally, you can query the <code>.results</code> property of the parser.</p>
300 <pre><code class="language-js">// parser.results is an array of possible parsings.
301 console.log(parser.results);
302 // [{&#39;type&#39;: &#39;if&#39;, &#39;condition&#39;: ..., &#39;body&#39;: ...}]</code></pre>
303 <h3 id="a-note-on-ambiguity">A note on ambiguity</h3>
304 <p>Why is <code>parser.results</code> an array? Sometimes, a grammar can parse a particular
305 string in multiple different ways. For example, the following grammar parses
306 the string <code>&quot;xyz&quot;</code> in two different ways.</p>
307 <pre><code class="language-ne">x -&gt; &quot;xy&quot; &quot;z&quot;
308 | &quot;x&quot; &quot;yz&quot;</code></pre>
309 <p>Such grammars are <em>ambiguous</em>. nearley provides you with <em>all</em> the parsings. In
310 most cases, however, your grammars should not be ambiguous (parsing ambiguous
311 grammars is inefficient!). Thus, the most common usage is to simply query
312 <code>parser.results[0]</code>.</p>
313 <p>You might like to check first that <code>parser.results.length</code> is exactly 1; if
314 there is more than one result, then your grammar is ambiguous!</p>
315 <h3 id="catching-errors">Catching errors</h3>
316 <p>nearley is a <em>streaming</em> parser: you can call <code>feed()</code> as many times as you
317 like. This means there are two ways parsing can go wrong.</p>
318 <p>Consider the simple parser below for the examples to follow.</p>
319 <pre><code class="language-js">main -&gt; &quot;Cow goes moo.&quot; {% function(d) {return &quot;yay!&quot;; } %}</code></pre>
320 <p>If nearley gets <strong>partway through the chunk</strong> you fed, and parsing cannot
321 continue, then nearley will throw an error whose <code>offset</code> property is the index
322 of the offending token. There is no way to recover from this by feeding more
323 data.</p>
324 <pre><code class="language-js">try {
325 parser.feed(&quot;Cow goes% moo.&quot;);
326 } catch (err) {
327 console.log(&quot;Error at character &quot; + parseError.offset); // &quot;Error at character 9&quot;
328 }</code></pre>
329 <p>Errors are nicely formatted for you:</p>
330 <pre><code>Error: invalid syntax at line 1 col 9:
331
332 Cow goes% moo
333 ^
334 Unexpected &quot;%&quot;</code></pre><p><strong>After <code>feed()</code> finishes</strong>, the <code>results</code> array will contain all possible
335 parsings.</p>
336 <p>If there are no possible parsings given the current input, but in the <em>future</em>
337 there <em>might</em> be results if you feed it more strings, then nearley will
338 temporarily set the <code>results</code> array to the empty array, <code>[]</code>.</p>
339 <pre><code class="language-js">parser.feed(&quot;Cow &quot;); // parser.results is []
340 parser.feed(&quot;goes &quot;); // parser.results is []
341 parser.feed(&quot;moo.&quot;); // parser.results is [&quot;yay!&quot;]</code></pre>
342 <p>If you’re done calling <code>feed()</code>, but the array is still empty, this indicates
343 “unexpected end of input”. Make sure to check there’s at least one result.</p>
344 <p>If there’s more than one result, that indicates ambiguity–read on.</p>
345 <h3 id="accessing-the-parse-table">Accessing the parse table</h3>
346 <p>If you are familiar with the Earley parsing algorithm, you can access the
347 internal parse table using <code>Parser.table</code> (this, for example, is how
348 <code>nearley-test</code> works). One caveat, however: you must pass the <code>keepHistory</code>
349 option to nearley to prevent it from garbage-collecting inaccessible columns of
350 the table.</p>
351 <pre><code class="language-js">const nearley = require(&quot;nearley&quot;);
352 const grammar = require(&quot;./grammar&quot;);
353
354 const parser = new nearley.Parser(
355 nearley.Grammar.fromCompiled(grammar),
356 { keepHistory: true }
357 );
358
359
360 parser.feed(...);
361 console.log(parser.table);</code></pre>
362 <h3 id="using-preprocessors">Using preprocessors</h3>
363 <p>By default, <code>nearleyc</code> compiles your grammar to JavaScript. However, you can
364 instead choose to compile to CoffeeScript or TypeScript by adding
365 <code>@preprocessor coffee</code> or <code>@preprocessor typescript</code> at the top of your grammar
366 file. This can be useful to write your postprocessors in a different language,
367 and to get type annotations if you wish to use nearley in a statically typed
368 dialect of JavaScript.</p>
369 <h4 id="typescript-preprocessor-changes">Typescript Preprocessor Changes</h4>
370 <p>If you have recently upgraded to a newer version of nearly, you might have run
371 into an issue with <code>error TS2345</code> talking about a variable
372 <code>missing the following properties from type &#39;CompiledRules&#39;: ParserStart, ParserRules</code>
373 This is a result of a change in the output format of the grammar, but is very easily fixed.
374 Just change the way you import the grammar from <code>import * as grammar from &quot;./path/to/grammar&quot;</code>
375 to <code>import grammar from &quot;./path/to/grammar&quot;</code> and everything should compile nicely again.</p>
376 <h3 id="whats-next">What’s next?</h3>
377 <p>Now that you know how to use parsers, <a href="tokenizers">learn how to add a tokenizer to speed
378 things up!</a></p>
379
380
381 <div id="footer"><p>nearley is MIT-licensed. It's maintained by <a
382 href="http://hardmath123.github.io">Hardmath123</a> (<a
383 href="http://github.com/Hardmath123">Github</a>). You're welcome to
384 leave questions, comments, advice, or ideas as Github issues. And
385 feel free to fork nearley with your own experiments!<br/>
386
387 <a href="https://js.org" target="_blank" title="JS.ORG | JavaScript Community">
388 <img src="https://logo.js.org/dark_horz.png" width="102" alt="JS.ORG Logo"/></a>
389 </div>
390
391 <script id="highlight-js" async src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
392 <script>
393 document.querySelector('#highlight-js').addEventListener('load', function() {
394 [].slice.apply(document.querySelectorAll('pre code')).forEach(function(b) {
395 hljs.highlightBlock(b)
396 })
397 })
398 </script>
399
400
401 <script>
402 window.addEventListener('scroll', onScroll)
403 window.addEventListener('resize', onScroll)
404
405 var timeout
406 function onScroll(e) {
407 if (timeout) clearTimeout(timeout)
408 timeout = setTimeout(scrollEnd, 50)
409 }
410
411 function scrollEnd() {
412 var headings = document.querySelectorAll('h3')
413 var offset = 60
414 for (var i=headings.length; i--; ) {
415 var h3 = headings[i]
416 if (h3.offsetTop < window.scrollY + offset) {
417 var cur = document.querySelector('.page-heading-active')
418 if (cur) cur.className = 'page-heading'
419 document.querySelector('a[href="#' + h3.id + '"]').parentNode.className = 'page-heading page-heading-active'
420 return
421 }
422 }
423 }
424 </script>
425
426 <script>
427 (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
428 (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
429 m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
430 })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
431 ga('create', 'UA-46120535-5', 'auto');
432 ga('send', 'pageview');
433 </script>
434