-
Notifications
You must be signed in to change notification settings - Fork 46
/
CSharpFirely2.cs
3004 lines (2515 loc) · 129 KB
/
CSharpFirely2.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
// <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.IO;
using Microsoft.Health.Fhir.SpecManager.Manager;
using Ncqa.Cql.Model;
namespace Microsoft.Health.Fhir.SpecManager.Language
{
/// <summary>A language exporter for Firely-compliant C# FHIR output.</summary>
public sealed class CSharpFirely2 : ILanguage
{
/// <summary>The namespace to use during export.</summary>
private const string Namespace = "Hl7.Fhir.Model";
/// <summary>FHIR information we are exporting.</summary>
private FhirVersionInfo _info;
/// <summary>Options for controlling the export.</summary>
private ExporterOptions _options;
/// <summary>Keep track of information about written value sets.</summary>
private Dictionary<string, WrittenValueSetInfo> _writtenValueSets = new();
/// <summary>The split characters.</summary>
private static readonly char[] _splitChars = { '|', ' ' };
/// <summary>The currently in-use text writer.</summary>
private ExportStreamWriter _writer;
/// <summary>The model writer.</summary>
private ExportStreamWriter _modelWriter;
/// <summary>Pathname of the export directory.</summary>
private string _exportDirectory;
/// <summary>Name of the language.</summary>
private const string _languageName = "CSharpFirely2";
/// <summary>The single file export extension (uses directory export).</summary>
private const string _singleFileExportExtension = null;
/// <summary>Structures to skip generating.</summary>
private static readonly HashSet<string> _exclusionSet = new()
{
/* Since Base defines its methods abstractly, the pattern for generating it
* is sufficiently different from derived classes that it makes sense not
* to generate the methods (it's pretty empty too - no members on this abstract class) */
"Base",
/* PrimitiveType defines the magic `ObjectValue` member used by all derived
* primitives to store their value. This makes the CopyTo(), IsExact() methods
* different enough that it does not make sense to generate them. */
"PrimitiveType",
/* Element has the special `id` element, that is both an attribute in the
* XML serialization and is not using a FHIR primitive for representation. Consequently,
* the generated CopyTo() and IsExact() methods diverge too much to be useful. */
"Element",
/* Extension has the special `url` element, that is both an attribute in the
* XML serialization and is not using a FHIR primitive for representation. Consequently,
* the generated CopyTo() and IsExact() methods diverge too much to be useful. */
"Extension",
/* Narrative has a special `div` element, serialized as an element frm the
* XHTML namespace, not using a normal FHIR primitive. This makes this class
* deviate in ways we cannot achieve with the generator. */
"Narrative",
/* These two types are interfaces rather than classes (at least, for now)
* so we're not generating them. Also, all types deriving from these
* are generated to derive from DomainResource instead */
"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",
};
/// <summary>
/// List of types introduced in R5 that are retrospectively introduced in R3 and R4.
/// </summary>
private static readonly List<WrittenModelInfo> _sharedR5DataTypes = new()
{
new WrittenModelInfo { CsName = "BackboneType", FhirName = "BackboneType", IsAbstract = true },
new WrittenModelInfo { CsName = "Base", FhirName = "Base", IsAbstract = true },
new WrittenModelInfo { CsName = "DataType", FhirName = "DataType", IsAbstract = true },
new WrittenModelInfo { CsName = "PrimitiveType", FhirName = "PrimitiveType", IsAbstract = 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 = new()
{
"Attachment",
"BackboneElement",
"BackboneType",
"Base",
"CodeableConcept",
"Coding",
"ContactPoint",
"ContactDetail",
"DataType",
"Element",
"Extension",
"Identifier",
"Meta",
"Narrative",
"Period",
"PrimitiveType",
"Quantity",
"Range",
"Reference",
"Signature",
"UsageContext",
};
/// <summary>
/// List of complex datatype classes that are part of the 'conformance' subset. See <see cref="GenSubset"/>.
/// </summary>
private static readonly List<string> _conformanceSubsetComplexTypes = new()
{
"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 = new()
{
"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 = new()
{
"CapabilityStatement",
"CodeSystem",
"ElementDefinition",
"StructureDefinition",
"ValueSet",
};
/// <summary>
/// List of all valuesets that we publish in the base subset
/// </summary>
private static readonly List<string> _baseSubsetValueSets = new()
{
"http://hl7.org/fhir/ValueSet/publication-status",
"http://hl7.org/fhir/ValueSet/FHIR-version",
// Doesn't strictly need to be in base (but in conformance),
// but we used to generate it for base, so I am keeping it that way.
"http://hl7.org/fhir/ValueSet/filter-operator",
};
/// <summary>
/// List of all valuesets that we publish in the conformance subset.
/// </summary>
private static readonly List<string> _conformanceSubsetValueSets = new List<string>()
{
"http://hl7.org/fhir/ValueSet/capability-statement-kind",
"http://hl7.org/fhir/ValueSet/binding-strength",
"http://hl7.org/fhir/ValueSet/search-param-type",
// 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 whather 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>
private static readonly List<(string, string)> _explicitSharedValueSets = new()
{
// 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 = new HashSet<string>();
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 readonly List<string> _codedElementOverrides = new()
{
"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>
private 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 SinceVersion(FhirPackageCommon.FhirSequenceEnum Since);
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[x]"] = "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[x]"] = "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[x]"] = "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[x]"] = "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[x]"] = "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.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", "")
};
/// <summary>True to export five ws.</summary>
private bool _exportFiveWs = true;
/// <summary>
/// Determines the subset of code to generate.
/// </summary>
[Flags]
private enum GenSubset
{
// Subset of datatypes and resources used in R3 and later
Base = 1,
// Subset of conformance resources used by the SDK
Conformance = 2,
// Subset of model classes that are not part of Base or Conformance
Satellite = 4,
}
/// <summary>Gets the name of the language.</summary>
/// <value>The name of the language.</value>
string ILanguage.LanguageName => _languageName;
/// <summary>
/// Gets the single file extension for this language - null or empty indicates a multi-file
/// export (exporter should copy the contents of the directory).
/// </summary>
string ILanguage.SingleFileExportExtension => _singleFileExportExtension;
/// <summary>Gets the FHIR primitive type map.</summary>
/// <value>The FHIR primitive type map.</value>
Dictionary<string, string> ILanguage.FhirPrimitiveTypeMap => CSharpFirelyCommon.PrimitiveTypeMap;
/// <summary>Gets the reserved words.</summary>
/// <value>The reserved words.</value>
HashSet<string> ILanguage.ReservedWords => _reservedWords;
/// <summary>
/// Gets a list of FHIR class types that the language WILL export, regardless of user choices.
/// Used to provide information to users.
/// </summary>
List<ExporterOptions.FhirExportClassType> ILanguage.RequiredExportClassTypes => new List<ExporterOptions.FhirExportClassType>();
/// <summary>
/// Gets a list of FHIR class types that the language CAN export, depending on user choices.
/// </summary>
List<ExporterOptions.FhirExportClassType> ILanguage.OptionalExportClassTypes => new List<ExporterOptions.FhirExportClassType>()
{
ExporterOptions.FhirExportClassType.PrimitiveType,
ExporterOptions.FhirExportClassType.ComplexType,
ExporterOptions.FhirExportClassType.Resource,
ExporterOptions.FhirExportClassType.Enum,
};
/// <summary>Gets language-specific options and their descriptions.</summary>
Dictionary<string, string> ILanguage.LanguageOptions => new Dictionary<string, string>()
{
{ "subset", "Which subset of language exports to make (base|conformance|satellite). Default is satellite." },
{ "w5", "If output should include 5 W's mappings (true|false). Default is true." },
{ "cqlmodel", "Name of the Cql model for which metadata attributes should be added to the pocos. 'Fhir401' is the only valid value at the moment." }
};
/// <summary>If a Cql ModelInfo is available, this will be the parsed XML model file.</summary>
private ModelInfo _cqlModelInfo = null;
private IDictionary<string, ClassInfo> _cqlModelClassInfo = null;
/// <summary>Export the passed FHIR version into the specified directory.</summary>
/// <param name="info"> The information.</param>
/// <param name="serverInfo"> Information describing the server.</param>
/// <param name="options"> Options for controlling the operation.</param>
/// <param name="exportDirectory">Directory to write files.</param>
void ILanguage.Export(
FhirVersionInfo info,
FhirCapabiltyStatement serverInfo,
ExporterOptions options,
string exportDirectory)
{
_ = options.LanguageOptions.TryGetValue("subset", out string ss);
var subset = (ss ?? "satellite") switch
{
"base" => GenSubset.Base,
"conformance" => GenSubset.Conformance,
"satellite" when info.FhirSequence == FhirPackageCommon.FhirSequenceEnum.STU3
=> GenSubset.Satellite | GenSubset.Conformance,
"satellite" => GenSubset.Satellite,
_ => throw new NotSupportedException($"Unknown subset flag '{ss}'.")
};
if (subset.HasFlag(GenSubset.Base) && info.FhirSequence != FhirPackageCommon.FhirSequenceEnum.R5)
{
Console.WriteLine($"Aborting {_languageName} for {info.FhirSequence}: code generation for the 'base' subset should be run on R5 only.");
return;
}
if (subset.HasFlag(GenSubset.Conformance) &&
(info.FhirSequence != FhirPackageCommon.FhirSequenceEnum.STU3 &&
info.FhirSequence != FhirPackageCommon.FhirSequenceEnum.R5))
{
Console.WriteLine($"Aborting {_languageName} for {info.FhirSequence}: code generation for the 'conformance' subset should be run on STU3 or R5 only.");
return;
}
if (options.LanguageOptions.TryGetValue("w5", out string valueW5) &&
(!string.IsNullOrEmpty(valueW5)) &&
valueW5.StartsWith("f", StringComparison.OrdinalIgnoreCase))
{
_exportFiveWs = false;
}
// set internal vars so we don't pass them to every function
_info = info;
_options = options;
_exportDirectory = exportDirectory;
_writtenValueSets = new Dictionary<string, WrittenValueSetInfo>();
if (!Directory.Exists(exportDirectory))
{
Directory.CreateDirectory(exportDirectory);
}
if (!Directory.Exists(Path.Combine(exportDirectory, "Generated")))
{
Directory.CreateDirectory(Path.Combine(exportDirectory, "Generated"));
}
if (options.LanguageOptions.TryGetValue("cqlmodel", out string 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");
// We need to modify the (R4+-based) definition of Binary, to include
// the pre-R4 element "content".
if (_info.Resources.TryGetValue("Binary", out FhirComplex binary))
{
if (!binary.Elements.ContainsKey("Binary.content") && binary.Elements.TryGetValue("Binary.data", out FhirElement data))
{
var contentElement = data.CopyWith(binary, "Binary.content", "Binary.content", 1, "1");
binary.Elements.Add(contentElement.Path, contentElement);
}
}
// We need to modify the definition of Signature, to include
// the STU3 content.
if (_info.ComplexTypes.TryGetValue("Signature", out FhirComplex signature))
{
if (!signature.Elements.ContainsKey("Signature.blob") && signature.Elements.TryGetValue("Signature.data", out FhirElement data))
{
var contentElement = data.CopyWith(signature, "Signature.blob", "Signature.blob", 0, "1");
signature.Elements.Add(contentElement.Path, contentElement);
}
if (!signature.Elements.ContainsKey("Signature.contentType"))
{
var contentTypeElement = new FhirElement(
rootArtifact: signature,
id: "Signature.contentType", path: "Signature.contentType", basePath: null, explicitName: null, url: null,
fieldOrder: 6, shortDescription: "The technical format of the signature",
purpose: null, comment: null, validationRegEx: null,
baseTypeName: null, elementTypes: new() { { "code", new("code", "string", new("http://hl7.org/fhir/code"), null, null) } }, cardinalityMin: 0, cardinalityMax: "1",
isModifier: false, isModifierReason: null, isSummary: true, isMustSupport: false,
isSimple: false, defaultFieldName: null, defaultFieldValue: null,
fixedFieldName: null, fixedFieldValue: null, patternFieldName: null, patternFieldValue: null,
isInherited: false, modifiesParent: false, bindingStrength: null, bindingName: null, valueSet: null,
representations: null, mappings: null
);
signature.Elements.Add(contentTypeElement.Path, contentTypeElement);
}
if (signature.Elements.TryGetValue("Signature.who", out FhirElement who))
{
// make it a choice type, like it was in STU3
who.ElementTypes.Add("uri", new FhirElementType("FhirUri"));
}
if (signature.Elements.TryGetValue("Signature.onBehalfOf", out FhirElement onBehalfOf))
{
// make it a choice type, like it was in STU3
onBehalfOf.ElementTypes.Add("uri", new FhirElementType("FhirUri"));
}
}
// 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.NodeByPath.TryGetValue("ValueSet.scope", out FhirNodeInfo scopeNode)
&& scopeNode.GetSource() is FhirComplex scopeComplex
&& !scopeComplex.Elements.ContainsKey("ValueSet.scope.focus"))
{
var focusElement = new FhirElement(
rootArtifact: scopeComplex,
id: "ValueSet.scope.focus", path: "ValueSet.scope.focus", basePath: null, explicitName: null, url: null,
fieldOrder: 3, shortDescription: "General focus of the Value Set as it relates to the intended semantic space",
purpose: null, comment: null, validationRegEx: null,
baseTypeName: "string", elementTypes: null, cardinalityMin: 0, cardinalityMax: "1",
isModifier: false, isModifierReason: null, isSummary: false, isMustSupport: false,
isSimple: false, defaultFieldName: null, defaultFieldValue: null,
fixedFieldName: null, fixedFieldValue: null, patternFieldName: null, patternFieldValue: null,
isInherited: false, modifiesParent: false, bindingStrength: null, bindingName: null, valueSet: null, representations: null,
mappings: null
);
scopeComplex.Elements.Add(focusElement.Path, focusElement);
}
// 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.NodeByPath.TryGetValue("Bundle.link", out FhirNodeInfo linkNode)
&& linkNode.GetSource() is FhirComplex linkComplex
&& linkComplex.Elements.TryGetValue("Bundle.link.relation", out FhirElement element))
{
element.BaseTypeName = "string";
}
// 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.NodeByPath.TryGetValue("ElementDefinition.constraint", out FhirNodeInfo constraintNode)
&& constraintNode.GetSource() is FhirComplex constraintComplex
&& !constraintComplex.Elements.ContainsKey("ElementDefinition.constraint.xpath"))
{
var xPathElement = new FhirElement(
rootArtifact: constraintComplex,
id: "ElementDefinition.constraint.xpath", path: "ElementDefinition.constraint.xpath",
basePath: null, explicitName: null, url: null,
fieldOrder: 7, shortDescription: "XPath expression of constraint",
purpose: null, comment: "Elements SHALL use \"f\" as the namespace prefix for the FHIR namespace, and \"x\" for the xhtml namespace, and SHALL NOT use any other prefixes. Note: XPath is generally considered not useful because it does not apply to JSON and other formats and because of XSLT implementation issues, and may be removed in the future.",
validationRegEx: null,
baseTypeName: "string", elementTypes: null, cardinalityMin: 0, cardinalityMax: "1",
isModifier: false, isModifierReason: null, isSummary: true, isMustSupport: false,
isSimple: false, defaultFieldName: null, defaultFieldValue: null,
fixedFieldName: null, fixedFieldValue: null, patternFieldName: null, patternFieldValue: null,
isInherited: false, modifiesParent: false, bindingStrength: null, bindingName: null, valueSet: null, representations: null,
mappings: null
); ;
constraintComplex.Elements.Add(xPathElement.Path, xPathElement);
}
// We need to modify the (R4+-based) definition of Binary, to include
// the pre-R4 element "content".
if (_info.ComplexTypes.TryGetValue("RelatedArtifact", out FhirComplex relatedArtifact))
{
if (!relatedArtifact.Elements.ContainsKey("RelatedArtifact.url"))
{
var urlElement = new FhirElement(
rootArtifact: relatedArtifact,
id: "RelatedArtifact.url", path: "RelatedArtifact.url", basePath: null, explicitName: null, url: null,
fieldOrder: 6, shortDescription: "Where the artifact can be accessed",
purpose: null, comment: null, validationRegEx: null,
baseTypeName: "url", elementTypes: null, cardinalityMin: 0, cardinalityMax: "1",
isModifier: false, isModifierReason: null, isSummary: true, isMustSupport: false,
isSimple: false, defaultFieldName: null, defaultFieldValue: null,
fixedFieldName: null, fixedFieldValue: null, patternFieldName: null, patternFieldValue: null,
isInherited: false, modifiesParent: false, bindingStrength: null, bindingName: null, valueSet: null, representations: null,
mappings: null
);
relatedArtifact.Elements.Add(urlElement.Path, urlElement);
}
}
using (var infoStream = new FileStream(infoFilename, FileMode.Create))
using (var infoWriter = new ExportStreamWriter(infoStream))
{
_modelWriter = infoWriter;
WriteGenerationComment(infoWriter);
if (options.OptionalClassTypesToExport.Contains(ExporterOptions.FhirExportClassType.Enum))
{
WriteSharedValueSets(subset);
}
_modelWriter.WriteLineIndented("// Generated items");
if (options.OptionalClassTypesToExport.Contains(ExporterOptions.FhirExportClassType.PrimitiveType))
{
WritePrimitiveTypes(_info.PrimitiveTypes.Values, ref dummy, subset);
}
AddModels(allPrimitives, _info.PrimitiveTypes.Values);
if (options.OptionalClassTypesToExport.Contains(ExporterOptions.FhirExportClassType.ComplexType))
{
WriteComplexDataTypes(_info.ComplexTypes.Values, ref dummy, subset);
}
AddModels(allComplexTypes, _info.ComplexTypes.Values);
AddModels(allComplexTypes, _sharedR5DataTypes);
if (options.OptionalClassTypesToExport.Contains(ExporterOptions.FhirExportClassType.Resource))
{
WriteResources(_info.Resources.Values, ref dummy, subset);
}
AddModels(allResources, _info.Resources.Values);
if (subset.HasFlag(GenSubset.Satellite))
{
WriteModelInfo(allPrimitives, allComplexTypes, allResources);
}
}
}
/// <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 (FileStream stream = new FileStream(filename, FileMode.Create))
using (ExportStreamWriter writer = new ExportStreamWriter(stream))
{
_writer = writer;
WriteGenerationComment();
_writer.WriteLineIndented("using System;");
_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();
// close class
CloseScope();
WriteNamespaceClose();
}
}
/// <summary>Writes the search parameters.</summary>
private void WriteSearchParameters()
{
_writer.WriteLineIndented("public static List<SearchParamDefinition> SearchParameters = new List<SearchParamDefinition>()");
OpenScope();
foreach (FhirComplex complex in _info.Resources.Values)
{
if (complex.SearchParameters == null)
{
continue;
}
foreach (FhirSearchParam sp in complex.SearchParameters.Values.OrderBy(s => s.Name))
{
if (sp.IsExperimental)
{
continue;
}
string description;
if ((!string.IsNullOrEmpty(sp.Description)) &&
sp.Description.StartsWith("Multiple", StringComparison.Ordinal))
{
description = string.Empty;
}
else
{
description = sp.Description;
}
string searchType = FhirUtils.SanitizedToConvention(sp.ValueType, FhirTypeBase.NamingConvention.PascalCase);
string path = string.Empty;
if (!string.IsNullOrEmpty(sp.XPath))
{
#pragma warning disable CA1307 // Specify StringComparison
string temp = sp.XPath.Replace("f:", string.Empty).Replace('/', '.').Replace('(', '[').Replace(')', ']');
#pragma warning restore CA1307 // Specify StringComparison
IEnumerable<string> split = temp
.Split(_splitChars, StringSplitOptions.RemoveEmptyEntries)
.Where(s => s.StartsWith(complex.Name + ".", StringComparison.Ordinal));
path = "\"" + string.Join("\", \"", split) + "\", ";
}
string target;
if ((sp.Targets == null) || (sp.Targets.Count == 0))
{
target = string.Empty;
}
else
{
SortedSet<string> sc = new SortedSet<string>();
foreach (string t in sp.Targets)
{
sc.Add("ResourceType." + t);
}
// HACK: for http://hl7.org/fhir/SearchParameter/clinical-encounter,
// none of the base resources have EpisodeOfCare as target, except
// Procedure and DeviceRequest. There is no way you can see this from the
// source data we generate this from, afaik, so we need to make
// a special case here.
// Brian P reported that there are many such exceptions - but this one
// was reported as a bug. Again, there is no way to know this from our
// inputs, so this will remain manually maintained input.
if (sp.Id == "clinical-encounter")
{
if (_info.FhirSequence == FhirPackageCommon.FhirSequenceEnum.STU3)
{
if (complex.Name != "Procedure" && complex.Name != "DeviceRequest")
{
sc.Remove("ResourceType.EpisodeOfCare");
}
}
else
{
if (complex.Name != "DocumentReference")
{
sc.Remove("ResourceType.EpisodeOfCare");
}
}
}
target = ", Target = new ResourceType[] { " + string.Join(", ", sc) + ", }";
}
string xpath = string.IsNullOrEmpty(sp.XPath) ? string.Empty : ", XPath = \"" + sp.XPath + "\"";
string expression = string.IsNullOrEmpty(sp.Expression) ? string.Empty : ", Expression = \"" + sp.Expression + "\"";
string urlComponent = $", Url = \"{sp.URL}\"";
string[] components = sp.Components?.Select(c => $"""new SearchParamComponent("{c.Definition}", "{c.Expression}")""").ToArray() ?? Array.Empty<string>();
string strComponents = (components.Length > 0) ? $", Component = new SearchParamComponent[] {{ {string.Join(',', components)} }}" : string.Empty;
_writer.WriteLineIndented(
$"new SearchParamDefinition() " +
$"{{" +
$" Resource = \"{complex.Name}\"," +
$" Name = \"{sp.Name}\"," +
$" Code = \"{sp.Code}\"," +
(_info.FhirSequence == FhirPackageCommon.FhirSequenceEnum.STU3 ?
$" Description = @\"{SanitizeForMarkdown(description)}\"," :
$" Description = new Markdown(@\"{SanitizeForMarkdown(description)}\"),") +
$" Type = SearchParamType.{searchType}," +
$" Path = new string[] {{ {path}}}" +
target +
xpath +
expression +
urlComponent +
strComponents +
$" }},");
}
}
CloseScope(true);
}
/// <summary>Sanitize for markdown.</summary>
/// <param name="value">The value.</param>
private static string SanitizeForMarkdown(string value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
#pragma warning disable CA1307 // Specify StringComparison
return value.Replace("\"", "\"\"").Replace("\r", @"\r").Replace("\n", @"\n");
#pragma warning restore CA1307 // Specify StringComparison
}
/// <summary>Writes the C# to FHIR map dictionary.</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 WriteCsToString(
IEnumerable<WrittenModelInfo> writtenPrimitives,
IEnumerable<WrittenModelInfo> writtenComplexTypes,
IEnumerable<WrittenModelInfo> writtenResources)
{
_writer.WriteLineIndented("public static Dictionary<Type,string> FhirCsTypeToString = new Dictionary<Type,string>()");
OpenScope();
foreach (WrittenModelInfo type in writtenPrimitives.Concat(writtenComplexTypes).OrderBy(t => t.FhirName))
{
_writer.WriteLineIndented($"{{ typeof({type.CsName}), \"{type.FhirName}\" }},");
}
_writer.WriteLine(string.Empty);
foreach (WrittenModelInfo type in writtenResources.OrderBy(t => t.FhirName))
{
_writer.WriteLineIndented($"{{ typeof({type.CsName}), \"{type.FhirName}\" }},");
}
CloseScope(true);
}
/// <summary>Writes the FHIR to C# map dictionary.</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 WriteFhirToCs(
IEnumerable<WrittenModelInfo> writtenPrimitives,
IEnumerable<WrittenModelInfo> writtenComplexTypes,
IEnumerable<WrittenModelInfo> writtenResources)
{
_writer.WriteLineIndented("public static Dictionary<string,Type> FhirTypeToCsType = new Dictionary<string,Type>()");
OpenScope();
foreach (WrittenModelInfo type in writtenPrimitives.Concat(writtenComplexTypes).OrderBy(t => t.FhirName))
{
_writer.WriteLineIndented($"{{ \"{type.FhirName}\", typeof({type.CsName}) }},");
}
_writer.WriteLine(string.Empty);
foreach (WrittenModelInfo type in writtenResources.OrderBy(t => t.FhirName))
{
_writer.WriteLineIndented($"{{ \"{type.FhirName}\", typeof({type.CsName}) }},");
}
CloseScope(true);
}
/// <summary>Writes the FHIR version.</summary>
private void WriteFhirVersion()
{
_writer.WriteLineIndented("public static string Version");
OpenScope();
_writer.WriteLineIndented($"get {{ return \"{_info.VersionString}\"; }}");
CloseScope();
}
/// <summary>Writes the supported resources dictionary.</summary>
/// <param name="resources">The written resources.</param>
private void WriteSupportedResources(IEnumerable<WrittenModelInfo> resources)
{
_writer.WriteLineIndented("public static List<string> SupportedResources = new List<string>()");
OpenScope();
foreach (WrittenModelInfo wmi in resources.OrderBy(s => s.FhirName))
{
_writer.WriteLineIndented($"\"{wmi.FhirName}\",");
}
CloseScope(true);
}
/// <summary>Writes the shared enums.</summary>
private void WriteSharedValueSets(GenSubset subset)
{
HashSet<string> usedEnumNames = new HashSet<string>();
string filename = Path.Combine(_exportDirectory, "Generated", "Template-Bindings.cs");
using (FileStream stream = new FileStream(filename, FileMode.Create))
using (ExportStreamWriter writer = new ExportStreamWriter(stream))
{
_writer = writer;
WriteHeaderBasic();
WriteNamespaceOpen();
foreach (FhirValueSetCollection collection in _info.ValueSetsByUrl.Values)
{
// traverse value sets starting with highest version
foreach (FhirValueSet vs in collection.ValueSetsByVersion.Values.OrderByDescending(s => s.Version))
{
if (vs.ReferencedByComplexes.Count < 2 && !_explicitSharedValueSets.Contains((_info.FhirSequence.ToString(), vs.URL)))
{
/* ValueSets that are used in a single POCO are generated as a nested enum inside that
* POCO, not here in the shared valuesets */
continue;
}
if (vs.StrongestBinding != FhirElement.ElementDefinitionBindingStrength.Required)
{
/* Since required bindings cannot be extended, those are the only bindings that
can be represented using enums in the POCO classes (using <c>Code<T></c>). All other coded members
use <c>Code</c>, <c>Coding</c> or <c>CodeableConcept</c>.
Consequently, we only need to generate enums for valuesets that are used as
required bindings anywhere in the datamodel. */
continue;
}
if (_exclusionSet.Contains(vs.URL))
{
continue;
}
// If this is a shared valueset that will be generated in the base or conformance subset,
// don't also generate it here.
bool writeValueSet =
(subset.HasFlag(GenSubset.Satellite) && !(_baseSubsetValueSets.Contains(vs.URL) || _conformanceSubsetValueSets.Contains(vs.URL)))
|| subset.HasFlag(GenSubset.Conformance) && _conformanceSubsetValueSets.Contains(vs.URL)
|| subset.HasFlag(GenSubset.Base) && _baseSubsetValueSets.Contains(vs.URL);
WriteEnum(vs, string.Empty, usedEnumNames, silent: !writeValueSet);
if (writeValueSet)
{
_modelWriter.WriteLineIndented($"// Generated Shared Enumeration: {_writtenValueSets[vs.URL].ValueSetName} ({vs.URL})");
}
else
{
_modelWriter.WriteLineIndented($"// Deferred generation of Shared Enumeration (will be generated in another subset): {_writtenValueSets[vs.URL].ValueSetName} ({vs.URL})");
}
_modelWriter.IncreaseIndent();
foreach (string path in vs.ReferencingElementsByPath.Keys)
{
string name = path.Split('.')[0];
if (_info.ComplexTypes.ContainsKey(name))
{
_modelWriter.WriteLineIndented($"// Used in model class (type): {path}");
continue;
}