-
Notifications
You must be signed in to change notification settings - Fork 526
Expand file tree
/
Copy pathRequirements.fs
More file actions
1353 lines (1233 loc) · 65 KB
/
Requirements.fs
File metadata and controls
1353 lines (1233 loc) · 65 KB
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
module Paket.Requirements
open System
open Paket
open Paket.Domain
open Paket.PackageSources
open Paket.Logging
open Paket.PlatformMatching
[<RequireQualifiedAccess>]
// To make reasoning and writing tests easier.
// Ideally we would "simplify" the trees to a "normal" form internally
[<CustomEquality; CustomComparison>]
[<System.Diagnostics.DebuggerDisplay("{InfixNotation}")>]
type FrameworkRestrictionP =
private
| ExactlyP of TargetProfile
| AtLeastP of TargetProfile
// Means: Take all frameworks NOT given by the restriction
| NotP of FrameworkRestrictionP
| OrP of FrameworkRestrictionP list
| AndP of FrameworkRestrictionP list
member x.InfixNotation =
match x with
| FrameworkRestrictionP.ExactlyP r -> "== " + r.ToString()
| FrameworkRestrictionP.AtLeastP r -> ">= " + r.ToString()
| FrameworkRestrictionP.NotP(FrameworkRestrictionP.AtLeastP r) -> sprintf "< " + r.ToString()
| FrameworkRestrictionP.NotP(fr) -> sprintf "NOT (%O)" fr
| FrameworkRestrictionP.OrP(frl) ->
match frl with
| [] -> "false"
| [single] -> sprintf "%O" single
| _ -> sprintf "(%s)" (System.String.Join(" || ", frl |> Seq.map (fun inner -> sprintf "(%s)" inner.InfixNotation)))
| FrameworkRestrictionP.AndP(frl) ->
match frl with
| [] -> "true"
| [single] -> sprintf "%O" single
| _ -> sprintf "(%s)" (System.String.Join(" && ", frl |> Seq.map (fun inner -> sprintf "(%s)" inner.InfixNotation)))
override this.ToString() =
match this with
| FrameworkRestrictionP.ExactlyP r -> "== " + r.ToString()
| FrameworkRestrictionP.AtLeastP r -> ">= " + r.ToString()
| FrameworkRestrictionP.NotP(FrameworkRestrictionP.AtLeastP r) -> sprintf "< " + r.ToString()
| FrameworkRestrictionP.NotP(fr) -> sprintf "NOT (%O)" fr
| FrameworkRestrictionP.OrP(frl) ->
match frl with
| [] -> "false"
| [single] -> sprintf "%O" single
| _ -> sprintf "|| %s" (System.String.Join(" ", frl |> Seq.map (sprintf "(%O)")))
| FrameworkRestrictionP.AndP(frl) ->
match frl with
| [] -> "true"
| [single] -> sprintf "%O" single
| _ -> sprintf "&& %s" (System.String.Join(" ", frl |> Seq.map (sprintf "(%O)")))
/// The list represented by this restriction (ie the included set of frameworks)
// NOTE: All critical paths test only if this set is empty, so we use lazy seq here
member x.RepresentedFrameworks =
match x with
| FrameworkRestrictionP.ExactlyP r -> [ r ] |> Set.ofList
| FrameworkRestrictionP.AtLeastP r -> r.PlatformsSupporting
//PlatformMatching.get r
//KnownTargetProfiles.AllProfiles
//|> Set.filter (fun plat -> r.IsSupportedBy plat)
| FrameworkRestrictionP.NotP(fr) ->
let notTaken = fr.RepresentedFrameworks
Set.difference KnownTargetProfiles.AllProfiles notTaken
| FrameworkRestrictionP.OrP (frl) ->
frl
|> Seq.map (fun fr -> fr.RepresentedFrameworks)
|> Set.unionMany
| FrameworkRestrictionP.AndP (frl) ->
match frl with
| h :: _ ->
frl
|> Seq.map (fun fr -> fr.RepresentedFrameworks)
|> Set.intersectMany
| [] ->
KnownTargetProfiles.AllProfiles
member x.IsMatch (tp:TargetProfile) =
match x with
| FrameworkRestrictionP.ExactlyP r -> r = tp
| FrameworkRestrictionP.AtLeastP r ->
tp.SupportedPlatformsTransitive |> Seq.contains r
| FrameworkRestrictionP.NotP(fr) ->
fr.IsMatch tp |> not
| FrameworkRestrictionP.OrP (frl) ->
frl
|> List.exists (fun fr -> fr.IsMatch tp)
| FrameworkRestrictionP.AndP (frl) ->
frl
|> List.forall (fun fr -> fr.IsMatch tp)
/// Returns true if the restriction x is a subset of the restriction y (a restriction basically represents a list, see RepresentedFrameworks)
/// For example =net46 is a subset of >=netstandard13
member x.IsSubsetOf (y:FrameworkRestrictionP) =
// better ~ 5 Mins, but below recursive logic should be even better.
let inline fallBack doAssert (x:FrameworkRestrictionP) (y:FrameworkRestrictionP) =
#if DEBUG
if doAssert then
assert (false)// make sure the fallback is never needed
#endif
let superset = y.RepresentedFrameworks
let subset = x.RepresentedFrameworks
Set.isSubset subset superset
// Because the formula simplifier needs it this is a quite HOT PATH
let inline isSubsetOfCalculation x y =
match x with
| FrameworkRestrictionP.ExactlyP x' ->
match y with
| FrameworkRestrictionP.ExactlyP y' -> x' = y'
| FrameworkRestrictionP.AtLeastP y' ->
// =x' is a subset of >=y' when 'y is smaller than 'x
y'.IsSmallerThanOrEqual x'
// these are or 'common' forms, others are not allowed
| FrameworkRestrictionP.NotP(FrameworkRestrictionP.AtLeastP y') ->
// =x is only a subset of <y when its not a subset of >= y
y'.IsSmallerThanOrEqual x'
|> not
| FrameworkRestrictionP.NotP(FrameworkRestrictionP.ExactlyP y') ->
x' <> y'
// This one should never actually hit.
| FrameworkRestrictionP.NotP(y') -> fallBack true x y
| FrameworkRestrictionP.OrP (ys) ->
ys
|> Seq.exists (fun y' -> x.IsSubsetOf y')
| FrameworkRestrictionP.AndP (ys) ->
ys
|> Seq.forall (fun y' -> x.IsSubsetOf y')
| FrameworkRestrictionP.AtLeastP x' ->
match y with
| FrameworkRestrictionP.ExactlyP y' ->
// >=x can only be a subset of =y when it is already the max
x' = y' && x'.SupportedPlatforms.IsEmpty
| FrameworkRestrictionP.AtLeastP y' ->
// >=x is only a subset of >=y when y is 'smaller" than x
y'.IsSmallerThanOrEqual x'
// these are or 'common' forms, others are not allowed
| FrameworkRestrictionP.NotP(FrameworkRestrictionP.AtLeastP y') ->
// >= x' is only a subset of < y' when their intersection is empty
Set.intersect (x'.PlatformsSupporting) (y'.PlatformsSupporting)
|> Set.isEmpty
| FrameworkRestrictionP.NotP(FrameworkRestrictionP.ExactlyP y') ->
// >= x' is only a subset of <> y' when y' is not part of >=x'
x'.PlatformsSupporting
|> Set.contains y'
|> not
// This one should never actually hit.
| FrameworkRestrictionP.NotP(y') -> fallBack true x y
| FrameworkRestrictionP.OrP (ys) ->
ys
|> Seq.exists (fun y' -> x.IsSubsetOf y')
| FrameworkRestrictionP.AndP (ys) ->
ys
|> Seq.forall (fun y' -> x.IsSubsetOf y')
// these are or 'common' forms, others are not allowed
| FrameworkRestrictionP.NotP(FrameworkRestrictionP.AtLeastP x' as notX) ->
match y with
| FrameworkRestrictionP.ExactlyP y' ->
// < x is a subset of ='y when?
#if DEBUG
assert (not (fallBack false x y))// TODO: can this happen?
#endif
false
| FrameworkRestrictionP.AtLeastP y' ->
// < x is a subset of >= y when there are no smaller things than y and
#if DEBUG
assert (not (fallBack false x y))// TODO: can this happen?
#endif
false
// these are or 'common' forms, others are not allowed
| FrameworkRestrictionP.NotP(FrameworkRestrictionP.AtLeastP y' as notY) ->
// < 'x is a subset of < y when >=y is a subset of >=x
notY.IsSubsetOf notX
| FrameworkRestrictionP.NotP(FrameworkRestrictionP.ExactlyP y' as notY) ->
// < 'x is a subset of <> y when =y is a subset of >=x
notY.IsSubsetOf notX
// This one should never actually hit.
| FrameworkRestrictionP.NotP(y') -> fallBack true x y
| FrameworkRestrictionP.OrP (ys) ->
ys
|> Seq.exists (fun y' -> x.IsSubsetOf y')
| FrameworkRestrictionP.AndP (ys) ->
ys
|> Seq.forall (fun y' -> x.IsSubsetOf y')
| FrameworkRestrictionP.NotP(FrameworkRestrictionP.ExactlyP x' as notX) ->
match y with
| FrameworkRestrictionP.ExactlyP y' ->
// <> x is a subset of =y ?
#if DEBUG
assert (not (fallBack false x y))// TODO: can this happen?
#endif
false
| FrameworkRestrictionP.AtLeastP y' ->
// <> x is a subset of >= y
#if DEBUG
assert (not (fallBack false x y))// TODO: can this happen?
#endif
false
//fallBack()
// these are or 'common' forms, others are not allowed
| FrameworkRestrictionP.NotP(FrameworkRestrictionP.AtLeastP y' as notY) ->
notY.IsSubsetOf notX
| FrameworkRestrictionP.NotP(FrameworkRestrictionP.ExactlyP y' as notY) ->
notY.IsSubsetOf notX
// This one should never actually hit.
| FrameworkRestrictionP.NotP(y') -> fallBack true x y
| FrameworkRestrictionP.OrP (ys) ->
ys
|> Seq.exists (fun y' -> x.IsSubsetOf y')
| FrameworkRestrictionP.AndP (ys) ->
ys
|> Seq.forall (fun y' -> x.IsSubsetOf y')
// This one should never actually hit.
| FrameworkRestrictionP.NotP(x') -> fallBack true x y
| FrameworkRestrictionP.OrP (xs) ->
xs
|> Seq.forall (fun x' -> x'.IsSubsetOf y)
| FrameworkRestrictionP.AndP (xs) ->
xs
|> Seq.exists (fun x' -> x'.IsSubsetOf y)
isSubsetOfCalculation x y
// Bad ~ 10 mins
//|> Seq.forall (fun inner -> superset |> Seq.contains inner)
static member ExactlyFramework (tf: FrameworkIdentifier) =
ExactlyP (TargetProfile.SinglePlatform tf)
override x.Equals(y) =
match y with
| :? FrameworkRestrictionP as r ->
if System.Object.ReferenceEquals(x, r) then true
elif (x.ToString() = r.ToString()) then true
else r.RepresentedFrameworks = x.RepresentedFrameworks
| _ -> false
override x.GetHashCode() = x.RepresentedFrameworks.GetHashCode()
interface System.IComparable with
member x.CompareTo(y) =
match y with
| :? FrameworkRestrictionP as r ->
if System.Object.ReferenceEquals(x, r) then 0
elif (x.ToString() = r.ToString()) then 0
else compare x.RepresentedFrameworks r.RepresentedFrameworks
| _ -> failwith "wrong type"
type FrameworkRestrictionLiteralI =
| ExactlyL of TargetProfile
| AtLeastL of TargetProfile
member internal x.RawFormular =
match x with
| ExactlyL id -> FrameworkRestrictionP.ExactlyP id
| AtLeastL id -> FrameworkRestrictionP.AtLeastP id
type FrameworkRestrictionLiteral =
{ LiteraL : FrameworkRestrictionLiteralI; IsNegated : bool }
member internal x.RawFormular =
let raw = x.LiteraL.RawFormular
if x.IsNegated then FrameworkRestrictionP.NotP raw else raw
static member FromLiteral l =
{ LiteraL = l ; IsNegated = false }
static member FromNegatedLiteral l =
{ LiteraL = l ; IsNegated = true }
type FrameworkRestrictionAndList =
{ Literals : FrameworkRestrictionLiteral list }
member internal x.RawFormular =
FrameworkRestrictionP.AndP (x.Literals |> List.map (fun literal -> literal.RawFormular))
[<CustomEquality; CustomComparison>]
type FrameworkRestriction =
private { OrFormulas : FrameworkRestrictionAndList list
mutable IsSimple : bool
mutable PrivateRawFormula : FrameworkRestrictionP option ref
mutable PrivateRepresentedFrameworks : TargetProfile Set option ref }
static member FromOrList l = { OrFormulas = l; IsSimple = false; PrivateRepresentedFrameworks = ref None; PrivateRawFormula = ref None }
static member internal WithOrListInternal orList l = { l with OrFormulas = orList; PrivateRawFormula = ref None }
member internal x.RawFormular =
match !x.PrivateRawFormula with
| Some f -> f
| None ->
let raw = FrameworkRestrictionP.OrP (x.OrFormulas |> List.map (fun andList -> andList.RawFormular))
x.PrivateRawFormula := Some raw
raw
override x.ToString() =
x.RawFormular.ToString()
member x.IsSubsetOf (y:FrameworkRestriction) =
x.RawFormular.IsSubsetOf y.RawFormular
member x.RepresentedFrameworks =
match !x.PrivateRepresentedFrameworks with
| Some s -> s
| None ->
let set = x.RawFormular.RepresentedFrameworks
x.PrivateRepresentedFrameworks := Some set
set
member x.IsMatch tp =
x.RawFormular.IsMatch tp
member x.ToMSBuildCondition() =
let formulas =
[for fr in x.RepresentedFrameworks do
let fr = fr.ToString()
yield sprintf "('$(TargetFramework)' == '%s')" fr
if fr.Contains "." then
yield sprintf "('$(TargetFramework)' == '%s')" (fr.Replace(".",""))]
String.Join(" OR ",formulas)
override x.Equals(y) =
match y with
| :? FrameworkRestriction as r ->
// Cannot delegate because we cache RepresentedFrameworks -> optimization
//x.RawFormular.Equals(r.RawFormular)
if System.Object.ReferenceEquals(x, y) then true
elif (x.ToString() = y.ToString()) then true
else r.RepresentedFrameworks = x.RepresentedFrameworks
| _ -> false
override x.GetHashCode() = x.RepresentedFrameworks.GetHashCode()
interface System.IComparable with
member x.CompareTo(y) =
match y with
| :? FrameworkRestriction as r ->
// Cannot delegate because we cache RepresentedFrameworks -> optimization
//compare x.RawFormular r.RawFormular
if System.Object.ReferenceEquals(x, y) then 0
elif (x.ToString() = y.ToString()) then 0
else compare x.RepresentedFrameworks r.RepresentedFrameworks
| _ -> failwith "wrong type"
module FrameworkRestriction =
let EmptySet = FrameworkRestriction.FromOrList [] // false
let NoRestriction = FrameworkRestriction.FromOrList [ { Literals = [] } ] // true
let FromLiteral lit = FrameworkRestriction.FromOrList [ { Literals = [ lit ] } ]
let AtLeastPlatform pf = FromLiteral (FrameworkRestrictionLiteral.FromLiteral (AtLeastL pf))
let ExactlyPlatform pf = FromLiteral (FrameworkRestrictionLiteral.FromLiteral (ExactlyL pf))
let Exactly id = ExactlyPlatform (TargetProfile.SinglePlatform id)
let AtLeastPortable (name, fws) = AtLeastPlatform (TargetProfile.FindPortable false fws)
let AtLeast id = AtLeastPlatform (TargetProfile.SinglePlatform id)
let NotAtLeastPlatform pf = FromLiteral (FrameworkRestrictionLiteral.FromNegatedLiteral (AtLeastL pf))
let NotAtLeast id = NotAtLeastPlatform (TargetProfile.SinglePlatform id)
let private simplify' (fr:FrameworkRestriction) =
/// When we have a restriction like (>=net35 && <net45) || >=net45
/// then we can "optimize" / simplify to (>=net35 || >= net45)
/// because we don't need to "pseudo" restrict the set with the first restriction
/// when we add back later all the things we removed.
/// Generally: We can remove all negated literals in all clauses when a positive literal exists as a standalone Or clause
let rec removeNegatedLiteralsWhichOccurSinglePositive (fr:FrameworkRestriction) =
let positiveSingles =
fr.OrFormulas
|> List.choose (fun andFormular -> match andFormular.Literals with [ { IsNegated = false } as h ] -> Some h | _ -> None)
let workDone, reworked =
fr.OrFormulas
|> List.fold (fun (workDone, reworkedOrFormulas) andFormula ->
let reworkedAnd =
andFormula.Literals
|> List.filter (fun literal ->
positiveSingles
|> List.exists (fun p -> literal.IsNegated && literal.LiteraL = p.LiteraL)
|> not)
if reworkedAnd.Length < andFormula.Literals.Length then
true, { Literals = reworkedAnd } :: reworkedOrFormulas
else
workDone, andFormula :: reworkedOrFormulas
) (false, [])
if workDone then removeNegatedLiteralsWhichOccurSinglePositive (FrameworkRestriction.WithOrListInternal reworked fr)
else fr
/// (>= net40-full) && (< net46) && (>= net20) can be simplified to (< net46) && (>= net40-full) because (>= net40-full) is a subset of (>= net20)
// NOTE: This optimization is kind of dangerous as future frameworks might make it invalid
// However a lot of tests expect this simplification... We maybe want to remove it (or at least test) after we know the new framework restriction works.
let removeSubsetLiteralsInAndClause (fr:FrameworkRestriction) =
let simplifyAndClause (andClause:FrameworkRestrictionAndList) =
let literals = andClause.Literals
let newLiterals =
literals
|> List.filter (fun literal ->
// we filter out literals, for which another literal exists which is a subset
literals
|> Seq.filter (fun l -> l <> literal)
|> Seq.exists (fun otherLiteral ->
otherLiteral.RawFormular.IsSubsetOf literal.RawFormular)
|> not)
if newLiterals.Length <> literals.Length
then true, {Literals = newLiterals}
else false, andClause
//andClause
let wasChanged, newOrList =
fr.OrFormulas
|> List.fold (fun (oldWasChanged, newList) andList ->
let wasChanged, newAndList = simplifyAndClause andList
oldWasChanged || wasChanged, newAndList :: newList) (false, [])
if wasChanged then
FrameworkRestriction.WithOrListInternal newOrList fr
else fr
/// (>= net40-full) || (< net46) || (>= net20) can be simplified to (< net46) || (>= net20) because (>= net40-full) is a subset of (>= net20)
// NOTE: This optimization is kind of dangerous as future frameworks might make it invalid
// However a lot of tests expect this simplification... We maybe want to remove it (or at least test) after we know the new framework restriction works.
let removeSubsetLiteralsInOrClause (fr:FrameworkRestriction) =
let simpleOrLiterals =
fr.OrFormulas
|> List.choose (function { Literals = [h] } -> Some h | _ -> None)
let newOrList =
fr.OrFormulas
|> List.filter (function
| { Literals = [h] } ->
simpleOrLiterals
|> Seq.filter (fun l -> l <> h)
|> Seq.exists (fun otherLiteral ->
h.RawFormular.IsSubsetOf otherLiteral.RawFormular)
|> not
| _ -> true)
if newOrList.Length < fr.OrFormulas.Length then
FrameworkRestriction.WithOrListInternal newOrList fr
else fr
/// ((>= net20) && (>= net40)) || (>= net20) can be simplified to (>= net20) because any AND clause with (>= net20) can be removed.
let removeUneccessaryOrClauses (fr:FrameworkRestriction) =
let orClauses =
fr.OrFormulas
let isContained (andList:FrameworkRestrictionAndList) (item:FrameworkRestrictionAndList) =
if item.Literals.Length >= andList.Literals.Length then false
else
item.Literals
|> Seq.forall (fun lit -> andList.Literals |> Seq.contains lit)
let newOrList =
fr.OrFormulas
|> List.filter (fun orClause ->
orClauses |> Seq.exists (isContained orClause) |> not)
if newOrList.Length < fr.OrFormulas.Length then
FrameworkRestriction.WithOrListInternal newOrList fr
else fr
/// clauses with ((>= net20) && (< net20) && ...) can be removed because they contains a literal and its negation.
let removeUneccessaryAndClauses (fr:FrameworkRestriction) =
let newOrList =
fr.OrFormulas
|> List.filter (fun andList ->
let normalizeLiterals =
andList.Literals
|> List.map (function
| { LiteraL = FrameworkRestrictionLiteralI.ExactlyL l; IsNegated = n } ->
{ LiteraL = FrameworkRestrictionLiteralI.AtLeastL l; IsNegated = n }
| lit -> lit)
let foundLiteralAndNegation =
normalizeLiterals
|> Seq.exists (fun l ->
normalizeLiterals |> Seq.contains { l with IsNegated = not l.IsNegated})
not foundLiteralAndNegation)
if newOrList.Length < fr.OrFormulas.Length then
FrameworkRestriction.WithOrListInternal newOrList fr
else fr
/// When we optmized a clause away completely we can replace the hole formula with "NoRestriction"
/// This happens for example with ( <net45 || >=net45) and the removeNegatedLiteralsWhichOccurSinglePositive
/// optimization
let replaceWithNoRestrictionIfAnyLiteralListIsEmpty (fr:FrameworkRestriction) =
let containsEmptyAnd =
fr.OrFormulas
|> Seq.exists (fun andFormular -> andFormular.Literals |> Seq.isEmpty)
if containsEmptyAnd then NoRestriction else fr
/// Remove unsupported frameworks:
/// Unsupported frameworks are expected to never exist,
/// therefore `= unsupported1.0` and `>= unsupported1.0` are the empty set (isNegated = false)
/// while `<> unsupported1.0` and `<unsupported1.0` are just all frameworks (isNegated = true)
let removeUnsupportedFrameworks (fr:FrameworkRestriction) =
let newOrList, workDone =
let mutable workDone = false
fr.OrFormulas
|> List.choose (fun andFormula ->
let filteredList, removeAndClause =
let mutable removeAndClause = false
andFormula.Literals
|> List.filter (function
| { LiteraL = FrameworkRestrictionLiteralI.ExactlyL (TargetProfile.SinglePlatform (FrameworkIdentifier.Unsupported _)); IsNegated = false }
| { LiteraL = FrameworkRestrictionLiteralI.AtLeastL (TargetProfile.SinglePlatform (FrameworkIdentifier.Unsupported _)); IsNegated = false } ->
// `>= unsupported` or `= unsupported` -> remove the clause as && with empty set is the empty set
removeAndClause <- true // we could break here.
workDone <- true
false
| { LiteraL = FrameworkRestrictionLiteralI.ExactlyL (TargetProfile.SinglePlatform (FrameworkIdentifier.Unsupported _)); IsNegated = true }
| { LiteraL = FrameworkRestrictionLiteralI.AtLeastL (TargetProfile.SinglePlatform (FrameworkIdentifier.Unsupported _)); IsNegated = true } ->
// `< unsupported` or `<> unsupported` -> remove the literal as any set && with all frameworks is the given set
workDone <- true
false
| _ -> true), removeAndClause
if removeAndClause then None else Some { Literals = filteredList }), workDone
if workDone then FrameworkRestriction.WithOrListInternal newOrList fr else fr
let sortClauses (fr:FrameworkRestriction) =
fr.OrFormulas
|> List.map (fun andFormula -> { Literals = andFormula.Literals |> List.distinct |> List.sort })
|> List.distinct
|> List.sort
|> fun newOrList ->
if newOrList <> fr.OrFormulas then FrameworkRestriction.WithOrListInternal newOrList fr
else fr
let optimize fr =
fr
|> removeUnsupportedFrameworks
|> removeNegatedLiteralsWhichOccurSinglePositive
|> removeSubsetLiteralsInAndClause
|> removeSubsetLiteralsInOrClause
|> removeUneccessaryAndClauses
|> removeUneccessaryOrClauses
|> replaceWithNoRestrictionIfAnyLiteralListIsEmpty
|> sortClauses
let mutable hasChanged = true
let mutable newFormula = fr
while hasChanged do
let old = newFormula
newFormula <- optimize newFormula
if System.Object.ReferenceEquals(old, newFormula) then hasChanged <- false
newFormula.IsSimple <- true
newFormula
// Equals and Hashcode means semantic equality, for memoize we need "exactly the same"
// (ie not only a different formula describing the same set, but the same exact formula)
let private simplify'', cacheSimple = memoizeByExt (fun (fr:FrameworkRestriction) -> fr.ToString()) simplify'
let internal simplify (fr:FrameworkRestriction) =
if fr.IsSimple then fr
else
let simpleFormula = simplify'' fr
// Add simple formula to cache just in case we construct the same in the future
cacheSimple (simpleFormula.ToString(), simpleFormula)
simpleFormula
let rec private And2 (left : FrameworkRestriction) (right : FrameworkRestriction) =
match left.OrFormulas, right.OrFormulas with
// false -> stay false
| [], _ -> true, left
| _, [] -> true, right
// true -> use the other
| _, [ { Literals = [] }] -> true, left
| [{ Literals = [] }], _ -> true, right
| otherFormulas, [h]
| [h], otherFormulas ->
false,
otherFormulas
|> List.map (fun andFormula -> { Literals = andFormula.Literals @ h.Literals } )
|> FrameworkRestriction.FromOrList
| h :: t, _ ->
false,
((And2 (FrameworkRestriction.FromOrList [h]) right) |> snd).OrFormulas @ ((And2 (FrameworkRestriction.FromOrList t) right) |> snd).OrFormulas
|> FrameworkRestriction.FromOrList
let inline private AndList (rst:FrameworkRestriction list) =
List.fold
(fun (isSimplified, current) next -> let wasSimple, result = And2 current next in wasSimple && isSimplified, result)
(true, NoRestriction)
rst
let And (rst:FrameworkRestriction list) =
let isSimple, result = AndList rst
if isSimple then result
else simplify result
let internal AndAlreadySimplified (rst:FrameworkRestriction list) =
let _, result = AndList rst
result
let private Or2 (left : FrameworkRestriction) (right : FrameworkRestriction) =
match left.OrFormulas, right.OrFormulas with
// false -> use the other
| [], _ -> true, right
| _, [] -> true, left
// true -> become true
| _, [ { Literals = [] }] -> true, right
| [{ Literals = [] }], _ -> true, left
| leftFormumas, rightFormulas ->
false,
leftFormumas @ rightFormulas
|> FrameworkRestriction.FromOrList
let inline private OrList (rst:FrameworkRestriction list) =
List.fold
(fun (isSimplified, current) next -> let wasSimple, result = Or2 current next in wasSimple && isSimplified, result)
(true, EmptySet)
rst
let Or (rst:FrameworkRestriction list) =
let isSimple, result = OrList rst
if isSimple then result
else simplify result
let internal OrAlreadySimplified (rst:FrameworkRestriction list) =
let _, result = OrList rst
result
//[<Obsolete ("Method is provided for completeness sake. But I don't think its needed")>]
//let Not (rst:FrameworkRestriction) =
// Unchecked.defaultof<_>
let Between (x, y) =
And [ AtLeast x; NotAtLeast y ]
//let isSimple, result = And2 (AtLeast x) (NotAtLeast y)
//if isSimple then result else simplify result
let combineRestrictionsWithOr (x : FrameworkRestriction) y =
Or [ x; y ]
//let isSimple, result = Or2 x y
//if isSimple then result else simplify result
let (|HasNoRestriction|_|) (x:FrameworkRestriction) =
// fast check.
if x.OrFormulas.Length = 1 && x.OrFormulas.Head.Literals.Length = 0
then Some () else None
//if x = NoRestriction then Some () else None
let combineRestrictionsWithAnd (x : FrameworkRestriction) y =
And [ x; y ]
//let isSimple, result = And2 x y
//if isSimple then result else simplify result
type FrameworkRestrictions =
| ExplicitRestriction of FrameworkRestriction
| AutoDetectFramework
override x.ToString() =
match x with
| ExplicitRestriction r -> r.ToString()
| AutoDetectFramework -> "AutoDetect"
member x.GetExplicitRestriction () =
match x with
| ExplicitRestriction list -> list
| AutoDetectFramework -> failwith "The framework restriction could not be determined."
member x.IsSupersetOf (fw:FrameworkRestriction) =
fw.IsSubsetOf(x.GetExplicitRestriction ())
let getExplicitRestriction (frameworkRestrictions:FrameworkRestrictions) =
frameworkRestrictions.GetExplicitRestriction()
type RestrictionParseProblem =
| ParseFramework of string
| ParseSecondOperator of string
| UnsupportedPortable of string
| SyntaxError of string
member x.AsMessage =
match x with
| ParseFramework framework -> sprintf "Could not parse framework '%s'. Try to update or install again or report a paket bug." framework
| ParseSecondOperator item -> sprintf "Could not parse second framework of between operator '%s'. Try to update or install again or report a paket bug." item
| UnsupportedPortable item -> sprintf "Profile '%s' is not a supported portable profile" item
| SyntaxError msg -> sprintf "Syntax error: %s" msg
member x.Framework =
match x with
| RestrictionParseProblem.UnsupportedPortable fm
| RestrictionParseProblem.ParseSecondOperator fm
| RestrictionParseProblem.ParseFramework fm -> Some fm
| SyntaxError _ -> None
member x.IsCritical =
match x with
| RestrictionParseProblem.UnsupportedPortable _ -> false
| RestrictionParseProblem.ParseSecondOperator _
| RestrictionParseProblem.ParseFramework _
| SyntaxError _ -> true
let parseRestrictionsLegacy failImmediatly (text:string) =
// older lockfiles to the new "restriction" semantics
let problems = ResizeArray<_>()
let handleError (p:RestrictionParseProblem) =
if failImmediatly && p.IsCritical then
failwith p.AsMessage
else
problems.Add p
let extractProfile framework =
PlatformMatching.extractPlatforms false framework |> Option.bind (fun pp ->
let prof = pp.ToTargetProfile false
match prof with
| Some v when v.IsUnsupportedPortable ->
handleError (RestrictionParseProblem.UnsupportedPortable framework)
| _ -> ()
prof)
let frameworkToken (str : string) =
let withoutLeading = str.TrimStart()
match withoutLeading.IndexOfAny([|' ';'=';'<';'>'|]) with
| -1 -> withoutLeading, ""
| i ->
let startIndex = str.Length - withoutLeading.Length
let remaining = str.Substring(startIndex + i).Trim()
withoutLeading.Substring (0, i), remaining
let tryParseFramework handlers (token : string) =
match handlers |> Seq.choose (fun f -> f token) |> Seq.tryHead with
| Some fw -> Some fw
| None ->
handleError (RestrictionParseProblem.ParseFramework token)
None
let parseExpr (str : string) =
let restriction, remaining =
match str.Trim() with
| x when x.StartsWith ">=" ->
let fw1, remaining = frameworkToken (x.Substring 2)
let fw2, remaining =
let p str =
let token, remaining = frameworkToken str
Some token, remaining
match remaining with
| x when x.StartsWith "<=" -> p (x.Substring 2)
| x when x.StartsWith "<" -> p (x.Substring 1)
| x -> None, x
let restriction =
match fw2 with
| None ->
let handlers =
[ FrameworkDetection.Extract >> Option.map FrameworkRestriction.AtLeast
extractProfile >> Option.map FrameworkRestriction.AtLeastPlatform ]
tryParseFramework handlers fw1
| Some fw2 ->
let tryParse = tryParseFramework [FrameworkDetection.Extract]
match tryParse fw1, tryParse fw2 with
| Some x, Some y -> Some (FrameworkRestriction.Between (x, y))
| _ -> None
restriction, remaining
| x when x.StartsWith "="->
let fw, remaining = frameworkToken (x.Substring 1)
let handlers =
[ FrameworkDetection.Extract >> Option.map FrameworkRestriction.Exactly ]
tryParseFramework handlers fw, remaining
| x when x.StartsWith "<="->
traceWarn "<= in framework restriction `%s` found. Interpretation as = ."
let fw, remaining = frameworkToken (x.Substring 2)
let handlers =
[ FrameworkDetection.Extract >> Option.map FrameworkRestriction.Exactly ]
tryParseFramework handlers fw, remaining
| x ->
let fw, remaining = frameworkToken x
let handlers =
[ FrameworkDetection.Extract >> Option.map FrameworkRestriction.Exactly
extractProfile >> Option.map FrameworkRestriction.AtLeastPlatform ]
tryParseFramework handlers fw, remaining
match remaining with
| "" -> restriction
| x ->
handleError (SyntaxError (sprintf "Expected end of input, got '%s'." x))
None
text.Trim().Split(',')
|> Seq.choose parseExpr
|> Seq.fold (fun state item -> FrameworkRestriction.combineRestrictionsWithOr state item) FrameworkRestriction.EmptySet,
problems.ToArray()
let private parseRestrictionsRaw skipSimplify (text:string) =
let problems = ResizeArray<_>()
let handleError (p:RestrictionParseProblem) =
problems.Add p
let rec parseOperator (text:string) =
let h = text.Trim()
let mutable found = false
let isGreatherEquals = h.StartsWith ">="
found <- isGreatherEquals
let isEqualsEquals = not found && h.StartsWith "=="
found <- found || isEqualsEquals
let isSmaller = not found && h.StartsWith "<"
found <- found || isSmaller
let isAndAnd = not found && h.StartsWith "&&"
found <- found || isAndAnd
let isOrOr = not found && h.StartsWith "||"
found <- found || isOrOr
let isNot = not found && h.StartsWith "NOT"
found <- found || isNot
let isTrue = not found && h.StartsWith "true"
found <- found || isTrue
let isFalse = not found && h.StartsWith "false"
found <- found || isFalse
match h with
| t when String.IsNullOrEmpty t -> failwithf "trying to parse an operator but got no content"
| h when isGreatherEquals || isEqualsEquals || isSmaller ->
// parse >=
let rest = h.Substring 2
let restTrimmed = rest.TrimStart()
let idx = restTrimmed.IndexOf(' ')
let endOperator =
if idx < 0 then
if restTrimmed.Length = 0 then failwithf "No parameter after >= or < in '%s'" text
else restTrimmed.Length
else idx
let rawOperator = restTrimmed.Substring(0, endOperator)
let operator = rawOperator.TrimEnd([|')'|])
let extractedPlatform = PlatformMatching.extractPlatforms false operator
let platFormPath =
extractedPlatform
|> Option.bind (fun (pp:PlatformMatching.ParsedPlatformPath) ->
let prof = pp.ToTargetProfile false
if prof.IsSome && prof.Value.IsUnsupportedPortable then
handleError (RestrictionParseProblem.UnsupportedPortable operator)
prof)
match platFormPath with
| None ->
match extractedPlatform with
| Some pp when pp.Platforms = [] ->
let operatorIndex = text.IndexOf operator
FrameworkRestriction.NoRestriction, text.Substring(operatorIndex + operator.Length)
| _ ->
failwithf "invalid parameter '%s' after >= or < in '%s'" operator text
| Some plat ->
let f =
if isSmaller then FrameworkRestriction.NotAtLeastPlatform
elif isEqualsEquals then FrameworkRestriction.ExactlyPlatform
else FrameworkRestriction.AtLeastPlatform
let operatorIndex = text.IndexOf operator
f plat, text.Substring(operatorIndex + operator.Length)
| h when isAndAnd || isOrOr ->
let next = h.Substring 2
let rec parseOperand cur (next:string) =
let trimmed = next.TrimStart()
if trimmed.StartsWith "(" then
let operand, remaining = parseOperator (trimmed.Substring 1)
let remaining = remaining.TrimStart()
if remaining.StartsWith ")" |> not then failwithf "expected ')' after operand, '%s'" text
parseOperand (operand::cur) (remaining.Substring 1)
else
cur, next
let operands, next = parseOperand [] next
if operands.Length = 0 then failwithf "Operand '%s' without argument is invalid in '%s'" (h.Substring (0, 2)) text
let f =
match isAndAnd, skipSimplify with
| true, true -> FrameworkRestriction.AndAlreadySimplified
| true, false -> FrameworkRestriction.And
| false, true -> FrameworkRestriction.OrAlreadySimplified
| false, false -> FrameworkRestriction.Or
operands |> List.rev |> f, next
| h when isNot ->
let next = h.Substring 2
if next.TrimStart().StartsWith "(" then
let operand, remaining = parseOperator (next.Substring 1)
let remaining = remaining.TrimStart()
if remaining.StartsWith ")" |> not then failwithf "expected ')' after operand, '%s'" text
let next = remaining.Substring 1
let negated =
match operand with
| { OrFormulas = [ {Literals = [ lit] } ] } ->
[ {Literals = [ { lit with IsNegated = not lit.IsNegated } ] } ]
|> FrameworkRestriction.FromOrList
| _ -> failwithf "a general NOT is not implemented (and shouldn't be emitted for now)"
negated, next
else
failwithf "Expected operand after NOT, '%s'" text
| h when isTrue ->
let rest = (h.Substring 4).TrimStart()
FrameworkRestriction.NoRestriction, rest
| h when isFalse ->
let rest = (h.Substring 5).TrimStart()
FrameworkRestriction.EmptySet, rest
| _ ->
failwithf "Expected operator, but got '%s'" text
let result, next = parseOperator text
if String.IsNullOrEmpty next |> not then
failwithf "Successfully parsed '%O' but got additional text '%s'" result next
result, problems.ToArray()
let parseRestrictions = memoize (parseRestrictionsRaw false)
// skips simplify
let internal parseRestrictionsSimplified = parseRestrictionsRaw true
let filterRestrictions (list1:FrameworkRestrictions) (list2:FrameworkRestrictions) =
match list1,list2 with
| ExplicitRestriction FrameworkRestriction.HasNoRestriction, AutoDetectFramework -> AutoDetectFramework
| AutoDetectFramework, ExplicitRestriction FrameworkRestriction.HasNoRestriction -> AutoDetectFramework
| AutoDetectFramework, AutoDetectFramework -> AutoDetectFramework
| ExplicitRestriction fr1 , ExplicitRestriction fr2 -> ExplicitRestriction (FrameworkRestriction.combineRestrictionsWithAnd fr1 fr2)
| _ -> failwithf "The framework restriction %O and %O could not be combined." list1 list2
/// Get if a target should be considered with the specified restrictions
let isTargetMatchingRestrictions (restriction:FrameworkRestriction, target)=
restriction.IsMatch target
/// Get all targets that should be considered with the specified restrictions
let applyRestrictionsToTargets (restriction:FrameworkRestriction) (targets: TargetProfile Set) =
Set.intersect targets restriction.RepresentedFrameworks
type ContentCopySettings =
| Omit
| Overwrite
| OmitIfExisting
type CopyToOutputDirectorySettings =
| Never
| Always
| PreserveNewest
[<RequireQualifiedAccess>]
type BindingRedirectsSettings =
| On
| Off
| Force
type InstallSettings =
{ ImportTargets : bool option
FrameworkRestrictions: FrameworkRestrictions
OmitContent : ContentCopySettings option
IncludeVersionInPath: bool option
LicenseDownload: bool option
ReferenceCondition : string option
CreateBindingRedirects : BindingRedirectsSettings option
EmbedInteropTypes : bool option
CopyLocal : bool option
SpecificVersion : bool option
StorageConfig : PackagesFolderGroupConfig option
Excludes : string list
Aliases : Map<string,string>
CopyContentToOutputDirectory : CopyToOutputDirectorySettings option
GenerateLoadScripts : bool option
Simplify : bool option }
static member Default =
{ EmbedInteropTypes = None
CopyLocal = None
SpecificVersion = None
StorageConfig = None
ImportTargets = None
FrameworkRestrictions = ExplicitRestriction FrameworkRestriction.NoRestriction
IncludeVersionInPath = None
ReferenceCondition = None
LicenseDownload = None
CreateBindingRedirects = None
Excludes = []
Aliases = Map.empty
CopyContentToOutputDirectory = None
OmitContent = None
GenerateLoadScripts = None
Simplify = None }
member this.ToString(groupSettings:InstallSettings,asLines) =
let options =
[ match this.CopyLocal with
| Some x when groupSettings.CopyLocal <> this.CopyLocal -> yield "copy_local: " + x.ToString().ToLower()
| _ -> ()
match this.SpecificVersion with
| Some x when groupSettings.SpecificVersion <> this.SpecificVersion -> yield "specific_version: " + x.ToString().ToLower()
| _ -> ()
match this.StorageConfig with
| Some (PackagesFolderGroupConfig.NoPackagesFolder) when groupSettings.StorageConfig <> this.StorageConfig -> yield "storage: none"
| Some (PackagesFolderGroupConfig.SymbolicLink) when groupSettings.StorageConfig <> this.StorageConfig -> yield "storage: symlink"
| Some (PackagesFolderGroupConfig.GivenPackagesFolder s) when groupSettings.StorageConfig <> this.StorageConfig -> failwithf "Not implemented yet."
| Some (PackagesFolderGroupConfig.DefaultPackagesFolder) when groupSettings.StorageConfig <> this.StorageConfig -> yield "storage: packages"
| _ -> ()
match this.CopyContentToOutputDirectory with
| Some CopyToOutputDirectorySettings.Never when groupSettings.CopyContentToOutputDirectory <> this.CopyContentToOutputDirectory -> yield "copy_content_to_output_dir: never"
| Some CopyToOutputDirectorySettings.Always when groupSettings.CopyContentToOutputDirectory <> this.CopyContentToOutputDirectory -> yield "copy_content_to_output_dir: always"
| Some CopyToOutputDirectorySettings.PreserveNewest when groupSettings.CopyContentToOutputDirectory <> this.CopyContentToOutputDirectory -> yield "copy_content_to_output_dir: preserve_newest"
| _ -> ()
match this.ImportTargets with
| Some x when groupSettings.ImportTargets <> this.ImportTargets -> yield "import_targets: " + x.ToString().ToLower()
| _ -> ()
match this.OmitContent with
| Some ContentCopySettings.Omit when groupSettings.OmitContent <> this.OmitContent -> yield "content: none"
| Some ContentCopySettings.Overwrite when groupSettings.OmitContent <> this.OmitContent -> yield "content: true"
| Some ContentCopySettings.OmitIfExisting when groupSettings.OmitContent <> this.OmitContent -> yield "content: once"
| _ -> ()
match this.IncludeVersionInPath with
| Some x when groupSettings.IncludeVersionInPath <> this.IncludeVersionInPath -> yield "version_in_path: " + x.ToString().ToLower()
| _ -> ()
match this.LicenseDownload with
| Some x when groupSettings.LicenseDownload <> this.LicenseDownload -> yield "license_download: " + x.ToString().ToLower()
| _ -> ()
match this.ReferenceCondition with
| Some x when groupSettings.ReferenceCondition <> this.ReferenceCondition -> yield "condition: " + x.ToUpper()
| _ -> ()
match this.CreateBindingRedirects with
| Some BindingRedirectsSettings.On when groupSettings.CreateBindingRedirects <> this.CreateBindingRedirects -> yield "redirects: on"
| Some BindingRedirectsSettings.Off when groupSettings.CreateBindingRedirects <> this.CreateBindingRedirects -> yield "redirects: off"
| Some BindingRedirectsSettings.Force when groupSettings.CreateBindingRedirects <> this.CreateBindingRedirects -> yield "redirects: force"
| _ -> ()
match this.FrameworkRestrictions with
| ExplicitRestriction FrameworkRestriction.HasNoRestriction when groupSettings.FrameworkRestrictions <> this.FrameworkRestrictions -> ()
| AutoDetectFramework -> ()
| ExplicitRestriction fr when groupSettings.FrameworkRestrictions <> this.FrameworkRestrictions -> yield "restriction: " + (fr.ToString())
| _ -> ()
match this.GenerateLoadScripts with
| Some true when groupSettings.GenerateLoadScripts <> this.GenerateLoadScripts -> yield "generate_load_scripts: true"
| Some false when groupSettings.GenerateLoadScripts <> this.GenerateLoadScripts -> yield "generate_load_scripts: false"
| _ -> ()
match this.Simplify with