-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBaseFhirPathExpressionVisitor.cs
1537 lines (1445 loc) · 46.9 KB
/
BaseFhirPathExpressionVisitor.cs
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
using Hl7.Fhir.Introspection;
using Hl7.Fhir.Model;
using Hl7.Fhir.Support;
using Hl7.Fhir.Utility;
using Hl7.FhirPath;
using Hl7.FhirPath.Expressions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Hl7.Fhir.FhirPath.Validator
{
public class BaseFhirPathExpressionVisitor : ExpressionVisitor<FhirPathVisitorProps>
{
public BaseFhirPathExpressionVisitor(ModelInspector mi, List<string> SupportedResources, Type[] OpenTypes)
{
_mi = mi;
_supportedResources = SupportedResources;
_openTypes = OpenTypes;
// Register some FHIR Standard variables (const strings)
// http://hl7.org/fhir/fhirpath.html#vars
RegisterVariable("ucum", typeof(Hl7.Fhir.Model.FhirString));
RegisterVariable("sct", typeof(Hl7.Fhir.Model.FhirString));
RegisterVariable("loinc", typeof(Hl7.Fhir.Model.FhirString));
_table = new SymbolTable(mi, SupportedResources, OpenTypes);
}
private SymbolTable _table;
public FhirPathVisitorProps RootContext { get; } = new FhirPathVisitorProps() { isRoot = true };
/// <summary>
/// Permit navigating to a variable without the % prefix (but log a warning anyway)
/// </summary>
/// <remarks>
/// This was introduced for supporting FML execution rules (do not enable outside that context)
/// </remarks>
public bool UseVariableAsName { get; set; }
/// <summary>
/// Set the Context of the expression to verify
/// (and also set the resource, rootResource and context variables)
/// </summary>
/// <param name="definitionPath">StructureDefinition style path to the property (not a fhirpath expression)</param>
public void SetContext(string definitionPath)
{
var path = definitionPath.Replace("[x]", "");
string typeName = path;
if (path.Contains('.'))
{
typeName = path.Substring(0, path.IndexOf("."));
path = path.Substring(path.IndexOf(".") + 1);
}
else
{
path = null;
}
var rootType = _mi.GetTypeForFhirType(typeName);
if (rootType != null)
{
RegisterVariable("rootResource", rootType);
if (string.IsNullOrEmpty(path))
{
RegisterVariable("resource", rootType);
RegisterVariable("context", rootType);
AddInputType(rootType);
return;
}
var resourceType = rootType; // don't set this till we get to the end, as it could be different
var nodes = path.Split('.').ToList();
IEnumerable<ClassMapping> cm = new[] { _mi.FindOrImportClassMapping(rootType) }.Where(v => v != null).ToList();
while (cm.Any() && nodes.Any())
{
var pm = cm.Select(cm => cm.FindMappedElementByName(nodes[0]) ?? cm.FindMappedElementByChoiceName(nodes[0]))
.Where(c => c != null)
.ToList();
cm = pm.SelectMany(pm2 =>
{
if (pm2.Choice == ChoiceType.DatatypeChoice && pm2.FhirType.Length == 1 && pm2.FhirType[0].Name == "DataType")
{
// This is the set of open types
return _openTypes.Select(ot => _mi.FindOrImportClassMapping(ot));
}
if (pm2.Name != nodes[0])
return pm2?.FhirType.Where(t => nodes[0].EndsWith(t.Name)).Select(ft => _mi.FindOrImportClassMapping(ft));
return pm2?.FhirType.Select(ft => _mi.FindOrImportClassMapping(ft));
}).Where(pm => pm != null).ToList();
nodes.RemoveAt(0);
}
RegisterVariable("resource", resourceType);
foreach (var tcm in cm)
{
RegisterVariable("context", tcm); // this won't replace things, so not quite right
AddInputType(tcm);
}
}
else
{
throw new ApplicationException($"Could not result type: {typeName}");
}
}
protected readonly ModelInspector _mi;
protected readonly List<string> _supportedResources;
protected readonly Type[] _openTypes;
// for repeat error checking
struct RepeatInfo
{
public ChildExpression ce;
public OperationOutcome.IssueComponent issue;
}
Dictionary<ChildExpression, OperationOutcome.IssueComponent> _repeatChildren;
public Hl7.Fhir.Model.OperationOutcome Outcome { get; } = new Hl7.Fhir.Model.OperationOutcome();
const string ExtNamespace = "http://fhirpath-lab.com/StructureDefinition/fhirpath-error-location";
public static void ReportErrorLocation(Expression expression, OperationOutcome.IssueComponent issue)
{
if (expression.Location is FhirPathExpressionLocationInfo pi)
{
issue.Location = new[] { $"Line {pi.LineNumber}, Column {pi.LinePosition} (Position: {pi.RawPosition} Length: {pi.Length})" };
var ext = new Extension() { Url = ExtNamespace };
ext.AddExtension("position", new Integer(pi.RawPosition));
ext.AddExtension("length", new Integer(pi.Length));
issue.Extension.Add(ext);
}
}
private readonly Stack<FhirPathVisitorProps> _stackPropertyContext = new();
private readonly Stack<FhirPathVisitorProps> _stackExpressionContext = new();
private readonly Stack<FhirPathVisitorProps> _stackAggregateTotal = new();
private readonly StringBuilder _result = new();
private int _indent = 0;
public void RegisterVariable(string name, Type type)
{
var cm = _mi.FindOrImportClassMapping(type);
RegisterVariable(name, cm);
}
/// <summary>
/// Walk a path to a property (as also used in SetContext)
/// </summary>
/// <param name="name"></param>
/// <param name="definitionPath"></param>
public void RegisterVariable(string name, string definitionPath)
{
if (variables.ContainsKey(name))
return;
var path = definitionPath.Replace("[x]", "");
string typeName = path;
if (path.Contains('.'))
{
typeName = path.Substring(0, path.IndexOf("."));
path = path.Substring(path.IndexOf(".") + 1);
}
else
{
path = null;
}
var rootType = _mi.GetTypeForFhirType(typeName);
if (rootType != null)
{
if (string.IsNullOrEmpty(path))
{
RegisterVariable(name, rootType);
return;
}
var resourceType = rootType; // don't set this till we get to the end, as it could be different
var nodes = path.Split('.').ToList();
IEnumerable<ClassMapping> cm = new[] { _mi.FindOrImportClassMapping(rootType) }.Where(v => v != null).ToList();
while (cm.Any() && nodes.Any())
{
var pm = cm.Select(cm => cm.FindMappedElementByName(nodes[0]) ?? cm.FindMappedElementByChoiceName(nodes[0]))
.Where(c => c != null)
.ToList();
cm = pm.SelectMany(pm2 =>
{
if (pm2.Choice == ChoiceType.DatatypeChoice && pm2.FhirType.Length == 1 && pm2.FhirType[0].Name == "DataType")
{
// This is the set of open types
return _openTypes.Select(ot => _mi.FindOrImportClassMapping(ot));
}
if (pm2.Name != nodes[0])
return pm2?.FhirType.Where(t => nodes[0].EndsWith(t.Name)).Select(ft => _mi.FindOrImportClassMapping(ft));
return pm2?.FhirType.Select(ft => _mi.FindOrImportClassMapping(ft));
}).Where(pm => pm != null).ToList();
nodes.RemoveAt(0);
}
FhirPathVisitorProps types = new FhirPathVisitorProps();
foreach (var tcm in cm)
{
types.Types.Add(new NodeProps(tcm));
}
RegisterVariable(name, types);
}
else
{
throw new ApplicationException($"Could not resolve type: {typeName}");
}
}
public void RegisterVariable(string name, ClassMapping cm)
{
FhirPathVisitorProps types = new FhirPathVisitorProps();
if (cm != null && !variables.ContainsKey(name))
{
types.Types.Add(new NodeProps(cm));
variables.Add(name, types);
}
}
public void RegisterVariable(string name, FhirPathVisitorProps types)
{
if (!variables.ContainsKey(name))
{
variables.Add(name, types);
}
}
private readonly Dictionary<string, FhirPathVisitorProps> variables = new();
private readonly Dictionary<string, FhirPathVisitorProps> definedVariables = new();
private Boolean _dynamicDefinedVariableInScope = false;
public override string ToString()
{
return _result.ToString();
}
private readonly Collection<ClassMapping> _inputTypes = new();
public void AddInputType(Type t)
{
var cm = _mi.FindOrImportClassMapping(t);
if (cm != null && !_inputTypes.Contains(cm))
{
_inputTypes.Add(cm);
RootContext.Types.Add(new NodeProps(cm));
}
}
public void AddInputType(ClassMapping cm)
{
if (!_inputTypes.Contains(cm))
{
_inputTypes.Add(cm);
RootContext.Types.Add(new NodeProps(cm));
}
}
public override FhirPathVisitorProps VisitConstant(ConstantExpression expression)
{
// ChildExpression ce
var r = new FhirPathVisitorProps();
var t = _mi.GetTypeForFhirType(expression.ExpressionType.Name);
if (t != null)
{
r.AddType(_mi, t);
var debugValue = expression.ExpressionType.Name.ToLower() switch
{
"boolean" => $"{expression.Value}",
"string" => $"'{expression.Value}'",
"integer" => $"{expression.Value}",
"decimal" => $"{expression.Value}",
"date" => $"@{expression.Value}",
"datetime" => $"@{expression.Value}",
"time" => $"@T{expression.Value}",
"quantity" => $"{expression.Value}",
_ => ""
};
AppendLine($"{debugValue} : {r}");
}
else
AppendLine($"{expression.Value} : {r}");
// appendType(expression);
return r;
}
private readonly string[] nonCollectionOperators = new[]
{
"=",
"~",
"!=",
"!~",
"<",
"<=",
">",
">=",
"as",
"is",
"or",
"xor",
"implies",
"and", // TODO: check for boolean values each side
};
private readonly string[] boolOperators = new[]
{
"=",
"~",
"!=",
"!~",
"<",
"<=",
">",
">=",
"in", // TODO: could check for type overlaps
"contains", // TODO: could check for type overlaps
"or",
"xor",
"implies",
"and", // TODO: check for boolean values each side
};
private readonly string[] boolFuncs = new[]
{
"empty",
"exists",
"allTrue",
"anyTrue",
"allFalse",
"anyFalse",
"binary.contains",
"binary.in",
"isDistinct",
"not",
"binary.=",
"binary.!=",
"binary.~",
"binary.!~",
"convertsToBoolean",
"convertsToInteger",
"convertsToLong",
"convertsToDecimal",
"convertsToQuantity",
"convertsToString",
"convertsToDate",
"convertsToDateTime",
"convertsToTime",
"startsWith",
"endsWith",
"matches",
"contains",
"is",
"binary.is",
"binary.and",
"or",
"binary.xor",
"binary.implies",
"all",
"any",
"supersetOf",
"subsetOf",
// FHIR extensions to fhirpath
"hasValue",
"conformsTo",
"memberOf",
"subsumes",
"subsumedBy",
"htmlChecks",
"comparable",
}.ToArray();
private readonly string[] stringFocusFuncs = new[]
{
// Section 6.6.7
"binary.&",
// Section 5.7 in the spec (CI build)
"encode",
"decode",
"escape",
"unescape",
"trim",
"split",
"join",
// Section 5.6 in the spec (normative)
// "indexOf", // handled in the symbol table
"substring",
"startsWith",
"endsWith",
"contains",
"upper",
"lower",
"replace",
"matches",
"replaceMatches",
"toChars",
};
private readonly string[] stringFuncs = new[]
{
"toString",
"upper",
"lower",
"toChars",
"substring",
"trim",
"join",
"split",
"encode",
"decode",
"escape",
"unescape",
"binary.&",
"replaceMatches",
"replace",
}.ToArray();
private readonly string[] expressionFuncs = new[]
{
"exists",
"all",
"select",
"where",
"repeat",
"iif",
"trace",
"defineVariable",
"aggregate",
}.ToArray();
private readonly string[] booleanArgFuncs = new[]
{
"where",
"all",
}.ToArray();
protected readonly string[] passthroughFuncs = new[]
{
"single",
"where",
"trace",
"first",
"skip",
"take",
"last",
"tail",
"intersect", // TODO: could validate that these types have overlap
"exclude", // TODO: could validate that these types have overlap
"distinct",
// New additions in FHIR R5
"lowBoundary",
"highBoundary",
// defineVariable not required here as it is handled in the SymbolTable logic
}.ToArray();
private readonly string[] mathFuncs = new[]
{
"+",
"-",
"/",
"*",
}.ToArray();
protected virtual void DeduceReturnType(FunctionCallExpression function, FhirPathVisitorProps focus, IEnumerable<FhirPathVisitorProps> props, FhirPathVisitorProps outputProps)
{
var fd = _table.Get(function.FunctionName);
if (fd != null)
{
// Perform any validations
foreach (var validation in fd.Validations)
{
validation(function, fd, props, Outcome);
}
// check the context of the function
if (!fd.IsSupportedContext(focus, function, Outcome))
{
// Error was already reported inside the function
}
else
{
// At least this is supported
IEnumerable<FunctionContext> contexts = fd.SupportedContexts;
if (function is UnaryExpression)
{
if (props.Any())
contexts = contexts.Where(c => props.Any(p => p.CanBeOfType(c.Type)));
}
else if (function is FunctionCallExpression)
{
contexts = contexts.Where(c => focus.CanBeOfType(c.Type));
}
var rts = contexts.Select(sc => sc.ReturnType).Distinct().ToList();
if (!rts.Any() && fd.GetReturnType != null)
{
foreach (var nprop in fd.GetReturnType(fd, focus, props, Outcome))
outputProps.Types.Add(nprop);
}
else
{
foreach (var rt in rts)
outputProps.Types.Add(new NodeProps(rt));
}
}
}
if (stringFocusFuncs.Contains(function.FunctionName))
{
// these string functions all have to work on an actual type of string too
if (!focus.CanBeOfType("string"))
{
var issue = new Hl7.Fhir.Model.OperationOutcome.IssueComponent()
{
Severity = Hl7.Fhir.Model.OperationOutcome.IssueSeverity.Error,
Code = Hl7.Fhir.Model.OperationOutcome.IssueType.NotSupported,
Details = new Hl7.Fhir.Model.CodeableConcept() { Text = $"String function '{function.FunctionName}' is not supported on {focus.TypeNames()}" }
};
ReportErrorLocation(function, issue);
Outcome.AddIssue(issue);
}
}
if (stringFuncs.Contains(function.FunctionName))
{
if (function.FunctionName == "toChars")
outputProps.AddType(_mi, typeof(Hl7.Fhir.Model.FhirString), true);
else
outputProps.AddType(_mi, typeof(Hl7.Fhir.Model.FhirString));
}
else if (function.FunctionName == "is")
{
// Check this before the boolfuncs tests
var isTypeArg = function.Arguments.First();
FhirPathVisitorProps isType = props.FirstOrDefault();
// Check if the type possibly COULD be evaluated as true
if (isTypeArg is ConstantExpression ceTa)
{
// ceTa.Value
var isTypeToCheck = _mi.GetTypeForFhirType(ceTa.Value as string);
var possibleTypeNames = focus.Types.Select(t => t.ClassMapping.Name);
var validResultTypes = focus.Types.Where(t => t.ClassMapping.NativeType.IsAssignableFrom(isTypeToCheck));
if (!focus.CanBeOfType(ceTa.Value as string))
{
var issue = new Hl7.Fhir.Model.OperationOutcome.IssueComponent()
{
Severity = Hl7.Fhir.Model.OperationOutcome.IssueSeverity.Error,
Code = Hl7.Fhir.Model.OperationOutcome.IssueType.NotSupported,
Details = new Hl7.Fhir.Model.CodeableConcept() { Text = $"Expression included an 'is' test for {ceTa.Value} where possible types are {string.Join(", ", possibleTypeNames)}" }
};
ReportErrorLocation(function, issue);
Outcome.AddIssue(issue);
}
else
{
outputProps.AddType(_mi, typeof(Hl7.Fhir.Model.FhirBoolean));
}
}
// Check the collection too
if (focus.IsCollection())
{
var issue = new Hl7.Fhir.Model.OperationOutcome.IssueComponent()
{
Severity = Hl7.Fhir.Model.OperationOutcome.IssueSeverity.Warning,
Code = Hl7.Fhir.Model.OperationOutcome.IssueType.MultipleMatches,
Details = new Hl7.Fhir.Model.CodeableConcept() { Text = $"Function '{function.FunctionName}' can experience unexpected runtime errors when used with a collection" },
};
ReportErrorLocation(function, issue);
Outcome.AddIssue(issue);
}
}
else if (function.FunctionName == "as" || function.FunctionName == "ofType")
{
// Check this before the boolfuncs tests
var isTypeArg = function.Arguments.First();
FhirPathVisitorProps isType = props.FirstOrDefault();
// Check if the type possibly COULD be evaluated as true
if (isTypeArg is ConstantExpression ceTa)
{
// ceTa.Value
var isTypeToCheck = _mi.GetTypeForFhirType(ceTa.Value as string);
var possibleTypeNames = focus.Types.Select(t => t.ClassMapping.Name);
var validResultTypes = focus.Types.Where(t => t.ClassMapping.NativeType.IsAssignableFrom(isTypeToCheck));
if (!focus.CanBeOfType(ceTa.Value as string))
{
var issue = new Hl7.Fhir.Model.OperationOutcome.IssueComponent()
{
Severity = Hl7.Fhir.Model.OperationOutcome.IssueSeverity.Error,
Code = Hl7.Fhir.Model.OperationOutcome.IssueType.NotSupported,
Details = new Hl7.Fhir.Model.CodeableConcept() { Text = $"Expression included an '{function.FunctionName}' test for {ceTa.Value} where possible types are {string.Join(", ", possibleTypeNames)}" }
};
ReportErrorLocation(function, issue);
Outcome.AddIssue(issue);
}
else
{
// filter down to the types listed
foreach (var rt in validResultTypes)
{
outputProps.Types.Add(rt);
}
}
}
if (function.FunctionName == "as")
{
// Check the collection too
if (focus.IsCollection())
{
var issue = new Hl7.Fhir.Model.OperationOutcome.IssueComponent()
{
Severity = Hl7.Fhir.Model.OperationOutcome.IssueSeverity.Warning,
Code = Hl7.Fhir.Model.OperationOutcome.IssueType.MultipleMatches,
Details = new Hl7.Fhir.Model.CodeableConcept() { Text = $"Function '{function.FunctionName}' can experience unexpected runtime errors when used with a collection" },
};
ReportErrorLocation(function, issue);
Outcome.AddIssue(issue);
}
}
}
// TODO: Also include ofType special case handling to look for possible warnings
else if (boolFuncs.Contains(function.FunctionName))
outputProps.AddType(_mi, typeof(Hl7.Fhir.Model.FhirBoolean));
else if (function.FunctionName == "count")
outputProps.AddType(_mi, typeof(Hl7.Fhir.Model.Integer));
else if (function.FunctionName == "extension")
outputProps.AddType(_mi, typeof(Hl7.Fhir.Model.Extension), true);
else if (mathFuncs.Contains(function.FunctionName))
{
foreach (var t in focus.Types)
outputProps.Types.Add(t);
}
else if (passthroughFuncs.Contains(function.FunctionName))
{
foreach (var t in focus.Types)
{
if (function.FunctionName == "first" || function.FunctionName == "last" || function.FunctionName == "tail")
outputProps.Types.Add(new NodeProps(t.ClassMapping, t.PropertyMapping) { IsCollection = false });
else
outputProps.Types.Add(t);
}
}
else if (function.FunctionName == "select")
{
// Return types here should also check for Arrays and convert result to an array if source type was a collection
bool bForceCollections = false;
foreach (var t in focus.Types)
{
if (t.IsCollection)
bForceCollections = true;
}
//
//foreach (var t in props)
//{
// System.Diagnostics.Trace.WriteLine($"select params: {t}");
//}
if (props.Count() == 1)
{
foreach (var t in props.First().Types)
{
var t2 = bForceCollections ? t.AsCollection() : t;
outputProps.Types.Add(t2);
}
}
}
else if (function.FunctionName == "resolve")
{
// Check the supported reference types for this resource type
foreach (var t in focus.Types)
{
var v = t.PropertyMapping.NativeProperty.GetCustomAttribute<ReferencesAttribute>();
if (v?.Resources?.Any() == true)
{
// retrieve the classname
foreach (var typeName in v.Resources)
{
if (v.Resources.Length == 1)
{
// Type not listed, so just enumerate ALL resources
foreach (var typeNameAny in _supportedResources)
{
var cmAny = _mi.FindClassMapping(typeNameAny);
outputProps.Types.Add(new NodeProps(cmAny));
}
break;
}
var cm = _mi.FindClassMapping(typeName);
outputProps.Types.Add(new NodeProps(cm));
}
}
else
{
// System.Diagnostics.Trace.WriteLine($"No types specified");
// Type not listed, so just enumerate ALL resources
foreach (var typeName in _supportedResources)
{
var cm = _mi.FindClassMapping(typeName);
outputProps.Types.Add(new NodeProps(cm));
}
}
// outputProps.Types.Add(t);
}
}
else if (function.FunctionName == "children")
{
// Check the supported reference types for this resource type
foreach (var t in focus.Types)
{
// walk through all the child properties
foreach (var p in t.ClassMapping.PropertyMappings)
{
outputProps.Types.Add(new NodeProps(p.PropertyTypeMapping, p));
}
}
}
else if (fd == null) // only warn if we didn't have a symbol table entry
{
var issue = new Hl7.Fhir.Model.OperationOutcome.IssueComponent()
{
Severity = Hl7.Fhir.Model.OperationOutcome.IssueSeverity.Warning,
Code = Hl7.Fhir.Model.OperationOutcome.IssueType.NotSupported,
Details = new Hl7.Fhir.Model.CodeableConcept() { Text = $"Unhandled function '{function.FunctionName}'" }
};
ReportErrorLocation(function, issue);
Outcome.AddIssue(issue);
}
if (function.FunctionName == "exists")
{
if (props.FirstOrDefault() != null && props.FirstOrDefault()?.ToString() != "boolean")
{
var issue = new Hl7.Fhir.Model.OperationOutcome.IssueComponent()
{
Severity = Hl7.Fhir.Model.OperationOutcome.IssueSeverity.Error,
Code = Hl7.Fhir.Model.OperationOutcome.IssueType.Invalid,
Details = new Hl7.Fhir.Model.CodeableConcept() { Text = $"{function.FunctionName} must have a boolean first argument, detected {props.FirstOrDefault()}" }
};
ReportErrorLocation(function, issue);
Outcome.AddIssue(issue);
}
}
if (function.FunctionName == "defineVariable")
{
var definedVariableResultType = focus;
if (props.Count() >= 2)
{
definedVariableResultType = props.Skip(1).FirstOrDefault();
}
// evaluate the first parameter as the name of the string
try
{
var cf = new FhirPathCompiler().Compile(function.Arguments.First());
var nv = cf(null, new FhirEvaluationContext());
if (nv.ToFhirValues()?.FirstOrDefault() is FhirString fs)
{
if (definedVariables.ContainsKey(fs.Value))
definedVariables[fs.Value] = definedVariableResultType;
else
definedVariables.Add(fs.Value, definedVariableResultType);
}
}
catch (Exception ex)
{
// Evaluation of the expression failed - this is typically a static string, so we can evalulate it,
// if not will fail, and we'll just continue and not know what type this is
_dynamicDefinedVariableInScope = true;
var issue = new Hl7.Fhir.Model.OperationOutcome.IssueComponent()
{
Severity = Hl7.Fhir.Model.OperationOutcome.IssueSeverity.Information,
Code = Hl7.Fhir.Model.OperationOutcome.IssueType.Informational,
Details = new Hl7.Fhir.Model.CodeableConcept() { Text = $"Dynamic {function.FunctionName} name argument unable to determine the variable type" }
};
ReportErrorLocation(function, issue);
Outcome.AddIssue(issue);
}
}
if (booleanArgFuncs.Contains(function.FunctionName))
{
if (props.FirstOrDefault()?.ToString() != "boolean")
{
var issue = new Hl7.Fhir.Model.OperationOutcome.IssueComponent()
{
Severity = Hl7.Fhir.Model.OperationOutcome.IssueSeverity.Error,
Code = Hl7.Fhir.Model.OperationOutcome.IssueType.Invalid,
Details = new Hl7.Fhir.Model.CodeableConcept() { Text = $"{function.FunctionName} must have a boolean first argument, detected {props.FirstOrDefault()}" }
};
ReportErrorLocation(function, issue);
Outcome.AddIssue(issue);
}
}
}
public override FhirPathVisitorProps VisitFunctionCall(FunctionCallExpression expression)
{
var result = new FhirPathVisitorProps();
if (expression is BinaryExpression be)
{
VisitBinaryExpression(expression, result, be);
AppendLine($": {result.TypeNames()} // op: {be.Op}");
return result;
}
var rFocus = expression.Focus.Accept(this);
_stackPropertyContext.Push(rFocus);
if (expression is IndexerExpression)
{
VisitIndexerExpression(expression, result, rFocus);
_stackPropertyContext.Pop();
return result;
}
if (expression is ChildExpression ce)
{
VisitChildExpression(expression, result, rFocus, ce);
Append($"{ce.ChildName}");
AppendLine($" : {result.TypeNames()}");
_stackPropertyContext.Pop();
return result;
}
if (!rFocus.isRoot)
Append(".");
Append($"{expression.FunctionName}(");
if (expression.FunctionName == "combine" || expression.FunctionName == "union")
{
VisitCombineOrUnionFunction(rFocus, expression, result);
Append(")");
AppendLine($" : {result.TypeNames()} // {expression.FunctionName}");
_stackPropertyContext.Pop();
return result;
}
if (expressionFuncs.Contains(expression.FunctionName))
{
if (expression.FunctionName == "select"
|| expression.FunctionName == "where"
|| expression.FunctionName == "exists"
|| expression.FunctionName == "aggregate"
|| expression.FunctionName == "all")
{
// Push them onto the stack without the collection as we're processing them individually
var rFocusSingle = rFocus.AsSingle();
_stackExpressionContext.Push(rFocusSingle);
}
else
{
_stackExpressionContext.Push(rFocus);
}
}
if (expression.FunctionName == "repeat")
{
VisitRepeatFunction(expression, result);
_stackPropertyContext.Pop();
_stackExpressionContext.Pop();
return result;
}
if (expression.FunctionName == "aggregate")
{
if (expression.Arguments.Any())
AppendLine();
IncrementTab();
VisitAggregateFunction(expression, result);
_stackExpressionContext.Pop();
DecrementTab();
Append(")");
AppendLine($" : {result.TypeNames()} // {expression.FunctionName}");
return result;
}
IncrementTab();
if (expression.Arguments.Any())
AppendLine();
List<FhirPathVisitorProps> argTypes = new();
foreach (var arg in expression.Arguments)
{
if (argTypes.Count > 0)
Append(", ");
argTypes.Add(arg.Accept(this));
}
DecrementTab();
Append(")");
DeduceReturnType(expression, rFocus, argTypes, result);
if (expressionFuncs.Contains(expression.FunctionName))
{
_stackExpressionContext.Pop();
}
if (expression.Arguments.Any())
AppendLine($" : {result.TypeNames()} // {expression.FunctionName}(...)");
else
AppendLine($" : {result.TypeNames()}");
_stackPropertyContext.Pop();
return result;
}
private void VisitRepeatFunction(FunctionCallExpression expression, FhirPathVisitorProps result)
{
_repeatChildren = new Dictionary<ChildExpression, OperationOutcome.IssueComponent>();
// Special handling for repeat,
// iteratively select types using the expressions we
// work out if all the names are actually possible
List<FhirPathVisitorProps> argTypesR = new();
foreach (var arg in expression.Arguments)
{
if (argTypesR.Count > 0)
Append(", ");
argTypesR.Add(arg.Accept(this));
foreach (var t in argTypesR)
{
foreach (var t2 in t.Types)
if (!result.Types.Contains(t2))
result.Types.Add(t2);
}
}
// Now iterate in with these result types
_stackPropertyContext.Push(result);
_stackExpressionContext.Push(result);
bool bChanged = false;
int maxIterations = 10;
do
{
bChanged = false;
maxIterations--;
foreach (var arg in expression.Arguments)
{
Append(", ");
argTypesR.Add(arg.Accept(this));
foreach (var t in argTypesR)
{
foreach (var t2 in t.Types)
if (!result.Types.Any(t => t.ClassMapping == t2.ClassMapping))
{
result.Types.Add(t2);
bChanged = true;
}
}
}
}
while (bChanged && maxIterations > 0);
if (maxIterations == 0)
{
var issue = new Hl7.Fhir.Model.OperationOutcome.IssueComponent()
{
Severity = Hl7.Fhir.Model.OperationOutcome.IssueSeverity.Error,
Code = Hl7.Fhir.Model.OperationOutcome.IssueType.NotFound,
Details = new Hl7.Fhir.Model.CodeableConcept() { Text = $"repeat() iterations exceeded 10" }
};
Outcome.AddIssue(issue);
}
_stackPropertyContext.Pop();
_stackExpressionContext.Pop();
if (_repeatChildren != null)
{
foreach (var iss in _repeatChildren.Values.Where(v => v != null))
{
Outcome.Issue.Add(iss);
}
_repeatChildren = null;
}
}
private void VisitAggregateFunction(FunctionCallExpression expression, FhirPathVisitorProps result)
{
// Special handling for aggregate as needs to evaluate what type $total is based on iteration
// Begin with type of second argument
// then actual type is the result of the 1st argument expression
int countArgs = expression.Arguments.Count();
if (countArgs == 0)
{
// error
var issue = new Hl7.Fhir.Model.OperationOutcome.IssueComponent()
{
Severity = Hl7.Fhir.Model.OperationOutcome.IssueSeverity.Error,
Code = Hl7.Fhir.Model.OperationOutcome.IssueType.Invalid,
Details = new Hl7.Fhir.Model.CodeableConcept() { Text = $"aggregate() requires parameters '(aggregator : expression [, init : value]', none provided" }
};
Outcome.AddIssue(issue);
return;
}
if (countArgs > 2)
{
// error
var issue = new Hl7.Fhir.Model.OperationOutcome.IssueComponent()
{
Severity = Hl7.Fhir.Model.OperationOutcome.IssueSeverity.Error,
Code = Hl7.Fhir.Model.OperationOutcome.IssueType.Invalid,