/
StructureMapUtilities.java
2842 lines (2627 loc) · 109 KB
/
StructureMapUtilities.java
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
package org.hl7.fhir.r5.utils.structuremap;
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// remember group resolution
// trace - account for which wasn't transformed in the source
import org.hl7.fhir.exceptions.DefinitionException;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.exceptions.FHIRFormatError;
import org.hl7.fhir.r5.conformance.profile.ProfileKnowledgeProvider;
import org.hl7.fhir.r5.conformance.profile.ProfileUtilities;
import org.hl7.fhir.r5.context.ContextUtilities;
import org.hl7.fhir.r5.context.IWorkerContext;
import org.hl7.fhir.r5.elementmodel.Element;
import org.hl7.fhir.r5.elementmodel.Manager;
import org.hl7.fhir.r5.elementmodel.Property;
import org.hl7.fhir.r5.fhirpath.ExpressionNode;
import org.hl7.fhir.r5.fhirpath.FHIRLexer;
import org.hl7.fhir.r5.fhirpath.FHIRPathEngine;
import org.hl7.fhir.r5.fhirpath.TypeDetails;
import org.hl7.fhir.r5.fhirpath.ExpressionNode.CollectionStatus;
import org.hl7.fhir.r5.fhirpath.FHIRLexer.FHIRLexerException;
import org.hl7.fhir.r5.fhirpath.TypeDetails.ProfiledType;
import org.hl7.fhir.r5.model.*;
import org.hl7.fhir.r5.model.ConceptMap.ConceptMapGroupComponent;
import org.hl7.fhir.r5.model.ConceptMap.ConceptMapGroupUnmappedMode;
import org.hl7.fhir.r5.model.ConceptMap.SourceElementComponent;
import org.hl7.fhir.r5.model.ConceptMap.TargetElementComponent;
import org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionMappingComponent;
import org.hl7.fhir.r5.model.Enumeration;
import org.hl7.fhir.r5.model.ElementDefinition.TypeRefComponent;
import org.hl7.fhir.r5.model.Enumerations.ConceptMapRelationship;
import org.hl7.fhir.r5.model.Enumerations.FHIRVersion;
import org.hl7.fhir.r5.model.Enumerations.PublicationStatus;
import org.hl7.fhir.r5.model.Narrative.NarrativeStatus;
import org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionMappingComponent;
import org.hl7.fhir.r5.model.StructureDefinition.TypeDerivationRule;
import org.hl7.fhir.r5.model.StructureMap.*;
import org.hl7.fhir.r5.model.ValueSet.ValueSetExpansionContainsComponent;
import org.hl7.fhir.r5.renderers.TerminologyRenderer;
import org.hl7.fhir.r5.terminologies.expansion.ValueSetExpansionOutcome;
import org.hl7.fhir.r5.terminologies.utilities.ValidationResult;
import org.hl7.fhir.r5.utils.ToolingExtensions;
import org.hl7.fhir.utilities.CommaSeparatedStringBuilder;
import org.hl7.fhir.utilities.FhirPublication;
import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.validation.ValidationOptions;
import org.hl7.fhir.utilities.xhtml.NodeType;
import org.hl7.fhir.utilities.xhtml.XhtmlNode;
import java.io.IOException;
import java.util.*;
/**
* Services in this class:
* <p>
* string render(map) - take a structure and convert it to text
* map parse(text) - take a text representation and parse it
* getTargetType(map) - return the definition for the type to create to hand in
* transform(appInfo, source, map, target) - transform from source to target following the map
* analyse(appInfo, map) - generate profiles and other analysis artifacts for the targets of the transform
* map generateMapFromMappings(StructureDefinition) - build a mapping from a structure definition with loigcal mappings
*
* @author Grahame Grieve
*/
public class StructureMapUtilities {
public static final String MAP_WHERE_CHECK = "map.where.check";
public static final String MAP_WHERE_LOG = "map.where.log";
public static final String MAP_WHERE_EXPRESSION = "map.where.expression";
public static final String MAP_SEARCH_EXPRESSION = "map.search.expression";
public static final String MAP_EXPRESSION = "map.transform.expression";
private static final boolean MULTIPLE_TARGETS_ONELINE = true;
public static final String AUTO_VAR_NAME = "vvv";
public static final String DEF_GROUP_NAME = "DefaultMappingGroupAnonymousAlias";
private final IWorkerContext worker;
private final FHIRPathEngine fpe;
private ITransformerServices services;
private ProfileKnowledgeProvider pkp;
private final Map<String, Integer> ids = new HashMap<String, Integer>();
private ValidationOptions terminologyServiceOptions = new ValidationOptions(FhirPublication.R5);
private final ProfileUtilities profileUtilities;
private boolean exceptionsForChecks = true;
private boolean debug;
public StructureMapUtilities(IWorkerContext worker, ITransformerServices services, ProfileKnowledgeProvider pkp) {
super();
this.worker = worker;
this.services = services;
this.pkp = pkp;
fpe = new FHIRPathEngine(worker);
fpe.setHostServices(new FHIRPathHostServices(this));
profileUtilities = new ProfileUtilities(worker, null, null);
}
public StructureMapUtilities(IWorkerContext worker, ITransformerServices services) {
super();
this.worker = worker;
this.services = services;
fpe = new FHIRPathEngine(worker);
fpe.setHostServices(new FHIRPathHostServices(this));
profileUtilities = new ProfileUtilities(worker, null, null);
}
public StructureMapUtilities(IWorkerContext worker) {
super();
this.worker = worker;
fpe = new FHIRPathEngine(worker);
fpe.setHostServices(new FHIRPathHostServices(this));
profileUtilities = new ProfileUtilities(worker, null, null);
}
public static String render(StructureMap map) {
StringBuilder b = new StringBuilder();
b.append("/// url = \""+map.getUrl()+"\"\r\n");
b.append("/// name = \""+map.getName()+"\"\r\n");
b.append("/// title = \""+map.getTitle()+"\"\r\n");
b.append("/// status = \""+map.getStatus().toCode()+"\"\r\n");
b.append("\r\n");
if (map.getDescription() != null) {
renderMultilineDoco(b, map.getDescription(), 0);
b.append("\r\n");
}
renderConceptMaps(b, map);
renderUses(b, map);
renderImports(b, map);
for (StructureMapGroupComponent g : map.getGroup())
renderGroup(b, g);
return b.toString();
}
private static void renderConceptMaps(StringBuilder b, StructureMap map) {
for (Resource r : map.getContained()) {
if (r instanceof ConceptMap) {
produceConceptMap(b, (ConceptMap) r);
}
}
}
private static void produceConceptMap(StringBuilder b, ConceptMap cm) {
b.append("conceptmap \"");
b.append(cm.getId());
b.append("\" {\r\n");
Map<String, String> prefixesSrc = new HashMap<String, String>();
Map<String, String> prefixesTgt = new HashMap<String, String>();
char prefix = 's';
for (ConceptMapGroupComponent cg : cm.getGroup()) {
if (!prefixesSrc.containsKey(cg.getSource())) {
prefixesSrc.put(cg.getSource(), String.valueOf(prefix));
b.append(" prefix ");
b.append(prefix);
b.append(" = \"");
b.append(cg.getSource());
b.append("\"\r\n");
prefix++;
}
if (!prefixesTgt.containsKey(cg.getTarget())) {
prefixesTgt.put(cg.getTarget(), String.valueOf(prefix));
b.append(" prefix ");
b.append(prefix);
b.append(" = \"");
b.append(cg.getTarget());
b.append("\"\r\n");
prefix++;
}
}
b.append("\r\n");
for (ConceptMapGroupComponent cg : cm.getGroup()) {
if (cg.hasUnmapped()) {
b.append(" unmapped for ");
b.append(prefixesSrc.get(cg.getSource()));
b.append(" = ");
b.append(cg.getUnmapped().getMode().toCode());
b.append("\r\n");
}
}
for (ConceptMapGroupComponent cg : cm.getGroup()) {
for (SourceElementComponent ce : cg.getElement()) {
b.append(" ");
b.append(prefixesSrc.get(cg.getSource()));
b.append(":");
if (Utilities.isToken(ce.getCode())) {
b.append(ce.getCode());
} else {
b.append("\"");
b.append(ce.getCode());
b.append("\"");
}
b.append(" ");
b.append(getChar(ce.getTargetFirstRep().getRelationship()));
b.append(" ");
b.append(prefixesTgt.get(cg.getTarget()));
b.append(":");
if (Utilities.isToken(ce.getTargetFirstRep().getCode())) {
b.append(ce.getTargetFirstRep().getCode());
} else {
b.append("\"");
b.append(ce.getTargetFirstRep().getCode());
b.append("\"");
}
b.append("\r\n");
}
}
b.append("}\r\n\r\n");
}
private static Object getChar(ConceptMapRelationship relationship) {
switch (relationship) {
case RELATEDTO:
return "-";
case EQUIVALENT:
return "==";
case NOTRELATEDTO:
return "!=";
case SOURCEISNARROWERTHANTARGET:
return "<=";
case SOURCEISBROADERTHANTARGET:
return ">=";
default:
return "??";
}
}
private static void renderUses(StringBuilder b, StructureMap map) {
for (StructureMapStructureComponent s : map.getStructure()) {
b.append("uses \"");
b.append(s.getUrl());
b.append("\" ");
if (s.hasAlias()) {
b.append("alias ");
b.append(s.getAlias());
b.append(" ");
}
b.append("as ");
b.append(s.getMode().toCode());
renderDoco(b, s.getDocumentation());
b.append("\r\n");
}
if (map.hasStructure())
b.append("\r\n");
}
private static void renderImports(StringBuilder b, StructureMap map) {
for (UriType s : map.getImport()) {
b.append("imports \"");
b.append(s.getValue());
b.append("\"\r\n");
}
if (map.hasImport())
b.append("\r\n");
}
public static String groupToString(StructureMapGroupComponent g) {
StringBuilder b = new StringBuilder();
renderGroup(b, g);
return b.toString();
}
private static void renderGroup(StringBuilder b, StructureMapGroupComponent g) {
if (g.hasDocumentation()) {
renderMultilineDoco(b, g.getDocumentation(), 0);
}
b.append("group ");
b.append(g.getName());
b.append("(");
boolean first = true;
for (StructureMapGroupInputComponent gi : g.getInput()) {
if (first)
first = false;
else
b.append(", ");
b.append(gi.getMode().toCode());
b.append(" ");
b.append(gi.getName());
if (gi.hasType()) {
b.append(" : ");
b.append(gi.getType());
}
}
b.append(")");
if (g.hasExtends()) {
b.append(" extends ");
b.append(g.getExtends());
}
if (g.hasTypeMode()) {
switch (g.getTypeMode()) {
case TYPES:
b.append(" <<types>>");
break;
case TYPEANDTYPES:
b.append(" <<type+>>");
break;
default: // NONE, NULL
}
}
b.append(" {\r\n");
for (StructureMapGroupRuleComponent r : g.getRule()) {
renderRule(b, r, 2);
}
b.append("}\r\n\r\n");
}
public static String ruleToString(StructureMapGroupRuleComponent r) {
StringBuilder b = new StringBuilder();
renderRule(b, r, 0);
return b.toString();
}
private static void renderRule(StringBuilder b, StructureMapGroupRuleComponent r, int indent) {
if (r.hasFormatCommentPre()) {
renderMultilineDoco(b, r.getFormatCommentsPre(), indent);
}
for (int i = 0; i < indent; i++)
b.append(' ');
boolean canBeAbbreviated = checkisSimple(r);
{
boolean first = true;
for (StructureMapGroupRuleSourceComponent rs : r.getSource()) {
if (first)
first = false;
else
b.append(", ");
renderSource(b, rs, canBeAbbreviated);
}
}
if (r.getTarget().size() > 1) {
b.append(" -> ");
boolean first = true;
for (StructureMapGroupRuleTargetComponent rt : r.getTarget()) {
if (first)
first = false;
else
b.append(", ");
if (MULTIPLE_TARGETS_ONELINE)
b.append(' ');
else {
b.append("\r\n");
for (int i = 0; i < indent + 4; i++)
b.append(' ');
}
renderTarget(b, rt, false);
}
} else if (r.hasTarget()) {
b.append(" -> ");
renderTarget(b, r.getTarget().get(0), canBeAbbreviated);
}
if (r.hasRule()) {
b.append(" then {\r\n");
for (StructureMapGroupRuleComponent ir : r.getRule()) {
renderRule(b, ir, indent + 2);
}
for (int i = 0; i < indent; i++)
b.append(' ');
b.append("}");
} else if (!canBeAbbreviated) {
if (r.hasDependent()) {
b.append(" then ");
boolean first = true;
for (StructureMapGroupRuleDependentComponent rd : r.getDependent()) {
if (first)
first = false;
else
b.append(", ");
b.append(rd.getName());
b.append("(");
boolean ifirst = true;
for (StructureMapGroupRuleTargetParameterComponent rdp : rd.getParameter()) {
if (ifirst)
ifirst = false;
else
b.append(", ");
renderTransformParam(b, rdp);
}
b.append(")");
}
}
}
if (r.hasName()) {
String n = ntail(r.getName());
if (!n.startsWith("\""))
n = "\"" + n + "\"";
if (!matchesName(n, r.getSource())) {
b.append(" ");
b.append(n);
}
}
b.append(";");
b.append("\r\n");
}
private static boolean matchesName(String n, List<StructureMapGroupRuleSourceComponent> source) {
if (source.size() != 1)
return false;
if (!source.get(0).hasElement())
return false;
String s = source.get(0).getElement();
if (n.equals(s) || n.equals("\"" + s + "\""))
return true;
if (source.get(0).hasType()) {
s = source.get(0).getElement() + "-" + source.get(0).getType();
return n.equals(s) || n.equals("\"" + s + "\"");
}
return false;
}
private static String ntail(String name) {
if (name == null)
return null;
if (name.startsWith("\"")) {
name = name.substring(1);
name = name.substring(0, name.length() - 1);
}
return "\"" + (name.contains(".") ? name.substring(name.lastIndexOf(".") + 1) : name) + "\"";
}
private static boolean checkisSimple(StructureMapGroupRuleComponent r) {
return
(r.getSource().size() == 1 && r.getSourceFirstRep().hasElement() && r.getSourceFirstRep().hasVariable()) &&
(r.getTarget().size() == 1 && r.getTargetFirstRep().hasVariable() && (r.getTargetFirstRep().getTransform() == null || r.getTargetFirstRep().getTransform() == StructureMapTransform.CREATE) && r.getTargetFirstRep().getParameter().size() == 0) &&
(r.getDependent().size() == 0 || (r.getDependent().size() == 1 && StructureMapUtilities.DEF_GROUP_NAME.equals(r.getDependentFirstRep().getName()))) && (r.getRule().size() == 0);
}
public static String sourceToString(StructureMapGroupRuleSourceComponent r) {
StringBuilder b = new StringBuilder();
renderSource(b, r, false);
return b.toString();
}
private static void renderSource(StringBuilder b, StructureMapGroupRuleSourceComponent rs, boolean abbreviate) {
b.append(rs.getContext());
if (rs.getContext().equals("@search")) {
b.append('(');
b.append(rs.getElement());
b.append(')');
} else if (rs.hasElement()) {
b.append('.');
b.append(rs.getElement());
}
if (rs.hasType()) {
b.append(" : ");
b.append(rs.getType());
if (rs.hasMin()) {
b.append(" ");
b.append(rs.getMin());
b.append("..");
b.append(rs.getMax());
}
}
if (rs.hasListMode()) {
b.append(" ");
b.append(rs.getListMode().toCode());
}
if (rs.hasDefaultValue()) {
b.append(" default ");
b.append("\"" + Utilities.escapeJson(rs.getDefaultValue()) + "\"");
}
if (!abbreviate && rs.hasVariable()) {
b.append(" as ");
b.append(rs.getVariable());
}
if (rs.hasCondition()) {
b.append(" where ");
b.append(rs.getCondition());
}
if (rs.hasCheck()) {
b.append(" check ");
b.append(rs.getCheck());
}
if (rs.hasLogMessage()) {
b.append(" log ");
b.append(rs.getLogMessage());
}
}
public static String targetToString(StructureMapGroupRuleTargetComponent rt) {
StringBuilder b = new StringBuilder();
renderTarget(b, rt, false);
return b.toString();
}
private static void renderTarget(StringBuilder b, StructureMapGroupRuleTargetComponent rt, boolean abbreviate) {
if (rt.hasContext()) {
b.append(rt.getContext());
if (rt.hasElement()) {
b.append('.');
b.append(rt.getElement());
}
}
if (!abbreviate && rt.hasTransform()) {
if (rt.hasContext())
b.append(" = ");
if (rt.getTransform() == StructureMapTransform.COPY && rt.getParameter().size() == 1) {
renderTransformParam(b, rt.getParameter().get(0));
} else if (rt.getTransform() == StructureMapTransform.EVALUATE && rt.getParameter().size() == 1) {
b.append("(");
b.append(((StringType) rt.getParameter().get(0).getValue()).asStringValue());
b.append(")");
} else if (rt.getTransform() == StructureMapTransform.EVALUATE && rt.getParameter().size() == 2) {
b.append(rt.getTransform().toCode());
b.append("(");
b.append(((IdType) rt.getParameter().get(0).getValue()).asStringValue());
b.append(", ");
b.append(((StringType) rt.getParameter().get(1).getValue()).asStringValue());
b.append(")");
} else {
b.append(rt.getTransform().toCode());
b.append("(");
boolean first = true;
for (StructureMapGroupRuleTargetParameterComponent rtp : rt.getParameter()) {
if (first)
first = false;
else
b.append(", ");
renderTransformParam(b, rtp);
}
b.append(")");
}
}
if (!abbreviate && rt.hasVariable()) {
b.append(" as ");
b.append(rt.getVariable());
}
for (Enumeration<StructureMapTargetListMode> lm : rt.getListMode()) {
b.append(" ");
b.append(lm.getValue().toCode());
if (lm.getValue() == StructureMapTargetListMode.SHARE) {
b.append(" ");
b.append(rt.getListRuleId());
}
}
}
public static String paramToString(StructureMapGroupRuleTargetParameterComponent rtp) {
StringBuilder b = new StringBuilder();
renderTransformParam(b, rtp);
return b.toString();
}
private static void renderTransformParam(StringBuilder b, StructureMapGroupRuleTargetParameterComponent rtp) {
try {
if (rtp.hasValueBooleanType())
b.append(rtp.getValueBooleanType().asStringValue());
else if (rtp.hasValueDecimalType())
b.append(rtp.getValueDecimalType().asStringValue());
else if (rtp.hasValueIdType())
b.append(rtp.getValueIdType().asStringValue());
else if (rtp.hasValueIntegerType())
b.append(rtp.getValueIntegerType().asStringValue());
else
b.append("'" + Utilities.escapeJava(rtp.getValueStringType().asStringValue()) + "'");
} catch (FHIRException e) {
e.printStackTrace();
b.append("error!");
}
}
private static void renderDoco(StringBuilder b, String doco) {
if (Utilities.noString(doco))
return;
if (b != null && b.length() > 1 && b.charAt(b.length() - 1) != '\n' && b.charAt(b.length() - 1) != ' ') {
b.append(" ");
}
b.append("// ");
b.append(doco.replace("\r\n", " ").replace("\r", " ").replace("\n", " "));
}
private static void renderMultilineDoco(StringBuilder b, String doco, int indent) {
if (Utilities.noString(doco))
return;
String[] lines = doco.split("\\r?\\n");
for (String line : lines) {
for (int i = 0; i < indent; i++)
b.append(' ');
renderDoco(b, line);
b.append("\r\n");
}
}
private static void renderMultilineDoco(StringBuilder b, List<String> doco, int indent) {
if (doco == null || doco.isEmpty())
return;
for (String line : doco) {
for (int i = 0; i < indent; i++)
b.append(' ');
renderDoco(b, line);
b.append("\r\n");
}
}
public ITransformerServices getServices() {
return services;
}
public IWorkerContext getWorker() {
return worker;
}
public StructureMap parse(String text, String srcName) throws FHIRException {
FHIRLexer lexer = new FHIRLexer(Utilities.stripBOM(text), srcName, true, true);
if (lexer.done())
throw lexer.error("Map Input cannot be empty");
StructureMap result = new StructureMap();
if (lexer.hasToken("map")) {
lexer.token("map");
result.setUrl(lexer.readConstant("url"));
lexer.token("=");
result.setName(lexer.readConstant("name"));
result.setDescription(lexer.getAllComments());
result.setStatus(PublicationStatus.DRAFT);
}
while (lexer.hasToken("///")) {
lexer.next();
String fid = lexer.takeDottedToken();
lexer.token("=");
switch (fid) {
case "url" :
result.setUrl(lexer.readConstant("url"));
break;
case "name" :
result.setName(lexer.readConstant("name"));
break;
case "title" :
result.setTitle(lexer.readConstant("title"));
break;
case "description" :
result.setTitle(lexer.readConstant("description"));
break;
case "status" :
result.setStatus(PublicationStatus.fromCode(lexer.readConstant("status")));
break;
default:
lexer.readConstant("nothing");
// nothing
}
}
if (!result.hasId() && result.hasName()) {
String id = Utilities.makeId(result.getName());
if (!Utilities.noString(id)) {
result.setId(id);
}
}
if (!result.hasStatus()) {
result.setStatus(PublicationStatus.DRAFT);
}
if (!result.hasDescription() && result.hasTitle()) {
result.setDescription(result.getTitle());
}
while (lexer.hasToken("conceptmap"))
parseConceptMap(result, lexer);
while (lexer.hasToken("uses"))
parseUses(result, lexer);
while (lexer.hasToken("imports"))
parseImports(result, lexer);
while (lexer.hasToken("conceptmap"))
parseConceptMap(result, lexer);
while (!lexer.done()) {
parseGroup(result, lexer);
}
return result;
}
private void parseConceptMap(StructureMap result, FHIRLexer lexer) throws FHIRLexerException {
ConceptMap map = new ConceptMap();
map.addFormatCommentsPre(lexer.getComments());
lexer.token("conceptmap");
String id = lexer.readConstant("map id");
if (id.startsWith("#"))
throw lexer.error("Concept Map identifier must start with #");
map.setId(id);
map.setStatus(PublicationStatus.DRAFT); // todo: how to add this to the text format
result.getContained().add(map);
lexer.token("{");
// lexer.token("source");
// map.setSource(new UriType(lexer.readConstant("source")));
// lexer.token("target");
// map.setSource(new UriType(lexer.readConstant("target")));
Map<String, String> prefixes = new HashMap<String, String>();
while (lexer.hasToken("prefix")) {
lexer.token("prefix");
String n = lexer.take();
lexer.token("=");
String v = lexer.readConstant("prefix url");
prefixes.put(n, v);
}
while (lexer.hasToken("unmapped")) {
List<String> comments = lexer.cloneComments();
lexer.token("unmapped");
lexer.token("for");
String n = readPrefix(prefixes, lexer);
ConceptMapGroupComponent g = getGroup(map, n, null);
g.addFormatCommentsPre(comments);
lexer.token("=");
String v = lexer.take();
if (v.equals("provided")) {
g.getUnmapped().setMode(ConceptMapGroupUnmappedMode.USESOURCECODE);
} else
throw lexer.error("Only unmapped mode PROVIDED is supported at this time");
}
while (!lexer.hasToken("}")) {
List<String> comments = lexer.cloneComments();
String srcs = readPrefix(prefixes, lexer);
lexer.token(":");
String sc = lexer.getCurrent().startsWith("\"") ? lexer.readConstant("code") : lexer.take();
ConceptMapRelationship rel = readRelationship(lexer);
String tgts = readPrefix(prefixes, lexer);
ConceptMapGroupComponent g = getGroup(map, srcs, tgts);
SourceElementComponent e = g.addElement();
e.addFormatCommentsPre(comments);
e.setCode(sc);
if (e.getCode().startsWith("\"")) {
e.setCode(lexer.processConstant(e.getCode()));
}
TargetElementComponent tgt = e.addTarget();
tgt.setRelationship(rel);
lexer.token(":");
tgt.setCode(lexer.take());
if (tgt.getCode().startsWith("\"")) {
tgt.setCode(lexer.processConstant(tgt.getCode()));
}
// tgt.setComment(lexer.getAllComments());
}
map.addFormatCommentsPost(lexer.getComments());
lexer.token("}");
}
private ConceptMapGroupComponent getGroup(ConceptMap map, String srcs, String tgts) {
for (ConceptMapGroupComponent grp : map.getGroup()) {
if (grp.getSource().equals(srcs))
if (!grp.hasTarget() || tgts == null || tgts.equals(grp.getTarget())) {
if (!grp.hasTarget() && tgts != null)
grp.setTarget(tgts);
return grp;
}
}
ConceptMapGroupComponent grp = map.addGroup();
grp.setSource(srcs);
grp.setTarget(tgts);
return grp;
}
private String readPrefix(Map<String, String> prefixes, FHIRLexer lexer) throws FHIRLexerException {
String prefix = lexer.take();
if (!prefixes.containsKey(prefix))
throw lexer.error("Unknown prefix '" + prefix + "'");
return prefixes.get(prefix);
}
private ConceptMapRelationship readRelationship(FHIRLexer lexer) throws FHIRLexerException {
String token = lexer.take();
if (token.equals("-"))
return ConceptMapRelationship.RELATEDTO;
if (token.equals("=="))
return ConceptMapRelationship.EQUIVALENT;
if (token.equals("!="))
return ConceptMapRelationship.NOTRELATEDTO;
if (token.equals("<="))
return ConceptMapRelationship.SOURCEISNARROWERTHANTARGET;
if (token.equals(">="))
return ConceptMapRelationship.SOURCEISBROADERTHANTARGET;
throw lexer.error("Unknown relationship token '" + token + "'");
}
private void parseUses(StructureMap result, FHIRLexer lexer) throws FHIRException {
lexer.token("uses");
StructureMapStructureComponent st = result.addStructure();
st.setUrl(lexer.readConstant("url"));
if (lexer.hasToken("alias")) {
lexer.token("alias");
st.setAlias(lexer.take());
}
lexer.token("as");
String doco;
if (lexer.getCurrent().equals("source")) {
st.setMode(StructureMapModelMode.SOURCE);
doco = lexer.tokenWithTrailingComment("source");
} else if (lexer.getCurrent().equals("target")) {
st.setMode(StructureMapModelMode.TARGET);
doco = lexer.tokenWithTrailingComment("target");
} else {
throw lexer.error("Found '"+lexer.getCurrent()+"' expecting 'source' or 'target'");
}
if (lexer.hasToken(";")) {
doco = lexer.tokenWithTrailingComment(";");
}
st.setDocumentation(doco);
}
private void parseImports(StructureMap result, FHIRLexer lexer) throws FHIRException {
lexer.token("imports");
result.addImport(lexer.readConstant("url"));
lexer.skipToken(";");
}
private void parseGroup(StructureMap result, FHIRLexer lexer) throws FHIRException {
String comment = lexer.getAllComments();
lexer.token("group");
StructureMapGroupComponent group = result.addGroup();
if (comment != null) {
group.setDocumentation(comment);
}
boolean newFmt = false;
if (lexer.hasToken("for")) {
lexer.token("for");
if ("type".equals(lexer.getCurrent())) {
lexer.token("type");
lexer.token("+");
lexer.token("types");
group.setTypeMode(StructureMapGroupTypeMode.TYPEANDTYPES);
} else {
lexer.token("types");
group.setTypeMode(StructureMapGroupTypeMode.TYPES);
}
}
group.setName(lexer.take());
if (lexer.hasToken("(")) {
newFmt = true;
lexer.take();
while (!lexer.hasToken(")")) {
parseInput(group, lexer, true);
if (lexer.hasToken(","))
lexer.token(",");
}
lexer.take();
}
if (lexer.hasToken("extends")) {
lexer.next();
group.setExtends(lexer.take());
}
if (newFmt) {
if (lexer.hasToken("<")) {
lexer.token("<");
lexer.token("<");
if (lexer.hasToken("types")) {
group.setTypeMode(StructureMapGroupTypeMode.TYPES);
lexer.token("types");
} else {
lexer.token("type");
lexer.token("+");
group.setTypeMode(StructureMapGroupTypeMode.TYPEANDTYPES);
}
lexer.token(">");
lexer.token(">");
}
lexer.token("{");
}
if (newFmt) {
while (!lexer.hasToken("}")) {
if (lexer.done())
throw lexer.error("premature termination expecting 'endgroup'");
parseRule(result, group.getRule(), lexer, true);
}
} else {
while (lexer.hasToken("input"))
parseInput(group, lexer, false);
while (!lexer.hasToken("endgroup")) {
if (lexer.done())
throw lexer.error("premature termination expecting 'endgroup'");
parseRule(result, group.getRule(), lexer, false);
}
}
group.addFormatCommentsPost(lexer.getComments());
lexer.next();
if (newFmt && lexer.hasToken(";"))
lexer.next();
}
private void parseInput(StructureMapGroupComponent group, FHIRLexer lexer, boolean newFmt) throws FHIRException {
StructureMapGroupInputComponent input = group.addInput();
if (newFmt) {
input.setMode(StructureMapInputMode.fromCode(lexer.take()));
} else
lexer.token("input");
input.setName(lexer.take());
if (lexer.hasToken(":")) {
lexer.token(":");
input.setType(lexer.take());
}
if (!newFmt) {
lexer.token("as");
input.setMode(StructureMapInputMode.fromCode(lexer.take()));
input.setDocumentation(lexer.getAllComments());
lexer.skipToken(";");
}
}
private void parseRule(StructureMap map, List<StructureMapGroupRuleComponent> list, FHIRLexer lexer, boolean newFmt) throws FHIRException {
StructureMapGroupRuleComponent rule = new StructureMapGroupRuleComponent();
if (!newFmt) {
rule.setName(lexer.takeDottedToken());
lexer.token(":");
lexer.token("for");
} else {
rule.addFormatCommentsPre(lexer.getComments());
}
list.add(rule);
boolean done = false;
while (!done) {
parseSource(rule, lexer);
done = !lexer.hasToken(",");
if (!done)
lexer.next();
}
if ((newFmt && lexer.hasToken("->")) || (!newFmt && lexer.hasToken("make"))) {
lexer.token(newFmt ? "->" : "make");
done = false;
while (!done) {
parseTarget(rule, lexer);
done = !lexer.hasToken(",");
if (!done)
lexer.next();
}
}
if (lexer.hasToken("then")) {
lexer.token("then");
if (lexer.hasToken("{")) {
lexer.token("{");
while (!lexer.hasToken("}")) {
if (lexer.done())
throw lexer.error("premature termination expecting '}' in nested group");
parseRule(map, rule.getRule(), lexer, newFmt);
}
lexer.token("}");
} else {
done = false;
while (!done) {
parseRuleReference(rule, lexer);
done = !lexer.hasToken(",");
if (!done)
lexer.next();
}
}
}
if (isSimpleSyntax(rule)) {
rule.getSourceFirstRep().setVariable(AUTO_VAR_NAME);
rule.getTargetFirstRep().setVariable(AUTO_VAR_NAME);
rule.getTargetFirstRep().setTransform(StructureMapTransform.CREATE); // with no parameter - e.g. imply what is to be created
// no dependencies - imply what is to be done based on types
}
if (newFmt) {
if (lexer.isConstant()) {
if (lexer.isStringConstant()) {
rule.setName(fixName(lexer.readConstant("ruleName")));
} else {
rule.setName(lexer.take());
}
} else {
if (rule.getSource().size() != 1 || !rule.getSourceFirstRep().hasElement() && exceptionsForChecks )
throw lexer.error("Complex rules must have an explicit name");
if (rule.getSourceFirstRep().hasType())