/
core.cljc
376 lines (319 loc) · 15 KB
/
core.cljc
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
(ns instaparse.core
(#?(:clj :require :cljs :require-macros)
[instaparse.macros :refer [defclone
set-global-var!]])
(:require [clojure.walk :as walk]
[instaparse.gll :as gll]
[instaparse.cfg :as cfg]
[instaparse.failure :as fail]
[instaparse.print :as print]
[instaparse.reduction :as red]
[instaparse.transform :as t]
[instaparse.abnf :as abnf]
[instaparse.repeat :as repeat]
[instaparse.combinators-source :as c]
[instaparse.line-col :as lc]
[instaparse.viz :as viz]
[instaparse.util :refer [throw-illegal-argument-exception]]))
(def ^:dynamic *default-output-format* :hiccup)
(defn set-default-output-format!
"Changes the default output format. Input should be :hiccup or :enlive"
[type]
{:pre [(#{:hiccup :enlive} type)]}
(set-global-var! *default-output-format* type))
(def ^:dynamic *default-input-format* :ebnf)
(defn set-default-input-format!
"Changes the default input format. Input should be :abnf or :ebnf"
[type]
{:pre [(#{:abnf :ebnf} type)]}
(set-global-var! *default-input-format* type))
(declare failure? standard-whitespace-parsers enable-tracing!)
(defn- unhide-parser [parser unhide]
(case unhide
nil parser
:content
(assoc parser :grammar (c/unhide-all-content (:grammar parser)))
:tags
(assoc parser :grammar (c/unhide-tags (:output-format parser)
(:grammar parser)))
:all
(assoc parser :grammar (c/unhide-all (:output-format parser)
(:grammar parser)))))
(defn parse
"Use parser to parse the text. Returns first parse tree found
that completely parses the text. If no parse tree is possible, returns
a Failure object.
Optional keyword arguments:
:start :keyword (where :keyword is name of starting production rule)
:partial true (parses that don't consume the whole string are okay)
:total true (if parse fails, embed failure node in tree)
:unhide <:tags or :content or :all> (for this parse, disable hiding)
:optimize :memory (when possible, employ strategy to use less memory)
Clj only:
:trace true (print diagnostic trace while parsing)"
[parser text &{:as options}]
{:pre [(contains? #{:tags :content :all nil} (get options :unhide))
(contains? #{:memory nil} (get options :optimize))]}
(let [start-production
(get options :start (:start-production parser)),
partial?
(get options :partial false)
optimize?
(get options :optimize false)
unhide
(get options :unhide)
trace?
(get options :trace false)
#?@(:clj [_ (when (and trace? (not gll/TRACE)) (enable-tracing!))])
parser (unhide-parser parser unhide)]
(->> (cond
(:total options)
(gll/parse-total (:grammar parser) start-production text
partial? (red/node-builders (:output-format parser)))
(and optimize? (not partial?))
(let [result (repeat/try-repeating-parse-strategy parser text start-production)]
(if (failure? result)
(gll/parse (:grammar parser) start-production text partial?)
result))
:else
(gll/parse (:grammar parser) start-production text partial?))
#?(:clj (gll/bind-trace trace?)))))
(defn parses
"Use parser to parse the text. Returns lazy seq of all parse trees
that completely parse the text. If no parse tree is possible, returns
() with a Failure object attached as metadata.
Optional keyword arguments:
:start :keyword (where :keyword is name of starting production rule)
:partial true (parses that don't consume the whole string are okay)
:total true (if parse fails, embed failure node in tree)
:unhide <:tags or :content or :all> (for this parse, disable hiding)
Clj only:
:trace true (print diagnostic trace while parsing)"
[parser text &{:as options}]
{:pre [(contains? #{:tags :content :all nil} (get options :unhide))]}
(let [start-production
(get options :start (:start-production parser)),
partial?
(get options :partial false)
unhide
(get options :unhide)
trace?
(get options :trace false)
#?@(:clj [_ (when (and trace? (not gll/TRACE)) (enable-tracing!))])
parser (unhide-parser parser unhide)]
(->> (cond
(:total options)
(gll/parses-total (:grammar parser) start-production text
partial? (red/node-builders (:output-format parser)))
:else
(gll/parses (:grammar parser) start-production text partial?))
#?(:clj (gll/bind-trace trace?)))))
(defrecord Parser [grammar start-production output-format]
#?@(:clj
[clojure.lang.IFn
(invoke [parser text] (parse parser text))
(invoke [parser text key1 val1] (parse parser text key1 val1))
(invoke [parser text key1 val1 key2 val2] (parse parser text key1 val1 key2 val2))
(invoke [parser text key1 val1 key2 val2 key3 val3] (parse parser text key1 val1 key2 val2 key3 val3))
(applyTo [parser args] (apply parse parser args))]
:cljs
[IFn
(-invoke [parser text] (parse parser text))
(-invoke [parser text key1 val1] (parse parser text key1 val1))
(-invoke [parser text key1 val1 key2 val2] (parse parser text key1 val1 key2 val2))
(-invoke [parser text key1 val1 key2 val2 key3 val3] (parse parser text key1 val1 key2 val2 key3 val3))
(-invoke [parser text a b c d e f g h] (parse parser text a b c d e f g h))
(-invoke [parser text a b c d e f g h i j] (parse parser text a b c d e f g h i j))
(-invoke [parser text a b c d e f g h i j k l] (parse parser text a b c d e f g h i j k l))
(-invoke [parser text a b c d e f g h i j k l m n] (parse parser text a b c d e f g h i j k l m n))
(-invoke [parser text a b c d e f g h i j k l m n o p] (parse parser text a b c d e f g h i j k l m n o p))
(-invoke [parser text a b c d e f g h i j k l m n o p q r] (parse parser text a b c d e f g h i j k l m n o p))
(-invoke [parser text a b c d e f g h i j k l m n o p q r s more] (apply parse parser text a b c d e f g h i j k l m n o p q r s more))]))
#?(:clj
(defmethod clojure.core/print-method Parser [x writer]
(binding [*out* writer]
(println (print/Parser->str x))))
:cljs
(extend-protocol IPrintWithWriter
instaparse.core/Parser
(-pr-writer [parser writer _]
(-write writer (print/Parser->str parser)))))
(defn parser
"Takes a string specification of a context-free grammar,
or a URI for a text file containing such a specification (Clj only),
or a map of parser combinators and returns a parser for that grammar.
Optional keyword arguments:
:input-format :ebnf
or
:input-format :abnf
:output-format :enlive
or
:output-format :hiccup
:start :keyword (where :keyword is name of starting production rule)
:string-ci true (treat all string literals as case insensitive)
:auto-whitespace (:standard or :comma)
or
:auto-whitespace custom-whitespace-parser
Clj only:
:no-slurp true (disables use of slurp to auto-detect whether
input is a URI. When using this option, input
must be a grammar string or grammar map. Useful
for platforms where slurp is slow or not available.)"
[grammar-specification &{:as options}]
{:pre [(contains? #{:abnf :ebnf nil} (get options :input-format))
(contains? #{:enlive :hiccup nil} (get options :output-format))
(let [ws-parser (get options :auto-whitespace)]
(or (nil? ws-parser)
(contains? standard-whitespace-parsers ws-parser)
(and
(map? ws-parser)
(contains? ws-parser :grammar)
(contains? ws-parser :start-production))))]}
(let [input-format (get options :input-format *default-input-format*)
build-parser
(fn [spec output-format]
(binding [cfg/*case-insensitive-literals* (:string-ci options :default)]
(case input-format
:abnf (abnf/build-parser spec output-format)
:ebnf (cfg/build-parser spec output-format))))
output-format (get options :output-format *default-output-format*)
start (get options :start nil)
built-parser
(cond
(string? grammar-specification)
(let [parser
#?(:clj
(if (get options :no-slurp)
;; if :no-slurp is set to true, string is a grammar spec
(build-parser grammar-specification output-format)
;; otherwise, grammar-specification might be a URI,
;; let's slurp to see
(try (let [spec (slurp grammar-specification)]
(build-parser spec output-format))
(catch java.io.FileNotFoundException e
(build-parser grammar-specification output-format))))
:cljs
(build-parser grammar-specification output-format))]
(if start (map->Parser (assoc parser :start-production start))
(map->Parser parser)))
(map? grammar-specification)
(let [parser
(cfg/build-parser-from-combinators grammar-specification
output-format
start)]
(map->Parser parser))
(vector? grammar-specification)
(let [start (if start start (grammar-specification 0))
parser
(cfg/build-parser-from-combinators (apply hash-map grammar-specification)
output-format
start)]
(map->Parser parser))
:else
#?(:clj
(let [spec (slurp grammar-specification)
parser (build-parser spec output-format)]
(map->Parser parser))
:cljs
(throw-illegal-argument-exception
"Expected string, map, or vector as grammar specification, got "
(pr-str grammar-specification))))]
(let [auto-whitespace (get options :auto-whitespace)
; auto-whitespace is keyword, parser, or nil
whitespace-parser (if (keyword? auto-whitespace)
(get standard-whitespace-parsers auto-whitespace)
auto-whitespace)]
(if-let [{ws-grammar :grammar ws-start :start-production} whitespace-parser]
(assoc built-parser :grammar
(c/auto-whitespace (:grammar built-parser) (:start-production built-parser)
ws-grammar ws-start))
built-parser))))
#?(:clj
(defmacro defparser
"Takes a string specification of a context-free grammar,
or a string URI for a text file containing such a specification,
or a map/vector of parser combinators, and sets a variable to a parser for that grammar.
String specifications are processed at macro-time, not runtime, so this is an
appealing alternative to (def _ (parser \"...\")) for ClojureScript users.
Optional keyword arguments unique to `defparser`:
- :instaparse.abnf/case-insensitive true"
[name grammar & {:as opts}]
;; For each of the macro-time opts, ensure that they are the data
;; types we expect, not more complex quoted expressions.
{:pre [(or (nil? (:input-format opts))
(keyword? (:input-format opts)))
(or (nil? (:output-format opts))
(keyword? (:output-format opts)))
(contains? #{true false nil} (:string-ci opts))
(contains? #{true false nil} (:no-slurp opts))]}
(if (string? grammar)
`(def ~name
(map->Parser
~(binding [abnf/*case-insensitive* (:instaparse.abnf/case-insensitive opts false)]
(let [macro-time-opts (select-keys opts [:input-format
:output-format
:string-ci
:no-slurp])
runtime-opts (dissoc opts :start)
macro-time-parser (apply parser grammar (apply concat macro-time-opts))
pre-processed-grammar (:grammar macro-time-parser)
grammar-producing-code
(->> pre-processed-grammar
(walk/postwalk
(fn [form]
(cond
;; Lists cannot be evaluated verbatim
(seq? form)
(list* 'list form)
;; Regexp terminals are handled differently in cljs
(= :regexp (:tag form))
`(merge (c/regexp ~(str (:regexp form)))
~(dissoc form :tag :regexp))
:else form))))
start-production
(or (:start opts) (:start-production macro-time-parser))]
`(parser ~grammar-producing-code
:start ~start-production
~@(apply concat runtime-opts))))))
`(def ~name (parser ~grammar ~@(apply concat opts))))))
(defn failure?
"Tests whether a parse result is a failure."
[result]
(or
(instance? gll/failure-type result)
(instance? gll/failure-type (meta result))))
(defn get-failure
"Extracts failure object from failed parse result."
[result]
(cond
(instance? gll/failure-type result)
result
(instance? gll/failure-type (meta result))
(meta result)
:else
nil))
(def ^:private standard-whitespace-parsers
{:standard (parser "whitespace = #'\\s+'")
:comma (parser "whitespace = #'[,\\s]+'")})
#?(:clj
(defn enable-tracing!
"Recompiles instaparse with tracing enabled.
This is called implicitly the first time you invoke a parser with
`:trace true` so usually you will not need to call this directly."
[]
(alter-var-root #'gll/TRACE (constantly true))
(alter-var-root #'gll/PROFILE (constantly true))
(require 'instaparse.gll :reload)))
#?(:clj
(defn disable-tracing!
"Recompiles instaparse with tracing disabled.
Call this to restore regular performance characteristics, eliminating
the small performance hit imposed by tracing."
[]
(alter-var-root #'gll/TRACE (constantly false))
(alter-var-root #'gll/PROFILE (constantly false))
(require 'instaparse.gll :reload)))
(defclone transform t/transform)
(defclone add-line-and-column-info-to-metadata lc/add-line-col-spans)
(defclone span viz/span)
#?(:clj (defclone visualize viz/tree-viz))