-
Notifications
You must be signed in to change notification settings - Fork 4
/
format.cljc
61 lines (51 loc) · 2.02 KB
/
format.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
(ns com.yetanalytics.flint.format
(:require [clojure.string :as cstr]
[clojure.walk :as w]
[com.yetanalytics.flint.util :as u]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Helpers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn bracketted-expr-str?
[s]
(boolean (re-matches #"\(.*\)" s)))
(defn bracketted-or-fn-expr-str?
"Determine if a expression string represents a bracketted expression or
a function call."
[s]
(boolean (or (re-matches #"\(.*\)" s)
;; Built-ins, IRI, and prefixed IRI functions
(re-matches #"[\<\w\-].*\(.*\)" s)
;; (NOT) EXISTS doesn't use parens
(cstr/starts-with? s "EXISTS")
(cstr/starts-with? s "NOT EXISTS"))))
(defn indent-str
"Add 4 spaces after each line break (including at the beginning)."
[s]
(str " " (cstr/replace s #"\n" "\n ")))
(defn wrap-in-braces
"Wrap the `clause` string in curly braces. If `pretty?` is true,
also add line breaks and indent `clause`."
[clause pretty?]
(if pretty?
(str "{\n" (indent-str clause) "\n}")
(str "{ " clause " }")))
(defn join-clauses
"Join the `clauses` coll. If `pretty?` is true, separate by line
breaks; otherwise separate by space."
[clauses pretty?]
(if pretty?
(cstr/join "\n" clauses)
(cstr/join " " clauses)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Formatting
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmulti format-ast-node
"Convert the AST node into a string."
(fn [_ x] (if-some [k (u/get-keyword x)] k :default)))
(defmethod format-ast-node :default [_ ast-node] ast-node)
(defn format-ast
"Convert `ast` into a string, with `opts` including:
- `:xsd-prefix` the prefix of the XSD IRI, used in RDF literals.
- `:pretty?` whether to add linebreaks or indents."
[ast opts]
(w/postwalk (partial format-ast-node opts) ast))