-
Notifications
You must be signed in to change notification settings - Fork 114
/
Copy pathcompiler.clj
2081 lines (1747 loc) · 97.9 KB
/
compiler.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
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(ns clara.rules.compiler
"This namespace is for internal use and may move in the future.
This is the Clara rules compiler, translating raw data structures into compiled versions and functions.
Most users should use only the clara.rules namespace."
(:require [clara.rules.engine :as eng]
[clara.rules.listener :as listener]
[clara.rules.platform :as platform]
[clara.rules.schema :as schema]
[clojure.core.reducers :as r]
[clojure.reflect :as reflect]
[clojure.set :as s]
[clojure.set :as set]
[clojure.string :as string]
[clojure.walk :as walk]
[schema.core :as sc]
[schema.macros :as sm])
(:import [clara.rules.engine
ProductionNode
QueryNode
AlphaNode
RootJoinNode
HashJoinNode
ExpressionJoinNode
NegationNode
NegationWithJoinFilterNode
TestNode
AccumulateNode
AccumulateWithJoinFilterNode
LocalTransport
LocalSession
Accumulator
ISystemFact]
[java.beans
PropertyDescriptor]
[clojure.lang
IFn]))
;; Protocol for loading rules from some arbitrary source.
(defprotocol IRuleSource
(load-rules [source]))
(sc/defschema BetaNode
"These nodes exist in the beta network."
(sc/pred (comp #{ProductionNode
QueryNode
RootJoinNode
HashJoinNode
ExpressionJoinNode
NegationNode
NegationWithJoinFilterNode
TestNode
AccumulateNode
AccumulateWithJoinFilterNode}
class)
"Some beta node type"))
;; A rulebase -- essentially an immutable Rete network with a collection of
;; alpha and beta nodes and supporting structure.
(sc/defrecord Rulebase [;; Map of matched type to the alpha nodes that handle them.
alpha-roots :- {sc/Any [AlphaNode]}
;; Root beta nodes (join, accumulate, etc.).
beta-roots :- [BetaNode]
;; Productions in the rulebase.
productions :- #{schema/Production}
;; Production nodes.
production-nodes :- [ProductionNode]
;; Map of queries to the nodes hosting them.
query-nodes :- {sc/Any QueryNode}
;; Map of id to one of the alpha or beta nodes (join, accumulate, etc).
id-to-node :- {sc/Num (sc/conditional
:activation AlphaNode
:else BetaNode)}
;; Function for sorting activation groups of rules for firing.
activation-group-sort-fn
;; Function that takes a rule and returns its activation group.
activation-group-fn
;; Function that takes facts and determines what alpha nodes they match.
get-alphas-fn
;; A map of [node-id field-name] to function.
node-expr-fn-lookup :- schema/NodeFnLookup])
(defn- is-variable?
"Returns true if the given expression is a variable (a symbol prefixed by ?)"
[expr]
(and (symbol? expr)
(.startsWith (name expr) "?")))
(def ^:private reflector
"For some reason (bug?) the default reflector doesn't use the
Clojure dynamic class loader, which prevents reflecting on
`defrecords`. Work around by supplying our own which does."
(clojure.reflect.JavaReflector. (clojure.lang.RT/makeClassLoader)))
;; This technique borrowed from Prismatic's schema library.
(defn compiling-cljs?
"Return true if we are currently generating cljs code. Useful because cljx does not
provide a hook for conditional macro expansion."
[]
(boolean
(when-let [n (find-ns 'cljs.analyzer)]
(when-let [v (ns-resolve n '*cljs-file*)]
;; We perform this require only if we are compiling ClojureScript
;; so non-ClojureScript users do not need to pull in
;; that dependency.
(require 'clara.macros)
@v))))
(defn get-namespace-info
"Get metadata about the given namespace."
[namespace]
(when-let [n (and (compiling-cljs?) (find-ns 'cljs.env))]
(when-let [v (ns-resolve n '*compiler*)]
(get-in @@v [ :cljs.analyzer/namespaces namespace]))))
(defn cljs-ns
"Returns the ClojureScript namespace being compiled during Clojurescript compilation."
[]
(if (compiling-cljs?)
(-> 'cljs.analyzer (find-ns) (ns-resolve '*cljs-ns*) deref)
nil))
(defn resolve-cljs-sym
"Resolves a ClojureScript symbol in the given namespace."
[ns-sym sym]
(let [ns-info (get-namespace-info ns-sym)]
(if (namespace sym)
;; Symbol qualified by a namespace, so look it up in the requires info.
(if-let [source-ns (get-in ns-info [:requires (symbol (namespace sym))])]
(symbol (name source-ns) (name sym))
;; Not in the requires block, so assume the qualified name is a refers and simply return the symbol.
sym)
;; Symbol is unqualified, so check in the uses block.
(if-let [source-ns (get-in ns-info [:uses sym])]
(symbol (name source-ns) (name sym))
;; Symbol not found in eiher block, so attempt to retrieve it from
;; the current namespace.
(if (get-in (get-namespace-info ns-sym) [:defs sym])
(symbol (name ns-sym) (name sym))
nil)))))
(defn- get-cljs-accessors
"Returns accessors for ClojureScript. WARNING: this touches
ClojureScript implementation details that may change."
[sym]
(let [resolved (resolve-cljs-sym (cljs-ns) sym)
constructor (symbol (str "->" (name resolved)))
namespace-info (get-namespace-info (symbol (namespace resolved)))
constructor-info (get-in namespace-info [:defs constructor])]
(if constructor-info
(into {}
(for [field (first (:method-params constructor-info))]
[field (keyword (name field))]))
[])))
(defn- get-field-accessors
"Given a clojure.lang.IRecord subclass, returns a map of field name to a
symbol representing the function used to access it."
[cls]
(into {}
(for [field-name (clojure.lang.Reflector/invokeStaticMethod ^Class cls
"getBasis"
^"[Ljava.lang.Object;" (make-array Object 0))]
;; Do not preserve the metadata on the field names returned from
;; IRecord.getBasis() since it may not be safe to eval this metadata
;; in other contexts. This mostly applies to :tag metadata that may
;; be unqualified class names symbols at this point.
[(with-meta field-name {}) (symbol (str ".-" field-name))])))
(defn- get-bean-accessors
"Returns a map of bean property name to a symbol representing the function used to access it."
[cls]
(into {}
;; Iterate through the bean properties, returning tuples and the corresponding methods.
(for [^PropertyDescriptor property (seq (.. java.beans.Introspector
(getBeanInfo cls)
(getPropertyDescriptors)))]
[(symbol (string/replace (.. property (getName)) #"_" "-")) ; Replace underscore with idiomatic dash.
(symbol (str "." (.. property (getReadMethod) (getName))))])))
(defn effective-type [type]
(if (compiling-cljs?)
type
(if (symbol? type)
(.loadClass (clojure.lang.RT/makeClassLoader) (name type))
type)))
(defn get-fields
"Returns a map of field name to a symbol representing the function used to access it."
[type]
(if (compiling-cljs?)
;; Get ClojureScript fields.
(if (symbol? type)
(get-cljs-accessors type)
[])
;; Attempt to load the corresponding class for the type if it's a symbol.
(let [type (effective-type type)]
(cond
(isa? type clojure.lang.IRecord) (get-field-accessors type)
(class? type) (get-bean-accessors type) ; Treat unrecognized classes as beans.
:default []))))
(defn- equality-expression? [expression]
(let [qualify-when-sym #(when-let [resolved (and (symbol? %)
(resolve %))]
(and (var? resolved)
(symbol (-> resolved meta :ns ns-name name)
(-> resolved meta :name name))))
op (first expression)]
;; Check for unqualified = or == to support original Clara unification
;; syntax where clojure.core/== was supposed to be excluded explicitly.
(boolean (or (#{'= '== 'clojure.core/= 'clojure.core/==} op)
(#{'clojure.core/= 'clojure.core/==} (qualify-when-sym op))))))
(def ^:dynamic *compile-ctx* nil)
(defn try-eval
"Evals the given `expr`. If an exception is thrown, it is caught and an
ex-info exception is thrown with more details added. Uses *compile-ctx*
for additional contextual info to add to the exception details."
[expr]
(try
(eval expr)
(catch Exception e
(let [edata (merge {:expr expr}
(dissoc *compile-ctx* :msg))
msg (:msg *compile-ctx*)]
(throw (ex-info (str (if msg (str "Failed " msg) "Failed compiling.") \newline
;; Put ex-data specifically in the string since
;; often only ExceptionInfo.toString() will be
;; called, which doesn't show this data.
edata \newline)
edata
e))))))
(defn- compile-constraints
"Compiles a sequence of constraints into a structure that can be evaluated.
Callers may also pass a collection of equality-only-variables, which instructs
this function to only do an equality check on them rather than create a unification binding."
([exp-seq]
(compile-constraints exp-seq #{}))
([exp-seq equality-only-variables]
(if (empty? exp-seq)
`(deref ~'?__bindings__)
(let [ [exp & rest-exp] exp-seq
variables (into #{}
(filter (fn [item]
(and (symbol? item)
(= \? (first (name item)))
(not (equality-only-variables item))))
exp))
expression-values (remove variables (rest exp))
binds-variables? (and (equality-expression? exp)
(seq variables))
;; if we intend on binding any variables at this level of the
;; expression then future layers should not be able to rebind them.
;; see https://github.com/cerner/clara-rules/issues/417 for more info
equality-only-variables (if binds-variables?
(into equality-only-variables
variables)
equality-only-variables)
compiled-rest (compile-constraints rest-exp equality-only-variables)]
(when (and binds-variables?
(empty? expression-values))
(throw (ex-info (str "Malformed variable binding for " variables ". No associated value.")
{:variables (map keyword variables)})))
(cond
binds-variables?
;; Bind each variable with the first value we encounter.
;; The additional equality checks are handled below so which value
;; we bind to is not important. So an expression like (= ?x value-1 value-2) will
;; bind ?x to value-1, and then ensure value-1 and value-2 are equal below.
;; First assign each value in a let, so it is visible to subsequent expressions.
`(let [~@(for [variable variables
let-expression [variable (first expression-values)]]
let-expression)]
;; Update the bindings produced by this expression.
~@(for [variable variables]
`(swap! ~'?__bindings__ assoc ~(keyword variable) ~variable))
;; If there is more than one expression value, we need to ensure they are
;; equal as well as doing the bind. This ensures that value-1 and value-2 are
;; equal.
~(if (> (count expression-values) 1)
`(if ~(cons '= expression-values) ~compiled-rest nil)
;; No additional values to check, so move on to the rest of
;; the expression
compiled-rest)
)
;; A contraint that is empty doesn't need to be added as a check,
;; simply move on to the rest
(empty? exp)
compiled-rest
;; No variables to unify, so simply check the expression and
;; move on to the rest.
:else
`(if ~exp ~compiled-rest nil))))))
(defn flatten-expression
"Flattens expression as clojure.core/flatten does, except will flatten
anything that is a collection rather than specifically sequential."
[expression]
(filter (complement coll?)
(tree-seq coll? seq expression)))
(defn variables-as-keywords
"Returns a set of the symbols in the given s-expression that start with '?' as keywords"
[expression]
(into #{} (for [item (flatten-expression expression)
:when (is-variable? item)]
(keyword item))))
(defn field-name->accessors-used
"Returns a map of field name to accessors for any field names of type used
in the constraints."
[type constraints]
(let [field-name->accessor (get-fields type)
all-fields (set (keys field-name->accessor))
fields-used (into #{}
(filter all-fields)
(flatten-expression constraints))]
(into {}
(filter (comp fields-used key))
field-name->accessor)))
(defn- add-meta
"Helper function to add metadata."
[fact-symbol fact-type]
(let [fact-type (if (symbol? fact-type)
(try
(resolve fact-type)
(catch Exception e
;; We shouldn't have to worry about exceptions being thrown here according
;; to `resolve`s docs.
;; However, due to http://dev.clojure.org/jira/browse/CLJ-1403 being open
;; still, it is safer to catch any exceptions thrown.
fact-type))
fact-type)]
(if (class? fact-type)
(vary-meta fact-symbol assoc :tag (symbol (.getName ^Class fact-type)))
fact-symbol)))
(defn compile-condition
"Returns a function definition that can be used in alpha nodes to test the condition."
[type destructured-fact constraints result-binding env]
(let [;; Get a map of fieldnames to access function symbols.
accessors (field-name->accessors-used type constraints)
binding-keys (variables-as-keywords constraints)
;; The assignments should use the argument destructuring if provided, or default to accessors otherwise.
assignments (if destructured-fact
;; Simply destructure the fact if arguments are provided.
[destructured-fact '?__fact__]
;; No argument provided, so use our default destructuring logic.
(concat '(this ?__fact__)
(mapcat (fn [[name accessor]]
[name (list accessor '?__fact__)])
accessors)))
;; The destructured environment, if any
destructured-env (if (> (count env) 0)
{:keys (mapv #(symbol (name %)) (keys env))}
'?__env__)
;; Initial bindings used in the return of the compiled condition expresion.
initial-bindings (if result-binding {result-binding '?__fact__} {})]
`(fn [~(add-meta '?__fact__ type)
~destructured-env] ;; TODO: add destructured environment parameter...
(let [~@assignments
~'?__bindings__ (atom ~initial-bindings)]
~(compile-constraints constraints)))))
(defn build-token-assignment
"A helper function to build variable assignment forms for tokens."
[binding-key]
(list (symbol (name binding-key))
(list `-> '?__token__ :bindings binding-key)))
;; FIXME: add env...
(defn compile-test [tests]
(let [binding-keys (variables-as-keywords tests)
assignments (mapcat build-token-assignment binding-keys)]
`(fn [~'?__token__]
(let [~@assignments]
(and ~@tests)))))
(defn compile-action
"Compile the right-hand-side action of a rule, returning a function to execute it."
[binding-keys rhs env]
(let [;; Avoid creating let bindings in the compile code that aren't actually used in the body.
;; The bindings only exist in the scope of the RHS body, not in any code called by it,
;; so this scanning strategy will detect all possible uses of binding variables in the RHS.
;; Note that some strategies with macros could introduce bindings, but these aren't something
;; we're trying to support. If necessary a user could macroexpand their RHS code manually before
;; providing it to Clara.
rhs-bindings-used (variables-as-keywords rhs)
assignments (sequence
(comp
(filter rhs-bindings-used)
(mapcat build-token-assignment))
binding-keys)
;; The destructured environment, if any.
destructured-env (if (> (count env) 0)
{:keys (mapv #(symbol (name %)) (keys env))}
'?__env__)]
`(fn [~'?__token__ ~destructured-env]
(let [~@assignments]
~rhs))))
(defn compile-accum
"Used to create accumulators that take the environment into account."
[accum env]
(let [destructured-env
(if (> (count env) 0)
{:keys (mapv #(symbol (name %)) (keys env))}
'?__env__)]
`(fn [~destructured-env]
~accum)))
(defn compile-join-filter
"Compiles to a predicate function that ensures the given items can be unified. Returns a ready-to-eval
function that accepts the following:
* a token from the parent node
* the fact
* a map of bindings from the fact, which was typically computed on the alpha side
* an environment
The function created here returns truthy if the given fact satisfies the criteria."
[{:keys [type constraints args] :as unification-condition} ancestor-bindings element-bindings env]
(let [accessors (field-name->accessors-used type constraints)
destructured-env (if (> (count env) 0)
{:keys (mapv #(symbol (name %)) (keys env))}
'?__env__)
destructured-fact (first args)
fact-assignments (if destructured-fact
;; Simply destructure the fact if arguments are provided.
[destructured-fact '?__fact__]
;; No argument provided, so use our default destructuring logic.
(concat '(this ?__fact__)
(mapcat (fn [[name accessor]]
[name (list accessor '?__fact__)])
accessors)))
;; Get the bindings used in the join filter expression that are pulled from
;; the token. This is simply the bindings in the constraints with the newly
;; created element bindings for this condition removed.
token-binding-keys (remove element-bindings (variables-as-keywords constraints))
token-assignments (mapcat build-token-assignment token-binding-keys)
new-binding-assignments (mapcat #(list (symbol (name %))
(list 'get '?__element-bindings__ %))
element-bindings)
assignments (concat
fact-assignments
token-assignments
new-binding-assignments)
equality-only-variables (into #{} (for [binding ancestor-bindings]
(symbol (name (keyword binding)))))]
`(fn [~'?__token__
~(add-meta '?__fact__ type)
~'?__element-bindings__
~destructured-env]
(let [~@assignments
~'?__bindings__ (atom {})]
~(compile-constraints constraints equality-only-variables)))))
(defn- expr-type [expression]
(if (map? expression)
:condition
(first expression)))
(defn- cartesian-join
"Performs a cartesian join to distribute disjunctions for disjunctive normal form.,
This distributing each disjunction across every other disjunction and also across each
given conjunction. Returns a sequence where each element contains a sequence
of conjunctions that can be used in rules."
[disjunctions-to-distribute conjunctions]
;; For every disjuction, do a cartesian join to distribute it
;; across every other disjuction. We also must distributed it across
;; each conjunction
(reduce
(fn [distributed-disjunctions disjunction-to-distribute]
(for [expression disjunction-to-distribute
distributed-disjunction distributed-disjunctions]
(conj distributed-disjunction expression)))
;; Start with our conjunctions to join to, since we must distribute
;; all disjunctions across these as well.
[conjunctions]
disjunctions-to-distribute))
(defn to-dnf
"Convert a lhs expression to disjunctive normal form."
[expression]
;; Always validate the expression schema, as this is only done at compile time.
(sc/validate schema/Condition expression)
(condp = (expr-type expression)
;; Individual conditions can return unchanged.
:condition
expression
:test
expression
:exists
expression
;; Apply de Morgan's law to push negation nodes to the leaves.
:not
(let [children (rest expression)
child (first children)]
(when (not= 1 (count children))
(throw (RuntimeException. "Negation must have only one child.")))
(condp = (expr-type child)
;; If the child is a single condition, simply return the ast.
:condition expression
:test expression
;; Note that :exists does not support further nested boolean conditions.
;; It is just syntax sugar over an accumulator.
:exists expression
;; Double negation, so just return the expression under the second negation.
:not
(to-dnf (second child))
;; DeMorgan's law converting conjunction to negated disjuctions.
:and (to-dnf (cons :or (for [grandchild (rest child)] [:not grandchild])))
;; DeMorgan's law converting disjuction to negated conjuctions.
:or (to-dnf (cons :and (for [grandchild (rest child)] [:not grandchild])))))
;; For all others, recursively process the children.
(let [children (map to-dnf (rest expression))
;; Get all conjunctions, which will not conain any disjunctions since they were processed above.
conjunctions (filter #(#{:and :condition :not :exists} (expr-type %)) children)]
;; If there is only one child, the and or or operator can simply be eliminated.
(if (= 1 (count children))
(first children)
(condp = (expr-type expression)
:and
(let [disjunctions (map rest (filter #(= :or (expr-type %)) children))
;; Merge all child conjunctions into a single conjunction.
combine-conjunctions (fn [children]
(cons :and
(for [child children
nested-child (if (= :and (expr-type child))
(rest child)
[child])]
nested-child)))]
(if (empty? disjunctions)
(combine-conjunctions children)
(cons :or
(for [c (cartesian-join disjunctions conjunctions)]
(combine-conjunctions c)))))
:or
;; Merge all child disjunctions into a single disjunction.
(let [disjunctions (mapcat rest (filter #(#{:or} (expr-type %)) children))]
(cons :or (concat disjunctions conjunctions))))))))
(defn- non-equality-unification? [expression previously-bound]
"Returns true if the given expression does a non-equality unification against a variable that
is not in the previously-bound set, indicating it can't be solved by simple unification."
(let [found-complex (atom false)
process-form (fn [form]
(when (and (seq? form)
(not (equality-expression? form))
(some (fn [sym] (and (symbol? sym)
(.startsWith (name sym) "?")
(not (previously-bound sym))))
(flatten-expression form)))
(reset! found-complex true))
form)]
;; Walk the expression to find use of a symbol that can't be solved by equality-based unificaiton.
(doall (walk/postwalk process-form expression))
@found-complex))
(defn condition-type
"Returns the type of a single condition that has been transformed
to disjunctive normal form. The types are: :negation, :accumulator, :test, :exists, and :join"
[condition]
(let [is-negation (= :not (first condition))
is-exists (= :exists (first condition))
accumulator (:accumulator condition)
result-binding (:result-binding condition) ; Get the optional result binding used by accumulators.
condition (cond
is-negation (second condition)
accumulator (:from condition)
:default condition)
node-type (cond
is-negation :negation
is-exists :exists
accumulator :accumulator
(:type condition) :join
:else :test)]
node-type))
(defn- extract-exists
"Converts :exists operations into an accumulator to detect
the presence of a fact and a test to check that count is
greater than zero.
It may be possible to replace this conversion with a specialized
ExtractNode in the future, but this transformation is simple
and meets the functional needs."
[conditions]
(for [condition conditions
expanded (if (= :exists (condition-type condition))
;; This is an :exists condition, so expand it
;; into an accumulator and a test.
(let [exists-count (gensym "?__gen__")]
[{:accumulator '(clara.rules.accumulators/exists)
:from (second condition)
:result-binding (keyword exists-count)}])
;; This is not an :exists condition, so do not change it.
[condition])]
expanded))
(defn- classify-variables
"Classifies the variables found in the given contraints into 'bound' vs 'free'
variables. Bound variables are those that are found in a valid
equality-based, top-level binding form. All other variables encountered are
considered free. Returns a tuple of the form
[bound-variables free-variables]
where bound-variables and free-variables are the sets of bound and free
variables found in the constraints respectively."
[constraints]
(reduce (fn [[bound-variables free-variables] constraint]
;; Only top-level constraint forms can introduce new variable bindings.
;; If the top-level constraint is an equality expression, add the
;; bound variables to the set of bound variables.
(if (and (seq? constraint) (equality-expression? constraint))
[(->> (rest constraint)
(filterv is-variable?)
;; A variable that was marked unbound in a previous expression should
;; not be considered bound.
(remove free-variables)
(into bound-variables))
;; Any other variables in a nested form are now considered "free".
(->> (rest constraint)
;; We already have checked this level symbols for bound variables.
(remove symbol?)
flatten-expression
(filter is-variable?)
;; Variables previously bound in an expression are not free.
(remove bound-variables)
(into free-variables))]
;; Binding forms are not supported nested within other forms, so
;; any variables that occur now are considered "free" variables.
[bound-variables
(->> (flatten-expression constraint)
(filterv is-variable?)
;; Variables previously bound in an expression are not free.
(remove bound-variables)
(into free-variables))]))
[#{} #{}]
constraints))
(sc/defn analyze-condition :- {;; Variables used in the condition that are bound
:bound #{sc/Symbol}
;; Variables used in the condition that are unbound.
:unbound #{sc/Symbol}
;; The condition that was analyzed
:condition schema/Condition
;; Flag indicating it is an accumulator.
:is-accumulator sc/Bool}
[condition :- schema/Condition]
(let [dnf-condition (to-dnf condition)
;; Break the condition up into leafs
leaf-conditions (case (first dnf-condition)
;; A top level disjunction, so get all child conjunctions and
;; flatten them.
:or
(for [nested-condition (rest dnf-condition)
leaf-condition (if (= :and (first nested-condition))
(rest nested-condition)
[nested-condition])]
leaf-condition)
;; A top level and of nested conditions, so just use them
:and
(rest dnf-condition)
;; The condition itself is a leaf, so keep it.
[dnf-condition])]
(reduce
(fn [{:keys [bound unbound condition is-accumulator]} leaf-condition]
;; The effective leaf for variable purposes may be contained in a negation or
;; an accumulator, so extract it.
(let [effective-leaf (condp = (condition-type leaf-condition)
:accumulator (:from leaf-condition)
:negation (second leaf-condition)
leaf-condition)
constraints (:constraints effective-leaf)
[bound-variables unbound-variables] (if (#{:negation :test} (condition-type leaf-condition))
;; Variables used in a negation should be considered
;; unbound since they aren't usable in another condition,
;; so label all variables as unbound. Similarly, :test
;; conditions can't bind new variables since they don't
;; have any new facts as input. See:
;; https://github.com/cerner/clara-rules/issues/357
[#{}
(apply s/union (classify-variables constraints))]
;; It is not a negation, so simply classify variables.
(classify-variables constraints))
bound-with-result-bindings (cond-> bound-variables
(:fact-binding effective-leaf) (conj (symbol (name (:fact-binding effective-leaf))))
(:result-binding leaf-condition) (conj (symbol (name (:result-binding leaf-condition)))))
;; All variables bound in this condition.
all-bound (s/union bound bound-with-result-bindings)
;; Unbound variables, minus those that have been bound elsewhere in this condition.
all-unbound (s/difference (s/union unbound-variables unbound) all-bound)]
{:bound all-bound
:unbound all-unbound
:condition condition
:is-accumulator (or is-accumulator
(= :accumulator
(condition-type leaf-condition)))}))
{:bound #{}
:unbound #{}
:condition condition
:is-accumulator false}
leaf-conditions)))
(sc/defn sort-conditions :- [schema/Condition]
"Performs a topologic sort of conditions to ensure variables needed by
child conditions are bound."
[conditions :- [schema/Condition]]
;; Get the bound and unbound variables for all conditions and sort them.
(let [classified-conditions (map analyze-condition conditions)]
(loop [sorted-conditions []
bound-variables #{}
remaining-conditions classified-conditions]
(if (empty? remaining-conditions)
;; No more conditions to sort, so return the raw conditions
;; in sorted order.
(map :condition sorted-conditions)
;; Unsatisfied conditions remain, so find ones we can satisfy.
(let [satisfied? (fn [classified-condition]
(clojure.set/subset? (:unbound classified-condition)
bound-variables))
;; Find non-accumulator conditions that are satisfied. We defer
;; accumulators until later in the rete network because they
;; may fire a default value if all needed bindings earlier
;; in the network are satisfied.
satisfied-non-accum? (fn [classified-condition]
(and (not (:is-accumulator classified-condition))
(clojure.set/subset? (:unbound classified-condition)
bound-variables)))
has-satisfied-non-accum (some satisfied-non-accum? remaining-conditions)
newly-satisfied (if has-satisfied-non-accum
(filter satisfied-non-accum? remaining-conditions)
(filter satisfied? remaining-conditions))
still-unsatisfied (if has-satisfied-non-accum
(remove satisfied-non-accum? remaining-conditions)
(remove satisfied? remaining-conditions))
updated-bindings (apply clojure.set/union bound-variables
(map :bound newly-satisfied))]
;; If no existing variables can be satisfied then the production is invalid.
(when (empty? newly-satisfied)
;; Get the subset of variables that cannot be satisfied.
(let [unsatisfiable (clojure.set/difference
(apply clojure.set/union (map :unbound still-unsatisfied))
bound-variables)]
(throw (ex-info (str "Using variable that is not previously bound. This can happen "
"when an expression uses a previously unbound variable, "
"or if a variable is referenced in a nested part of a parent "
"expression, such as (or (= ?my-expression my-field) ...). " \newline
"Note that variables used in negations are not bound for subsequent
rules since the negation can never match." \newline
"Production: " \newline
(:production *compile-ctx*) \newline
"Unbound variables: "
unsatisfiable)
{:production (:production *compile-ctx*)
:variables unsatisfiable}))))
(recur (into sorted-conditions newly-satisfied)
updated-bindings
still-unsatisfied))))))
(defn- non-equality-unifications
"Returns a set of unifications that do not use equality-based checks."
[constraints]
(let [[bound-variables unbound-variables] (classify-variables constraints)]
(into #{}
(for [constraint constraints
:when (non-equality-unification? constraint bound-variables)]
constraint))))
(sc/defn condition-to-node :- schema/ConditionNode
"Converts a condition to a node structure."
[condition :- schema/Condition
env :- (sc/maybe {sc/Keyword sc/Any})
parent-bindings :- #{sc/Keyword}]
(let [node-type (condition-type condition)
accumulator (:accumulator condition)
result-binding (:result-binding condition) ; Get the optional result binding used by accumulators.
condition (cond
(= :negation node-type) (second condition)
accumulator (:from condition)
:default condition)
;; Convert a test within a negation to a negation of the test. This is necessary
;; because negation nodes expect an additional condition to match against.
[node-type condition] (if (and (= node-type :negation)
(= :test (condition-type condition)))
;; Create a negated version of our test condition.
[:test {:constraints [(list 'not (cons 'and (:constraints condition)))]}]
;; This was not a test within a negation, so keep the previous values.
[node-type condition])
;; Get the set of non-equality unifications that cannot be resolved locally to the rule.
non-equality-unifications (if (or (= :accumulator node-type)
(= :negation node-type)
(= :join node-type))
(non-equality-unifications (:constraints condition))
#{})
;; If there are any non-equality unitifications, create a join with filter expression to handle them.
join-filter-expressions (if (seq non-equality-unifications)
(assoc condition :constraints (filterv non-equality-unifications (:constraints condition)))
nil)
;; Remove instances of non-equality constraints from accumulator
;; and negation nodes, since those are handled with specialized node implementations.
condition (if (seq non-equality-unifications)
(assoc condition
:constraints (into [] (remove non-equality-unifications (:constraints condition)))
:original-constraints (:constraints condition))
condition)
;; Variables used in the constraints
constraint-bindings (variables-as-keywords (:constraints condition))
;; Variables used in the condition.
cond-bindings (if (:fact-binding condition)
(conj constraint-bindings (:fact-binding condition))
constraint-bindings)
new-bindings (s/difference (variables-as-keywords (:constraints condition))
parent-bindings)
join-filter-bindings (if join-filter-expressions
(variables-as-keywords join-filter-expressions)
nil)]
(cond->
{:node-type node-type
:condition condition
:new-bindings new-bindings
:used-bindings (s/union cond-bindings join-filter-bindings)}
(seq env) (assoc :env env)
;; Add the join bindings to join, accumulator or negation nodes.
(#{:join :negation :accumulator} node-type) (assoc :join-bindings (s/intersection cond-bindings parent-bindings))
accumulator (assoc :accumulator accumulator)
result-binding (assoc :result-binding result-binding)
join-filter-expressions (assoc :join-filter-expressions join-filter-expressions)
join-filter-bindings (assoc :join-filter-join-bindings (s/intersection join-filter-bindings parent-bindings)))))
(sc/defn ^:private add-node :- schema/BetaGraph
"Adds a node to the beta graph."
[beta-graph :- schema/BetaGraph
source-ids :- [sc/Int]
target-id :- sc/Int
target-node :- (sc/either schema/ConditionNode schema/ProductionNode)]
;; Add the production or condition to the network.
(let [beta-graph (assoc-in beta-graph [:id-to-new-bindings target-id]
;; A ProductionNode will not have the set of new bindings previously created,
;; so we assign them an empty set here. A ConditionNode will always have a set of new bindings,
;; even if it is an empty one; this is enforced by the schema. Having an empty set of new bindings
;; is a valid and meaningful state that just means that all join bindings in that node come from right-activations
;; earlier in the network.
(or (:new-bindings target-node)
#{}))
beta-graph (if (#{:production :query} (:node-type target-node))
(assoc-in beta-graph [:id-to-production-node target-id] target-node)
(assoc-in beta-graph [:id-to-condition-node target-id] target-node))]
;; Associate the forward and backward edges.
(reduce (fn [beta-graph source-id]
(let [forward-path [:forward-edges source-id]
forward-previous (get-in beta-graph forward-path)
backward-path [:backward-edges target-id]
backward-previous (get-in beta-graph backward-path)]
(-> beta-graph
(assoc-in
forward-path
(if forward-previous
(conj forward-previous target-id)
(sorted-set target-id)))
(assoc-in
backward-path
(if backward-previous
(conj backward-previous source-id)
(sorted-set source-id))))))
beta-graph
source-ids)))
(declare add-production)
(sc/defn ^:private extract-negation :- {:new-expression schema/Condition