-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathpratt-example.html
214 lines (190 loc) · 12.6 KB
/
pratt-example.html
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
<html>
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<head>
<title>
leontrolski - Pratt parsing
</title>
<style>
body {margin: 5% auto; background: #fff7f7; color: #444444; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.8; max-width: 63%;}
@media screen and (max-width: 800px) {body {font-size: 14px; line-height: 1.4; max-width: 90%;}}
pre {width: 100%; border-top: 3px solid gray; border-bottom: 3px solid gray;}
a {border-bottom: 1px solid #444444; color: #444444; text-decoration: none; text-shadow: 0 1px 0 #ffffff; }
a:hover {border-bottom: 0;}
.inline {background: #b3b2b226; padding-left: 0.3em; padding-right: 0.3em; white-space: nowrap;}
blockquote {font-style: italic;color:black;background-color:#f2f2f2;padding:2em;}
details {border-bottom:solid 5px gray;}
table{background-color: white;}
td{padding-right:1rem;}
</style>
<link href="https://unpkg.com/[email protected]/themes/prism-vs.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.20.0/components/prism-core.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.20.0/plugins/autoloader/prism-autoloader.min.js">
</script>
</head>
<body>
<a href="index.html">
<img src="pic.png" style="height:2em">
⇦
</a>
<p><i>2024-07-26</i></p>
<h1>
Pratt parser for a subset of JavaScript
</h1>
<p>This post presents a Pratt parser for a subset of JavaScript implemented in Python.</p>
<p>This type of parser has become fairly popular due to the simplicity with which it handles operator precedence. In fact I'm part of a <a href="https://www.oilshell.org/blog/2017/03/31.html">long lineage</a> of bloggers - it's the "monad is a burrito" of parsing posts. I thought I'd bother writing up my attempt as I had a fun time writing it and was particularly happy with the brevity of the resulting code. Thank you thank you <a href="https://andychu.net/">Andy C</a> for bringing it into my life.</p>
<p>The parser will turn the following source:</p>
<pre><code class="lang-javascript">{
<span class="hljs-attr">"a"</span>: {<span class="hljs-attr">"b"</span>: {<span class="hljs-attr">"c"</span>: <span class="hljs-string">"d"</span>}},
<span class="hljs-attr">"foo"</span>: (<span class="hljs-number">1</span> === <span class="hljs-number">2</span>)
? <span class="hljs-string">"bar"</span>
: <span class="hljs-number">3</span> * <span class="hljs-number">4</span> + <span class="hljs-number">5</span>
}
</code></pre>
<p>Into the following AST:</p>
<pre><code class="lang-clojure">({
(<span class="hljs-name">:</span> <span class="hljs-string">"a"</span> ({ (<span class="hljs-name">:</span> <span class="hljs-string">"b"</span> ({ (<span class="hljs-name">:</span> <span class="hljs-string">"c"</span> <span class="hljs-string">"d"</span>)))))
(<span class="hljs-name">:</span> <span class="hljs-string">"foo"</span> (<span class="hljs-name">?</span> (<span class="hljs-name">===</span> <span class="hljs-number">1</span> <span class="hljs-number">2</span>)
<span class="hljs-string">"bar"</span>
(<span class="hljs-name"><span class="hljs-builtin-name">+</span></span> (<span class="hljs-name"><span class="hljs-builtin-name">*</span></span> <span class="hljs-number">3</span> <span class="hljs-number">4</span>) <span class="hljs-number">5</span>))))
</code></pre>
<p>Some more examples:</p>
<table>
<tr>
<td><code>1</code></td>
<td><code>1</code></td>
</tr>
<tr>
<td><code>1 + 2</code></td>
<td><code>(+ 1 2)</code></td>
</tr>
<tr>
<td><code>1 + 2 * 3</code></td>
<td><code>(+ 1 (* 2 3))</code></td>
</tr>
<tr>
<td><code>1 * 2 + 3</code></td>
<td><code>(+ (* 1 2) 3)</code></td>
</tr>
<tr>
<td><code>1 * (2 + 3)</code></td>
<td><code>(* 1 (+ 2 3))</code></td>
</tr>
<tr>
<td><code>{1, 2, 3}</code></td>
<td><code>({ 1 2 3)</code></td>
</tr>
<tr>
<td><code>{"a": 1, "c": 1 + 2}</code></td>
<td><code>({ (: "a" 1) (: "c" (+ 1 2)))</code></td>
</tr>
</table>
<br>
<br>
<details>
<summary>Firstly, some imports and a tokenizer, for more details on these, see my <a href="weenie-lisp.html">other parsing post</a>.</summary>
<pre><code class="lang-python"><span class="hljs-built_in">from</span> __future__ import annotations
<span class="hljs-built_in">from</span> dataclasses import dataclass
import <span class="hljs-keyword">string</span>
<span class="hljs-built_in">from</span> typing import Iterator
<span class="hljs-literal">EOF</span> = <span class="hljs-string">"\x1a"</span>
@dataclass
class PeekableIterator:
iter: Iterator[str]
peek: str = <span class="hljs-literal">EOF</span>
def __post_init__(self) -> None:
next(self)
def __next__(self) -> None:
self.peek = next(self.iter, <span class="hljs-literal">EOF</span>)
def tokenize(<span class="hljs-keyword">chars</span>: PeekableIterator) -> Iterator[str]:
<span class="hljs-keyword">while</span> <span class="hljs-keyword">chars</span>.peek != <span class="hljs-literal">EOF</span>:
<span class="hljs-keyword">if</span> <span class="hljs-keyword">chars</span>.peek <span class="hljs-keyword">in</span> <span class="hljs-keyword">string</span>.whitespace:
next(<span class="hljs-keyword">chars</span>)
elif <span class="hljs-keyword">chars</span>.peek <span class="hljs-keyword">in</span> <span class="hljs-string">"{}():?+*,"</span>:
yield <span class="hljs-keyword">chars</span>.peek
next(<span class="hljs-keyword">chars</span>)
elif <span class="hljs-keyword">chars</span>.peek == <span class="hljs-string">"="</span>:
next(<span class="hljs-keyword">chars</span>)
assert <span class="hljs-keyword">chars</span>.peek == <span class="hljs-string">"="</span>
next(<span class="hljs-keyword">chars</span>)
assert <span class="hljs-keyword">chars</span>.peek == <span class="hljs-string">"="</span>
next(<span class="hljs-keyword">chars</span>)
yield <span class="hljs-string">"==="</span>
elif <span class="hljs-keyword">chars</span>.peek == <span class="hljs-string">'"'</span>:
current = <span class="hljs-string">""</span>
current += <span class="hljs-keyword">chars</span>.peek
next(<span class="hljs-keyword">chars</span>)
<span class="hljs-keyword">while</span> <span class="hljs-keyword">chars</span>.peek != <span class="hljs-string">'"'</span>:
current += <span class="hljs-keyword">chars</span>.peek
next(<span class="hljs-keyword">chars</span>)
current += <span class="hljs-keyword">chars</span>.peek
next(<span class="hljs-keyword">chars</span>)
yield current
<span class="hljs-keyword">else</span>:
current = <span class="hljs-string">""</span>
<span class="hljs-keyword">while</span> <span class="hljs-keyword">chars</span>.peek <span class="hljs-keyword">in</span> <span class="hljs-string">"0123456789"</span>:
current += <span class="hljs-keyword">chars</span>.peek
next(<span class="hljs-keyword">chars</span>)
yield current
</code></pre>
</details>
<br>
<br>
<p>With that defined, given the example <code>source</code> from above, <code>list(tokenize(PeekableIterator(iter(source))))</code> should give:</p>
<pre><code class="lang-python">['{', '<span class="hljs-string">"a"</span>', <span class="hljs-symbol">':</span>', '{', '<span class="hljs-string">"b"</span>', <span class="hljs-symbol">':</span>', '{', '<span class="hljs-string">"c"</span>', <span class="hljs-symbol">':</span>', '<span class="hljs-string">"d"</span>', '}', '}', ',', '<span class="hljs-string">"foo"</span>', <span class="hljs-symbol">':</span>', '(', <span class="hljs-symbol">'1</span>', <span class="hljs-symbol">'===</span>', <span class="hljs-symbol">'2</span>', ')', <span class="hljs-symbol">'?</span>', '<span class="hljs-string">"bar"</span>', <span class="hljs-symbol">':</span>', <span class="hljs-symbol">'3</span>', <span class="hljs-symbol">'*</span>', <span class="hljs-symbol">'4</span>', <span class="hljs-symbol">'+</span>', <span class="hljs-symbol">'5</span>', '}']
</code></pre>
<br>
<br>
<p>Now we define the AST <code>Node</code> type and a small helper:</p>
<pre><code class="lang-python"><span class="hljs-meta">@dataclass</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Node</span>:</span>
token: str
children: list[Node]
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">next_assert</span><span class="hljs-params">(tokens: PeekableIterator, to: str)</span> -> <span class="hljs-keyword">None</span>:</span>
<span class="hljs-keyword">assert</span> tokens.peek == to
next(tokens)
</code></pre>
<p>Then the relative precedence of each of the infix operators:</p>
<pre><code class="lang-python"><span class="hljs-attr">INFIX_PRECEDENCES</span> = {
<span class="hljs-string">"==="</span>: <span class="hljs-number">2</span>,
<span class="hljs-string">":"</span>: <span class="hljs-number">11</span>,
<span class="hljs-string">"?"</span>: <span class="hljs-number">12</span>,
<span class="hljs-string">"+"</span>: <span class="hljs-number">14</span>,
<span class="hljs-string">"*"</span>: <span class="hljs-number">15</span>,
}
</code></pre>
<p>The parser itself is then pretty simple!</p>
<pre><code class="lang-python">def <span class="hljs-keyword">parse</span>(tokens: PeekableIterator, precedence: int) -> Node:
<span class="hljs-keyword">token</span> = tokens.peek
next(tokens)
<span class="hljs-keyword">if</span> <span class="hljs-keyword">token</span>[0] <span class="hljs-keyword">in</span> '"0123456789':
node = <span class="hljs-keyword">token</span> # atom
elif <span class="hljs-keyword">token</span> == <span class="hljs-string">"{"</span>:
node = Node(<span class="hljs-keyword">token</span>, [])
<span class="hljs-keyword">while</span> tokens.peek != <span class="hljs-string">"}"</span>:
<span class="hljs-keyword">if</span> tokens.peek == <span class="hljs-string">","</span>:
next(tokens)
<span class="hljs-keyword">else</span>:
node.children.<span class="hljs-keyword">append</span>(<span class="hljs-keyword">parse</span>(tokens, 2))
next_assert(tokens, <span class="hljs-string">"}"</span>)
elif <span class="hljs-keyword">token</span> == <span class="hljs-string">"("</span>:
node = <span class="hljs-keyword">parse</span>(tokens, -1)
next_assert(tokens, <span class="hljs-string">")"</span>)
<span class="hljs-keyword">else</span>:
raise ValueError(f<span class="hljs-string">"Unrecognised token: {token}"</span>)
<span class="hljs-keyword">return</span> <span class="hljs-keyword">infix</span>(tokens, precedence, node)
def <span class="hljs-keyword">infix</span>(tokens: PeekableIterator, precedence: int, left: Node) -> Node:
<span class="hljs-keyword">token</span> = tokens.peek
next_precedence = INFIX_PRECEDENCES.<span class="hljs-built_in">get</span>(<span class="hljs-keyword">token</span>)
<span class="hljs-keyword">if</span> next_precedence is None or precedence >= next_precedence:
<span class="hljs-keyword">return</span> left
next(tokens)
node = Node(<span class="hljs-keyword">token</span>, [left, <span class="hljs-keyword">parse</span>(tokens, next_precedence)])
<span class="hljs-keyword">if</span> <span class="hljs-keyword">token</span> == <span class="hljs-string">"?"</span>: # ? is a ternary expression, <span class="hljs-keyword">so</span> we <span class="hljs-keyword">parse</span> <span class="hljs-keyword">one</span> <span class="hljs-keyword">more</span> child
next_assert(tokens, <span class="hljs-string">":"</span>)
node.children.<span class="hljs-keyword">append</span>(<span class="hljs-keyword">parse</span>(tokens, next_precedence))
<span class="hljs-keyword">return</span> <span class="hljs-keyword">infix</span>(tokens, precedence, node)
</code></pre>
<p>If that was fun, here's a more complicated <a href="https://github.com/leontrolski/dnjs/blob/master/dnjs/parser.py#L43">parser</a> for <a href="https://github.com/leontrolski/dnjs">an old hobby project of mine</a>.</p>
</body>
</html>