-
Notifications
You must be signed in to change notification settings - Fork 814
/
Copy pathCheckComputationExpressions.fs
2926 lines (2470 loc) · 126 KB
/
CheckComputationExpressions.fs
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
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
/// The typechecker. Left-to-right constrained type checking
/// with generalization at appropriate points.
module internal FSharp.Compiler.CheckComputationExpressions
open FSharp.Compiler.TcGlobals
open Internal.Utilities.Library
open FSharp.Compiler.AccessibilityLogic
open FSharp.Compiler.AttributeChecking
open FSharp.Compiler.CheckExpressionsOps
open FSharp.Compiler.CheckExpressions
open FSharp.Compiler.CheckBasics
open FSharp.Compiler.ConstraintSolver
open FSharp.Compiler.DiagnosticsLogger
open FSharp.Compiler.Features
open FSharp.Compiler.Infos
open FSharp.Compiler.InfoReader
open FSharp.Compiler.NameResolution
open FSharp.Compiler.Syntax.PrettyNaming
open FSharp.Compiler.Syntax
open FSharp.Compiler.SyntaxTrivia
open FSharp.Compiler.SyntaxTreeOps
open FSharp.Compiler.Text
open FSharp.Compiler.Text.Range
open FSharp.Compiler.TypedTree
open FSharp.Compiler.TypedTreeOps
open System.Collections.Generic
type cenv = TcFileState
/// Used to flag if this is the first or a subsequent translation pass through a computation expression
[<RequireQualifiedAccess; Struct; NoComparison>]
type CompExprTranslationPass =
| Initial
| Subsequent
/// Used to flag if computation expression custom operations are allowed in a given context
[<RequireQualifiedAccess; Struct; NoComparison; NoEquality>]
type CustomOperationsMode =
| Allowed
| Denied
[<NoComparison; NoEquality>]
type ComputationExpressionContext<'a> =
{
cenv: TcFileState
env: TcEnv
tpenv: UnscopedTyparEnv
customOperationMethodsIndexedByKeyword:
IDictionary<string, list<string * bool * bool * bool * bool * bool * bool * option<string> * MethInfo>>
customOperationMethodsIndexedByMethodName:
IDictionary<string, list<string * bool * bool * bool * bool * bool * bool * option<string> * MethInfo>>
sourceMethInfo: 'a list
builderValName: string
ad: AccessorDomain
builderTy: TType
isQuery: bool
enableImplicitYield: bool
origComp: SynExpr
mWhole: range
emptyVarSpace: LazyWithContext<list<Val> * TcEnv, range>
}
let inline TryFindIntrinsicOrExtensionMethInfo collectionSettings (cenv: cenv) (env: TcEnv) m ad nm ty =
AllMethInfosOfTypeInScope collectionSettings cenv.infoReader env.NameEnv (Some nm) ad IgnoreOverrides m ty
/// Ignores an attribute
let inline IgnoreAttribute _ = None
let inline arbPat (m: range) =
mkSynPatVar None (mkSynId (m.MakeSynthetic()) "_missingVar")
let inline arbKeySelectors m =
mkSynBifix m "=" (arbExpr ("_keySelectors", m)) (arbExpr ("_keySelector2", m))
// Flag that a debug point should get emitted prior to both the evaluation of 'rhsExpr' and the call to Using
let inline addBindDebugPoint spBind e =
match spBind with
| DebugPointAtBinding.Yes m -> SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes m, false, e)
| _ -> e
let inline mkSynDelay2 (e: SynExpr) = mkSynDelay (e.Range.MakeSynthetic()) e
/// Make a builder.Method(...) call
let mkSynCall nm (m: range) args builderValName =
let m = m.MakeSynthetic() // Mark as synthetic so the language service won't pick it up.
let args =
match args with
| [] -> SynExpr.Const(SynConst.Unit, m)
| [ arg ] -> SynExpr.Paren(SynExpr.Paren(arg, range0, None, m), range0, None, m)
| args -> SynExpr.Paren(SynExpr.Tuple(false, args, [], m), range0, None, m)
let builderVal = mkSynIdGet m builderValName
mkSynApp1 (SynExpr.DotGet(builderVal, range0, SynLongIdent([ mkSynId m nm ], [], [ None ]), m)) args m
// Optionally wrap sources of "let!", "yield!", "use!" in "query.Source"
let mkSourceExpr callExpr sourceMethInfo builderValName =
match sourceMethInfo with
| [] -> callExpr
| _ -> mkSynCall "Source" callExpr.Range [ callExpr ] builderValName
let mkSourceExprConditional isFromSource callExpr sourceMethInfo builderValName =
if isFromSource then
mkSourceExpr callExpr sourceMethInfo builderValName
else
callExpr
let inline mkSynLambda p e m =
SynExpr.Lambda(false, false, p, e, None, m, SynExprLambdaTrivia.Zero)
let mkExprForVarSpace m (patvs: Val list) =
match patvs with
| [] -> SynExpr.Const(SynConst.Unit, m)
| [ v ] -> SynExpr.Ident v.Id
| vs -> SynExpr.Tuple(false, (vs |> List.map (fun v -> SynExpr.Ident(v.Id))), [], m)
let mkSimplePatForVarSpace m (patvs: Val list) =
let spats =
match patvs with
| [] -> []
| [ v ] -> [ mkSynSimplePatVar false v.Id ]
| vs -> vs |> List.map (fun v -> mkSynSimplePatVar false v.Id)
SynSimplePats.SimplePats(spats, [], m)
let mkPatForVarSpace m (patvs: Val list) =
match patvs with
| [] -> SynPat.Const(SynConst.Unit, m)
| [ v ] -> mkSynPatVar None v.Id
| vs -> SynPat.Tuple(false, (vs |> List.map (fun x -> mkSynPatVar None x.Id)), [], m)
let hasMethInfo nm cenv env mBuilderVal ad builderTy =
match TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBuilderVal ad nm builderTy with
| [] -> false
| _ -> true
let getCustomOperationMethods (cenv: TcFileState) (env: TcEnv) ad mBuilderVal builderTy =
let allMethInfos =
AllMethInfosOfTypeInScope
ResultCollectionSettings.AllResults
cenv.infoReader
env.NameEnv
None
ad
IgnoreOverrides
mBuilderVal
builderTy
[
for methInfo in allMethInfos do
if IsMethInfoAccessible cenv.amap mBuilderVal ad methInfo then
let nameSearch =
TryBindMethInfoAttribute
cenv.g
mBuilderVal
cenv.g.attrib_CustomOperationAttribute
methInfo
IgnoreAttribute // We do not respect this attribute for IL methods
(fun attr ->
// NOTE: right now, we support of custom operations with spaces in them ([<CustomOperation("foo bar")>])
// In the parameterless CustomOperationAttribute - we use the method name, and also allow it to be ````-quoted (member _.``foo bar`` _ = ...)
match attr with
// Empty string and parameterless constructor - we use the method name
| Attrib(unnamedArgs = [ AttribStringArg "" ]) // Empty string as parameter
| Attrib(unnamedArgs = []) -> // No parameters, same as empty string for compat reasons.
Some methInfo.LogicalName
// Use the specified name
| Attrib(unnamedArgs = [ AttribStringArg msg ]) -> Some msg
| _ -> None)
IgnoreAttribute // We do not respect this attribute for provided methods
match nameSearch with
| None -> ()
| Some nm ->
let joinConditionWord =
TryBindMethInfoAttribute
cenv.g
mBuilderVal
cenv.g.attrib_CustomOperationAttribute
methInfo
IgnoreAttribute // We do not respect this attribute for IL methods
(function
| Attrib(propVal = ExtractAttribNamedArg "JoinConditionWord" (AttribStringArg s)) -> Some s
| _ -> None)
IgnoreAttribute // We do not respect this attribute for provided methods
let flagSearch (propName: string) =
TryBindMethInfoAttribute
cenv.g
mBuilderVal
cenv.g.attrib_CustomOperationAttribute
methInfo
IgnoreAttribute // We do not respect this attribute for IL methods
(function
| Attrib(propVal = ExtractAttribNamedArg propName (AttribBoolArg b)) -> Some b
| _ -> None)
IgnoreAttribute // We do not respect this attribute for provided methods
let maintainsVarSpaceUsingBind =
defaultArg (flagSearch "MaintainsVariableSpaceUsingBind") false
let maintainsVarSpace = defaultArg (flagSearch "MaintainsVariableSpace") false
let allowInto = defaultArg (flagSearch "AllowIntoPattern") false
let isLikeZip = defaultArg (flagSearch "IsLikeZip") false
let isLikeJoin = defaultArg (flagSearch "IsLikeJoin") false
let isLikeGroupJoin = defaultArg (flagSearch "IsLikeGroupJoin") false
nm,
maintainsVarSpaceUsingBind,
maintainsVarSpace,
allowInto,
isLikeZip,
isLikeJoin,
isLikeGroupJoin,
joinConditionWord,
methInfo
]
/// Decide if the identifier represents a use of a custom query operator
let tryGetDataForCustomOperation (nm: Ident) ceenv =
let isOpDataCountAllowed opDatas =
match opDatas with
| [ _ ] -> true
| _ :: _ -> ceenv.cenv.g.langVersion.SupportsFeature LanguageFeature.OverloadsForCustomOperations
| _ -> false
match ceenv.customOperationMethodsIndexedByKeyword.TryGetValue nm.idText with
| true, opDatas when isOpDataCountAllowed opDatas ->
for opData in opDatas do
let (opName,
maintainsVarSpaceUsingBind,
maintainsVarSpace,
_allowInto,
isLikeZip,
isLikeJoin,
isLikeGroupJoin,
_joinConditionWord,
methInfo) =
opData
if
(maintainsVarSpaceUsingBind && maintainsVarSpace)
|| (isLikeZip && isLikeJoin)
|| (isLikeZip && isLikeGroupJoin)
|| (isLikeJoin && isLikeGroupJoin)
then
errorR (Error(FSComp.SR.tcCustomOperationInvalid opName, nm.idRange))
if not (ceenv.cenv.g.langVersion.SupportsFeature LanguageFeature.OverloadsForCustomOperations) then
match ceenv.customOperationMethodsIndexedByMethodName.TryGetValue methInfo.LogicalName with
| true, [ _ ] -> ()
| _ -> errorR (Error(FSComp.SR.tcCustomOperationMayNotBeOverloaded nm.idText, nm.idRange))
Some opDatas
| true, opData :: _ ->
errorR (Error(FSComp.SR.tcCustomOperationMayNotBeOverloaded nm.idText, nm.idRange))
Some [ opData ]
| _ -> None
let isCustomOperation ceenv nm =
tryGetDataForCustomOperation nm ceenv |> Option.isSome
let customOperationCheckValidity m f opDatas =
let vs = List.map f opDatas
let v0 = vs[0]
let (opName,
_maintainsVarSpaceUsingBind,
_maintainsVarSpace,
_allowInto,
_isLikeZip,
_isLikeJoin,
_isLikeGroupJoin,
_joinConditionWord,
_methInfo) =
opDatas[0]
if not (List.allEqual vs) then
errorR (Error(FSComp.SR.tcCustomOperationInvalid opName, m))
v0
// Check for the MaintainsVariableSpace on custom operation
let customOperationMaintainsVarSpace ceenv (nm: Ident) =
match tryGetDataForCustomOperation nm ceenv with
| None -> false
| Some opDatas ->
opDatas
|> customOperationCheckValidity
nm.idRange
(fun
(_nm,
_maintainsVarSpaceUsingBind,
maintainsVarSpace,
_allowInto,
_isLikeZip,
_isLikeJoin,
_isLikeGroupJoin,
_joinConditionWord,
_methInfo) -> maintainsVarSpace)
let customOperationMaintainsVarSpaceUsingBind ceenv (nm: Ident) =
match tryGetDataForCustomOperation nm ceenv with
| None -> false
| Some opDatas ->
opDatas
|> customOperationCheckValidity
nm.idRange
(fun
(_nm,
maintainsVarSpaceUsingBind,
_maintainsVarSpace,
_allowInto,
_isLikeZip,
_isLikeJoin,
_isLikeGroupJoin,
_joinConditionWord,
_methInfo) -> maintainsVarSpaceUsingBind)
let customOperationIsLikeZip ceenv (nm: Ident) =
match tryGetDataForCustomOperation nm ceenv with
| None -> false
| Some opDatas ->
opDatas
|> customOperationCheckValidity
nm.idRange
(fun
(_nm,
_maintainsVarSpaceUsingBind,
_maintainsVarSpace,
_allowInto,
isLikeZip,
_isLikeJoin,
_isLikeGroupJoin,
_joinConditionWord,
_methInfo) -> isLikeZip)
let customOperationIsLikeJoin ceenv (nm: Ident) =
match tryGetDataForCustomOperation nm ceenv with
| None -> false
| Some opDatas ->
opDatas
|> customOperationCheckValidity
nm.idRange
(fun
(_nm,
_maintainsVarSpaceUsingBind,
_maintainsVarSpace,
_allowInto,
_isLikeZip,
isLikeJoin,
_isLikeGroupJoin,
_joinConditionWord,
_methInfo) -> isLikeJoin)
let customOperationIsLikeGroupJoin ceenv (nm: Ident) =
match tryGetDataForCustomOperation nm ceenv with
| None -> false
| Some opDatas ->
opDatas
|> customOperationCheckValidity
nm.idRange
(fun
(_nm,
_maintainsVarSpaceUsingBind,
_maintainsVarSpace,
_allowInto,
_isLikeZip,
_isLikeJoin,
isLikeGroupJoin,
_joinConditionWord,
_methInfo) -> isLikeGroupJoin)
let customOperationJoinConditionWord ceenv (nm: Ident) =
match tryGetDataForCustomOperation nm ceenv with
| Some opDatas ->
opDatas
|> customOperationCheckValidity
nm.idRange
(fun
(_nm,
_maintainsVarSpaceUsingBind,
_maintainsVarSpace,
_allowInto,
_isLikeZip,
_isLikeJoin,
_isLikeGroupJoin,
joinConditionWord,
_methInfo) -> joinConditionWord)
|> function
| None -> "on"
| Some v -> v
| _ -> "on"
let customOperationAllowsInto ceenv (nm: Ident) =
match tryGetDataForCustomOperation nm ceenv with
| None -> false
| Some opDatas ->
opDatas
|> customOperationCheckValidity
nm.idRange
(fun
(_nm,
_maintainsVarSpaceUsingBind,
_maintainsVarSpace,
allowInto,
_isLikeZip,
_isLikeJoin,
_isLikeGroupJoin,
_joinConditionWord,
_methInfo) -> allowInto)
let customOpUsageText ceenv nm =
match tryGetDataForCustomOperation nm ceenv with
| Some((_nm,
_maintainsVarSpaceUsingBind,
_maintainsVarSpace,
_allowInto,
isLikeZip,
isLikeJoin,
isLikeGroupJoin,
_joinConditionWord,
_methInfo) :: _) ->
if isLikeGroupJoin then
Some(
FSComp.SR.customOperationTextLikeGroupJoin (
nm.idText,
customOperationJoinConditionWord ceenv nm,
customOperationJoinConditionWord ceenv nm
)
)
elif isLikeJoin then
Some(
FSComp.SR.customOperationTextLikeJoin (
nm.idText,
customOperationJoinConditionWord ceenv nm,
customOperationJoinConditionWord ceenv nm
)
)
elif isLikeZip then
Some(FSComp.SR.customOperationTextLikeZip (nm.idText))
else
None
| _ -> None
let tryGetArgAttribsForCustomOperator ceenv (nm: Ident) =
match tryGetDataForCustomOperation nm ceenv with
| Some argInfos ->
argInfos
|> List.map
(fun
(_nm,
__maintainsVarSpaceUsingBind,
_maintainsVarSpace,
_allowInto,
_isLikeZip,
_isLikeJoin,
_isLikeGroupJoin,
_joinConditionWord,
methInfo) ->
match methInfo.GetParamAttribs(ceenv.cenv.amap, ceenv.mWhole) with
| [ curriedArgInfo ] -> Some curriedArgInfo // one for the actual argument group
| _ -> None)
|> Some
| _ -> None
let tryGetArgInfosForCustomOperator ceenv (nm: Ident) =
match tryGetDataForCustomOperation nm ceenv with
| Some argInfos ->
argInfos
|> List.map
(fun
(_nm,
__maintainsVarSpaceUsingBind,
_maintainsVarSpace,
_allowInto,
_isLikeZip,
_isLikeJoin,
_isLikeGroupJoin,
_joinConditionWord,
methInfo) ->
match methInfo with
| FSMeth(_, _, vref, _) ->
match ArgInfosOfMember ceenv.cenv.g vref with
| [ curriedArgInfo ] -> Some curriedArgInfo
| _ -> None
| _ -> None)
|> Some
| _ -> None
let tryExpectedArgCountForCustomOperator ceenv (nm: Ident) =
match tryGetArgAttribsForCustomOperator ceenv nm with
| None -> None
| Some argInfosForOverloads ->
let nums =
argInfosForOverloads
|> List.map (function
| None -> -1
| Some argInfos -> List.length argInfos)
// Prior to 'OverloadsForCustomOperations' we count exact arguments.
//
// With 'OverloadsForCustomOperations' we don't compute an exact expected argument count
// if any arguments are optional, out or ParamArray.
let isSpecial =
if ceenv.cenv.g.langVersion.SupportsFeature LanguageFeature.OverloadsForCustomOperations then
argInfosForOverloads
|> List.exists (fun info ->
match info with
| None -> false
| Some args ->
args
|> List.exists (fun (ParamAttribs(isParamArrayArg, _isInArg, isOutArg, optArgInfo, _callerInfo, _reflArgInfo)) ->
isParamArrayArg || isOutArg || optArgInfo.IsOptional))
else
false
if not isSpecial && nums |> List.forall (fun v -> v >= 0 && v = nums[0]) then
Some(max (nums[0] - 1) 0) // drop the computation context argument
else
None
// Check for the [<ProjectionParameter>] attribute on an argument position
let isCustomOperationProjectionParameter ceenv i (nm: Ident) =
match tryGetArgInfosForCustomOperator ceenv nm with
| None -> false
| Some argInfosForOverloads ->
let vs =
argInfosForOverloads
|> List.map (function
| None -> false
| Some argInfos ->
i < argInfos.Length
&& let _, argInfo = List.item i argInfos in
HasFSharpAttribute ceenv.cenv.g ceenv.cenv.g.attrib_ProjectionParameterAttribute argInfo.Attribs)
if List.allEqual vs then
vs[0]
else
let opDatas = (tryGetDataForCustomOperation nm ceenv).Value
let opName, _, _, _, _, _, _, _j, _ = opDatas[0]
errorR (Error(FSComp.SR.tcCustomOperationInvalid opName, nm.idRange))
false
[<return: Struct>]
let (|ExprAsPat|_|) (f: SynExpr) =
match f with
| SingleIdent v1
| SynExprParen(SingleIdent v1, _, _, _) -> ValueSome(mkSynPatVar None v1)
| SynExprParen(SynExpr.Tuple(false, elems, commas, _), _, _, _) ->
let elems = elems |> List.map (|SingleIdent|_|)
if elems |> List.forall (fun x -> x.IsSome) then
ValueSome(SynPat.Tuple(false, (elems |> List.map (fun x -> mkSynPatVar None x.Value)), commas, f.Range))
else
ValueNone
| _ -> ValueNone
// For join clauses that join on nullable, we syntactically insert the creation of nullable values on the appropriate side of the condition,
// then pull the syntax apart again
[<return: Struct>]
let (|JoinRelation|_|) ceenv (expr: SynExpr) =
let m = expr.Range
let ad = ceenv.env.eAccessRights
let isOpName opName vref s =
(s = opName)
&& match
ResolveExprLongIdent
ceenv.cenv.tcSink
ceenv.cenv.nameResolver
m
ad
ceenv.env.eNameResEnv
TypeNameResolutionInfo.Default
[ ident (opName, m) ]
None
with
| Result(_, Item.Value vref2, []) -> valRefEq ceenv.cenv.g vref vref2
| _ -> false
match expr with
| BinOpExpr(opId, a, b) when isOpName opNameEquals ceenv.cenv.g.equals_operator_vref opId.idText -> ValueSome(a, b)
| BinOpExpr(opId, a, b) when isOpName opNameEqualsNullable ceenv.cenv.g.equals_nullable_operator_vref opId.idText ->
let a =
SynExpr.App(ExprAtomicFlag.Atomic, false, mkSynLidGet a.Range [ MangledGlobalName; "System" ] "Nullable", a, a.Range)
ValueSome(a, b)
| BinOpExpr(opId, a, b) when isOpName opNameNullableEquals ceenv.cenv.g.nullable_equals_operator_vref opId.idText ->
let b =
SynExpr.App(ExprAtomicFlag.Atomic, false, mkSynLidGet b.Range [ MangledGlobalName; "System" ] "Nullable", b, b.Range)
ValueSome(a, b)
| BinOpExpr(opId, a, b) when isOpName opNameNullableEqualsNullable ceenv.cenv.g.nullable_equals_nullable_operator_vref opId.idText ->
ValueSome(a, b)
| _ -> ValueNone
let (|ForEachThen|_|) synExpr =
match synExpr with
| SynExpr.ForEach(_spFor,
_spIn,
SeqExprOnly false,
isFromSource,
pat1,
expr1,
SynExpr.Sequential(isTrueSeq = true; expr1 = clause; expr2 = rest),
_) -> Some(isFromSource, pat1, expr1, clause, rest)
| _ -> None
let (|CustomOpId|_|) isCustomOperation predicate synExpr =
match synExpr with
| SingleIdent nm when isCustomOperation nm && predicate nm -> Some nm
| _ -> None
// e1 in e2 ('in' is parsed as 'JOIN_IN')
let (|InExpr|_|) synExpr =
match synExpr with
| SynExpr.JoinIn(e1, _, e2, mApp) -> Some(e1, e2, mApp)
| _ -> None
// e1 on e2 (note: 'on' is the 'JoinConditionWord')
let (|OnExpr|_|) ceenv nm synExpr =
match tryGetDataForCustomOperation nm ceenv with
| None -> None
| Some _ ->
match synExpr with
| SynExpr.App(funcExpr = SynExpr.App(funcExpr = e1; argExpr = SingleIdent opName); argExpr = e2) when
opName.idText = customOperationJoinConditionWord ceenv nm
->
let item = Item.CustomOperation(opName.idText, (fun () -> None), None)
CallNameResolutionSink
ceenv.cenv.tcSink
(opName.idRange, ceenv.env.NameEnv, item, emptyTyparInst, ItemOccurrence.Use, ceenv.env.AccessRights)
Some(e1, e2)
| _ -> None
// e1 into e2
let (|IntoSuffix|_|) (e: SynExpr) =
match e with
| SynExpr.App(funcExpr = SynExpr.App(funcExpr = x; argExpr = SingleIdent nm2); argExpr = ExprAsPat intoPat) when
nm2.idText = CustomOperations.Into
->
Some(x, nm2.idRange, intoPat)
| _ -> None
let JoinOrGroupJoinOp ceenv detector synExpr =
match synExpr with
| SynExpr.App(_, _, CustomOpId (isCustomOperation ceenv) detector nm, ExprAsPat innerSourcePat, mJoinCore) ->
Some(nm, innerSourcePat, mJoinCore, false)
// join with bad pattern (gives error on "join" and continues)
| SynExpr.App(_, _, CustomOpId (isCustomOperation ceenv) detector nm, _innerSourcePatExpr, mJoinCore) ->
errorR (Error(FSComp.SR.tcBinaryOperatorRequiresVariable (nm.idText, Option.get (customOpUsageText ceenv nm)), nm.idRange))
Some(nm, arbPat mJoinCore, mJoinCore, true)
// join (without anything after - gives error on "join" and continues)
| CustomOpId (isCustomOperation ceenv) detector nm ->
errorR (Error(FSComp.SR.tcBinaryOperatorRequiresVariable (nm.idText, Option.get (customOpUsageText ceenv nm)), nm.idRange))
Some(nm, arbPat synExpr.Range, synExpr.Range, true)
| _ -> None
// JoinOrGroupJoinOp customOperationIsLikeJoin
let (|JoinOp|_|) ceenv synExpr =
JoinOrGroupJoinOp ceenv (customOperationIsLikeJoin ceenv) synExpr
let (|GroupJoinOp|_|) ceenv synExpr =
JoinOrGroupJoinOp ceenv (customOperationIsLikeGroupJoin ceenv) synExpr
let MatchIntoSuffixOrRecover ceenv alreadyGivenError (nm: Ident) synExpr =
match synExpr with
| IntoSuffix(x, intoWordRange, intoPat) ->
// record the "into" as a custom operation for colorization
let item = Item.CustomOperation("into", (fun () -> None), None)
CallNameResolutionSink
ceenv.cenv.tcSink
(intoWordRange, ceenv.env.NameEnv, item, emptyTyparInst, ItemOccurrence.Use, ceenv.env.eAccessRights)
(x, intoPat, alreadyGivenError)
| _ ->
if not alreadyGivenError then
errorR (Error(FSComp.SR.tcOperatorIncorrectSyntax (nm.idText, Option.get (customOpUsageText ceenv nm)), nm.idRange))
(synExpr, arbPat synExpr.Range, true)
let MatchOnExprOrRecover ceenv alreadyGivenError nm (onExpr: SynExpr) =
match onExpr with
| OnExpr ceenv nm (innerSource, SynExprParen(keySelectors, _, _, _)) -> (innerSource, keySelectors)
| _ ->
if not alreadyGivenError then
suppressErrorReporting (fun () -> TcExprOfUnknownType ceenv.cenv ceenv.env ceenv.tpenv onExpr)
|> ignore
errorR (Error(FSComp.SR.tcOperatorIncorrectSyntax (nm.idText, Option.get (customOpUsageText ceenv nm)), nm.idRange))
(arbExpr ("_innerSource", onExpr.Range),
mkSynBifix onExpr.Range "=" (arbExpr ("_keySelectors", onExpr.Range)) (arbExpr ("_keySelector2", onExpr.Range)))
let (|JoinExpr|_|) (ceenv: ComputationExpressionContext<'a>) synExpr =
match synExpr with
| InExpr(JoinOp ceenv (nm, innerSourcePat, _, alreadyGivenError), onExpr, mJoinCore) ->
let innerSource, keySelectors =
MatchOnExprOrRecover ceenv alreadyGivenError nm onExpr
Some(nm, innerSourcePat, innerSource, keySelectors, mJoinCore)
| JoinOp ceenv (nm, innerSourcePat, mJoinCore, alreadyGivenError) ->
if alreadyGivenError then
errorR (Error(FSComp.SR.tcOperatorRequiresIn (nm.idText, Option.get (customOpUsageText ceenv nm)), nm.idRange))
Some(nm, innerSourcePat, arbExpr ("_innerSource", synExpr.Range), arbKeySelectors synExpr.Range, mJoinCore)
| _ -> None
let (|GroupJoinExpr|_|) ceenv synExpr =
match synExpr with
| InExpr(GroupJoinOp ceenv (nm, innerSourcePat, _, alreadyGivenError), intoExpr, mGroupJoinCore) ->
let onExpr, intoPat, alreadyGivenError =
MatchIntoSuffixOrRecover ceenv alreadyGivenError nm intoExpr
let innerSource, keySelectors =
MatchOnExprOrRecover ceenv alreadyGivenError nm onExpr
Some(nm, innerSourcePat, innerSource, keySelectors, intoPat, mGroupJoinCore)
| GroupJoinOp ceenv (nm, innerSourcePat, mGroupJoinCore, alreadyGivenError) ->
if alreadyGivenError then
errorR (Error(FSComp.SR.tcOperatorRequiresIn (nm.idText, Option.get (customOpUsageText ceenv nm)), nm.idRange))
Some(
nm,
innerSourcePat,
arbExpr ("_innerSource", synExpr.Range),
arbKeySelectors synExpr.Range,
arbPat synExpr.Range,
mGroupJoinCore
)
| _ -> None
let (|JoinOrGroupJoinOrZipClause|_|) (ceenv: ComputationExpressionContext<'a>) synExpr =
match synExpr with
// join innerSourcePat in innerSource on (keySelector1 = keySelector2)
| JoinExpr ceenv (nm, innerSourcePat, innerSource, keySelectors, mJoinCore) ->
Some(nm, innerSourcePat, innerSource, Some keySelectors, None, mJoinCore)
// groupJoin innerSourcePat in innerSource on (keySelector1 = keySelector2) into intoPat
| GroupJoinExpr ceenv (nm, innerSourcePat, innerSource, keySelectors, intoPat, mGroupJoinCore) ->
Some(nm, innerSourcePat, innerSource, Some keySelectors, Some intoPat, mGroupJoinCore)
// zip intoPat in secondSource
| InExpr(SynExpr.App(_, _, CustomOpId (isCustomOperation ceenv) (customOperationIsLikeZip ceenv) nm, ExprAsPat secondSourcePat, _),
secondSource,
mZipCore) -> Some(nm, secondSourcePat, secondSource, None, None, mZipCore)
// zip (without secondSource or in - gives error)
| CustomOpId (isCustomOperation ceenv) (customOperationIsLikeZip ceenv) nm ->
errorR (Error(FSComp.SR.tcOperatorIncorrectSyntax (nm.idText, Option.get (customOpUsageText ceenv nm)), nm.idRange))
Some(nm, arbPat synExpr.Range, arbExpr ("_secondSource", synExpr.Range), None, None, synExpr.Range)
// zip secondSource (without in - gives error)
| SynExpr.App(_, _, CustomOpId (isCustomOperation ceenv) (customOperationIsLikeZip ceenv) nm, ExprAsPat secondSourcePat, mZipCore) ->
errorR (Error(FSComp.SR.tcOperatorIncorrectSyntax (nm.idText, Option.get (customOpUsageText ceenv nm)), mZipCore))
Some(nm, secondSourcePat, arbExpr ("_innerSource", synExpr.Range), None, None, mZipCore)
| _ -> None
let (|ForEachThenJoinOrGroupJoinOrZipClause|_|) (ceenv: ComputationExpressionContext<'a>) strict synExpr =
match synExpr with
| ForEachThen(isFromSource,
firstSourcePat,
firstSource,
JoinOrGroupJoinOrZipClause ceenv (nm, secondSourcePat, secondSource, keySelectorsOpt, pat3opt, mOpCore),
innerComp) when
(let _firstSourceSimplePats, later1 =
use _holder = TemporarilySuspendReportingTypecheckResultsToSink ceenv.cenv.tcSink
SimplePatsOfPat ceenv.cenv.synArgNameGenerator firstSourcePat
Option.isNone later1)
->
Some(isFromSource, firstSourcePat, firstSource, nm, secondSourcePat, secondSource, keySelectorsOpt, pat3opt, mOpCore, innerComp)
| JoinOrGroupJoinOrZipClause ceenv (nm, pat2, expr2, expr3, pat3opt, mOpCore) when strict ->
errorR (Error(FSComp.SR.tcBinaryOperatorRequiresBody (nm.idText, Option.get (customOpUsageText ceenv nm)), nm.idRange))
Some(
true,
arbPat synExpr.Range,
arbExpr ("_outerSource", synExpr.Range),
nm,
pat2,
expr2,
expr3,
pat3opt,
mOpCore,
arbExpr ("_innerComp", synExpr.Range)
)
| _ -> None
let (|StripApps|) e =
let rec strip e =
match e with
| SynExpr.FromParseError(SynExpr.App(funcExpr = f; argExpr = arg), _)
| SynExpr.App(funcExpr = f; argExpr = arg) ->
let g, acc = strip f
g, (arg :: acc)
| _ -> e, []
let g, acc = strip e
g, List.rev acc
let (|OptionalIntoSuffix|) e =
match e with
| IntoSuffix(body, intoWordRange, intoInfo) -> (body, Some(intoWordRange, intoInfo))
| body -> (body, None)
let (|CustomOperationClause|_|) ceenv e =
match e with
| OptionalIntoSuffix(StripApps(SingleIdent nm, _) as core, intoOpt) when isCustomOperation ceenv nm ->
// Now we know we have a custom operation, commit the name resolution
let intoInfoOpt =
match intoOpt with
| Some(intoWordRange, intoInfo) ->
let item = Item.CustomOperation("into", (fun () -> None), None)
CallNameResolutionSink
ceenv.cenv.tcSink
(intoWordRange, ceenv.env.NameEnv, item, emptyTyparInst, ItemOccurrence.Use, ceenv.env.eAccessRights)
Some intoInfo
| None -> None
Some(nm, Option.get (tryGetDataForCustomOperation nm ceenv), core, core.Range, intoInfoOpt)
| _ -> None
let (|OptionalSequential|) e =
match e with
| SynExpr.Sequential(debugPoint = _sp; isTrueSeq = true; expr1 = dataComp1; expr2 = dataComp2) -> (dataComp1, Some dataComp2)
| _ -> (e, None)
// use! x = ...
// use! (x) = ...
// use! (__) = ...
// use! _ = ...
// use! (_) = ...
[<return: Struct>]
let rec (|UnwrapUseBang|_|) supportsUseBangBindingValueDiscard pat =
match pat with
| SynPat.Named(ident = SynIdent(id, _); isThisVal = false) -> ValueSome(id, pat)
| SynPat.LongIdent(longDotId = SynLongIdent(id = [ id ])) -> ValueSome(id, pat)
| SynPat.Wild(m) when supportsUseBangBindingValueDiscard ->
// To properly call the Using(disposable) CE member, we need to convert the wildcard to a SynPat.Named
let tmpIdent = mkSynId m "_"
ValueSome(tmpIdent, SynPat.Named(SynIdent(tmpIdent, None), false, None, m))
| SynPat.Paren(pat = UnwrapUseBang supportsUseBangBindingValueDiscard (id, pat)) -> ValueSome(id, pat)
| _ -> ValueNone
[<return: Struct>]
let (|ExprAsUseBang|_|) expr =
match expr with
| SynExpr.LetOrUseBang(
bindDebugPoint = spBind
isUse = true
isFromSource = isFromSource
pat = pat
rhs = rhsExpr
andBangs = andBangs
body = innerComp
trivia = { LetOrUseBangKeyword = mBind }) -> ValueSome(spBind, isFromSource, pat, rhsExpr, andBangs, innerComp, mBind)
| _ -> ValueNone
// "cexpr; cexpr" is treated as builder.Combine(cexpr1, cexpr1)
// This is not pretty - we have to decide which range markers we use for the calls to Combine and Delay
// NOTE: we should probably suppress these sequence points altogether
let rangeForCombine innerComp1 =
let m =
match innerComp1 with
| SynExpr.IfThenElse(trivia = { IfToThenRange = mIfToThen }) -> mIfToThen
| SynExpr.Match(matchDebugPoint = DebugPointAtBinding.Yes mMatch) -> mMatch
| SynExpr.TryWith(trivia = { TryKeyword = mTry }) -> mTry
| SynExpr.TryFinally(trivia = { TryKeyword = mTry }) -> mTry
| SynExpr.For(forDebugPoint = DebugPointAtFor.Yes mBind) -> mBind
| SynExpr.ForEach(forDebugPoint = DebugPointAtFor.Yes mBind) -> mBind
| SynExpr.While(whileDebugPoint = DebugPointAtWhile.Yes mWhile) -> mWhile
| _ -> innerComp1.Range
m.NoteSourceConstruct(NotedSourceConstruct.Combine)
// Check for 'where x > y', 'select x, y' and other mis-applications of infix operators, give a good error message, and return a flag
let checkForBinaryApp ceenv comp =
match comp with
| StripApps(SingleIdent nm, [ StripApps(SingleIdent nm2, args); arg2 ]) when
IsLogicalInfixOpName nm.idText
&& (match tryExpectedArgCountForCustomOperator ceenv nm2 with
| Some n -> n > 0
| _ -> false)
&& not (List.isEmpty args)
->
let estimatedRangeOfIntendedLeftAndRightArguments =
unionRanges (List.last args).Range arg2.Range
errorR (Error(FSComp.SR.tcUnrecognizedQueryBinaryOperator (), estimatedRangeOfIntendedLeftAndRightArguments))
true
| SynExpr.Tuple(false, StripApps(SingleIdent nm2, args) :: _, _, m) when
(match tryExpectedArgCountForCustomOperator ceenv nm2 with
| Some n -> n > 0
| _ -> false)
&& not (List.isEmpty args)
->
let estimatedRangeOfIntendedLeftAndRightArguments =
unionRanges (List.last args).Range m.EndRange
errorR (Error(FSComp.SR.tcUnrecognizedQueryBinaryOperator (), estimatedRangeOfIntendedLeftAndRightArguments))
true
| _ -> false
let inline addVarsToVarSpace (varSpace: LazyWithContext<Val list * TcEnv, range>) f =
LazyWithContext.Create(
(fun m ->
let (patvs: Val list, env) = varSpace.Force m
let vs, envinner = f m env
let patvs =
List.append
patvs
(vs
|> List.filter (fun v -> not (patvs |> List.exists (fun v2 -> v.LogicalName = v2.LogicalName))))
patvs, envinner),
id
)
/// Checks if a builder method exists and reports an error if it doesn't
let requireBuilderMethod methodName m1 cenv env ad builderTy m2 =
if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m1 ad methodName builderTy) then
error (Error(FSComp.SR.tcRequireBuilderMethod methodName, m2))
/// <summary>
/// Try translate the syntax sugar
/// </summary>
/// <param name="ceenv">Computation expression context (carrying caches, environments, ranges, etc)</param>
/// <param name="firstTry">Flag if it's initial check</param>
/// <param name="q">a flag indicating if custom operators are allowed. They are not allowed inside try/with, try/finally, if/then/else etc.</param>
/// <param name="varSpace">a lazy data structure indicating the variables bound so far in the overall computation</param>
/// <param name="comp">the computation expression being analyzed</param>
/// <param name="translatedCtxt">represents the translation of the context in which the computation expression 'comp' occurs,
/// up to a hole to be filled by (part of) the results of translating 'comp'.</param>
/// <typeparam name="'a"></typeparam>
/// <returns></returns>
let rec TryTranslateComputationExpression
(ceenv: ComputationExpressionContext<'a>)
(firstTry: CompExprTranslationPass)
(q: CustomOperationsMode)
(varSpace: LazyWithContext<(Val list * TcEnv), range>)
(comp: SynExpr)
(translatedCtxt: SynExpr -> SynExpr)
: SynExpr option =
// Guard the stack for deeply nested computation expressions
let cenv = ceenv.cenv
cenv.stackGuard.Guard
<| fun () ->
match comp with
// for firstSourcePat in firstSource do
// join secondSourcePat in expr2 on (expr3 = expr4)
// ...
// -->
// join expr1 expr2 (fun firstSourcePat -> expr3) (fun secondSourcePat -> expr4) (fun firstSourcePat secondSourcePat -> ...)
// for firstSourcePat in firstSource do
// groupJoin secondSourcePat in expr2 on (expr3 = expr4) into groupPat
// ...
// -->
// groupJoin expr1 expr2 (fun firstSourcePat -> expr3) (fun secondSourcePat -> expr4) (fun firstSourcePat groupPat -> ...)
// for firstSourcePat in firstSource do
// zip secondSource into secondSourcePat
// ...
// -->
// zip expr1 expr2 (fun pat1 pat3 -> ...)
| ForEachThenJoinOrGroupJoinOrZipClause ceenv true (isFromSource,
firstSourcePat,
firstSource,
nm,
secondSourcePat,