-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathCSharpFirely2.cs
More file actions
3847 lines (3200 loc) · 154 KB
/
CSharpFirely2.cs
File metadata and controls
3847 lines (3200 loc) · 154 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
// <copyright file="CSharpFirely2.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// </copyright>
using System.Diagnostics.CodeAnalysis;
using Hl7.Fhir.Model;
using Hl7.Fhir.Utility;
using Microsoft.Health.Fhir.CodeGen.FhirExtensions;
using Microsoft.Health.Fhir.CodeGen.Models;
using Microsoft.Health.Fhir.CodeGen.Utils;
using Microsoft.Health.Fhir.CodeGenCommon.FhirExtensions;
using Microsoft.Health.Fhir.CodeGenCommon.Models;
using Microsoft.Health.Fhir.CodeGenCommon.Packaging;
using Microsoft.Health.Fhir.CodeGenCommon.Utils;
using Ncqa.Cql.Model;
using static Microsoft.Health.Fhir.CodeGen.Language.Firely.CSharpFirelyCommon;
using static Microsoft.Health.Fhir.CodeGenCommon.Extensions.FhirNameConventionExtensions;
#if NETSTANDARD2_0
using Microsoft.Health.Fhir.CodeGenCommon.Polyfill;
#endif
namespace Microsoft.Health.Fhir.CodeGen.Language.Firely;
public sealed class CSharpFirely2 : ILanguage, IFileHashTestable
{
private bool _generateHashesInsteadOfOutput = false;
bool IFileHashTestable.GenerateHashesInsteadOfOutput
{
get => _generateHashesInsteadOfOutput;
set => _generateHashesInsteadOfOutput = value;
}
private readonly Dictionary<string, string> _fileHashes = [];
Dictionary<string, string> IFileHashTestable.FileHashes => _fileHashes;
/// <summary>(Immutable) Name of the language.</summary>
private const string LanguageName = "CSharpFirely2";
/// <summary>Gets the language name.</summary>
public string Name => LanguageName;
public Type ConfigType => typeof(FirelyGenOptions);
/// <summary>Gets a value indicating whether this language is idempotent.</summary>
public bool IsIdempotent => false;
/// <summary>The namespace to use during export.</summary>
private const string Namespace = "Hl7.Fhir.Model";
/// <summary>FHIR information we are exporting.</summary>
private DefinitionCollection _info = null!;
/// <summary>Options for controlling the export.</summary>
private FirelyGenOptions _options = null!;
/// <summary>Keep track of information about written value sets.</summary>
private Dictionary<string, WrittenValueSetInfo> _writtenValueSets = [];
/// <summary>The split characters.</summary>
private static readonly char[] _splitChars = ['|', ' '];
/// <summary>The currently in-use text writer.</summary>
private ExportStreamWriter _writer = null!;
/// <summary>The model writer.</summary>
private ExportStreamWriter _modelWriter = null!;
/// <summary>Pathname of the export directory.</summary>
private string _exportDirectory = string.Empty;
/// <summary>Structures to skip generating.</summary>
internal static readonly HashSet<string> ExclusionSet =
[
/* These two types are generated as interfaces, so require special handling and
* are not to be treated as normal resources. */
"CanonicalResource",
"MetadataResource",
/* UCUM is used as a required binding in a codeable concept. Since we do not
* use enums in this situation, it is not useful to generate this valueset
*/
"http://hl7.org/fhir/ValueSet/ucum-units",
/* R5 made Resource.language a required binding to all-languages, which contains
* all of bcp:47 and is listed as infinite. This is not useful to generate.
* Note that in R5, many elements that are required to all-languages also have bound
* starter value sets. TODO: consider if we want to generate constants for those.
*/
"http://hl7.org/fhir/ValueSet/all-languages",
/* MIME types are infinite, so we do not want to generate these.
* Note that in R5, many elements that are required to MIME type also have bound
* starter value sets. TODO: consider if we want to generate constants for those.
*/
"http://hl7.org/fhir/ValueSet/mimetypes",
];
private static readonly Dictionary<(string,string), VersionIndependentResourceTypesAll> _searchParamDefsTargetRemovals = new()
{
[("DiagnosticReport", "encounter")] = VersionIndependentResourceTypesAll.EpisodeOfCare,
[("RiskAssessment", "encounter")] = VersionIndependentResourceTypesAll.EpisodeOfCare,
[("List", "encounter")] = VersionIndependentResourceTypesAll.EpisodeOfCare,
[("VisionPrescription", "encounter")] = VersionIndependentResourceTypesAll.EpisodeOfCare,
[("ServiceRequest", "encounter")] = VersionIndependentResourceTypesAll.EpisodeOfCare,
[("Flag", "encounter")] = VersionIndependentResourceTypesAll.EpisodeOfCare,
[("Observation", "encounter")] = VersionIndependentResourceTypesAll.EpisodeOfCare,
[("NutritionOrder", "encounter")] = VersionIndependentResourceTypesAll.EpisodeOfCare,
[("Composition", "encounter")] = VersionIndependentResourceTypesAll.EpisodeOfCare,
[("DeviceRequest", "encounter")] = VersionIndependentResourceTypesAll.EpisodeOfCare,
[("Procedure", "encounter")] = VersionIndependentResourceTypesAll.EpisodeOfCare,
};
/// <summary>
/// List of types introduced in R5 that are retrospectively introduced in R3 and R4.
/// </summary>
internal static readonly List<WrittenModelInfo> SharedR5DataTypes =
[
new("BackboneType", "BackboneType", true),
new("Base", "Base",true),
new("DataType", "DataType", true),
new("PrimitiveType", "PrimitiveType", true),
];
/// <summary>
/// List of complex datatype classes that are part of the 'base' subset. See <see cref="GenSubset"/>.
/// </summary>
private static readonly List<string> _baseSubsetComplexTypes =
[
"Address",
"Attachment",
"BackboneElement",
"BackboneType",
"Base",
"CodeableConcept",
"Coding",
"ContactPoint",
"ContactDetail",
"DataType",
"Duration",
"Element",
"Extension",
"HumanName",
"Identifier",
"Meta",
"Narrative",
"Period",
"PrimitiveType",
"Quantity",
"Range",
"Ratio",
"Reference",
"Signature",
"UsageContext",
"CodeableReference"
];
/// <summary>
/// List of complex datatype classes that are part of the 'conformance' subset. See <see cref="GenSubset"/>.
/// </summary>
private static readonly List<string> _conformanceSubsetComplexTypes =
[
"ElementDefinition",
"RelatedArtifact",
];
/// <summary>
/// List of resource classes that are part of the 'base' subset. See <see cref="GenSubset"/>.
/// </summary>
private static readonly List<string> _baseSubsetResourceTypes =
[
"Binary",
"Bundle",
"DomainResource",
"OperationOutcome",
"Parameters",
"Resource",
];
/// <summary>
/// List of resource classes that are part of the 'conformance' subset. See <see cref="GenSubset"/>.
/// </summary>
private static readonly List<string> _conformanceSubsetResourceTypes =
[
"CapabilityStatement",
"CodeSystem",
"ElementDefinition",
"StructureDefinition",
"ValueSet",
];
/// <summary>
/// List of all valuesets that we publish in the base subset
/// </summary>
private static readonly HashSet<string> _baseSubsetValueSets =
[
"http://hl7.org/fhir/ValueSet/publication-status",
"http://hl7.org/fhir/ValueSet/FHIR-version",
"http://hl7.org/fhir/ValueSet/search-param-type",
"http://hl7.org/fhir/ValueSet/filter-operator",
"http://hl7.org/fhir/ValueSet/version-independent-all-resource-types"
];
/// <summary>
/// List of all valuesets that we publish in the conformance subset.
/// </summary>
private static readonly HashSet<string> _conformanceSubsetValueSets =
[
"http://hl7.org/fhir/ValueSet/capability-statement-kind",
"http://hl7.org/fhir/ValueSet/binding-strength",
// These are necessary for CapabilityStatement/CapabilityStatement2
// CapStat2 has disappeared in ballot, if that becomes final,
// these don't have to be created as shared valuesets anymore.
"http://hl7.org/fhir/ValueSet/restful-capability-mode",
"http://hl7.org/fhir/ValueSet/type-restful-interaction",
"http://hl7.org/fhir/ValueSet/system-restful-interaction",
// For these valuesets the algorithm to determine whether a vs is shared
// is still considering core extensions too. When this is corrected,
// these can probably go.
"http://hl7.org/fhir/ValueSet/constraint-severity",
"http://hl7.org/fhir/ValueSet/codesystem-content-mode"
];
/// <summary>
/// List of all valuesets that we should publish as a shared Enum although there is only 1 reference to it.
/// </summary>
internal static readonly List<(string, string)> ExplicitSharedValueSets =
[
// This enum should go to Template-binding.cs because otherwise it will introduce a breaking change.
("R4", "http://hl7.org/fhir/ValueSet/messageheader-response-request"),
("R4", "http://hl7.org/fhir/ValueSet/concept-map-equivalence"),
("R4B", "http://hl7.org/fhir/ValueSet/messageheader-response-request"),
("R4B", "http://hl7.org/fhir/ValueSet/concept-map-equivalence"),
("R5", "http://hl7.org/fhir/ValueSet/constraint-severity"),
];
/// <summary>Gets the reserved words.</summary>
/// <value>The reserved words.</value>
private static readonly HashSet<string> _reservedWords = [];
private static readonly Func<WrittenModelInfo, bool> _supportedResourcesFilter = wmi => !wmi.IsAbstract;
private static readonly Func<WrittenModelInfo, bool> _fhirToCsFilter = wmi => !_excludeFromCsToFhir!.Contains(wmi.FhirName);
private static readonly Func<WrittenModelInfo, bool> _csToStringFilter = _fhirToCsFilter;
private static readonly string[] _excludeFromCsToFhir =
[
"CanonicalResource",
"MetadataResource",
];
/// <summary>
/// The list of elements that would normally be represented using a CodeOfT enum, but that we
/// want to be generated as a normal Code instead.
/// </summary>
private static readonly List<string> _codedElementOverrides =
[
"CapabilityStatement.rest.resource.type"
];
/// <summary>
/// Some valuesets have names that are the same as element names or are just not nice - use this collection
/// to change the name of the generated enum as required.
/// </summary>
internal static readonly Dictionary<string, string> EnumNamesOverride = new()
{
["http://hl7.org/fhir/ValueSet/characteristic-combination"] = "CharacteristicCombinationCode",
["http://hl7.org/fhir/ValueSet/claim-use"] = "ClaimUseCode",
["http://hl7.org/fhir/ValueSet/content-type"] = "ContentTypeCode",
["http://hl7.org/fhir/ValueSet/exposure-state"] = "ExposureStateCode",
["http://hl7.org/fhir/ValueSet/verificationresult-status"] = "StatusCode",
["http://terminology.hl7.org/ValueSet/v3-Confidentiality"] = "ConfidentialityCode",
["http://hl7.org/fhir/ValueSet/variable-type"] = "VariableTypeCode",
["http://hl7.org/fhir/ValueSet/group-measure"] = "GroupMeasureCode",
["http://hl7.org/fhir/ValueSet/coverage-kind"] = "CoverageKindCode",
["http://hl7.org/fhir/ValueSet/fhir-types"] = "FHIRAllTypes"
};
private record ElementTypeChange(FhirReleases.FhirSequenceCodes Since,
TypeReference DeclaredTypeReference);
private static readonly ElementTypeChange[] _stringToMarkdown =
[
new(FhirReleases.FhirSequenceCodes.STU3, PrimitiveTypeReference.String),
new(FhirReleases.FhirSequenceCodes.R5, PrimitiveTypeReference.Markdown)
];
/// <summary>
/// Given one of the versions, returns a string that describes from which version until which
/// version that change was in effect.
/// </summary>
private static string VersionChangeMessage(ElementTypeChange[] changeSet, ElementTypeChange thisChange, bool capitalize)
{
int index = Array.IndexOf(changeSet, thisChange);
if (index == -1) throw new ArgumentException("Change needs to be part of the set", nameof(thisChange));
if (index + 1 >= changeSet.Length)
{
// This is the last change in the set
return $"{(capitalize ? "S" : "s")}tarting from {thisChange.Since}";
}
int now = (int)thisChange.Since;
int next = (int)changeSet[index + 1].Since;
IEnumerable<FhirReleases.FhirSequenceCodes> versionOrdinals =
Enumerable.Range(now, next - now).Cast<FhirReleases.FhirSequenceCodes>();
string versions = string.Join(", ", versionOrdinals.Select(v => v.ToString()));
versions = replaceLastOccurrence(versions, ", ", " and ");
return $"{(capitalize ? "I" : "i")}n {versions}";
static string replaceLastOccurrence(string source, string find, string replace)
{
int place = source.LastIndexOf(find, StringComparison.Ordinal);
if (place == -1)
return source;
return source.Remove(place, find.Length).Insert(place, replace);
}
}
// ReSharper disable ArrangeObjectCreationWhenTypeNotEvident
private static readonly Dictionary<string, ElementTypeChange[]> _elementTypeChanges = new()
{
["Attachment.size"] = [
new(FhirReleases.FhirSequenceCodes.STU3, PrimitiveTypeReference.UnsignedInt),
new (FhirReleases.FhirSequenceCodes.R5, PrimitiveTypeReference.Integer64),
],
["Attachment.url"] = [
new(FhirReleases.FhirSequenceCodes.STU3, PrimitiveTypeReference.Uri),
new(FhirReleases.FhirSequenceCodes.R4, PrimitiveTypeReference.Url),
],
["Meta.profile"] = [
new(FhirReleases.FhirSequenceCodes.STU3, PrimitiveTypeReference.Uri),
new(FhirReleases.FhirSequenceCodes.R4, PrimitiveTypeReference.Canonical),
],
["Bundle.link.relation"] = [
new(FhirReleases.FhirSequenceCodes.STU3, PrimitiveTypeReference.String),
new(FhirReleases.FhirSequenceCodes.R5, PrimitiveTypeReference.Code)
],
["ElementDefinition.constraint.requirements"] = _stringToMarkdown,
["ElementDefinition.binding.description"] = _stringToMarkdown,
["ElementDefinition.mapping.comment"] = _stringToMarkdown,
["CapabilityStatement.implementation.description"] = _stringToMarkdown,
};
// ReSharper restore ArrangeObjectCreationWhenTypeNotEvident
private readonly Dictionary<string, string> _sinceAttributes = new()
{
["Meta.source"] = "R4",
["Reference.type"] = "R4",
["Bundle.timestamp"] = "R4",
["Binary.data"] = "R4",
["ValueSet.compose.property"] = "R5",
["ValueSet.compose.include.copyright"] = "R5",
["ValueSet.expansion.property"] = "R5",
["ValueSet.expansion.contains.property"] = "R5",
["ValueSet.scope"] = "R5",
["Bundle.issues"] = "R5",
["CapabilityStatement.rest.resource.conditionalPatch"] = "R5",
["CapabilityStatement.versionAlgorithm"] = "R5",
["CapabilityStatement.copyrightLabel"] = "R5",
["CapabilityStatement.acceptLanguage"] = "R5",
["CapabilityStatement.identifier"] = "R5",
["CodeSystem.concept.designation.additionalUse"] = "R5",
["CodeSystem.approvalDate"] = "R5",
["CodeSystem.lastReviewDate"] = "R5",
["CodeSystem.effectivePeriod"] = "R5",
["CodeSystem.topic"] = "R5",
["CodeSystem.author"] = "R5",
["CodeSystem.editor"] = "R5",
["CodeSystem.reviewer"] = "R5",
["CodeSystem.endorser"] = "R5",
["CodeSystem.relatedArtifact"] = "R5",
["CodeSystem.copyrightLabel"] = "R5",
["CodeSystem.versionAlgorithm"] = "R5",
["ElementDefinition.constraint.suppress"] = "R5",
["ElementDefinition.mustHaveValue"] = "R5",
["ElementDefinition.valueAlternatives"] = "R5",
["ElementDefinition.obligation"] = "R5",
["ElementDefinition.obligation.code"] = "R5",
["ElementDefinition.obligation.actor"] = "R5",
["ElementDefinition.obligation.documentation"] = "R5",
["ElementDefinition.obligation.usage"] = "R5",
["ElementDefinition.obligation.filter"] = "R5",
["ElementDefinition.obligation.filterDocumentation"] = "R5",
["ElementDefinition.obligation.process"] = "R5",
["ElementDefinition.binding.additional"] = "R5",
["ElementDefinition.binding.additional.purpose"] = "R5",
["ElementDefinition.binding.additional.valueSet"] = "R5",
["ElementDefinition.binding.additional.documentation"] = "R5",
["ElementDefinition.binding.additional.shortDoco"] = "R5",
["ElementDefinition.binding.additional.usage"] = "R5",
["ElementDefinition.binding.additional.any"] = "R5",
["StructureDefinition.versionAlgorithm"] = "R5",
["StructureDefinition.copyrightLabel"] = "R5",
["ValueSet.compose.include.concept.designation.additionalUse"] = "R5",
["ValueSet.expansion.next"] = "R5",
["ValueSet.expansion.contains.property.subProperty"] = "R5",
["ValueSet.expansion.contains.property.subProperty.code"] = "R5",
["ValueSet.expansion.contains.property.subProperty.value"] = "R5",
["ValueSet.approvalDate"] = "R5",
["ValueSet.lastReviewDate"] = "R5",
["ValueSet.effectivePeriod"] = "R5",
["ValueSet.topic"] = "R5",
["ValueSet.author"] = "R5",
["ValueSet.editor"] = "R5",
["ValueSet.reviewer"] = "R5",
["ValueSet.endorser"] = "R5",
["ValueSet.relatedArtifact"] = "R5",
["ValueSet.copyrightLabel"] = "R5",
["ValueSet.versionAlgorithm"] = "R5",
["Attachment.height"] = "R5",
["Attachment.width"] = "R5",
["Attachment.frames"] = "R5",
["Attachment.duration"] = "R5",
["Attachment.pages"] = "R5",
["RelatedArtifact.classifier"] = "R5",
["RelatedArtifact.resourceReference"] = "R5",
["RelatedArtifact.publicationStatus"] = "R5",
["RelatedArtifact.publicationDate"] = "R5",
["Signature.data"] = "R4",
["Signature.who"] = "R4",
["Signature.onBehalfOf"] = "R4",
["Signature.sigFormat"] = "R4",
["Signature.targetFormat"] = "R4"
};
private readonly Dictionary<string, (string since, string newName)> _untilAttributes = new()
{
["Binary.content"] = ("R4", "Binary.data"),
["ElementDefinition.constraint.xpath"] = ("R5", ""),
["ValueSet.scope.focus"] = ("R5", ""),
["RelatedArtifact.url"] = ("R5", ""),
["Signature.blob"] = ("R4", "Signature.data"),
["Signature.contentType"] = ("R4", "")
};
private static string? GetExplicitName(ElementDefinition ed, FhirReleases.FhirSequenceCodes sequence) =>
(ed.Path, sequence) switch
{
("Evidence.statistic.attributeEstimate.attributeEstimate", _) => "AttributeEstimate",
("Citation.citedArtifact.contributorship.summary", _) => "CitedArtifactContributorshipSummary",
("Measure.group", FhirReleases.FhirSequenceCodes.R6) => "GroupBackboneComponent",
("Measure.group.component", FhirReleases.FhirSequenceCodes.R6) => "GroupComponent",
("Measure.group.stratifier.component", FhirReleases.FhirSequenceCodes.R6) => "GroupStratifierComponent",
("MolecularDefinition.location.sequenceLocation.coordinateInterval", FhirReleases.FhirSequenceCodes.R6) =>
"LocationSequenceLocationCoordinateIntervalComponent",
("MolecularDefinition.location.sequenceLocation.coordinateInterval.coordinateSystem", FhirReleases.FhirSequenceCodes.R6) =>
"LocationSequenceLocationCoordinateIntervalCoordinateSystemComponent",
("MolecularDefinition.representation.extracted.coordinateInterval", FhirReleases.FhirSequenceCodes.R6) =>
"RepresentationExtractedCoordinateIntervalComponent",
("MolecularDefinition.representation.extracted.coordinateInterval.coordinateSystem", FhirReleases.FhirSequenceCodes.R6) =>
"RepresentationExtractedCoordinateIntervalCoordinateSystemComponent",
("MolecularDefinition.representation.relative.edit.coordinateInterval", FhirReleases.FhirSequenceCodes.R6) =>
"RepresentationRelativeEditCoordinateIntervalComponent",
("MolecularDefinition.representation.relative.edit.coordinateInterval.coordinateSystem", FhirReleases.FhirSequenceCodes.R6) =>
"RepresentationRelativeEditCoordinateIntervalCoordinateSystemComponent",
("TestPlan.scope", FhirReleases.FhirSequenceCodes.R6) => "ScopeComponent",
("TestPlan.testCase.scope", FhirReleases.FhirSequenceCodes.R6) => "TestCaseScopeComponent",
_ => ed.cgExplicitName()
};
/// <summary>True to export five ws.</summary>
private bool _exportFiveWs = true;
/// <summary>Gets the FHIR primitive type map.</summary>
/// <value>The FHIR primitive type map.</value>
Dictionary<string, string> ILanguage.FhirPrimitiveTypeMap => PrimitiveTypeMap;
/// <summary>If a Cql ModelInfo is available, this will be the parsed XML model file.</summary>
private Ncqa.Cql.Model.ModelInfo? _cqlModelInfo = null;
private IDictionary<string, Ncqa.Cql.Model.ClassInfo>? _cqlModelClassInfo = null;
/// <summary>Export the passed FHIR version into the specified directory.</summary>
/// <param name="untypedOptions"></param>
/// <param name="info"> The information.</param>
public void Export(object untypedOptions, DefinitionCollection info)
{
if (untypedOptions is not FirelyGenOptions options)
{
throw new ArgumentException("Options must be of type FirelyGenOptions");
}
var subset = options.Subset;
// STU3 satellite is a combination of satellite and conformance
if ((info.FhirSequence == FhirReleases.FhirSequenceCodes.STU3) &&
(subset == GenSubset.Satellite))
{
subset = GenSubset.Satellite | GenSubset.Conformance;
}
// By definition, we should not have any element type changes for sattelites, they
// should only have their own, defined types from the spec.
if (subset.HasFlag(GenSubset.Satellite))
_elementTypeChanges.Clear();
// only generate base definitions for R5
if (subset.HasFlag(GenSubset.Base) &&
info.FhirSequence is not (FhirReleases.FhirSequenceCodes.R6 or FhirReleases.FhirSequenceCodes.R5))
{
Console.WriteLine($"Aborting {LanguageName} for {info.FhirSequence}: code generation for the 'base' subset should be run on R5/R6 only.");
return;
}
// conformance subset is only valid for STU3 and R5
if (subset.HasFlag(GenSubset.Conformance) &&
info.FhirSequence is not (FhirReleases.FhirSequenceCodes.STU3 or
FhirReleases.FhirSequenceCodes.R5 or FhirReleases.FhirSequenceCodes.R6))
{
Console.WriteLine($"Aborting {LanguageName} for {info.FhirSequence}: code generation for the 'conformance' subset should be run on STU3 or R5/R6 only.");
return;
}
_exportFiveWs = options.ExportFiveWs;
// set internal vars so we don't pass them to every function
_info = info;
_options = options;
_exportDirectory = options.OutputDirectory;
_writtenValueSets = [];
if (!Directory.Exists(_exportDirectory))
{
Directory.CreateDirectory(_exportDirectory);
}
if (!Directory.Exists(Path.Combine(_exportDirectory, "Generated")))
{
Directory.CreateDirectory(Path.Combine(_exportDirectory, "Generated"));
}
string cqlModelResourceKey = options.CqlModel;
if (!string.IsNullOrEmpty(cqlModelResourceKey))
{
_cqlModelInfo = CqlModels.LoadEmbeddedResource(cqlModelResourceKey);
_cqlModelClassInfo = CqlModels.ClassesByName(_cqlModelInfo);
}
var allPrimitives = new Dictionary<string, WrittenModelInfo>();
var allComplexTypes = new Dictionary<string, WrittenModelInfo>();
var allResources = new Dictionary<string, WrittenModelInfo>();
var dummy = new Dictionary<string, WrittenModelInfo>();
string infoFilename = Path.Combine(_exportDirectory, "Generated", "_GeneratorLog.cs");
// update the models for consistency across different versions of FHIR
ModifyDefinitionsForConsistency();
using Stream infoStream = _generateHashesInsteadOfOutput
? new MemoryStream()
: new FileStream(infoFilename, FileMode.Create);
using ExportStreamWriter infoWriter = new(infoStream);
if (_generateHashesInsteadOfOutput)
{
infoWriter.NewLine = "\r\n";
}
_modelWriter = infoWriter;
WriteGenerationComment(infoWriter);
if (options.ExportStructures.Contains(FhirArtifactClassEnum.ValueSet))
{
WriteSharedValueSets(subset);
}
_modelWriter.WriteLineIndented("// Generated items");
if (options.ExportStructures.Contains(FhirArtifactClassEnum.PrimitiveType))
{
WritePrimitiveTypes(_info.PrimitiveTypesByName.Values, ref dummy, subset);
}
AddModels(allPrimitives, _info.PrimitiveTypesByName.Values);
if (options.ExportStructures.Contains(FhirArtifactClassEnum.ComplexType))
{
WriteComplexDataTypes(_info.ComplexTypesByName.Values, ref dummy, subset);
}
AddModels(allComplexTypes, _info.ComplexTypesByName.Values);
AddModels(allComplexTypes, SharedR5DataTypes);
if (options.ExportStructures.Contains(FhirArtifactClassEnum.Resource))
{
WriteResources(_info.ResourcesByName.Values, ref dummy, subset);
}
AddModels(allResources, _info.ResourcesByName.Values);
if (options.ExportStructures.Contains(FhirArtifactClassEnum.Interface))
{
WriteInterfaces(_info.InterfacesByName.Values, ref dummy, subset);
}
if (subset.HasFlag(GenSubset.Satellite))
{
WriteModelInfo(allPrimitives, allComplexTypes, allResources);
}
if (_generateHashesInsteadOfOutput)
{
infoWriter.Flush();
// generate the hash
string hash = FileSystemUtils.GenerateSha256(infoStream);
_fileHashes.Add(infoFilename[_exportDirectory.Length..], hash);
infoWriter.Close();
}
else
{
infoWriter.Flush();
infoWriter.Close();
}
}
/// <summary>
/// Modifies the definition structures for consistency. Note that this makes the export *not* idempotent.
/// </summary>
private void ModifyDefinitionsForConsistency()
{
// We need to modify the (R4+-based) definition of Binary, to include
// the pre-R4 element "content".
if (_info.ResourcesByName.TryGetValue("Binary", out StructureDefinition? sdBinary))
{
if (!sdBinary.cgTryGetElementByPath("Binary.content", out _) &&
sdBinary.cgTryGetElementByPath("Binary.data", out ElementDefinition? edData))
{
// make a copy of the data element
ElementDefinition edContent = (ElementDefinition)edData.DeepCopy();
// update the copied element to be the content element
edContent.ElementId = "Binary.content";
edContent.Path = "Binary.content";
edContent.Base = new ElementDefinition.BaseComponent { Path = "Binary.content", Min = 0, Max = "1" };
edContent.cgSetFieldOrder(edData.cgFieldOrder(), edData.cgComponentFieldOrder());
// add our element and track info, note that we are not increasing
// the orders since they are duplicate elements from different versions
_ = _info.TryInsertElement(sdBinary, edContent, false);
}
}
// We need to modify the definition of Signature, to include
// the STU3 content.
if (_info.ComplexTypesByName.TryGetValue("Signature", out StructureDefinition? sdSignature))
{
if (!sdSignature.cgTryGetElementByPath("Signature.blob", out _) &&
sdSignature.cgTryGetElementByPath("Signature.data", out ElementDefinition? edData))
{
// make a copy of the data element
ElementDefinition edBlob = (ElementDefinition)edData.DeepCopy();
// update the copied element to be the blob element
edBlob.ElementId = "Signature.blob";
edBlob.Path = "Signature.blob";
edBlob.Base = new() { Path = "Signature.blob", Min = 0, Max = "1" };
edBlob.Min = 0;
edBlob.Max = "1";
edBlob.cgSetFieldOrder(edData.cgFieldOrder(), edData.cgComponentFieldOrder());
//edBlob.RemoveExtension(CommonDefinitions.ExtUrlEdFieldOrder);
//edBlob.RemoveExtension(CommonDefinitions.ExtUrlEdComponentFieldOrder);
//edBlob.AddExtension(CommonDefinitions.ExtUrlEdFieldOrder, new Integer(edData.cgFieldOrder() + 1));
//edBlob.AddExtension(CommonDefinitions.ExtUrlEdComponentFieldOrder, new Integer(edData.cgComponentFieldOrder() + 1));
// add our element and track info
_ = _info.TryInsertElement(sdSignature, edBlob, false);
}
if (!sdSignature.cgTryGetElementByPath("Signature.contentType", out ElementDefinition? edContentType))
{
// create a new element for the contentType (values pulled from STU3)
edContentType = new()
{
ElementId = "Signature.contentType",
Path = "Signature.contentType",
Short = "The technical format of the signature",
Definition = "A mime type that indicates the technical format of the signature. Important mime types are application/signature+xml for X ML DigSig, application/jwt for JWT, and image/* for a graphical image of a signature, etc.",
Min = 0,
Max = "1",
Base = new() { Path = "Signature.contentType", Min = 0, Max = "1" },
Type = [new() { Code = "code" }],
IsSummary = true,
Binding = new()
{
Strength = Hl7.Fhir.Model.BindingStrength.Required,
ValueSet = new Canonical("http://www.rfc-editor.org/bcp/bcp13.txt"),
Description = "The mime type of an attachment. Any valid mime type is allowed.",
Extension =
[
new()
{
Url = CommonDefinitions.ExtUrlBindingName,
Value = new FhirString("MimeType"),
},
new()
{
Url = CommonDefinitions.ExtUrlIsCommonBinding,
Value = new FhirBoolean(true),
}
]
}
};
edContentType.cgSetFieldOrder(7, 6);
// add our element and track info
_ = _info.TryInsertElement(sdSignature, edContentType, false);
}
else
{
// move the current element to after onBehalfOf
edContentType.cgSetFieldOrder(7, 6);
}
if (sdSignature.cgTryGetElementById("Signature.who", out ElementDefinition? edWho))
{
// make it a choice type by adding uri, like it was in STU3
edWho.ElementId = "Signature.who[x]";
edWho.Path = "Signature.who[x]";
edWho.Base.Path = "Signature.who[x]";
edWho.Type.Add(new() { Code = "uri" });
//_ = _info.TryUpdateElement(sdSignature, edWho);
}
if (sdSignature.cgTryGetElementById("Signature.onBehalfOf", out ElementDefinition? edOnBehalfOf))
{
// make it a choice type by adding uri, like it was in STU3
edOnBehalfOf.ElementId = "Signature.onBehalfOf[x]";
edOnBehalfOf.Path = "Signature.onBehalfOf[x]";
edOnBehalfOf.Base.Path = "Signature.onBehalfOf[x]";
edOnBehalfOf.Type.Add(new() { Code = "uri" });
// TODO: fix the order (should be 6th total, 5th in component)
edOnBehalfOf.cgSetFieldOrder(6, 5);
}
}
// Element ValueSet.scope.focus has been removed in R5 (5.0.0-snapshot3). Adding this element to the list of Resources,
// so we can add a [NotMapped] attribute later.
if (_info.ResourcesByName.TryGetValue("ValueSet", out StructureDefinition? sdValueSet) &&
sdValueSet.cgTryGetElementById("ValueSet.scope", out _) &&
!sdValueSet.cgTryGetElementById("ValueSet.scope.focus", out _))
{
// create a new element for the focus (values pulled from 5.0.0-snapshot1)
ElementDefinition edFocus = new()
{
ElementId = "ValueSet.scope.focus",
Path = "ValueSet.scope.focus",
Short = "General focus of the Value Set as it relates to the intended semantic space",
Definition = "The general focus of the Value Set as it relates to the intended semantic space. This can be the information about clinical relevancy or the statement about the general focus of the Value Set, such as a description of types of messages, payment options, geographic locations, etc.",
Min = 0,
Max = "1",
Base = new() { Path = "ValueSet.scope.focus", Min = 0, Max = "1" },
Type = [new() { Code = "string" }],
Constraint =
[
new()
{
Key = "ele-1",
Severity = ConstraintSeverity.Error,
Human = "All FHIR elements must have a @value or children",
Expression = "hasValue() or (children().count() > id.count())",
},
],
IsSummary = false,
IsModifier = false,
MustSupport = false,
};
edFocus.cgSetFieldOrder(123, 3);
// TODO(ginoc): This insertion is currently pushing exclusionCriteria to Order=60 in file (componentOrder 5) - it should not
// add our element and track info
_ = _info.TryInsertElement(sdValueSet, edFocus, true);
}
// Element Bundle.link.relation changed from FhirString to Code<Hl7.Fhir.Model.Bundle.LinkRelationTypes> in R5 (5.0.0-snapshot3).
// We decided to leave the type to FhirString
if (_info.ResourcesByName.TryGetValue("Bundle", out StructureDefinition? sdBundle) &&
sdBundle.cgTryGetElementById("Bundle.link.relation", out ElementDefinition? edRelation))
{
edRelation.Type = [new() { Code = "string" }];
_ = _info.TryUpdateElement(sdBundle, edRelation);
}
// Element ElementDefinition.constraint.xpath has been removed in R5 (5.0.0-snapshot3). Adding this element to the list of ComplexTypes,
// so we can add a [NotMapped] attribute later.
if (_info.ComplexTypesByName.TryGetValue("ElementDefinition", out StructureDefinition? sdElementDefinition) &&
sdElementDefinition.cgTryGetElementById("ElementDefinition.constraint", out _) &&
!sdElementDefinition.cgTryGetElementById("ElementDefinition.constraint.xpath", out _))
{
// create a new element for the xpath (values pulled from 5.0.0-snapshot1)
ElementDefinition edXPath = new()
{
ElementId = "ElementDefinition.constraint.xpath",
Path = "ElementDefinition.constraint.xpath",
Short = "XPath expression of constraint",
Definition = "An XPath expression of constraint that can be executed to see if this constraint is met.",
Min = 0,
Max = "1",
Base = new() { Path = "ElementDefinition.constraint.xpath", Min = 0, Max = "1" },
Type = [new() { Code = "string" }],
IsSummary = true,
};
// try to get the offsets from ElementDefinition.constraint.expression (we want to be after that element)
if (sdElementDefinition.cgTryGetElementById("ElementDefinition.constraint.expression", out ElementDefinition? edConstraintExpression))
{
edXPath.cgSetFieldOrder(edConstraintExpression.cgFieldOrder() + 1, edConstraintExpression.cgComponentFieldOrder() + 1);
}
else
{
edXPath.cgSetFieldOrder(66, 8);
}
// add our element and track info
_ = _info.TryInsertElement(sdElementDefinition, edXPath, true);
}
// We need to modify the (R4+-based) definition of RelatedArtifact, to include
// the pre-R4 element "url".
if (_info.ComplexTypesByName.TryGetValue("RelatedArtifact", out StructureDefinition? sdRelatedArtifact) &&
!sdRelatedArtifact.cgTryGetElementById("RelatedArtifact.url", out _))
{
// create a new element for the url (values pulled from STU3)
ElementDefinition edUrl = new()
{
ElementId = "RelatedArtifact.url",
Path = "RelatedArtifact.url",
Short = "Where the artifact can be accessed",
Definition = "A url for the artifact that can be followed to access the actual content.",
Comment = "If a document or resource element is present, this element SHALL NOT be provided (use the url or reference in the Attachment or resource reference).",
Min = 0,
Max = "1",
Base = new() { Path = "RelatedArtifact.url", Min = 0, Max = "1" },
Type = [new() { Code = "url" }],
IsSummary = true,
};
edUrl.cgSetFieldOrder(8, 7);
// add our element and track info
_ = _info.TryInsertElement(sdRelatedArtifact, edUrl, true);
}
// correct issues in FHIR 6.0.0-ballot2
if ((_info.MainPackageId == "hl7.fhir.r6.core") && (_info.MainPackageVersion == "6.0.0-ballot2"))
{
if (_info.ResourcesByName.TryGetValue("TestScript", out StructureDefinition? sdTestScript))
{
if (sdTestScript.cgTryGetElementById("TestScript.setup.action.common.parameter", out ElementDefinition? edSetupCommonParameter))
{
// Set the class name to use for this new backbone element
edSetupCommonParameter.AddExtension("http://hl7.org/fhir/StructureDefinition/structuredefinition-explicit-type-name", new FhirString("SetupActionCommonParameter"));
}
if (sdTestScript.cgTryGetElementById("TestScript.common.parameter", out ElementDefinition? edCommonParameter))
{
// Set the class name to use for this new backbone element
edCommonParameter.AddExtension("http://hl7.org/fhir/StructureDefinition/structuredefinition-explicit-type-name", new FhirString("CommonParameter"));
}
if (sdTestScript.cgTryGetElementById("TestScript.setup.action.common", out ElementDefinition? edSetupActionCommon))
{
// Set the class name to use for this new backbone element
edSetupActionCommon.AddExtension("http://hl7.org/fhir/StructureDefinition/structuredefinition-explicit-type-name", new FhirString("SetupActionCommon"));
}
}
}
}
/// <summary>Writes a model information.</summary>
/// <param name="writtenPrimitives"> The written primitives.</param>
/// <param name="writtenComplexTypes">List of types of the written complexes.</param>
/// <param name="writtenResources"> The written resources.</param>
private void WriteModelInfo(
Dictionary<string, WrittenModelInfo> writtenPrimitives,
Dictionary<string, WrittenModelInfo> writtenComplexTypes,
Dictionary<string, WrittenModelInfo> writtenResources)
{
string filename = Path.Combine(_exportDirectory, "Generated", "Template-ModelInfo.cs");
using Stream stream = _generateHashesInsteadOfOutput
? new MemoryStream()
: new FileStream(filename, FileMode.Create);
using ExportStreamWriter writer = new(stream);
if (_generateHashesInsteadOfOutput)
{
writer.NewLine = "\r\n";
}
_writer = writer;
WriteGenerationComment();
_writer.WriteLineIndented("using System;");
_writer.WriteLineIndented("using System.Collections;");
_writer.WriteLineIndented("using System.Collections.Generic;");
_writer.WriteLineIndented("using Hl7.Fhir.Introspection;");
_writer.WriteLineIndented("using Hl7.Fhir.Validation;");
_writer.WriteLineIndented("using System.Linq;");
_writer.WriteLineIndented("using System.Runtime.Serialization;");
_writer.WriteLine(string.Empty);
WriteCopyright();
WriteNamespaceOpen();
WriteIndentedComment(
"A class with methods to retrieve information about the\n" +
"FHIR definitions based on which this assembly was generated.");
_writer.WriteLineIndented("public partial class ModelInfo");
// open class
OpenScope();
WriteSupportedResources(writtenResources.Values.Where(_supportedResourcesFilter));
WriteFhirVersion();
WriteFhirToCs(writtenPrimitives.Values.Where(_fhirToCsFilter), writtenComplexTypes.Values.Where(_fhirToCsFilter), writtenResources.Values.Where(_fhirToCsFilter));
WriteCsToString(writtenPrimitives.Values.Where(_csToStringFilter), writtenComplexTypes.Values.Where(_csToStringFilter), writtenResources.Values.Where(_csToStringFilter));
WriteSearchParameters();
var dataTypes = writtenPrimitives.Concat(writtenComplexTypes).ToDictionary(we => we.Key, we => we.Value);
WriteOpenTypes(dataTypes);
// close class
CloseScope();
WriteNamespaceClose();
if (_generateHashesInsteadOfOutput)
{
writer.Flush();
// generate the hash
string hash = FileSystemUtils.GenerateSha256(stream);
_fileHashes.Add(filename[_exportDirectory.Length..], hash);
writer.Close();
}
else
{
writer.Flush();
writer.Close();
}
}
private void WriteOpenTypes(Dictionary<string,WrittenModelInfo> types)
{
_writer.WriteIndentedComment("The open types that are used in the FHIR model. These are types that can be used in the 'value' field of an Extension.", isSummary: true);
_writer.WriteIndentedComment("This list differs from the one in the written documentation (https://www.hl7.org/fhir/datatypes.html),\n" +
"but we assume the list in Extension.value[x] is the more authorative.",
isRemarks: true, isSummary: false);
_writer.WriteLineIndented("public static readonly Type[] OpenTypes =");
OpenScope();
var extensionValue = _info.TryFindElementByPath("Extension.value[x]",
out StructureDefinition? _,
out ElementDefinition? edExtensionValue)
? edExtensionValue.Type
: throw new InvalidOperationException("Could not find Extension.value[x] element in definitions");
foreach (var typeName in extensionValue.Select(ev => ev.Code).OrderBy(c => c))
{
_writer.WriteLineIndented($"typeof({types[typeName].CsName}),");
}
CloseScope(includeSemicolon: true);
}
/// <summary>Writes the search parameters.</summary>
private void WriteSearchParameters()
{
_writer.WriteLineIndented("public static List<SearchParamDefinition> SearchParameters = new List<SearchParamDefinition>()");
OpenScope();
foreach (StructureDefinition complex in _info.ResourcesByName.Values.OrderBy(c => c.Name))
{
IReadOnlyDictionary<string, SearchParameter> resourceSearchParams = _info.SearchParametersForBase(complex.Name);