-
Notifications
You must be signed in to change notification settings - Fork 1
/
expressions.clj
328 lines (289 loc) · 16.3 KB
/
expressions.clj
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
;
; Copyright © 2023 Peter Monks
;
; Licensed under the Apache License Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; SPDX-License-Identifier: Apache-2.0
;
(ns spdx.expressions
"SPDX license expression functionality. This functionality is bespoke (it is
not provided by Spdx-Java-Library)."
(:require [clojure.string :as s]
[clojure.set :as set]
[instaparse.core :as insta]
[spdx.licenses :as lic]
[spdx.exceptions :as exc]))
; Adapted from ABNF grammar at https://spdx.github.io/spdx-spec/v2.3/SPDX-license-expressions/
(def ^:private spdx-license-expression-grammar-format "
(* Primitive tokens *)
<ws> = <#\"\\s+\">
<ows> = <#\"\\s*\">
<id-string> = #\"[\\p{Alnum}-\\.]+\"
and = <ws 'AND' ws>
or = <ws 'OR' ws>
<with> = <ws 'WITH' ws>
<or-later> = <'+'>
(* Identifiers *)
license-id = %s
license-exception-id = %s
license-ref = [<'DocumentRef-'> id-string <':'>] <'LicenseRef-'> id-string
(* Composite expressions *)
license-or-later = license-id or-later
<simple-expression> = license-id | license-or-later | license-ref
with-expression = simple-expression with license-exception-id
<composite-expression> = compound-expression ((and|or) compound-expression)+
nested-expression = <'('> ows compound-expression ows <')'>
<compound-expression> = simple-expression | with-expression | composite-expression | nested-expression
(* Start rule *)
<license-expression> = ows compound-expression ows
")
(defn- escape-re
"Escapes the given string for use in a regex."
[s]
(when s
(s/escape s {\< "\\<"
\( "\\("
\[ "\\["
\{ "\\{"
\\ "\\\\"
\^ "\\^"
\- "\\-"
\= "\\="
\$ "\\$"
\! "\\!"
\| "\\|"
\] "\\]"
\} "\\}"
\) "\\)"
\? "\\?"
\* "\\*"
\+ "\\+"
\. "\\."
\> "\\>"
})))
(def ^:private spdx-license-expression-grammar-d (delay (format spdx-license-expression-grammar-format
(s/join " | " (map #(str "#\"(?i)" (escape-re %) "\"") (filter #(not (s/ends-with? % "+")) (lic/ids)))) ; Filter out the few deprecated ids that end in "+", since they break the parser
(s/join " | " (map #(str "#\"(?i)" (escape-re %) "\"") (exc/ids))))))
(def ^:private spdx-license-expression-parser-d (delay (insta/parser @spdx-license-expression-grammar-d :start :license-expression)))
(def ^:private normalised-spdx-ids-map-d (delay (merge (into {} (map #(vec [(s/lower-case %) %]) (lic/ids)))
(into {} (map #(vec [(s/lower-case %) %]) (exc/ids))))))
(def ^:private current-gpl-family-ids #{
"AGPL-1.0-only" "AGPL-1.0-or-later" "AGPL-3.0-only" "AGPL-3.0-or-later"
"GPL-1.0-only" "GPL-1.0-or-later" "GPL-2.0-only" "GPL-2.0-or-later" "GPL-3.0-only" "GPL-3.0-or-later"
"LGPL-2.0-only" "LGPL-2.0-or-later" "LGPL-2.1-only" "LGPL-2.1-or-later" "LGPL-3.0-only" "LGPL-3.0-or-later"})
(def ^:private deprecated-simple-gpl-family-ids {
"AGPL-1.0" "AGPL-1.0-only"
; Note: AGPL-1.0+ never existed as a listed SPDX license identifier
"AGPL-3.0" "AGPL-3.0-only"
; Note: AGPL-3.0+ never existed as a listed SPDX license identifier
"GPL-1.0" "GPL-1.0-only"
"GPL-1.0+" "GPL-1.0-or-later"
"GPL-2.0" "GPL-2.0-only"
"GPL-2.0+" "GPL-2.0-or-later"
"GPL-3.0" "GPL-3.0-only"
"GPL-3.0+" "GPL-3.0-or-later"
"LGPL-2.0" "LGPL-2.0-only"
"LGPL-2.0+" "LGPL-2.0-or-later"
"LGPL-2.1" "LGPL-2.1-only"
"LGPL-2.1+" "LGPL-2.1-or-later"
"LGPL-3.0" "LGPL-3.0-only"
"LGPL-3.0+" "LGPL-3.0-or-later"})
(def ^:private deprecated-compound-gpl-family-ids {
"GPL-2.0-with-autoconf-exception" ["GPL-2.0-only" "Autoconf-exception-2.0"]
"GPL-2.0-with-bison-exception" ["GPL-2.0-only" "Bison-exception-2.2"]
"GPL-2.0-with-classpath-exception" ["GPL-2.0-only" "Classpath-exception-2.0"]
"GPL-2.0-with-font-exception" ["GPL-2.0-only" "Font-exception-2.0"]
"GPL-2.0-with-GCC-exception" ["GPL-2.0-only" "GCC-exception-2.0"]
"GPL-3.0-with-autoconf-exception" ["GPL-3.0-only" "Autoconf-exception-3.0"]
"GPL-3.0-with-GCC-exception" ["GPL-3.0-only" "GCC-exception-3.1"]})
(def ^:private deprecated-gpl-family-ids (set/union (set (keys deprecated-simple-gpl-family-ids)) (set (keys deprecated-compound-gpl-family-ids))))
(def ^:private gpl-family-ids (set/union current-gpl-family-ids deprecated-gpl-family-ids))
(def ^:private not-blank? (complement s/blank?))
(defn- normalise-gpl-id
"Normalises a GPL family `license-id` to a tuple (2 element vector) containing
the non-deprecated equivalent license id in first position, and (optionally -
may be nil) a license-exception-id in second position if `license-id` was a
compound id (an id that also identifies an exception, such as
\"GPL-2.0-with-classpath-exception\").
If `license-id` is not deprecated, returns it as-is (in the first position in
the tuple)."
[license-id]
(get deprecated-compound-gpl-family-ids
license-id
[(get deprecated-simple-gpl-family-ids
license-id
license-id)
nil]))
(defn- normalise-gpl-license-map
"Normalises a license map that is known to contain a GPL family `license-id`.
This involves:
1. Replacing deprecated GPL family license ids with their non-deprecated
equivalent
2. Turning `:or-later?` flags into the '-or-later' variant of the `license-id`
3. Expanding 'compound' license ids (e.g. GPL-2.0-with-classpath-exception)"
[{:keys [license-id or-later? license-exception-id]}]
(let [[new-license-id new-license-exception-id] (normalise-gpl-id license-id)
new-license-id (let [or-later-variant (s/replace new-license-id "-only" "-or-later")]
(if (and or-later? (lic/listed-id? or-later-variant))
or-later-variant
new-license-id))]
; Check if we have two license exception ids after expanding the license-id (e.g. from a valid but weird expression such as "GPL-2.0-with-autoconf-exception WITH Classpath-exception-2.0")
(if (and (not-blank? license-exception-id)
(not-blank? new-license-exception-id)
(not= license-exception-id new-license-exception-id))
[{:license-id new-license-id :license-exception-id new-license-exception-id} :and {:license-id new-license-id :license-exception-id license-exception-id}]
(merge {:license-id new-license-id}
(when (not-blank? license-exception-id) {:license-exception-id license-exception-id})
(when (not-blank? new-license-exception-id) {:license-exception-id new-license-exception-id})))))
(defn- normalise-gpl-elements
"Normalises all of the GPL elements in `parse-tree`."
[parse-tree]
(cond
(keyword? parse-tree) parse-tree
(sequential? parse-tree) (some-> (seq (map normalise-gpl-elements parse-tree)) vec) ; Note: naive (stack consuming) recursion
(map? parse-tree) (if (contains? gpl-family-ids (:license-id parse-tree))
(normalise-gpl-license-map parse-tree)
parse-tree)))
(defn parse-with-info
"As for parse, but returns an instaparse parse error info if parsing fails,
instead of nil.
See also https://github.com/Engelberg/instaparse#parse-errors"
([s] (parse-with-info s nil))
([^String s {:keys [normalise-gpl-ids?] :or {normalise-gpl-ids? true}}]
(when-not (s/blank? s)
(let [raw-parse-result (insta/parse @spdx-license-expression-parser-d s)]
(if (insta/failure? raw-parse-result)
raw-parse-result
(let [transformed-result (insta/transform {:and (constantly :and)
:or (constantly :or)
:license-id #(hash-map :license-id (get @normalised-spdx-ids-map-d (s/lower-case (first %&)) (first %&)))
:license-exception-id #(hash-map :license-exception-id (get @normalised-spdx-ids-map-d (s/lower-case (first %&)) (first %&)))
:license-ref #(case (count %&)
1 {:license-ref (first %&)}
2 {:document-ref (first %&) :license-ref (second %&)})
:license-or-later #(merge {:or-later? true} (first %&))
:with-expression #(merge (first %&) (second %&))
:nested-expression #(case (count %&)
1 (first %&) ; Collapse redundant nesting e.g. "(((Apache-2.0)))"
(vec %&))}
raw-parse-result)
transformed-result (if normalise-gpl-ids? (normalise-gpl-elements transformed-result) transformed-result)]
(if (sequential? transformed-result)
(case (count transformed-result)
1 (first transformed-result)
(vec transformed-result))
transformed-result)))))))
(defn parse
"Attempt to parse `s` (a String) as an SPDX license expression, returning a
data structure representing the parse tree, or nil if it cannot be parsed.
The optional `opts` map has these keys:
* `normalise-gpl-ids?` (boolean, default true) - controls whether
deprecated 'historical oddity' GPL family ids in the expression are
normalised to their non-deprecated replacements as part of the parsing
process.
Notes:
* The parser always normalises SPDX ids to their canonical case
e.g. aPAcHe-2.0 -> Apache-2.0
* The parser always removes redundant grouping
e.g. (((((Apache-2.0)))))) -> Apache-2.0
Examples (assuming default options):
\"Apache-2.0\"
-> {:license-id \"Apache-2.0\"}
\"Apache-2.0+\"
-> {:license-id \"Apache-2.0\" :or-later? true}
\"GPL-2.0+\"
-> {:license-id \"GPL-2.0-or-later\"}
\"GPL-2.0 WITH Classpath-exception-2.0\"
-> {:license-id \"GPL-2.0-only\"
:license-exception-id \"Classpath-exception-2.0\"}
\"CDDL-1.1 OR (GPL-2.0+ WITH Classpath-exception-2.0)\"
-> [{:license-id \"CDDL-1.1\"}
:or
{:license-id \"GPL-2.0-or-later\"
:license-exception-id \"Classpath-exception-2.0\"}]
See SPDX Specification Annex D for more details on SPDX license expressions:
https://spdx.github.io/spdx-spec/v2.3/SPDX-license-expressions/"
([s] (parse s nil))
([s opts]
(when-let [raw-parse-result (parse-with-info s opts)]
(when-not (insta/failure? raw-parse-result)
raw-parse-result))))
(defn- unparse-internal
"Internal implementation of unparse."
[parse-result]
(when parse-result
(cond
(= :or parse-result) "OR"
(= :and parse-result) "AND"
(sequential? parse-result) (when (pos? (count parse-result)) (str "(" (s/join " " (map unparse-internal parse-result)) ")")) ; Note: naive (stack consuming) recursion
(map? parse-result) (str (:license-id parse-result)
(when (:or-later? parse-result) "+")
(when (:license-exception-id parse-result) (str " WITH " (:license-exception-id parse-result)))
(when (:license-ref parse-result) (str (when (:document-ref parse-result) (str "DocumentRef-" (:document-ref parse-result) ":"))
"LicenseRef-" (:license-ref parse-result)))))))
(defn unparse
"Turns a valid `parse-result` back into an SPDX expression string. Results
are undefined for invalid parse trees. Returns nil if `parse-result` is nil."
[parse-result]
(when parse-result
(when-let [result (if (sequential? parse-result)
(s/join " " (map unparse-internal parse-result))
(unparse-internal parse-result))]
(when-not (s/blank? result)
(s/trim result)))))
(defn normalise
"Normalises an SPDX expression, by running it through parse then unparse.
Returns nil if `s` is nil or is not a valid SPDX expression.
`opts` are as for parse"
([s] (normalise s nil))
([s opts]
(some-> s
(parse opts)
unparse)))
(defn valid?
"Is `s` (a String) a valid SPDX license expression?
Note: if you intend to parse `s` if it's valid, it's more efficient to call
parse directly and check for a nil result instead of calling this method
first (it avoids double parsing)."
[^String s]
(not (or (s/blank? s)
(insta/failure? (insta/parse @spdx-license-expression-parser-d s)))))
(defn extract-ids
"Extract all SPDX ids (as a set of strings) from the given `parse-result`.
The optional `opts` map has these keys:
* include-or-later? (boolean, default false) - controls whether the output
includes the 'or later' indicator ('+') after license ids that have that
designation in the parse tree."
([parse-result] (extract-ids parse-result nil))
([parse-result {:keys [include-or-later?] :or {include-or-later? false} :as opts}]
(when parse-result
(cond
(sequential? parse-result) (set (mapcat #(extract-ids % opts) parse-result)) ; Note: naive (stack consuming) recursion
(map? parse-result) (set/union (when (:license-id parse-result) #{(str (:license-id parse-result) (when (and include-or-later? (:or-later? parse-result)) "+"))})
(when (:license-exception-id parse-result) #{(:license-exception-id parse-result)})
(when (:license-ref parse-result)
#{(str (when (:document-ref parse-result) (str "DocumentRef-" (:document-ref parse-result) ":"))
"LicenseRef-" (:license-ref parse-result))}))
:else nil))))
(defn init!
"Initialises this namespace upon first call (and does nothing on subsequent
calls), returning nil. Consumers of this namespace are not required to call
this fn, as initialisation will occur implicitly anyway; it is provided to
allow explicit control of the cost of initialisation to callers who need it."
[]
(lic/init!)
(exc/init!)
@spdx-license-expression-grammar-d
@spdx-license-expression-parser-d
@normalised-spdx-ids-map-d
nil)