001package org.hl7.fhir.r4.utils;
002
003/*
004  Copyright (c) 2011+, HL7, Inc.
005  All rights reserved.
006  
007  Redistribution and use in source and binary forms, with or without modification, 
008  are permitted provided that the following conditions are met:
009    
010   * Redistributions of source code must retain the above copyright notice, this 
011     list of conditions and the following disclaimer.
012   * Redistributions in binary form must reproduce the above copyright notice, 
013     this list of conditions and the following disclaimer in the documentation 
014     and/or other materials provided with the distribution.
015   * Neither the name of HL7 nor the names of its contributors may be used to 
016     endorse or promote products derived from this software without specific 
017     prior written permission.
018  
019  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
020  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
021  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
022  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
023  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
024  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
025  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
026  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
027  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
028  POSSIBILITY OF SUCH DAMAGE.
029  
030 */
031
032// remember group resolution
033// trace - account for which wasn't transformed in the source
034
035import java.io.IOException;
036import java.util.ArrayList;
037import java.util.EnumSet;
038import java.util.HashMap;
039import java.util.HashSet;
040import java.util.List;
041import java.util.Map;
042import java.util.Set;
043import java.util.UUID;
044
045import lombok.extern.slf4j.Slf4j;
046import org.apache.commons.lang3.NotImplementedException;
047import org.hl7.fhir.exceptions.DefinitionException;
048import org.hl7.fhir.exceptions.FHIRException;
049import org.hl7.fhir.exceptions.FHIRFormatError;
050import org.hl7.fhir.exceptions.PathEngineException;
051import org.hl7.fhir.r4.conformance.ProfileUtilities;
052import org.hl7.fhir.r4.conformance.ProfileUtilities.ProfileKnowledgeProvider;
053import org.hl7.fhir.r4.context.IWorkerContext;
054import org.hl7.fhir.r4.context.IWorkerContext.ValidationResult;
055import org.hl7.fhir.r4.elementmodel.Element;
056import org.hl7.fhir.r4.elementmodel.Property;
057import org.hl7.fhir.r4.fhirpath.ExpressionNode;
058import org.hl7.fhir.r4.fhirpath.FHIRLexer;
059import org.hl7.fhir.r4.fhirpath.FHIRPathEngine;
060import org.hl7.fhir.r4.fhirpath.TypeDetails;
061import org.hl7.fhir.r4.fhirpath.ExpressionNode.CollectionStatus;
062import org.hl7.fhir.r4.fhirpath.FHIRLexer.FHIRLexerException;
063import org.hl7.fhir.r4.fhirpath.IHostApplicationServices;
064import org.hl7.fhir.r4.fhirpath.FHIRPathUtilityClasses.FunctionDetails;
065import org.hl7.fhir.r4.fhirpath.TypeDetails.ProfiledType;
066import org.hl7.fhir.r4.model.*;
067import org.hl7.fhir.r4.model.ConceptMap.ConceptMapGroupComponent;
068import org.hl7.fhir.r4.model.ConceptMap.ConceptMapGroupUnmappedMode;
069import org.hl7.fhir.r4.model.ConceptMap.SourceElementComponent;
070import org.hl7.fhir.r4.model.ConceptMap.TargetElementComponent;
071import org.hl7.fhir.r4.model.ElementDefinition.ElementDefinitionMappingComponent;
072import org.hl7.fhir.r4.model.ElementDefinition.TypeRefComponent;
073import org.hl7.fhir.r4.model.Enumerations.ConceptMapEquivalence;
074import org.hl7.fhir.r4.model.Enumerations.FHIRVersion;
075import org.hl7.fhir.r4.model.Enumerations.PublicationStatus;
076import org.hl7.fhir.r4.model.Narrative.NarrativeStatus;
077import org.hl7.fhir.r4.model.StructureDefinition.StructureDefinitionMappingComponent;
078import org.hl7.fhir.r4.model.StructureDefinition.TypeDerivationRule;
079import org.hl7.fhir.r4.model.StructureMap.StructureMapContextType;
080import org.hl7.fhir.r4.model.StructureMap.StructureMapGroupComponent;
081import org.hl7.fhir.r4.model.StructureMap.StructureMapGroupInputComponent;
082import org.hl7.fhir.r4.model.StructureMap.StructureMapGroupRuleComponent;
083import org.hl7.fhir.r4.model.StructureMap.StructureMapGroupRuleDependentComponent;
084import org.hl7.fhir.r4.model.StructureMap.StructureMapGroupRuleSourceComponent;
085import org.hl7.fhir.r4.model.StructureMap.StructureMapGroupRuleTargetComponent;
086import org.hl7.fhir.r4.model.StructureMap.StructureMapGroupRuleTargetParameterComponent;
087import org.hl7.fhir.r4.model.StructureMap.StructureMapGroupTypeMode;
088import org.hl7.fhir.r4.model.StructureMap.StructureMapInputMode;
089import org.hl7.fhir.r4.model.StructureMap.StructureMapModelMode;
090import org.hl7.fhir.r4.model.StructureMap.StructureMapSourceListMode;
091import org.hl7.fhir.r4.model.StructureMap.StructureMapStructureComponent;
092import org.hl7.fhir.r4.model.StructureMap.StructureMapTargetListMode;
093import org.hl7.fhir.r4.model.StructureMap.StructureMapTransform;
094import org.hl7.fhir.r4.model.ValueSet.ValueSetExpansionContainsComponent;
095import org.hl7.fhir.r4.terminologies.ValueSetExpander.ValueSetExpansionOutcome;
096import org.hl7.fhir.r4.utils.validation.IResourceValidator;
097import org.hl7.fhir.utilities.CommaSeparatedStringBuilder;
098import org.hl7.fhir.utilities.FhirPublication;
099import org.hl7.fhir.utilities.MarkedToMoveToAdjunctPackage;
100import org.hl7.fhir.utilities.TerminologyServiceOptions;
101import org.hl7.fhir.utilities.Utilities;
102import org.hl7.fhir.utilities.fhirpath.FHIRPathConstantEvaluationMode;
103import org.hl7.fhir.utilities.validation.ValidationMessage;
104import org.hl7.fhir.utilities.xhtml.NodeType;
105import org.hl7.fhir.utilities.xhtml.XhtmlNode;
106
107/**
108 * Services in this class:
109 * 
110 * string render(map) - take a structure and convert it to text map parse(text)
111 * - take a text representation and parse it getTargetType(map) - return the
112 * definition for the type to create to hand in transform(appInfo, source, map,
113 * target) - transform from source to target following the map analyse(appInfo,
114 * map) - generate profiles and other analysis artifacts for the targets of the
115 * transform map generateMapFromMappings(StructureDefinition) - build a mapping
116 * from a structure definition with logical mappings
117 * 
118 * @author Grahame Grieve
119 *
120 */
121@MarkedToMoveToAdjunctPackage
122@Slf4j
123public class StructureMapUtilities {
124
125  public class ResolvedGroup {
126    public StructureMapGroupComponent target;
127    public StructureMap targetMap;
128  }
129
130  public static final String MAP_WHERE_CHECK = "map.where.check";
131  public static final String MAP_WHERE_LOG = "map.where.log";
132  public static final String MAP_WHERE_EXPRESSION = "map.where.expression";
133  public static final String MAP_SEARCH_EXPRESSION = "map.search.expression";
134  public static final String MAP_EXPRESSION = "map.transform.expression";
135  private static final boolean RENDER_MULTIPLE_TARGETS_ONELINE = true;
136  private static final String AUTO_VAR_NAME = "vvv";
137
138  public interface ITransformerServices {
139    // public boolean validateByValueSet(Coding code, String valuesetId);
140    public void log(String message); // log internal progress
141
142    public Base createType(Object appInfo, String name) throws FHIRException;
143
144    public Base createResource(Object appInfo, Base res, boolean atRootofTransform); // an already created resource is
145                                                                                     // provided; this is to
146                                                                                     // identify/store it
147
148    public Coding translate(Object appInfo, Coding source, String conceptMapUrl) throws FHIRException;
149
150    // public Coding translate(Coding code)
151    // ValueSet validation operation
152    // Translation operation
153    // Lookup another tree of data
154    // Create an instance tree
155    // Return the correct string format to refer to a tree (input or output)
156    public Base resolveReference(Object appContext, String url) throws FHIRException;
157
158    public List<Base> performSearch(Object appContext, String url) throws FHIRException;
159  }
160
161  private class FHIRPathHostServices implements IHostApplicationServices {
162
163    public List<Base> resolveConstant(FHIRPathEngine engine, Object appContext, String name, FHIRPathConstantEvaluationMode mode)
164        throws PathEngineException {
165      Variables vars = (Variables) appContext;
166      Base res = vars.get(VariableMode.INPUT, name);
167      if (res == null)
168        res = vars.get(VariableMode.OUTPUT, name);
169      List<Base> result = new ArrayList<Base>();
170      if (res != null)
171        result.add(res);
172      return result;
173    }
174
175    @Override
176    public TypeDetails resolveConstantType(FHIRPathEngine engine, Object appContext, String name, FHIRPathConstantEvaluationMode mode) throws PathEngineException {
177      if (!(appContext instanceof VariablesForProfiling))
178        throw new Error(
179            "Internal Logic Error (wrong type '" + appContext.getClass().getName() + "' in resolveConstantType)");
180      VariablesForProfiling vars = (VariablesForProfiling) appContext;
181      VariableForProfiling v = vars.get(null, name);
182      if (v == null)
183        throw new PathEngineException("Unknown variable '" + name + "' from variables " + vars.summary());
184      return v.property.types;
185    }
186
187    @Override
188    public boolean log(String argument, List<Base> focus) {
189      throw new Error("Not Implemented Yet");
190    }
191
192    @Override
193    public FunctionDetails resolveFunction(FHIRPathEngine engine, String functionName) {
194      return null; // throw new Error("Not Implemented Yet");
195    }
196
197    @Override
198    public TypeDetails checkFunction(FHIRPathEngine engine, Object appContext, String functionName, TypeDetails focus, List<TypeDetails> parameters)
199        throws PathEngineException {
200      throw new Error("Not Implemented Yet");
201    }
202
203    @Override
204    public List<Base> executeFunction(FHIRPathEngine engine, Object appContext, List<Base> focus, String functionName,
205        List<List<Base>> parameters) {
206      throw new Error("Not Implemented Yet");
207    }
208
209    @Override
210    public Base resolveReference(FHIRPathEngine engine, Object appContext, String url, Identifier identifier, Base base) throws FHIRException {
211      if (services == null)
212        return null;
213      return services.resolveReference(appContext, url);
214    }
215
216    @Override
217    public boolean conformsToProfile(FHIRPathEngine engine, Object appContext, Base item, String url) throws FHIRException {
218      IResourceValidator val = worker.newValidator();
219      List<ValidationMessage> valerrors = new ArrayList<ValidationMessage>();
220      if (item instanceof Resource) {
221        val.validate(appContext, valerrors, (Resource) item, url);
222        boolean ok = true;
223        for (ValidationMessage v : valerrors)
224          ok = ok && v.getLevel().isError();
225        return ok;
226      }
227      throw new NotImplementedException("Not done yet (FHIRPathHostServices.conformsToProfile), when item is element");
228    }
229
230    @Override
231    public ValueSet resolveValueSet(FHIRPathEngine engine, Object appContext, String url) {
232      throw new Error("Not Implemented Yet");
233    }
234
235    @Override
236    public boolean paramIsType(String name, int index) {
237      return false;
238    }
239  }
240
241  private IWorkerContext worker;
242  private FHIRPathEngine fpe;
243  private ITransformerServices services;
244  private ProfileKnowledgeProvider pkp;
245  private Map<String, Integer> ids = new HashMap<String, Integer>();
246  private TerminologyServiceOptions terminologyServiceOptions = new TerminologyServiceOptions(FhirPublication.R4);
247
248  public StructureMapUtilities(IWorkerContext worker, ITransformerServices services, ProfileKnowledgeProvider pkp) {
249    super();
250    this.worker = worker;
251    this.services = services;
252    this.pkp = pkp;
253    fpe = new FHIRPathEngine(worker);
254    fpe.setHostServices(new FHIRPathHostServices());
255  }
256
257  public StructureMapUtilities(IWorkerContext worker, ITransformerServices services) {
258    super();
259    this.worker = worker;
260    this.services = services;
261    fpe = new FHIRPathEngine(worker);
262    fpe.setHostServices(new FHIRPathHostServices());
263  }
264
265  public StructureMapUtilities(IWorkerContext worker) {
266    super();
267    this.worker = worker;
268    if (worker != null) {
269      fpe = new FHIRPathEngine(worker);
270      fpe.setHostServices(new FHIRPathHostServices());
271    }
272  }
273
274  public static String render(StructureMap map) {
275    StringBuilder b = new StringBuilder();
276    b.append("map \"");
277    b.append(map.getUrl());
278    b.append("\" = \"");
279    b.append(Utilities.escapeJson(map.getName()));
280    b.append("\"\r\n\r\n");
281
282    renderConceptMaps(b, map);
283    renderUses(b, map);
284    renderImports(b, map);
285    for (StructureMapGroupComponent g : map.getGroup())
286      renderGroup(b, g);
287    return b.toString();
288  }
289
290  private static void renderConceptMaps(StringBuilder b, StructureMap map) {
291    for (Resource r : map.getContained()) {
292      if (r instanceof ConceptMap) {
293        produceConceptMap(b, (ConceptMap) r);
294      }
295    }
296  }
297
298  private static void produceConceptMap(StringBuilder b, ConceptMap cm) {
299    b.append("conceptmap \"");
300    b.append(cm.getId());
301    b.append("\" {\r\n");
302    Map<String, String> prefixesSrc = new HashMap<String, String>();
303    Map<String, String> prefixesTgt = new HashMap<String, String>();
304    char prefix = 's';
305    for (ConceptMapGroupComponent cg : cm.getGroup()) {
306      if (!prefixesSrc.containsKey(cg.getSource())) {
307        prefixesSrc.put(cg.getSource(), String.valueOf(prefix));
308        b.append("  prefix ");
309        b.append(prefix);
310        b.append(" = \"");
311        b.append(cg.getSource());
312        b.append("\"\r\n");
313        prefix++;
314      }
315      if (!prefixesTgt.containsKey(cg.getTarget())) {
316        prefixesTgt.put(cg.getTarget(), String.valueOf(prefix));
317        b.append("  prefix ");
318        b.append(prefix);
319        b.append(" = \"");
320        b.append(cg.getTarget());
321        b.append("\"\r\n");
322        prefix++;
323      }
324    }
325    b.append("\r\n");
326    for (ConceptMapGroupComponent cg : cm.getGroup()) {
327      if (cg.hasUnmapped()) {
328        b.append("  unmapped for ");
329        b.append(prefixesSrc.get(cg.getSource()));
330        b.append(" = ");
331        b.append(cg.getUnmapped().getMode().toCode());
332        b.append("\r\n");
333      }
334    }
335
336    for (ConceptMapGroupComponent cg : cm.getGroup()) {
337      for (SourceElementComponent ce : cg.getElement()) {
338        b.append("  ");
339        b.append(prefixesSrc.get(cg.getSource()));
340        b.append(":");
341        if (Utilities.isToken(ce.getCode())) {
342          b.append(ce.getCode());
343        } else {
344          b.append("\"");
345          b.append(ce.getCode());
346          b.append("\"");
347        }
348        b.append(" ");
349        b.append(getChar(ce.getTargetFirstRep().getEquivalence()));
350        b.append(" ");
351        b.append(prefixesTgt.get(cg.getTarget()));
352        b.append(":");
353        if (Utilities.isToken(ce.getTargetFirstRep().getCode())) {
354          b.append(ce.getTargetFirstRep().getCode());
355        } else {
356          b.append("\"");
357          b.append(ce.getTargetFirstRep().getCode());
358          b.append("\"");
359        }
360        b.append("\r\n");
361      }
362    }
363    b.append("}\r\n\r\n");
364  }
365
366  private static Object getChar(ConceptMapEquivalence equivalence) {
367    switch (equivalence) {
368    case RELATEDTO:
369      return "-";
370    case EQUAL:
371      return "=";
372    case EQUIVALENT:
373      return "==";
374    case DISJOINT:
375      return "!=";
376    case UNMATCHED:
377      return "--";
378    case WIDER:
379      return "<=";
380    case SUBSUMES:
381      return "<-";
382    case NARROWER:
383      return ">=";
384    case SPECIALIZES:
385      return ">-";
386    case INEXACT:
387      return "~";
388    default:
389      return "??";
390    }
391  }
392
393  private static void renderUses(StringBuilder b, StructureMap map) {
394    for (StructureMapStructureComponent s : map.getStructure()) {
395      b.append("uses \"");
396      b.append(s.getUrl());
397      b.append("\" ");
398      if (s.hasAlias()) {
399        b.append("alias ");
400        b.append(s.getAlias());
401        b.append(" ");
402      }
403      b.append("as ");
404      b.append(s.getMode().toCode());
405      b.append("\r\n");
406      renderDoco(b, s.getDocumentation());
407    }
408    if (map.hasStructure())
409      b.append("\r\n");
410  }
411
412  private static void renderImports(StringBuilder b, StructureMap map) {
413    for (UriType s : map.getImport()) {
414      b.append("imports \"");
415      b.append(s.getValue());
416      b.append("\"\r\n");
417    }
418    if (map.hasImport())
419      b.append("\r\n");
420  }
421
422  public static String groupToString(StructureMapGroupComponent g) {
423    StringBuilder b = new StringBuilder();
424    renderGroup(b, g);
425    return b.toString();
426  }
427
428  private static void renderGroup(StringBuilder b, StructureMapGroupComponent g) {
429    b.append("group ");
430    b.append(g.getName());
431    b.append("(");
432    boolean first = true;
433    for (StructureMapGroupInputComponent gi : g.getInput()) {
434      if (first)
435        first = false;
436      else
437        b.append(", ");
438      b.append(gi.getMode().toCode());
439      b.append(" ");
440      b.append(gi.getName());
441      if (gi.hasType()) {
442        b.append(" : ");
443        b.append(gi.getType());
444      }
445    }
446    b.append(")");
447    if (g.hasExtends()) {
448      b.append(" extends ");
449      b.append(g.getExtends());
450    }
451
452    if (g.hasTypeMode()) {
453      switch (g.getTypeMode()) {
454      case TYPES:
455        b.append(" <<types>>");
456        break;
457      case TYPEANDTYPES:
458        b.append(" <<type+>>");
459        break;
460      default: // NONE, NULL
461      }
462    }
463    b.append(" {\r\n");
464    for (StructureMapGroupRuleComponent r : g.getRule()) {
465      renderRule(b, r, 2);
466    }
467    b.append("}\r\n\r\n");
468  }
469
470  public static String ruleToString(StructureMapGroupRuleComponent r) {
471    StringBuilder b = new StringBuilder();
472    renderRule(b, r, 0);
473    return b.toString();
474  }
475
476  private static void renderRule(StringBuilder b, StructureMapGroupRuleComponent r, int indent) {
477    for (int i = 0; i < indent; i++)
478      b.append(' ');
479    boolean canBeAbbreviated = checkisSimple(r);
480
481    boolean first = true;
482    for (StructureMapGroupRuleSourceComponent rs : r.getSource()) {
483      if (first)
484        first = false;
485      else
486        b.append(", ");
487      renderSource(b, rs, canBeAbbreviated);
488    }
489    if (r.getTarget().size() > 1) {
490      b.append(" -> ");
491      first = true;
492      for (StructureMapGroupRuleTargetComponent rt : r.getTarget()) {
493        if (first)
494          first = false;
495        else
496          b.append(", ");
497        if (RENDER_MULTIPLE_TARGETS_ONELINE)
498          b.append(' ');
499        else {
500          b.append("\r\n");
501          for (int i = 0; i < indent + 4; i++)
502            b.append(' ');
503        }
504        renderTarget(b, rt, false);
505      }
506    } else if (r.hasTarget()) {
507      b.append(" -> ");
508      renderTarget(b, r.getTarget().get(0), canBeAbbreviated);
509    }
510    if (r.hasRule()) {
511      b.append(" then {\r\n");
512      renderDoco(b, r.getDocumentation());
513      for (StructureMapGroupRuleComponent ir : r.getRule()) {
514        renderRule(b, ir, indent + 2);
515      }
516      for (int i = 0; i < indent; i++)
517        b.append(' ');
518      b.append("}");
519    } else {
520      if (r.hasDependent()) {
521        b.append(" then ");
522        first = true;
523        for (StructureMapGroupRuleDependentComponent rd : r.getDependent()) {
524          if (first)
525            first = false;
526          else
527            b.append(", ");
528          b.append(rd.getName());
529          b.append("(");
530          boolean ifirst = true;
531          for (StringType rdp : rd.getVariable()) {
532            if (ifirst)
533              ifirst = false;
534            else
535              b.append(", ");
536            b.append(rdp.asStringValue());
537          }
538          b.append(")");
539        }
540      }
541    }
542    if (r.hasName()) {
543      String n = ntail(r.getName());
544      if (!n.startsWith("\""))
545        n = "\"" + n + "\"";
546      if (!matchesName(n, r.getSource())) {
547        b.append(" ");
548        b.append(n);
549      }
550    }
551    b.append(";");
552    renderDoco(b, r.getDocumentation());
553    b.append("\r\n");
554  }
555
556  private static boolean matchesName(String n, List<StructureMapGroupRuleSourceComponent> source) {
557    if (source.size() != 1)
558      return false;
559    if (!source.get(0).hasElement())
560      return false;
561    String s = source.get(0).getElement();
562    if (n.equals(s) || n.equals("\"" + s + "\""))
563      return true;
564    if (source.get(0).hasType()) {
565      s = source.get(0).getElement() + "-" + source.get(0).getType();
566      if (n.equals(s) || n.equals("\"" + s + "\""))
567        return true;
568    }
569    return false;
570  }
571
572  private static String ntail(String name) {
573    if (name == null)
574      return null;
575    if (name.startsWith("\"")) {
576      name = name.substring(1);
577      name = name.substring(0, name.length() - 1);
578    }
579    return "\"" + (name.contains(".") ? name.substring(name.lastIndexOf(".") + 1) : name) + "\"";
580  }
581
582  private static boolean checkisSimple(StructureMapGroupRuleComponent r) {
583    return (r.getSource().size() == 1 && r.getSourceFirstRep().hasElement() && r.getSourceFirstRep().hasVariable())
584        && (r.getTarget().size() == 1 && r.getTargetFirstRep().hasVariable()
585            && (r.getTargetFirstRep().getTransform() == null
586                || r.getTargetFirstRep().getTransform() == StructureMapTransform.CREATE)
587            && r.getTargetFirstRep().getParameter().size() == 0)
588        && (r.getDependent().size() == 0) && (r.getRule().size() == 0);
589  }
590
591  public static String sourceToString(StructureMapGroupRuleSourceComponent r) {
592    StringBuilder b = new StringBuilder();
593    renderSource(b, r, false);
594    return b.toString();
595  }
596
597  private static void renderSource(StringBuilder b, StructureMapGroupRuleSourceComponent rs, boolean abbreviate) {
598    b.append(rs.getContext());
599    if (rs.getContext().equals("@search")) {
600      b.append('(');
601      b.append(rs.getElement());
602      b.append(')');
603    } else if (rs.hasElement()) {
604      b.append('.');
605      b.append(rs.getElement());
606    }
607    if (rs.hasType()) {
608      b.append(" : ");
609      b.append(rs.getType());
610      if (rs.hasMin()) {
611        b.append(" ");
612        b.append(rs.getMin());
613        b.append("..");
614        b.append(rs.getMax());
615      }
616    }
617
618    if (rs.hasListMode()) {
619      b.append(" ");
620      b.append(rs.getListMode().toCode());
621    }
622    if (rs.hasDefaultValue()) {
623      b.append(" default ");
624      assert rs.getDefaultValue() instanceof StringType;
625      b.append("\"" + Utilities.escapeJson(((StringType) rs.getDefaultValue()).asStringValue()) + "\"");
626    }
627    if (!abbreviate && rs.hasVariable()) {
628      b.append(" as ");
629      b.append(rs.getVariable());
630    }
631    if (rs.hasCondition()) {
632      b.append(" where ");
633      b.append(rs.getCondition());
634    }
635    if (rs.hasCheck()) {
636      b.append(" check ");
637      b.append(rs.getCheck());
638    }
639    if (rs.hasLogMessage()) {
640      b.append(" log ");
641      b.append(rs.getLogMessage());
642    }
643  }
644
645  public static String targetToString(StructureMapGroupRuleTargetComponent rt) {
646    StringBuilder b = new StringBuilder();
647    renderTarget(b, rt, false);
648    return b.toString();
649  }
650
651  private static void renderTarget(StringBuilder b, StructureMapGroupRuleTargetComponent rt, boolean abbreviate) {
652    if (rt.hasContext()) {
653      if (rt.getContextType() == StructureMapContextType.TYPE)
654        b.append("@");
655      b.append(rt.getContext());
656      if (rt.hasElement()) {
657        b.append('.');
658        b.append(rt.getElement());
659      }
660    }
661    if (!abbreviate && rt.hasTransform()) {
662      if (rt.hasContext())
663        b.append(" = ");
664      if (rt.getTransform() == StructureMapTransform.COPY && rt.getParameter().size() == 1) {
665        renderTransformParam(b, rt.getParameter().get(0));
666      } else if (rt.getTransform() == StructureMapTransform.EVALUATE && rt.getParameter().size() == 1) {
667        b.append("(");
668        b.append("\"" + ((StringType) rt.getParameter().get(0).getValue()).asStringValue() + "\"");
669        b.append(")");
670      } else if (rt.getTransform() == StructureMapTransform.EVALUATE && rt.getParameter().size() == 2) {
671        b.append(rt.getTransform().toCode());
672        b.append("(");
673        b.append(((IdType) rt.getParameter().get(0).getValue()).asStringValue());
674        b.append("\"" + ((StringType) rt.getParameter().get(1).getValue()).asStringValue() + "\"");
675        b.append(")");
676      } else {
677        b.append(rt.getTransform().toCode());
678        b.append("(");
679        boolean first = true;
680        for (StructureMapGroupRuleTargetParameterComponent rtp : rt.getParameter()) {
681          if (first)
682            first = false;
683          else
684            b.append(", ");
685          renderTransformParam(b, rtp);
686        }
687        b.append(")");
688      }
689    }
690    if (!abbreviate && rt.hasVariable()) {
691      b.append(" as ");
692      b.append(rt.getVariable());
693    }
694    for (Enumeration<StructureMapTargetListMode> lm : rt.getListMode()) {
695      b.append(" ");
696      b.append(lm.getValue().toCode());
697      if (lm.getValue() == StructureMapTargetListMode.SHARE) {
698        b.append(" ");
699        b.append(rt.getListRuleId());
700      }
701    }
702  }
703
704  public static String paramToString(StructureMapGroupRuleTargetParameterComponent rtp) {
705    StringBuilder b = new StringBuilder();
706    renderTransformParam(b, rtp);
707    return b.toString();
708  }
709
710  private static void renderTransformParam(StringBuilder b, StructureMapGroupRuleTargetParameterComponent rtp) {
711    try {
712      if (rtp.hasValueBooleanType())
713        b.append(rtp.getValueBooleanType().asStringValue());
714      else if (rtp.hasValueDecimalType())
715        b.append(rtp.getValueDecimalType().asStringValue());
716      else if (rtp.hasValueIdType())
717        b.append(rtp.getValueIdType().asStringValue());
718      else if (rtp.hasValueDecimalType())
719        b.append(rtp.getValueDecimalType().asStringValue());
720      else if (rtp.hasValueIntegerType())
721        b.append(rtp.getValueIntegerType().asStringValue());
722      else
723        b.append("'" + Utilities.escapeJava(rtp.getValueStringType().asStringValue()) + "'");
724    } catch (FHIRException e) {
725      e.printStackTrace();
726      b.append("error!");
727    }
728  }
729
730  private static void renderDoco(StringBuilder b, String doco) {
731    if (Utilities.noString(doco))
732      return;
733    b.append(" // ");
734    b.append(doco.replace("\r\n", " ").replace("\r", " ").replace("\n", " "));
735  }
736
737  public StructureMap parse(String text, String srcName) throws FHIRException {
738    FHIRLexer lexer = new FHIRLexer(text, srcName, true, true);
739    if (lexer.done())
740      throw lexer.error("Map Input cannot be empty");
741    lexer.skipComments();
742    lexer.token("map");
743    StructureMap result = new StructureMap();
744    result.setUrl(lexer.readConstant("url"));
745    result.setId(tail(result.getUrl()));
746    lexer.token("=");
747    result.setName(lexer.readConstant("name"));
748    lexer.skipComments();
749
750    while (lexer.hasToken("conceptmap"))
751      parseConceptMap(result, lexer);
752
753    while (lexer.hasToken("uses"))
754      parseUses(result, lexer);
755    while (lexer.hasToken("imports"))
756      parseImports(result, lexer);
757
758    while (!lexer.done()) {
759      parseGroup(result, lexer);
760    }
761
762    Narrative textNode = result.getText();
763    textNode.setStatus(Narrative.NarrativeStatus.ADDITIONAL);
764    XhtmlNode node = new XhtmlNode(NodeType.Element, "div");
765    textNode.setDiv(node);
766    node.pre().tx(text);
767
768    return result;
769  }
770
771  private void parseConceptMap(StructureMap result, FHIRLexer lexer) throws FHIRLexerException {
772    lexer.token("conceptmap");
773    ConceptMap map = new ConceptMap();
774    String id = lexer.readConstant("map id");
775    if (id.startsWith("#"))
776      throw lexer.error("Concept Map identifier must start with #");
777    map.setId(id);
778    map.setStatus(PublicationStatus.DRAFT); // todo: how to add this to the text format
779    result.getContained().add(map);
780    lexer.token("{");
781    lexer.skipComments();
782    // lexer.token("source");
783    // map.setSource(new UriType(lexer.readConstant("source")));
784    // lexer.token("target");
785    // map.setSource(new UriType(lexer.readConstant("target")));
786    Map<String, String> prefixes = new HashMap<String, String>();
787    while (lexer.hasToken("prefix")) {
788      lexer.token("prefix");
789      String n = lexer.take();
790      lexer.token("=");
791      String v = lexer.readConstant("prefix url");
792      prefixes.put(n, v);
793    }
794    while (lexer.hasToken("unmapped")) {
795      lexer.token("unmapped");
796      lexer.token("for");
797      String n = readPrefix(prefixes, lexer);
798      ConceptMapGroupComponent g = getGroup(map, n, null);
799      lexer.token("=");
800      String v = lexer.take();
801      if (v.equals("provided")) {
802        g.getUnmapped().setMode(ConceptMapGroupUnmappedMode.PROVIDED);
803      } else
804        throw lexer.error("Only unmapped mode PROVIDED is supported at this time");
805    }
806    while (!lexer.hasToken("}")) {
807      String srcs = readPrefix(prefixes, lexer);
808      lexer.token(":");
809      String sc = lexer.getCurrent().startsWith("\"") ? lexer.readConstant("code") : lexer.take();
810      ConceptMapEquivalence eq = readEquivalence(lexer);
811      String tgts = (eq != ConceptMapEquivalence.UNMATCHED) ? readPrefix(prefixes, lexer) : "";
812      ConceptMapGroupComponent g = getGroup(map, srcs, tgts);
813      SourceElementComponent e = g.addElement();
814      e.setCode(sc);
815      if (e.getCode().startsWith("\""))
816        e.setCode(lexer.processConstant(e.getCode()));
817      TargetElementComponent tgt = e.addTarget();
818      tgt.setEquivalence(eq);
819      if (tgt.getEquivalence() != ConceptMapEquivalence.UNMATCHED) {
820        lexer.token(":");
821        tgt.setCode(lexer.take());
822        if (tgt.getCode().startsWith("\""))
823          tgt.setCode(lexer.processConstant(tgt.getCode()));
824      }
825      if (lexer.hasComment())
826        tgt.setComment(lexer.take().substring(2).trim());
827    }
828    lexer.token("}");
829  }
830
831  private ConceptMapGroupComponent getGroup(ConceptMap map, String srcs, String tgts) {
832    for (ConceptMapGroupComponent grp : map.getGroup()) {
833      if (grp.getSource().equals(srcs))
834        if (!grp.hasTarget() || tgts == null || tgts.equals(grp.getTarget())) {
835          if (!grp.hasTarget() && tgts != null)
836            grp.setTarget(tgts);
837          return grp;
838        }
839    }
840    ConceptMapGroupComponent grp = map.addGroup();
841    grp.setSource(srcs);
842    grp.setTarget(tgts);
843    return grp;
844  }
845
846  private String readPrefix(Map<String, String> prefixes, FHIRLexer lexer) throws FHIRLexerException {
847    String prefix = lexer.take();
848    if (!prefixes.containsKey(prefix))
849      throw lexer.error("Unknown prefix '" + prefix + "'");
850    return prefixes.get(prefix);
851  }
852
853  private ConceptMapEquivalence readEquivalence(FHIRLexer lexer) throws FHIRLexerException {
854    String token = lexer.take();
855    if (token.equals("-"))
856      return ConceptMapEquivalence.RELATEDTO;
857    if (token.equals("="))
858      return ConceptMapEquivalence.EQUAL;
859    if (token.equals("=="))
860      return ConceptMapEquivalence.EQUIVALENT;
861    if (token.equals("!="))
862      return ConceptMapEquivalence.DISJOINT;
863    if (token.equals("--"))
864      return ConceptMapEquivalence.UNMATCHED;
865    if (token.equals("<="))
866      return ConceptMapEquivalence.WIDER;
867    if (token.equals("<-"))
868      return ConceptMapEquivalence.SUBSUMES;
869    if (token.equals(">="))
870      return ConceptMapEquivalence.NARROWER;
871    if (token.equals(">-"))
872      return ConceptMapEquivalence.SPECIALIZES;
873    if (token.equals("~"))
874      return ConceptMapEquivalence.INEXACT;
875    throw lexer.error("Unknown equivalence token '" + token + "'");
876  }
877
878  private void parseUses(StructureMap result, FHIRLexer lexer) throws FHIRException {
879    lexer.token("uses");
880    StructureMapStructureComponent st = result.addStructure();
881    st.setUrl(lexer.readConstant("url"));
882    if (lexer.hasToken("alias")) {
883      lexer.token("alias");
884      st.setAlias(lexer.take());
885    }
886    lexer.token("as");
887    st.setMode(StructureMapModelMode.fromCode(lexer.take()));
888    lexer.skipToken(";");
889    if (lexer.hasComment()) {
890      st.setDocumentation(lexer.take().substring(2).trim());
891    }
892    lexer.skipComments();
893  }
894
895  private void parseImports(StructureMap result, FHIRLexer lexer) throws FHIRException {
896    lexer.token("imports");
897    result.addImport(lexer.readConstant("url"));
898    lexer.skipToken(";");
899    if (lexer.hasComment()) {
900      lexer.next();
901    }
902    lexer.skipComments();
903  }
904
905  private void parseGroup(StructureMap result, FHIRLexer lexer) throws FHIRException {
906    lexer.token("group");
907    StructureMapGroupComponent group = result.addGroup();
908    boolean newFmt = false;
909    if (lexer.hasToken("for")) {
910      lexer.token("for");
911      if ("type".equals(lexer.getCurrent())) {
912        lexer.token("type");
913        lexer.token("+");
914        lexer.token("types");
915        group.setTypeMode(StructureMapGroupTypeMode.TYPEANDTYPES);
916      } else {
917        lexer.token("types");
918        group.setTypeMode(StructureMapGroupTypeMode.TYPES);
919      }
920    } else
921      group.setTypeMode(StructureMapGroupTypeMode.NONE);
922    group.setName(lexer.take());
923    if (lexer.hasToken("(")) {
924      newFmt = true;
925      lexer.take();
926      while (!lexer.hasToken(")")) {
927        parseInput(group, lexer, true);
928        if (lexer.hasToken(","))
929          lexer.token(",");
930      }
931      lexer.take();
932    }
933    if (lexer.hasToken("extends")) {
934      lexer.next();
935      group.setExtends(lexer.take());
936    }
937    if (newFmt) {
938      group.setTypeMode(StructureMapGroupTypeMode.NONE);
939      if (lexer.hasToken("<")) {
940        lexer.token("<");
941        lexer.token("<");
942        if (lexer.hasToken("types")) {
943          group.setTypeMode(StructureMapGroupTypeMode.TYPES);
944          lexer.token("types");
945        } else {
946          lexer.token("type");
947          lexer.token("+");
948          group.setTypeMode(StructureMapGroupTypeMode.TYPEANDTYPES);
949        }
950        lexer.token(">");
951        lexer.token(">");
952      }
953      lexer.token("{");
954    }
955    lexer.skipComments();
956    if (newFmt) {
957      while (!lexer.hasToken("}")) {
958        if (lexer.done())
959          throw lexer.error("premature termination expecting 'endgroup'");
960        parseRule(result, group.getRule(), lexer, true);
961      }
962    } else {
963      while (lexer.hasToken("input"))
964        parseInput(group, lexer, false);
965      while (!lexer.hasToken("endgroup")) {
966        if (lexer.done())
967          throw lexer.error("premature termination expecting 'endgroup'");
968        parseRule(result, group.getRule(), lexer, false);
969      }
970    }
971    lexer.next();
972    if (newFmt && lexer.hasToken(";"))
973      lexer.next();
974    lexer.skipComments();
975  }
976
977  private void parseInput(StructureMapGroupComponent group, FHIRLexer lexer, boolean newFmt) throws FHIRException {
978    StructureMapGroupInputComponent input = group.addInput();
979    if (newFmt) {
980      input.setMode(StructureMapInputMode.fromCode(lexer.take()));
981    } else
982      lexer.token("input");
983    input.setName(lexer.take());
984    if (lexer.hasToken(":")) {
985      lexer.token(":");
986      input.setType(lexer.take());
987    }
988    if (!newFmt) {
989      lexer.token("as");
990      input.setMode(StructureMapInputMode.fromCode(lexer.take()));
991      if (lexer.hasComment()) {
992        input.setDocumentation(lexer.take().substring(2).trim());
993      }
994      lexer.skipToken(";");
995      lexer.skipComments();
996    }
997  }
998
999  private void parseRule(StructureMap map, List<StructureMapGroupRuleComponent> list, FHIRLexer lexer, boolean newFmt)
1000      throws FHIRException {
1001    StructureMapGroupRuleComponent rule = new StructureMapGroupRuleComponent();
1002    list.add(rule);
1003    if (!newFmt) {
1004      rule.setName(lexer.takeDottedToken());
1005      lexer.token(":");
1006      lexer.token("for");
1007    }
1008    boolean done = false;
1009    while (!done) {
1010      parseSource(rule, lexer);
1011      done = !lexer.hasToken(",");
1012      if (!done)
1013        lexer.next();
1014    }
1015    if ((newFmt && lexer.hasToken("->")) || (!newFmt && lexer.hasToken("make"))) {
1016      lexer.token(newFmt ? "->" : "make");
1017      done = false;
1018      while (!done) {
1019        parseTarget(rule, lexer);
1020        done = !lexer.hasToken(",");
1021        if (!done)
1022          lexer.next();
1023      }
1024    }
1025    if (lexer.hasToken("then")) {
1026      lexer.token("then");
1027      if (lexer.hasToken("{")) {
1028        lexer.token("{");
1029        if (lexer.hasComment()) {
1030          rule.setDocumentation(lexer.take().substring(2).trim());
1031        }
1032        lexer.skipComments();
1033        while (!lexer.hasToken("}")) {
1034          if (lexer.done())
1035            throw lexer.error("premature termination expecting '}' in nested group");
1036          parseRule(map, rule.getRule(), lexer, newFmt);
1037        }
1038        lexer.token("}");
1039      } else {
1040        done = false;
1041        while (!done) {
1042          parseRuleReference(rule, lexer);
1043          done = !lexer.hasToken(",");
1044          if (!done)
1045            lexer.next();
1046        }
1047      }
1048    } else if (lexer.hasComment()) {
1049      rule.setDocumentation(lexer.take().substring(2).trim());
1050    }
1051    if (isSimpleSyntax(rule)) {
1052      rule.getSourceFirstRep().setVariable(AUTO_VAR_NAME);
1053      rule.getTargetFirstRep().setVariable(AUTO_VAR_NAME);
1054      rule.getTargetFirstRep().setTransform(StructureMapTransform.CREATE); // with no parameter - e.g. imply what is to
1055                                                                           // be created
1056      // no dependencies - imply what is to be done based on types
1057    }
1058    if (newFmt) {
1059      if (lexer.isConstant()) {
1060        if (lexer.isStringConstant()) {
1061          rule.setName(lexer.readConstant("ruleName"));
1062        } else {
1063          rule.setName(lexer.take());
1064        }
1065      } else {
1066        if (rule.getSource().size() != 1 || !rule.getSourceFirstRep().hasElement())
1067          throw lexer.error("Complex rules must have an explicit name");
1068        if (rule.getSourceFirstRep().hasType())
1069          rule.setName(rule.getSourceFirstRep().getElement() + "-" + rule.getSourceFirstRep().getType());
1070        else
1071          rule.setName(rule.getSourceFirstRep().getElement());
1072      }
1073      lexer.token(";");
1074    }
1075    lexer.skipComments();
1076  }
1077
1078  private boolean isSimpleSyntax(StructureMapGroupRuleComponent rule) {
1079    return (rule.getSource().size() == 1 && rule.getSourceFirstRep().hasContext()
1080        && rule.getSourceFirstRep().hasElement() && !rule.getSourceFirstRep().hasVariable())
1081        && (rule.getTarget().size() == 1 && rule.getTargetFirstRep().hasContext()
1082            && rule.getTargetFirstRep().hasElement() && !rule.getTargetFirstRep().hasVariable()
1083            && !rule.getTargetFirstRep().hasParameter())
1084        && (rule.getDependent().size() == 0 && rule.getRule().size() == 0);
1085  }
1086
1087  private void parseRuleReference(StructureMapGroupRuleComponent rule, FHIRLexer lexer) throws FHIRLexerException {
1088    StructureMapGroupRuleDependentComponent ref = rule.addDependent();
1089    ref.setName(lexer.take());
1090    lexer.token("(");
1091    boolean done = false;
1092    while (!done) {
1093      ref.addVariable(lexer.take());
1094      done = !lexer.hasToken(",");
1095      if (!done)
1096        lexer.next();
1097    }
1098    lexer.token(")");
1099  }
1100
1101  private void parseSource(StructureMapGroupRuleComponent rule, FHIRLexer lexer) throws FHIRException {
1102    StructureMapGroupRuleSourceComponent source = rule.addSource();
1103    source.setContext(lexer.take());
1104    if (source.getContext().equals("search") && lexer.hasToken("(")) {
1105      source.setContext("@search");
1106      lexer.take();
1107      ExpressionNode node = fpe.parse(lexer);
1108      source.setUserData(MAP_SEARCH_EXPRESSION, node);
1109      source.setElement(node.toString());
1110      lexer.token(")");
1111    } else if (lexer.hasToken(".")) {
1112      lexer.token(".");
1113      source.setElement(lexer.take());
1114    }
1115    if (lexer.hasToken(":")) {
1116      // type and cardinality
1117      lexer.token(":");
1118      source.setType(lexer.takeDottedToken());
1119      if (!lexer.hasToken("as", "first", "last", "not_first", "not_last", "only_one", "default")) {
1120        source.setMin(lexer.takeInt());
1121        lexer.token("..");
1122        source.setMax(lexer.take());
1123      }
1124    }
1125    if (lexer.hasToken("default")) {
1126      lexer.token("default");
1127      source.setDefaultValue(new StringType(lexer.readConstant("default value")));
1128    }
1129    if (Utilities.existsInList(lexer.getCurrent(), "first", "last", "not_first", "not_last", "only_one"))
1130      source.setListMode(StructureMapSourceListMode.fromCode(lexer.take()));
1131
1132    if (lexer.hasToken("as")) {
1133      lexer.take();
1134      source.setVariable(lexer.take());
1135    }
1136    if (lexer.hasToken("where")) {
1137      lexer.take();
1138      ExpressionNode node = fpe.parse(lexer);
1139      source.setUserData(MAP_WHERE_EXPRESSION, node);
1140      source.setCondition(node.toString());
1141    }
1142    if (lexer.hasToken("check")) {
1143      lexer.take();
1144      ExpressionNode node = fpe.parse(lexer);
1145      source.setUserData(MAP_WHERE_CHECK, node);
1146      source.setCheck(node.toString());
1147    }
1148    if (lexer.hasToken("log")) {
1149      lexer.take();
1150      ExpressionNode node = fpe.parse(lexer);
1151      source.setUserData(MAP_WHERE_CHECK, node);
1152      source.setLogMessage(node.toString());
1153    }
1154  }
1155
1156  private void parseTarget(StructureMapGroupRuleComponent rule, FHIRLexer lexer) throws FHIRException {
1157    StructureMapGroupRuleTargetComponent target = rule.addTarget();
1158    String start = lexer.take();
1159    if (lexer.hasToken(".")) {
1160      target.setContext(start);
1161      target.setContextType(StructureMapContextType.VARIABLE);
1162      start = null;
1163      lexer.token(".");
1164      target.setElement(lexer.take());
1165    }
1166    String name;
1167    boolean isConstant = false;
1168    if (lexer.hasToken("=")) {
1169      if (start != null)
1170        target.setContext(start);
1171      lexer.token("=");
1172      isConstant = lexer.isConstant();
1173      name = lexer.take();
1174    } else
1175      name = start;
1176
1177    if ("(".equals(name)) {
1178      // inline fluentpath expression
1179      target.setTransform(StructureMapTransform.EVALUATE);
1180      ExpressionNode node = fpe.parse(lexer);
1181      target.setUserData(MAP_EXPRESSION, node);
1182      target.addParameter().setValue(new StringType(node.toString()));
1183      lexer.token(")");
1184    } else if (lexer.hasToken("(")) {
1185      target.setTransform(StructureMapTransform.fromCode(name));
1186      lexer.token("(");
1187      if (target.getTransform() == StructureMapTransform.EVALUATE) {
1188        parseParameter(target, lexer);
1189        lexer.token(",");
1190        ExpressionNode node = fpe.parse(lexer);
1191        target.setUserData(MAP_EXPRESSION, node);
1192        target.addParameter().setValue(new StringType(node.toString()));
1193      } else {
1194        while (!lexer.hasToken(")")) {
1195          parseParameter(target, lexer);
1196          if (!lexer.hasToken(")"))
1197            lexer.token(",");
1198        }
1199      }
1200      lexer.token(")");
1201    } else if (name != null) {
1202      target.setTransform(StructureMapTransform.COPY);
1203      if (!isConstant) {
1204        String id = name;
1205        while (lexer.hasToken(".")) {
1206          id = id + lexer.take() + lexer.take();
1207        }
1208        target.addParameter().setValue(new IdType(id));
1209      } else
1210        target.addParameter().setValue(readConstant(name, lexer));
1211    }
1212    if (lexer.hasToken("as")) {
1213      lexer.take();
1214      target.setVariable(lexer.take());
1215    }
1216    while (Utilities.existsInList(lexer.getCurrent(), "first", "last", "share", "collate")) {
1217      if (lexer.getCurrent().equals("share")) {
1218        target.addListMode(StructureMapTargetListMode.SHARE);
1219        lexer.next();
1220        target.setListRuleId(lexer.take());
1221      } else {
1222        if (lexer.getCurrent().equals("first"))
1223          target.addListMode(StructureMapTargetListMode.FIRST);
1224        else
1225          target.addListMode(StructureMapTargetListMode.LAST);
1226        lexer.next();
1227      }
1228    }
1229  }
1230
1231  private void parseParameter(StructureMapGroupRuleTargetComponent target, FHIRLexer lexer)
1232      throws FHIRLexerException, FHIRFormatError {
1233    if (!lexer.isConstant()) {
1234      target.addParameter().setValue(new IdType(lexer.take()));
1235    } else if (lexer.isStringConstant())
1236      target.addParameter().setValue(new StringType(lexer.readConstant("??")));
1237    else {
1238      target.addParameter().setValue(readConstant(lexer.take(), lexer));
1239    }
1240  }
1241
1242  private Type readConstant(String s, FHIRLexer lexer) throws FHIRLexerException {
1243    if (Utilities.isInteger(s))
1244      return new IntegerType(s);
1245    else if (Utilities.isDecimal(s, false))
1246      return new DecimalType(s);
1247    else if (Utilities.existsInList(s, "true", "false"))
1248      return new BooleanType(s.equals("true"));
1249    else
1250      return new StringType(lexer.processConstant(s));
1251  }
1252
1253  public StructureDefinition getTargetType(StructureMap map) throws FHIRException {
1254    boolean found = false;
1255    StructureDefinition res = null;
1256    for (StructureMapStructureComponent uses : map.getStructure()) {
1257      if (uses.getMode() == StructureMapModelMode.TARGET) {
1258        if (found)
1259          throw new FHIRException("Multiple targets found in map " + map.getUrl());
1260        found = true;
1261        res = worker.fetchResource(StructureDefinition.class, uses.getUrl());
1262        if (res == null)
1263          throw new FHIRException("Unable to find " + uses.getUrl() + " referenced from map " + map.getUrl());
1264      }
1265    }
1266    if (res == null)
1267      throw new FHIRException("No targets found in map " + map.getUrl());
1268    return res;
1269  }
1270
1271  public enum VariableMode {
1272    INPUT, OUTPUT, SHARED
1273  }
1274
1275  public class Variable {
1276    private VariableMode mode;
1277    private String name;
1278    private Base object;
1279
1280    public Variable(VariableMode mode, String name, Base object) {
1281      super();
1282      this.mode = mode;
1283      this.name = name;
1284      this.object = object;
1285    }
1286
1287    public VariableMode getMode() {
1288      return mode;
1289    }
1290
1291    public String getName() {
1292      return name;
1293    }
1294
1295    public Base getObject() {
1296      return object;
1297    }
1298
1299    public String summary() {
1300      if (object == null)
1301        return null;
1302      else if (object instanceof PrimitiveType)
1303        return name + ": \"" + ((PrimitiveType) object).asStringValue() + '"';
1304      else
1305        return name + ": (" + object.fhirType() + ")";
1306    }
1307  }
1308
1309  public class Variables {
1310    private List<Variable> list = new ArrayList<Variable>();
1311
1312    public void add(VariableMode mode, String name, Base object) {
1313      Variable vv = null;
1314      for (Variable v : list)
1315        if ((v.mode == mode) && v.getName().equals(name))
1316          vv = v;
1317      if (vv != null)
1318        list.remove(vv);
1319      list.add(new Variable(mode, name, object));
1320    }
1321
1322    public Variables copy() {
1323      Variables result = new Variables();
1324      result.list.addAll(list);
1325      return result;
1326    }
1327
1328    public Base get(VariableMode mode, String name) {
1329      for (Variable v : list)
1330        if ((v.mode == mode) && v.getName().equals(name))
1331          return v.getObject();
1332      return null;
1333    }
1334
1335    public String summary() {
1336      CommaSeparatedStringBuilder s = new CommaSeparatedStringBuilder();
1337      CommaSeparatedStringBuilder t = new CommaSeparatedStringBuilder();
1338      CommaSeparatedStringBuilder sh = new CommaSeparatedStringBuilder();
1339      for (Variable v : list)
1340        switch (v.mode) {
1341        case INPUT:
1342          s.append(v.summary());
1343          break;
1344        case OUTPUT:
1345          t.append(v.summary());
1346          break;
1347        case SHARED:
1348          sh.append(v.summary());
1349          break;
1350        }
1351      return "source variables [" + s.toString() + "], target variables [" + t.toString() + "], shared variables ["
1352          + sh.toString() + "]";
1353    }
1354
1355  }
1356
1357  public class TransformContext {
1358    private Object appInfo;
1359
1360    public TransformContext(Object appInfo) {
1361      super();
1362      this.appInfo = appInfo;
1363    }
1364
1365    public Object getAppInfo() {
1366      return appInfo;
1367    }
1368
1369  }
1370
1371  private void log(String cnt) {
1372    if (services != null)
1373      services.log(cnt);
1374    else
1375      log.info(cnt);
1376  }
1377
1378  /**
1379   * Given an item, return all the children that conform to the pattern described
1380   * in name
1381   * 
1382   * Possible patterns: - a simple name (which may be the base of a name with []
1383   * e.g. value[x]) - a name with a type replacement e.g. valueCodeableConcept - *
1384   * which means all children - ** which means all descendents
1385   * 
1386   * @param item
1387   * @param name
1388   * @param result
1389   * @throws FHIRException
1390   */
1391  protected void getChildrenByName(Base item, String name, List<Base> result) throws FHIRException {
1392    for (Base v : item.listChildrenByName(name, true))
1393      if (v != null)
1394        result.add(v);
1395  }
1396
1397  public void transform(Object appInfo, Base source, StructureMap map, Base target) throws FHIRException {
1398    TransformContext context = new TransformContext(appInfo);
1399    log("Start Transform " + map.getUrl());
1400    StructureMapGroupComponent g = map.getGroup().get(0);
1401
1402    Variables vars = new Variables();
1403    vars.add(VariableMode.INPUT, getInputName(g, StructureMapInputMode.SOURCE, "source"), source);
1404    if (target != null)
1405      vars.add(VariableMode.OUTPUT, getInputName(g, StructureMapInputMode.TARGET, "target"), target);
1406
1407    executeGroup("", context, map, vars, g, true);
1408    if (target instanceof Element)
1409      ((Element) target).sort();
1410  }
1411
1412  private String getInputName(StructureMapGroupComponent g, StructureMapInputMode mode, String def)
1413      throws DefinitionException {
1414    String name = null;
1415    for (StructureMapGroupInputComponent inp : g.getInput()) {
1416      if (inp.getMode() == mode)
1417        if (name != null)
1418          throw new DefinitionException("This engine does not support multiple source inputs");
1419        else
1420          name = inp.getName();
1421    }
1422    return name == null ? def : name;
1423  }
1424
1425  private void executeGroup(String indent, TransformContext context, StructureMap map, Variables vars,
1426      StructureMapGroupComponent group, boolean atRoot) throws FHIRException {
1427    log(indent + "Group : " + group.getName() + "; vars = " + vars.summary());
1428    // todo: check inputs
1429    if (group.hasExtends()) {
1430      ResolvedGroup rg = resolveGroupReference(map, group, group.getExtends());
1431      executeGroup(indent + " ", context, rg.targetMap, vars, rg.target, false);
1432    }
1433
1434    for (StructureMapGroupRuleComponent r : group.getRule()) {
1435      executeRule(indent + "  ", context, map, vars, group, r, atRoot);
1436    }
1437  }
1438
1439  private void executeRule(String indent, TransformContext context, StructureMap map, Variables vars,
1440      StructureMapGroupComponent group, StructureMapGroupRuleComponent rule, boolean atRoot) throws FHIRException {
1441    log(indent + "rule : " + rule.getName() + "; vars = " + vars.summary());
1442    Variables srcVars = vars.copy();
1443    if (rule.getSource().size() != 1)
1444      throw new FHIRException("Rule \"" + rule.getName() + "\": not handled yet");
1445    List<Variables> source = processSource(rule.getName(), context, srcVars, rule.getSource().get(0), map.getUrl(),
1446        indent);
1447    if (source != null) {
1448      for (Variables v : source) {
1449        for (StructureMapGroupRuleTargetComponent t : rule.getTarget()) {
1450          processTarget(rule.getName(), context, v, map, group, t,
1451              rule.getSource().size() == 1 ? rule.getSourceFirstRep().getVariable() : null, atRoot, vars);
1452        }
1453        if (rule.hasRule()) {
1454          for (StructureMapGroupRuleComponent childrule : rule.getRule()) {
1455            executeRule(indent + "  ", context, map, v, group, childrule, false);
1456          }
1457        } else if (rule.hasDependent()) {
1458          for (StructureMapGroupRuleDependentComponent dependent : rule.getDependent()) {
1459            executeDependency(indent + "  ", context, map, v, group, dependent);
1460          }
1461        } else if (rule.getSource().size() == 1 && rule.getSourceFirstRep().hasVariable()
1462            && rule.getTarget().size() == 1 && rule.getTargetFirstRep().hasVariable()
1463            && rule.getTargetFirstRep().getTransform() == StructureMapTransform.CREATE
1464            && !rule.getTargetFirstRep().hasParameter()) {
1465          // simple inferred, map by type
1466          log.info(v.summary());
1467          Base src = v.get(VariableMode.INPUT, rule.getSourceFirstRep().getVariable());
1468          Base tgt = v.get(VariableMode.OUTPUT, rule.getTargetFirstRep().getVariable());
1469          String srcType = src.fhirType();
1470          String tgtType = tgt.fhirType();
1471          ResolvedGroup defGroup = resolveGroupByTypes(map, rule.getName(), group, srcType, tgtType);
1472          Variables vdef = new Variables();
1473          vdef.add(VariableMode.INPUT, defGroup.target.getInput().get(0).getName(), src);
1474          vdef.add(VariableMode.OUTPUT, defGroup.target.getInput().get(1).getName(), tgt);
1475          executeGroup(indent + "  ", context, defGroup.targetMap, vdef, defGroup.target, false);
1476        }
1477      }
1478    }
1479  }
1480
1481  private void executeDependency(String indent, TransformContext context, StructureMap map, Variables vin,
1482      StructureMapGroupComponent group, StructureMapGroupRuleDependentComponent dependent) throws FHIRException {
1483    ResolvedGroup rg = resolveGroupReference(map, group, dependent.getName());
1484
1485    if (rg.target.getInput().size() != dependent.getVariable().size()) {
1486      throw new FHIRException("Rule '" + dependent.getName() + "' has " + Integer.toString(rg.target.getInput().size())
1487          + " but the invocation has " + Integer.toString(dependent.getVariable().size()) + " variables");
1488    }
1489    Variables v = new Variables();
1490    for (int i = 0; i < rg.target.getInput().size(); i++) {
1491      StructureMapGroupInputComponent input = rg.target.getInput().get(i);
1492      StringType rdp = dependent.getVariable().get(i);
1493      String var = rdp.asStringValue();
1494      VariableMode mode = input.getMode() == StructureMapInputMode.SOURCE ? VariableMode.INPUT : VariableMode.OUTPUT;
1495      Base vv = vin.get(mode, var);
1496      if (vv == null && mode == VariableMode.INPUT) // * once source, always source. but target can be treated as source
1497                                                    // at user convenient
1498        vv = vin.get(VariableMode.OUTPUT, var);
1499      if (vv == null)
1500        throw new FHIRException("Rule '" + dependent.getName() + "' " + mode.toString() + " variable '"
1501            + input.getName() + "' named as '" + var + "' has no value (vars = " + vin.summary() + ")");
1502      v.add(mode, input.getName(), vv);
1503    }
1504    executeGroup(indent + "  ", context, rg.targetMap, v, rg.target, false);
1505  }
1506
1507  private String determineTypeFromSourceType(StructureMap map, StructureMapGroupComponent source, Base base,
1508      String[] types) throws FHIRException {
1509    String type = base.fhirType();
1510    String kn = "type^" + type;
1511    if (source.hasUserData(kn))
1512      return source.getUserString(kn);
1513
1514    ResolvedGroup res = new ResolvedGroup();
1515    res.targetMap = null;
1516    res.target = null;
1517    for (StructureMapGroupComponent grp : map.getGroup()) {
1518      if (matchesByType(map, grp, type)) {
1519        if (res.targetMap == null) {
1520          res.targetMap = map;
1521          res.target = grp;
1522        } else
1523          throw new FHIRException("Multiple possible matches looking for default rule for '" + type + "'");
1524      }
1525    }
1526    if (res.targetMap != null) {
1527      String result = getActualType(res.targetMap, res.target.getInput().get(1).getType());
1528      source.setUserData(kn, result);
1529      return result;
1530    }
1531
1532    for (UriType imp : map.getImport()) {
1533      List<StructureMap> impMapList = findMatchingMaps(imp.getValue());
1534      if (impMapList.size() == 0)
1535        throw new FHIRException("Unable to find map(s) for " + imp.getValue());
1536      for (StructureMap impMap : impMapList) {
1537        if (!impMap.getUrl().equals(map.getUrl())) {
1538          for (StructureMapGroupComponent grp : impMap.getGroup()) {
1539            if (matchesByType(impMap, grp, type)) {
1540              if (res.targetMap == null) {
1541                res.targetMap = impMap;
1542                res.target = grp;
1543              } else
1544                throw new FHIRException(
1545                    "Multiple possible matches for default rule for '" + type + "' in " + res.targetMap.getUrl() + " ("
1546                        + res.target.getName() + ") and " + impMap.getUrl() + " (" + grp.getName() + ")");
1547            }
1548          }
1549        }
1550      }
1551    }
1552    if (res.target == null)
1553      throw new FHIRException("No matches found for default rule for '" + type + "' from " + map.getUrl());
1554    String result = getActualType(res.targetMap, res.target.getInput().get(1).getType()); // should be .getType, but
1555                                                                                          // R2...
1556    source.setUserData(kn, result);
1557    return result;
1558  }
1559
1560  private List<StructureMap> findMatchingMaps(String value) {
1561    List<StructureMap> res = new ArrayList<StructureMap>();
1562    if (value.contains("*")) {
1563      for (StructureMap sm : worker.listTransforms()) {
1564        if (urlMatches(value, sm.getUrl())) {
1565          res.add(sm);
1566        }
1567      }
1568    } else {
1569      StructureMap sm = worker.getTransform(value);
1570      if (sm != null)
1571        res.add(sm);
1572    }
1573    Set<String> check = new HashSet<String>();
1574    for (StructureMap sm : res) {
1575      if (check.contains(sm.getUrl()))
1576        throw new Error("duplicate");
1577      else
1578        check.add(sm.getUrl());
1579    }
1580    return res;
1581  }
1582
1583  private boolean urlMatches(String mask, String url) {
1584    return url.length() > mask.length() && url.startsWith(mask.substring(0, mask.indexOf("*")))
1585        && url.endsWith(mask.substring(mask.indexOf("*") + 1));
1586  }
1587
1588  private ResolvedGroup resolveGroupByTypes(StructureMap map, String ruleid, StructureMapGroupComponent source,
1589      String srcType, String tgtType) throws FHIRException {
1590    String kn = "types^" + srcType + ":" + tgtType;
1591    if (source.hasUserData(kn))
1592      return (ResolvedGroup) source.getUserData(kn);
1593
1594    ResolvedGroup res = new ResolvedGroup();
1595    res.targetMap = null;
1596    res.target = null;
1597    for (StructureMapGroupComponent grp : map.getGroup()) {
1598      if (matchesByType(map, grp, srcType, tgtType)) {
1599        if (res.targetMap == null) {
1600          res.targetMap = map;
1601          res.target = grp;
1602        } else
1603          throw new FHIRException("Multiple possible matches looking for rule for '" + srcType + "/" + tgtType
1604              + "', from rule '" + ruleid + "'");
1605      }
1606    }
1607    if (res.targetMap != null) {
1608      source.setUserData(kn, res);
1609      return res;
1610    }
1611
1612    for (UriType imp : map.getImport()) {
1613      List<StructureMap> impMapList = findMatchingMaps(imp.getValue());
1614      if (impMapList.size() == 0)
1615        throw new FHIRException("Unable to find map(s) for " + imp.getValue());
1616      for (StructureMap impMap : impMapList) {
1617        if (!impMap.getUrl().equals(map.getUrl())) {
1618          for (StructureMapGroupComponent grp : impMap.getGroup()) {
1619            if (matchesByType(impMap, grp, srcType, tgtType)) {
1620              if (res.targetMap == null) {
1621                res.targetMap = impMap;
1622                res.target = grp;
1623              } else
1624                throw new FHIRException("Multiple possible matches for rule for '" + srcType + "/" + tgtType + "' in "
1625                    + res.targetMap.getUrl() + " and " + impMap.getUrl() + ", from rule '" + ruleid + "'");
1626            }
1627          }
1628        }
1629      }
1630    }
1631    if (res.target == null)
1632      throw new FHIRException("No matches found for rule for '" + srcType + " to " + tgtType + "' from " + map.getUrl()
1633          + ", from rule '" + ruleid + "'");
1634    source.setUserData(kn, res);
1635    return res;
1636  }
1637
1638  private boolean matchesByType(StructureMap map, StructureMapGroupComponent grp, String type) throws FHIRException {
1639    if (grp.getTypeMode() != StructureMapGroupTypeMode.TYPEANDTYPES)
1640      return false;
1641    if (grp.getInput().size() != 2 || grp.getInput().get(0).getMode() != StructureMapInputMode.SOURCE
1642        || grp.getInput().get(1).getMode() != StructureMapInputMode.TARGET)
1643      return false;
1644    return matchesType(map, type, grp.getInput().get(0).getType());
1645  }
1646
1647  private boolean matchesByType(StructureMap map, StructureMapGroupComponent grp, String srcType, String tgtType)
1648      throws FHIRException {
1649    if (grp.getTypeMode() == StructureMapGroupTypeMode.NONE)
1650      return false;
1651    if (grp.getInput().size() != 2 || grp.getInput().get(0).getMode() != StructureMapInputMode.SOURCE
1652        || grp.getInput().get(1).getMode() != StructureMapInputMode.TARGET)
1653      return false;
1654    if (!grp.getInput().get(0).hasType() || !grp.getInput().get(1).hasType())
1655      return false;
1656    return matchesType(map, srcType, grp.getInput().get(0).getType())
1657        && matchesType(map, tgtType, grp.getInput().get(1).getType());
1658  }
1659
1660  private boolean matchesType(StructureMap map, String actualType, String statedType) throws FHIRException {
1661    // check the aliases
1662    for (StructureMapStructureComponent imp : map.getStructure()) {
1663      if (imp.hasAlias() && statedType.equals(imp.getAlias())) {
1664        StructureDefinition sd = worker.fetchResource(StructureDefinition.class, imp.getUrl());
1665        if (sd != null)
1666          statedType = sd.getType();
1667        break;
1668      }
1669    }
1670
1671    if (Utilities.isAbsoluteUrl(actualType)) {
1672      StructureDefinition sd = worker.fetchResource(StructureDefinition.class, actualType);
1673      if (sd != null)
1674        actualType = sd.getType();
1675    }
1676    if (Utilities.isAbsoluteUrl(statedType)) {
1677      StructureDefinition sd = worker.fetchResource(StructureDefinition.class, statedType);
1678      if (sd != null)
1679        statedType = sd.getType();
1680    }
1681    return actualType.equals(statedType);
1682  }
1683
1684  private String getActualType(StructureMap map, String statedType) throws FHIRException {
1685    // check the aliases
1686    for (StructureMapStructureComponent imp : map.getStructure()) {
1687      if (imp.hasAlias() && statedType.equals(imp.getAlias())) {
1688        StructureDefinition sd = worker.fetchResource(StructureDefinition.class, imp.getUrl());
1689        if (sd == null)
1690          throw new FHIRException("Unable to resolve structure " + imp.getUrl());
1691        return sd.getId(); // should be sd.getType(), but R2...
1692      }
1693    }
1694    return statedType;
1695  }
1696
1697  private ResolvedGroup resolveGroupReference(StructureMap map, StructureMapGroupComponent source, String name)
1698      throws FHIRException {
1699    String kn = "ref^" + name;
1700    if (source.hasUserData(kn))
1701      return (ResolvedGroup) source.getUserData(kn);
1702
1703    ResolvedGroup res = new ResolvedGroup();
1704    res.targetMap = null;
1705    res.target = null;
1706    for (StructureMapGroupComponent grp : map.getGroup()) {
1707      if (grp.getName().equals(name)) {
1708        if (res.targetMap == null) {
1709          res.targetMap = map;
1710          res.target = grp;
1711        } else
1712          throw new FHIRException("Multiple possible matches for rule '" + name + "'");
1713      }
1714    }
1715    if (res.targetMap != null) {
1716      source.setUserData(kn, res);
1717      return res;
1718    }
1719
1720    for (UriType imp : map.getImport()) {
1721      List<StructureMap> impMapList = findMatchingMaps(imp.getValue());
1722      if (impMapList.size() == 0)
1723        throw new FHIRException("Unable to find map(s) for " + imp.getValue());
1724      for (StructureMap impMap : impMapList) {
1725        if (!impMap.getUrl().equals(map.getUrl())) {
1726          for (StructureMapGroupComponent grp : impMap.getGroup()) {
1727            if (grp.getName().equals(name)) {
1728              if (res.targetMap == null) {
1729                res.targetMap = impMap;
1730                res.target = grp;
1731              } else
1732                throw new FHIRException(
1733                    "Multiple possible matches for rule group '" + name + "' in " + res.targetMap.getUrl() + "#"
1734                        + res.target.getName() + " and " + impMap.getUrl() + "#" + grp.getName());
1735            }
1736          }
1737        }
1738      }
1739    }
1740    if (res.target == null)
1741      throw new FHIRException("No matches found for rule '" + name + "'. Reference found in " + map.getUrl());
1742    source.setUserData(kn, res);
1743    return res;
1744  }
1745
1746  private List<Variables> processSource(String ruleId, TransformContext context, Variables vars,
1747      StructureMapGroupRuleSourceComponent src, String pathForErrors, String indent) throws FHIRException {
1748    List<Base> items;
1749    if (src.getContext().equals("@search")) {
1750      ExpressionNode expr = (ExpressionNode) src.getUserData(MAP_SEARCH_EXPRESSION);
1751      if (expr == null) {
1752        expr = fpe.parse(src.getElement());
1753        src.setUserData(MAP_SEARCH_EXPRESSION, expr);
1754      }
1755      String search = fpe.evaluateToString(vars, null, null, new StringType(), expr); // string is a holder of nothing
1756                                                                                      // to ensure that variables are
1757                                                                                      // processed correctly
1758      items = services.performSearch(context.appInfo, search);
1759    } else {
1760      items = new ArrayList<Base>();
1761      Base b = vars.get(VariableMode.INPUT, src.getContext());
1762      if (b == null)
1763        throw new FHIRException("Unknown input variable " + src.getContext() + " in " + pathForErrors + " rule "
1764            + ruleId + " (vars = " + vars.summary() + ")");
1765
1766      if (!src.hasElement())
1767        items.add(b);
1768      else {
1769        getChildrenByName(b, src.getElement(), items);
1770        if (items.size() == 0 && src.hasDefaultValue())
1771          items.add(src.getDefaultValue());
1772      }
1773    }
1774
1775    if (src.hasType()) {
1776      List<Base> remove = new ArrayList<Base>();
1777      for (Base item : items) {
1778        if (item != null && !isType(item, src.getType())) {
1779          remove.add(item);
1780        }
1781      }
1782      items.removeAll(remove);
1783    }
1784
1785    if (src.hasCondition()) {
1786      ExpressionNode expr = (ExpressionNode) src.getUserData(MAP_WHERE_EXPRESSION);
1787      if (expr == null) {
1788        expr = fpe.parse(src.getCondition());
1789        // fpe.check(context.appInfo, ??, ??, expr)
1790        src.setUserData(MAP_WHERE_EXPRESSION, expr);
1791      }
1792      List<Base> remove = new ArrayList<Base>();
1793      for (Base item : items) {
1794        if (!fpe.evaluateToBoolean(vars, null, null, item, expr)) {
1795          log(indent + "  condition [" + src.getCondition() + "] for " + item.toString() + " : false");
1796          remove.add(item);
1797        } else
1798          log(indent + "  condition [" + src.getCondition() + "] for " + item.toString() + " : true");
1799      }
1800      items.removeAll(remove);
1801    }
1802
1803    if (src.hasCheck()) {
1804      ExpressionNode expr = (ExpressionNode) src.getUserData(MAP_WHERE_CHECK);
1805      if (expr == null) {
1806        expr = fpe.parse(src.getCheck());
1807        // fpe.check(context.appInfo, ??, ??, expr)
1808        src.setUserData(MAP_WHERE_CHECK, expr);
1809      }
1810      List<Base> remove = new ArrayList<Base>();
1811      for (Base item : items) {
1812        if (!fpe.evaluateToBoolean(vars, null, null, item, expr))
1813          throw new FHIRException("Rule \"" + ruleId + "\": Check condition failed");
1814      }
1815    }
1816
1817    if (src.hasLogMessage()) {
1818      ExpressionNode expr = (ExpressionNode) src.getUserData(MAP_WHERE_LOG);
1819      if (expr == null) {
1820        expr = fpe.parse(src.getLogMessage());
1821        // fpe.check(context.appInfo, ??, ??, expr)
1822        src.setUserData(MAP_WHERE_LOG, expr);
1823      }
1824      CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
1825      for (Base item : items)
1826        b.appendIfNotNull(fpe.evaluateToString(vars, null, null, item, expr));
1827      if (b.length() > 0)
1828        services.log(b.toString());
1829    }
1830
1831    if (src.hasListMode() && !items.isEmpty()) {
1832      switch (src.getListMode()) {
1833      case FIRST:
1834        Base bt = items.get(0);
1835        items.clear();
1836        items.add(bt);
1837        break;
1838      case NOTFIRST:
1839        if (items.size() > 0)
1840          items.remove(0);
1841        break;
1842      case LAST:
1843        bt = items.get(items.size() - 1);
1844        items.clear();
1845        items.add(bt);
1846        break;
1847      case NOTLAST:
1848        if (items.size() > 0)
1849          items.remove(items.size() - 1);
1850        break;
1851      case ONLYONE:
1852        if (items.size() > 1)
1853          throw new FHIRException(
1854              "Rule \"" + ruleId + "\": Check condition failed: the collection has more than one item");
1855        break;
1856      case NULL:
1857      }
1858    }
1859    List<Variables> result = new ArrayList<Variables>();
1860    for (Base r : items) {
1861      Variables v = vars.copy();
1862      if (src.hasVariable())
1863        v.add(VariableMode.INPUT, src.getVariable(), r);
1864      result.add(v);
1865    }
1866    return result;
1867  }
1868
1869  private boolean isType(Base item, String type) {
1870    if (type.equals(item.fhirType()))
1871      return true;
1872    return false;
1873  }
1874
1875  private void processTarget(String ruleId, TransformContext context, Variables vars, StructureMap map,
1876      StructureMapGroupComponent group, StructureMapGroupRuleTargetComponent tgt, String srcVar, boolean atRoot,
1877      Variables sharedVars) throws FHIRException {
1878    Base dest = null;
1879    if (tgt.hasContext()) {
1880      dest = vars.get(VariableMode.OUTPUT, tgt.getContext());
1881      if (dest == null)
1882        throw new FHIRException("Rule \"" + ruleId + "\": target context not known: " + tgt.getContext());
1883      if (!tgt.hasElement())
1884        throw new FHIRException("Rule \"" + ruleId + "\": Not supported yet");
1885    }
1886    Base v = null;
1887    if (tgt.hasTransform()) {
1888      v = runTransform(ruleId, context, map, group, tgt, vars, dest, tgt.getElement(), srcVar, atRoot);
1889      if (v != null && dest != null)
1890        v = dest.setProperty(tgt.getElement().hashCode(), tgt.getElement(), v); // reset v because some implementations
1891                                                                                // may have to rewrite v when setting
1892                                                                                // the value
1893    } else if (dest != null) {
1894      if (tgt.hasListMode(StructureMapTargetListMode.SHARE)) {
1895        v = sharedVars.get(VariableMode.SHARED, tgt.getListRuleId());
1896        if (v == null) {
1897          v = dest.makeProperty(tgt.getElement().hashCode(), tgt.getElement());
1898          sharedVars.add(VariableMode.SHARED, tgt.getListRuleId(), v);
1899        }
1900      } else {
1901        v = dest.makeProperty(tgt.getElement().hashCode(), tgt.getElement());
1902      }
1903    }
1904    if (tgt.hasVariable() && v != null)
1905      vars.add(VariableMode.OUTPUT, tgt.getVariable(), v);
1906  }
1907
1908  private Base runTransform(String ruleId, TransformContext context, StructureMap map, StructureMapGroupComponent group,
1909      StructureMapGroupRuleTargetComponent tgt, Variables vars, Base dest, String element, String srcVar, boolean root)
1910      throws FHIRException {
1911    try {
1912      switch (tgt.getTransform()) {
1913      case CREATE:
1914        String tn;
1915        if (tgt.getParameter().isEmpty()) {
1916          // we have to work out the type. First, we see if there is a single type for the
1917          // target. If there is, we use that
1918          String[] types = dest.getTypesForProperty(element.hashCode(), element);
1919          if (types.length == 1 && !"*".equals(types[0]) && !types[0].equals("Resource"))
1920            tn = types[0];
1921          else if (srcVar != null) {
1922            tn = determineTypeFromSourceType(map, group, vars.get(VariableMode.INPUT, srcVar), types);
1923          } else
1924            throw new Error("Cannot determine type implicitly because there is no single input variable");
1925        } else {
1926          tn = getParamStringNoNull(vars, tgt.getParameter().get(0), tgt.toString());
1927          // ok, now we resolve the type name against the import statements
1928          for (StructureMapStructureComponent uses : map.getStructure()) {
1929            if (uses.getMode() == StructureMapModelMode.TARGET && uses.hasAlias() && tn.equals(uses.getAlias())) {
1930              tn = uses.getUrl();
1931              break;
1932            }
1933          }
1934        }
1935        Base res = services != null ? services.createType(context.getAppInfo(), tn)
1936            : ResourceFactory.createResourceOrType(tn);
1937        if (res.isResource() && !res.fhirType().equals("Parameters")) {
1938//              res.setIdBase(tgt.getParameter().size() > 1 ? getParamString(vars, tgt.getParameter().get(0)) : UUID.randomUUID().toString().toLowerCase());
1939          if (services != null)
1940            res = services.createResource(context.getAppInfo(), res, root);
1941        }
1942        if (tgt.hasUserData("profile"))
1943          res.setUserData("profile", tgt.getUserData("profile"));
1944        return res;
1945      case COPY:
1946        return getParam(vars, tgt.getParameter().get(0));
1947      case EVALUATE:
1948        ExpressionNode expr = (ExpressionNode) tgt.getUserData(MAP_EXPRESSION);
1949        if (expr == null) {
1950          expr = fpe.parse(getParamStringNoNull(vars, tgt.getParameter().get(1), tgt.toString()));
1951          tgt.setUserData(MAP_WHERE_EXPRESSION, expr);
1952        }
1953        List<Base> v = fpe.evaluate(vars, null, null,
1954            tgt.getParameter().size() == 2 ? getParam(vars, tgt.getParameter().get(0)) : new BooleanType(false), expr);
1955        if (v.size() == 0)
1956          return null;
1957        else if (v.size() != 1)
1958          throw new FHIRException("Rule \"" + ruleId + "\": Evaluation of " + expr.toString() + " returned "
1959              + Integer.toString(v.size()) + " objects");
1960        else
1961          return v.get(0);
1962
1963      case TRUNCATE:
1964        String src = getParamString(vars, tgt.getParameter().get(0));
1965        String len = getParamStringNoNull(vars, tgt.getParameter().get(1), tgt.toString());
1966        if (Utilities.isInteger(len)) {
1967          int l = Integer.parseInt(len);
1968          if (src.length() > l)
1969            src = src.substring(0, l);
1970        }
1971        return new StringType(src);
1972      case ESCAPE:
1973        throw new Error("Rule \"" + ruleId + "\": Transform " + tgt.getTransform().toCode() + " not supported yet");
1974      case CAST:
1975        src = getParamString(vars, tgt.getParameter().get(0));
1976        if (tgt.getParameter().size() == 1)
1977          throw new FHIRException("Implicit type parameters on cast not yet supported");
1978        String t = getParamString(vars, tgt.getParameter().get(1));
1979        if (t.equals("string"))
1980          return new StringType(src);
1981        else
1982          throw new FHIRException("cast to " + t + " not yet supported");
1983      case APPEND:
1984        StringBuilder sb = new StringBuilder(getParamString(vars, tgt.getParameter().get(0)));
1985        for (int i = 1; i < tgt.getParameter().size(); i++)
1986          sb.append(getParamString(vars, tgt.getParameter().get(i)));
1987        return new StringType(sb.toString());
1988      case TRANSLATE:
1989        return translate(context, map, vars, tgt.getParameter());
1990      case REFERENCE:
1991        Base b = getParam(vars, tgt.getParameter().get(0));
1992        if (b == null)
1993          throw new FHIRException("Rule \"" + ruleId + "\": Unable to find parameter "
1994              + ((IdType) tgt.getParameter().get(0).getValue()).asStringValue());
1995        if (!b.isResource())
1996          throw new FHIRException(
1997              "Rule \"" + ruleId + "\": Transform engine cannot point at an element of type " + b.fhirType());
1998        else {
1999          String id = b.getIdBase();
2000          if (id == null) {
2001            id = UUID.randomUUID().toString().toLowerCase();
2002            b.setIdBase(id);
2003          }
2004          return new Reference().setReference(b.fhirType() + "/" + id);
2005        }
2006      case DATEOP:
2007        throw new Error("Rule \"" + ruleId + "\": Transform " + tgt.getTransform().toCode() + " not supported yet");
2008      case UUID:
2009        return new IdType(UUID.randomUUID().toString());
2010      case POINTER:
2011        b = getParam(vars, tgt.getParameter().get(0));
2012        if (b instanceof Resource)
2013          return new UriType("urn:uuid:" + ((Resource) b).getId());
2014        else
2015          throw new FHIRException(
2016              "Rule \"" + ruleId + "\": Transform engine cannot point at an element of type " + b.fhirType());
2017      case CC:
2018        CodeableConcept cc = new CodeableConcept();
2019        cc.addCoding(buildCoding(getParamStringNoNull(vars, tgt.getParameter().get(0), tgt.toString()),
2020            getParamStringNoNull(vars, tgt.getParameter().get(1), tgt.toString())));
2021        return cc;
2022      case C:
2023        Coding c = buildCoding(getParamStringNoNull(vars, tgt.getParameter().get(0), tgt.toString()),
2024            getParamStringNoNull(vars, tgt.getParameter().get(1), tgt.toString()));
2025        return c;
2026      default:
2027        throw new Error("Rule \"" + ruleId + "\": Transform Unknown: " + tgt.getTransform().toCode());
2028      }
2029    } catch (Exception e) {
2030      throw new FHIRException(
2031          "Exception executing transform " + tgt.toString() + " on Rule \"" + ruleId + "\": " + e.getMessage(), e);
2032    }
2033  }
2034
2035  private Coding buildCoding(String uri, String code) throws FHIRException {
2036    // if we can get this as a valueSet, we will
2037    String system = null;
2038    String display = null;
2039    ValueSet vs = Utilities.noString(uri) ? null : worker.fetchResourceWithException(ValueSet.class, uri);
2040    if (vs != null) {
2041      ValueSetExpansionOutcome vse = worker.expandVS(vs, true, false);
2042      if (vse.getError() != null)
2043        throw new FHIRException(vse.getError());
2044      CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
2045      for (ValueSetExpansionContainsComponent t : vse.getValueset().getExpansion().getContains()) {
2046        if (t.hasCode())
2047          b.append(t.getCode());
2048        if (code.equals(t.getCode()) && t.hasSystem()) {
2049          system = t.getSystem();
2050          display = t.getDisplay();
2051          break;
2052        }
2053        if (code.equalsIgnoreCase(t.getDisplay()) && t.hasSystem()) {
2054          system = t.getSystem();
2055          display = t.getDisplay();
2056          break;
2057        }
2058      }
2059      if (system == null)
2060        throw new FHIRException("The code '" + code + "' is not in the value set '" + uri + "' (valid codes: "
2061            + b.toString() + "; also checked displays)");
2062    } else
2063      system = uri;
2064    ValidationResult vr = worker.validateCode(terminologyServiceOptions, system, code, null);
2065    if (vr != null && vr.getDisplay() != null)
2066      display = vr.getDisplay();
2067    return new Coding().setSystem(system).setCode(code).setDisplay(display);
2068  }
2069
2070  private String getParamStringNoNull(Variables vars, StructureMapGroupRuleTargetParameterComponent parameter,
2071      String message) throws FHIRException {
2072    Base b = getParam(vars, parameter);
2073    if (b == null)
2074      throw new FHIRException("Unable to find a value for " + parameter.toString() + ". Context: " + message);
2075    if (!b.hasPrimitiveValue())
2076      throw new FHIRException("Found a value for " + parameter.toString() + ", but it has a type of " + b.fhirType()
2077          + " and cannot be treated as a string. Context: " + message);
2078    return b.primitiveValue();
2079  }
2080
2081  private String getParamString(Variables vars, StructureMapGroupRuleTargetParameterComponent parameter)
2082      throws DefinitionException {
2083    Base b = getParam(vars, parameter);
2084    if (b == null || !b.hasPrimitiveValue())
2085      return null;
2086    return b.primitiveValue();
2087  }
2088
2089  private Base getParam(Variables vars, StructureMapGroupRuleTargetParameterComponent parameter)
2090      throws DefinitionException {
2091    Type p = parameter.getValue();
2092    if (!(p instanceof IdType))
2093      return p;
2094    else {
2095      String n = ((IdType) p).asStringValue();
2096      Base b = vars.get(VariableMode.INPUT, n);
2097      if (b == null)
2098        b = vars.get(VariableMode.OUTPUT, n);
2099      if (b == null)
2100        throw new DefinitionException("Variable " + n + " not found (" + vars.summary() + ")");
2101      return b;
2102    }
2103  }
2104
2105  private Base translate(TransformContext context, StructureMap map, Variables vars,
2106      List<StructureMapGroupRuleTargetParameterComponent> parameter) throws FHIRException {
2107    Base src = getParam(vars, parameter.get(0));
2108    String id = getParamString(vars, parameter.get(1));
2109    String fld = parameter.size() > 2 ? getParamString(vars, parameter.get(2)) : null;
2110    return translate(context, map, src, id, fld);
2111  }
2112
2113  private class SourceElementComponentWrapper {
2114    private ConceptMapGroupComponent group;
2115    private SourceElementComponent comp;
2116
2117    public SourceElementComponentWrapper(ConceptMapGroupComponent group, SourceElementComponent comp) {
2118      super();
2119      this.group = group;
2120      this.comp = comp;
2121    }
2122  }
2123
2124  public Base translate(TransformContext context, StructureMap map, Base source, String conceptMapUrl,
2125      String fieldToReturn) throws FHIRException {
2126    Coding src = new Coding();
2127    if (source.isPrimitive()) {
2128      src.setCode(source.primitiveValue());
2129    } else if ("Coding".equals(source.fhirType())) {
2130      Base[] b = source.getProperty("system".hashCode(), "system", true);
2131      if (b.length == 1)
2132        src.setSystem(b[0].primitiveValue());
2133      b = source.getProperty("code".hashCode(), "code", true);
2134      if (b.length == 1)
2135        src.setCode(b[0].primitiveValue());
2136    } else if ("CE".equals(source.fhirType())) {
2137      Base[] b = source.getProperty("codeSystem".hashCode(), "codeSystem", true);
2138      if (b.length == 1)
2139        src.setSystem(b[0].primitiveValue());
2140      b = source.getProperty("code".hashCode(), "code", true);
2141      if (b.length == 1)
2142        src.setCode(b[0].primitiveValue());
2143    } else
2144      throw new FHIRException("Unable to translate source " + source.fhirType());
2145
2146    String su = conceptMapUrl;
2147    if (conceptMapUrl.equals("http://hl7.org/fhir/ConceptMap/special-oid2uri")) {
2148      String uri = worker.oid2Uri(src.getCode());
2149      if (uri == null)
2150        uri = "urn:oid:" + src.getCode();
2151      if ("uri".equals(fieldToReturn))
2152        return new UriType(uri);
2153      else
2154        throw new FHIRException("Error in return code");
2155    } else {
2156      ConceptMap cmap = null;
2157      if (conceptMapUrl.startsWith("#")) {
2158        for (Resource r : map.getContained()) {
2159          if (r instanceof ConceptMap && ((ConceptMap) r).getId().equals(conceptMapUrl.substring(1))) {
2160            cmap = (ConceptMap) r;
2161            su = map.getUrl() + "#" + conceptMapUrl;
2162          }
2163        }
2164        if (cmap == null)
2165          throw new FHIRException("Unable to translate - cannot find map " + conceptMapUrl);
2166      } else {
2167        if (conceptMapUrl.contains("#")) {
2168          String[] p = conceptMapUrl.split("\\#");
2169          StructureMap mapU = worker.fetchResource(StructureMap.class, p[0]);
2170          for (Resource r : mapU.getContained()) {
2171            if (r instanceof ConceptMap && ((ConceptMap) r).getId().equals(p[1])) {
2172              cmap = (ConceptMap) r;
2173              su = conceptMapUrl;
2174            }
2175          }
2176        }
2177        if (cmap == null)
2178          cmap = worker.fetchResource(ConceptMap.class, conceptMapUrl);
2179      }
2180      Coding outcome = null;
2181      boolean done = false;
2182      String message = null;
2183      if (cmap == null) {
2184        if (services == null)
2185          message = "No map found for " + conceptMapUrl;
2186        else {
2187          outcome = services.translate(context.appInfo, src, conceptMapUrl);
2188          done = true;
2189        }
2190      } else {
2191        List<SourceElementComponentWrapper> list = new ArrayList<SourceElementComponentWrapper>();
2192        for (ConceptMapGroupComponent g : cmap.getGroup()) {
2193          for (SourceElementComponent e : g.getElement()) {
2194            if (!src.hasSystem() && src.getCode().equals(e.getCode()))
2195              list.add(new SourceElementComponentWrapper(g, e));
2196            else if (src.hasSystem() && src.getSystem().equals(g.getSource()) && src.getCode().equals(e.getCode()))
2197              list.add(new SourceElementComponentWrapper(g, e));
2198          }
2199        }
2200        if (list.size() == 0)
2201          done = true;
2202        else if (list.get(0).comp.getTarget().size() == 0)
2203          message = "Concept map " + su + " found no translation for " + src.getCode();
2204        else {
2205          for (TargetElementComponent tgt : list.get(0).comp.getTarget()) {
2206            if (tgt.getEquivalence() == null || EnumSet.of(ConceptMapEquivalence.EQUAL, ConceptMapEquivalence.RELATEDTO,
2207                ConceptMapEquivalence.EQUIVALENT, ConceptMapEquivalence.WIDER).contains(tgt.getEquivalence())) {
2208              if (done) {
2209                message = "Concept map " + su + " found multiple matches for " + src.getCode();
2210                done = false;
2211              } else {
2212                done = true;
2213                outcome = new Coding().setCode(tgt.getCode()).setSystem(list.get(0).group.getTarget());
2214              }
2215            } else if (tgt.getEquivalence() == ConceptMapEquivalence.UNMATCHED) {
2216              done = true;
2217            }
2218          }
2219          if (!done)
2220            message = "Concept map " + su + " found no usable translation for " + src.getCode();
2221        }
2222      }
2223      if (!done)
2224        throw new FHIRException(message);
2225      if (outcome == null)
2226        return null;
2227      if ("code".equals(fieldToReturn))
2228        return new CodeType(outcome.getCode());
2229      else
2230        return outcome;
2231    }
2232  }
2233
2234  public class PropertyWithType {
2235    private String path;
2236    private Property baseProperty;
2237    private Property profileProperty;
2238    private TypeDetails types;
2239
2240    public PropertyWithType(String path, Property baseProperty, Property profileProperty, TypeDetails types) {
2241      super();
2242      this.baseProperty = baseProperty;
2243      this.profileProperty = profileProperty;
2244      this.path = path;
2245      this.types = types;
2246    }
2247
2248    public TypeDetails getTypes() {
2249      return types;
2250    }
2251
2252    public String getPath() {
2253      return path;
2254    }
2255
2256    public Property getBaseProperty() {
2257      return baseProperty;
2258    }
2259
2260    public void setBaseProperty(Property baseProperty) {
2261      this.baseProperty = baseProperty;
2262    }
2263
2264    public Property getProfileProperty() {
2265      return profileProperty;
2266    }
2267
2268    public void setProfileProperty(Property profileProperty) {
2269      this.profileProperty = profileProperty;
2270    }
2271
2272    public String summary() {
2273      return path;
2274    }
2275
2276  }
2277
2278  public class VariableForProfiling {
2279    private VariableMode mode;
2280    private String name;
2281    private PropertyWithType property;
2282
2283    public VariableForProfiling(VariableMode mode, String name, PropertyWithType property) {
2284      super();
2285      this.mode = mode;
2286      this.name = name;
2287      this.property = property;
2288    }
2289
2290    public VariableMode getMode() {
2291      return mode;
2292    }
2293
2294    public String getName() {
2295      return name;
2296    }
2297
2298    public PropertyWithType getProperty() {
2299      return property;
2300    }
2301
2302    public String summary() {
2303      return name + ": " + property.summary();
2304    }
2305  }
2306
2307  public class VariablesForProfiling {
2308    private List<VariableForProfiling> list = new ArrayList<VariableForProfiling>();
2309    private boolean optional;
2310    private boolean repeating;
2311
2312    public VariablesForProfiling(boolean optional, boolean repeating) {
2313      this.optional = optional;
2314      this.repeating = repeating;
2315    }
2316
2317    public void add(VariableMode mode, String name, String path, Property property, TypeDetails types) {
2318      add(mode, name, new PropertyWithType(path, property, null, types));
2319    }
2320
2321    public void add(VariableMode mode, String name, String path, Property baseProperty, Property profileProperty,
2322        TypeDetails types) {
2323      add(mode, name, new PropertyWithType(path, baseProperty, profileProperty, types));
2324    }
2325
2326    public void add(VariableMode mode, String name, PropertyWithType property) {
2327      VariableForProfiling vv = null;
2328      for (VariableForProfiling v : list)
2329        if ((v.mode == mode) && v.getName().equals(name))
2330          vv = v;
2331      if (vv != null)
2332        list.remove(vv);
2333      list.add(new VariableForProfiling(mode, name, property));
2334    }
2335
2336    public VariablesForProfiling copy(boolean optional, boolean repeating) {
2337      VariablesForProfiling result = new VariablesForProfiling(optional, repeating);
2338      result.list.addAll(list);
2339      return result;
2340    }
2341
2342    public VariablesForProfiling copy() {
2343      VariablesForProfiling result = new VariablesForProfiling(optional, repeating);
2344      result.list.addAll(list);
2345      return result;
2346    }
2347
2348    public VariableForProfiling get(VariableMode mode, String name) {
2349      if (mode == null) {
2350        for (VariableForProfiling v : list)
2351          if ((v.mode == VariableMode.OUTPUT) && v.getName().equals(name))
2352            return v;
2353        for (VariableForProfiling v : list)
2354          if ((v.mode == VariableMode.INPUT) && v.getName().equals(name))
2355            return v;
2356      }
2357      for (VariableForProfiling v : list)
2358        if ((v.mode == mode) && v.getName().equals(name))
2359          return v;
2360      return null;
2361    }
2362
2363    public String summary() {
2364      CommaSeparatedStringBuilder s = new CommaSeparatedStringBuilder();
2365      CommaSeparatedStringBuilder t = new CommaSeparatedStringBuilder();
2366      for (VariableForProfiling v : list)
2367        if (v.mode == VariableMode.INPUT)
2368          s.append(v.summary());
2369        else
2370          t.append(v.summary());
2371      return "source variables [" + s.toString() + "], target variables [" + t.toString() + "]";
2372    }
2373  }
2374
2375  public class StructureMapAnalysis {
2376    private List<StructureDefinition> profiles = new ArrayList<StructureDefinition>();
2377    private XhtmlNode summary;
2378
2379    public List<StructureDefinition> getProfiles() {
2380      return profiles;
2381    }
2382
2383    public XhtmlNode getSummary() {
2384      return summary;
2385    }
2386
2387  }
2388
2389  /**
2390   * Given a structure map, return a set of analyses on it.
2391   * 
2392   * Returned: - a list or profiles for what it will create. First profile is the
2393   * target - a table with a summary (in xhtml) for easy human undertanding of the
2394   * mapping
2395   * 
2396   * 
2397   * @param appInfo
2398   * @param map
2399   * @return
2400   * @throws Exception
2401   */
2402  public StructureMapAnalysis analyse(Object appInfo, StructureMap map) throws FHIRException {
2403    ids.clear();
2404    StructureMapAnalysis result = new StructureMapAnalysis();
2405    TransformContext context = new TransformContext(appInfo);
2406    VariablesForProfiling vars = new VariablesForProfiling(false, false);
2407    StructureMapGroupComponent start = map.getGroup().get(0);
2408    for (StructureMapGroupInputComponent t : start.getInput()) {
2409      PropertyWithType ti = resolveType(map, t.getType(), t.getMode());
2410      if (t.getMode() == StructureMapInputMode.SOURCE)
2411        vars.add(VariableMode.INPUT, t.getName(), ti);
2412      else
2413        vars.add(VariableMode.OUTPUT, t.getName(), createProfile(map, result.profiles, ti, start.getName(), start));
2414    }
2415
2416    result.summary = new XhtmlNode(NodeType.Element, "table").setAttribute("class", "grid");
2417    XhtmlNode tr = result.summary.addTag("tr");
2418    tr.addTag("td").addTag("b").addText("Source");
2419    tr.addTag("td").addTag("b").addText("Target");
2420
2421    log("Start Profiling Transform " + map.getUrl());
2422    analyseGroup("", context, map, vars, start, result);
2423    ProfileUtilities pu = new ProfileUtilities(worker, null, pkp);
2424    for (StructureDefinition sd : result.getProfiles())
2425      pu.cleanUpDifferential(sd);
2426    return result;
2427  }
2428
2429  private void analyseGroup(String indent, TransformContext context, StructureMap map, VariablesForProfiling vars,
2430      StructureMapGroupComponent group, StructureMapAnalysis result) throws FHIRException {
2431    log(indent + "Analyse Group : " + group.getName());
2432    // todo: extends
2433    // todo: check inputs
2434    XhtmlNode tr = result.summary.addTag("tr").setAttribute("class", "diff-title");
2435    XhtmlNode xs = tr.addTag("td");
2436    XhtmlNode xt = tr.addTag("td");
2437    for (StructureMapGroupInputComponent inp : group.getInput()) {
2438      if (inp.getMode() == StructureMapInputMode.SOURCE)
2439        noteInput(vars, inp, VariableMode.INPUT, xs);
2440      if (inp.getMode() == StructureMapInputMode.TARGET)
2441        noteInput(vars, inp, VariableMode.OUTPUT, xt);
2442    }
2443    for (StructureMapGroupRuleComponent r : group.getRule()) {
2444      analyseRule(indent + "  ", context, map, vars, group, r, result);
2445    }
2446  }
2447
2448  private void noteInput(VariablesForProfiling vars, StructureMapGroupInputComponent inp, VariableMode mode,
2449      XhtmlNode xs) {
2450    VariableForProfiling v = vars.get(mode, inp.getName());
2451    if (v != null)
2452      xs.addText("Input: " + v.property.getPath());
2453  }
2454
2455  private void analyseRule(String indent, TransformContext context, StructureMap map, VariablesForProfiling vars,
2456      StructureMapGroupComponent group, StructureMapGroupRuleComponent rule, StructureMapAnalysis result)
2457      throws FHIRException {
2458    log(indent + "Analyse rule : " + rule.getName());
2459    XhtmlNode tr = result.summary.addTag("tr");
2460    XhtmlNode xs = tr.addTag("td");
2461    XhtmlNode xt = tr.addTag("td");
2462
2463    VariablesForProfiling srcVars = vars.copy();
2464    if (rule.getSource().size() != 1)
2465      throw new FHIRException("Rule \"" + rule.getName() + "\": not handled yet");
2466    VariablesForProfiling source = analyseSource(rule.getName(), context, srcVars, rule.getSourceFirstRep(), xs);
2467
2468    TargetWriter tw = new TargetWriter();
2469    for (StructureMapGroupRuleTargetComponent t : rule.getTarget()) {
2470      analyseTarget(rule.getName(), context, source, map, t, rule.getSourceFirstRep().getVariable(), tw,
2471          result.profiles, rule.getName());
2472    }
2473    tw.commit(xt);
2474
2475    for (StructureMapGroupRuleComponent childrule : rule.getRule()) {
2476      analyseRule(indent + "  ", context, map, source, group, childrule, result);
2477    }
2478//    for (StructureMapGroupRuleDependentComponent dependent : rule.getDependent()) {
2479//      executeDependency(indent+"  ", context, map, v, group, dependent); // do we need group here?
2480//    }
2481  }
2482
2483  public class StringPair {
2484    private String var;
2485    private String desc;
2486
2487    public StringPair(String var, String desc) {
2488      super();
2489      this.var = var;
2490      this.desc = desc;
2491    }
2492
2493    public String getVar() {
2494      return var;
2495    }
2496
2497    public String getDesc() {
2498      return desc;
2499    }
2500  }
2501
2502  public class TargetWriter {
2503    private Map<String, String> newResources = new HashMap<String, String>();
2504    private List<StringPair> assignments = new ArrayList<StringPair>();
2505    private List<StringPair> keyProps = new ArrayList<StringPair>();
2506    private CommaSeparatedStringBuilder txt = new CommaSeparatedStringBuilder();
2507
2508    public void newResource(String var, String name) {
2509      newResources.put(var, name);
2510      txt.append("new " + name);
2511    }
2512
2513    public void valueAssignment(String context, String desc) {
2514      assignments.add(new StringPair(context, desc));
2515      txt.append(desc);
2516    }
2517
2518    public void keyAssignment(String context, String desc) {
2519      keyProps.add(new StringPair(context, desc));
2520      txt.append(desc);
2521    }
2522
2523    public void commit(XhtmlNode xt) {
2524      if (newResources.size() == 1 && assignments.size() == 1 && newResources.containsKey(assignments.get(0).getVar())
2525          && keyProps.size() == 1 && newResources.containsKey(keyProps.get(0).getVar())) {
2526        xt.addText("new " + assignments.get(0).desc + " ("
2527            + keyProps.get(0).desc.substring(keyProps.get(0).desc.indexOf(".") + 1) + ")");
2528      } else if (newResources.size() == 1 && assignments.size() == 1
2529          && newResources.containsKey(assignments.get(0).getVar()) && keyProps.size() == 0) {
2530        xt.addText("new " + assignments.get(0).desc);
2531      } else {
2532        xt.addText(txt.toString());
2533      }
2534    }
2535  }
2536
2537  private VariablesForProfiling analyseSource(String ruleId, TransformContext context, VariablesForProfiling vars,
2538      StructureMapGroupRuleSourceComponent src, XhtmlNode td) throws FHIRException {
2539    VariableForProfiling var = vars.get(VariableMode.INPUT, src.getContext());
2540    if (var == null)
2541      throw new FHIRException("Rule \"" + ruleId + "\": Unknown input variable " + src.getContext());
2542    PropertyWithType prop = var.getProperty();
2543
2544    boolean optional = false;
2545    boolean repeating = false;
2546
2547    if (src.hasCondition()) {
2548      optional = true;
2549    }
2550
2551    if (src.hasElement()) {
2552      Property element = prop.getBaseProperty().getChild(prop.types.getType(), src.getElement());
2553      if (element == null)
2554        throw new FHIRException("Rule \"" + ruleId + "\": Unknown element name " + src.getElement());
2555      if (element.getDefinition().getMin() == 0)
2556        optional = true;
2557      if (element.getDefinition().getMax().equals("*"))
2558        repeating = true;
2559      VariablesForProfiling result = vars.copy(optional, repeating);
2560      TypeDetails type = new TypeDetails(CollectionStatus.SINGLETON);
2561      for (TypeRefComponent tr : element.getDefinition().getType()) {
2562        if (!tr.hasCode())
2563          throw new Error("Rule \"" + ruleId + "\": Element has no type");
2564        ProfiledType pt = new ProfiledType(tr.getWorkingCode());
2565        if (tr.hasProfile())
2566          pt.addProfiles(tr.getProfile());
2567        if (element.getDefinition().hasBinding())
2568          pt.addBinding(element.getDefinition().getBinding());
2569        type.addType(pt);
2570      }
2571      td.addText(prop.getPath() + "." + src.getElement());
2572      if (src.hasVariable())
2573        result.add(VariableMode.INPUT, src.getVariable(),
2574            new PropertyWithType(prop.getPath() + "." + src.getElement(), element, null, type));
2575      return result;
2576    } else {
2577      td.addText(prop.getPath()); // ditto!
2578      return vars.copy(optional, repeating);
2579    }
2580  }
2581
2582  private void analyseTarget(String ruleId, TransformContext context, VariablesForProfiling vars, StructureMap map,
2583      StructureMapGroupRuleTargetComponent tgt, String tv, TargetWriter tw, List<StructureDefinition> profiles,
2584      String sliceName) throws FHIRException {
2585    VariableForProfiling var = null;
2586    if (tgt.hasContext()) {
2587      var = vars.get(VariableMode.OUTPUT, tgt.getContext());
2588      if (var == null)
2589        throw new FHIRException("Rule \"" + ruleId + "\": target context not known: " + tgt.getContext());
2590      if (!tgt.hasElement())
2591        throw new FHIRException("Rule \"" + ruleId + "\": Not supported yet");
2592    }
2593
2594    TypeDetails type = null;
2595    if (tgt.hasTransform()) {
2596      type = analyseTransform(context, map, tgt, var, vars);
2597      // profiling: dest.setProperty(tgt.getElement().hashCode(), tgt.getElement(),
2598      // v);
2599    } else {
2600      Property vp = var.property.baseProperty.getChild(tgt.getElement(), tgt.getElement());
2601      if (vp == null)
2602        throw new FHIRException("Unknown Property " + tgt.getElement() + " on " + var.property.path);
2603
2604      type = new TypeDetails(CollectionStatus.SINGLETON, vp.getType(tgt.getElement()));
2605    }
2606
2607    if (tgt.getTransform() == StructureMapTransform.CREATE) {
2608      String s = getParamString(vars, tgt.getParameter().get(0));
2609      if (worker.getResourceNames().contains(s))
2610        tw.newResource(tgt.getVariable(), s);
2611    } else {
2612      boolean mapsSrc = false;
2613      for (StructureMapGroupRuleTargetParameterComponent p : tgt.getParameter()) {
2614        Type pr = p.getValue();
2615        if (pr instanceof IdType && ((IdType) pr).asStringValue().equals(tv))
2616          mapsSrc = true;
2617      }
2618      if (mapsSrc) {
2619        if (var == null)
2620          throw new Error("Rule \"" + ruleId + "\": Attempt to assign with no context");
2621        tw.valueAssignment(tgt.getContext(),
2622            var.property.getPath() + "." + tgt.getElement() + getTransformSuffix(tgt.getTransform()));
2623      } else if (tgt.hasContext()) {
2624        if (isSignificantElement(var.property, tgt.getElement())) {
2625          String td = describeTransform(tgt);
2626          if (td != null)
2627            tw.keyAssignment(tgt.getContext(), var.property.getPath() + "." + tgt.getElement() + " = " + td);
2628        }
2629      }
2630    }
2631    Type fixed = generateFixedValue(tgt);
2632
2633    PropertyWithType prop = updateProfile(var, tgt.getElement(), type, map, profiles, sliceName, fixed, tgt);
2634    if (tgt.hasVariable())
2635      if (tgt.hasElement())
2636        vars.add(VariableMode.OUTPUT, tgt.getVariable(), prop);
2637      else
2638        vars.add(VariableMode.OUTPUT, tgt.getVariable(), prop);
2639  }
2640
2641  private Type generateFixedValue(StructureMapGroupRuleTargetComponent tgt) {
2642    if (!allParametersFixed(tgt))
2643      return null;
2644    if (!tgt.hasTransform())
2645      return null;
2646    switch (tgt.getTransform()) {
2647    case COPY:
2648      return tgt.getParameter().get(0).getValue();
2649    case TRUNCATE:
2650      return null;
2651    // case ESCAPE:
2652    // case CAST:
2653    // case APPEND:
2654    case TRANSLATE:
2655      return null;
2656    // case DATEOP,
2657    // case UUID,
2658    // case POINTER,
2659    // case EVALUATE,
2660    case CC:
2661      CodeableConcept cc = new CodeableConcept();
2662      cc.addCoding(buildCoding(tgt.getParameter().get(0).getValue(), tgt.getParameter().get(1).getValue()));
2663      return cc;
2664    case C:
2665      return buildCoding(tgt.getParameter().get(0).getValue(), tgt.getParameter().get(1).getValue());
2666    case QTY:
2667      return null;
2668    // case ID,
2669    // case CP,
2670    default:
2671      return null;
2672    }
2673  }
2674
2675  @SuppressWarnings("rawtypes")
2676  private Coding buildCoding(Type value1, Type value2) {
2677    return new Coding().setSystem(((PrimitiveType) value1).asStringValue())
2678        .setCode(((PrimitiveType) value2).asStringValue());
2679  }
2680
2681  private boolean allParametersFixed(StructureMapGroupRuleTargetComponent tgt) {
2682    for (StructureMapGroupRuleTargetParameterComponent p : tgt.getParameter()) {
2683      Type pr = p.getValue();
2684      if (pr instanceof IdType)
2685        return false;
2686    }
2687    return true;
2688  }
2689
2690  private String describeTransform(StructureMapGroupRuleTargetComponent tgt) throws FHIRException {
2691    switch (tgt.getTransform()) {
2692    case COPY:
2693      return null;
2694    case TRUNCATE:
2695      return null;
2696    // case ESCAPE:
2697    // case CAST:
2698    // case APPEND:
2699    case TRANSLATE:
2700      return null;
2701    // case DATEOP,
2702    // case UUID,
2703    // case POINTER,
2704    // case EVALUATE,
2705    case CC:
2706      return describeTransformCCorC(tgt);
2707    case C:
2708      return describeTransformCCorC(tgt);
2709    case QTY:
2710      return null;
2711    // case ID,
2712    // case CP,
2713    default:
2714      return null;
2715    }
2716  }
2717
2718  @SuppressWarnings("rawtypes")
2719  private String describeTransformCCorC(StructureMapGroupRuleTargetComponent tgt) throws FHIRException {
2720    if (tgt.getParameter().size() < 2)
2721      return null;
2722    Type p1 = tgt.getParameter().get(0).getValue();
2723    Type p2 = tgt.getParameter().get(1).getValue();
2724    if (p1 instanceof IdType || p2 instanceof IdType)
2725      return null;
2726    if (!(p1 instanceof PrimitiveType) || !(p2 instanceof PrimitiveType))
2727      return null;
2728    String uri = ((PrimitiveType) p1).asStringValue();
2729    String code = ((PrimitiveType) p2).asStringValue();
2730    if (Utilities.noString(uri))
2731      throw new FHIRException("Describe Transform, but the uri is blank");
2732    if (Utilities.noString(code))
2733      throw new FHIRException("Describe Transform, but the code is blank");
2734    Coding c = buildCoding(uri, code);
2735    return NarrativeGenerator.describeSystem(c.getSystem()) + "#" + c.getCode()
2736        + (c.hasDisplay() ? "(" + c.getDisplay() + ")" : "");
2737  }
2738
2739  private boolean isSignificantElement(PropertyWithType property, String element) {
2740    if ("Observation".equals(property.getPath()))
2741      return "code".equals(element);
2742    else if ("Bundle".equals(property.getPath()))
2743      return "type".equals(element);
2744    else
2745      return false;
2746  }
2747
2748  private String getTransformSuffix(StructureMapTransform transform) {
2749    switch (transform) {
2750    case COPY:
2751      return "";
2752    case TRUNCATE:
2753      return " (truncated)";
2754    // case ESCAPE:
2755    // case CAST:
2756    // case APPEND:
2757    case TRANSLATE:
2758      return " (translated)";
2759    // case DATEOP,
2760    // case UUID,
2761    // case POINTER,
2762    // case EVALUATE,
2763    case CC:
2764      return " (--> CodeableConcept)";
2765    case C:
2766      return " (--> Coding)";
2767    case QTY:
2768      return " (--> Quantity)";
2769    // case ID,
2770    // case CP,
2771    default:
2772      return " {??)";
2773    }
2774  }
2775
2776  private PropertyWithType updateProfile(VariableForProfiling var, String element, TypeDetails type, StructureMap map,
2777      List<StructureDefinition> profiles, String sliceName, Type fixed, StructureMapGroupRuleTargetComponent tgt)
2778      throws FHIRException {
2779    if (var == null) {
2780      assert (Utilities.noString(element));
2781      // 1. start the new structure definition
2782      StructureDefinition sdn = worker.fetchResource(StructureDefinition.class, type.getType());
2783      if (sdn == null)
2784        throw new FHIRException("Unable to find definition for " + type.getType());
2785      ElementDefinition edn = sdn.getSnapshot().getElementFirstRep();
2786      PropertyWithType pn = createProfile(map, profiles,
2787          new PropertyWithType(sdn.getId(), new Property(worker, edn, sdn), null, type), sliceName, tgt);
2788
2789//      // 2. hook it into the base bundle
2790//      if (type.getType().startsWith("http://hl7.org/fhir/StructureDefinition/") && worker.getResourceNames().contains(type.getType().substring(40))) {
2791//        StructureDefinition sd = var.getProperty().profileProperty.getStructure();
2792//        ElementDefinition ed = sd.getDifferential().addElement();
2793//        ed.setPath("Bundle.entry");
2794//        ed.setName(sliceName);
2795//        ed.setMax("1"); // well, it is for now...
2796//        ed = sd.getDifferential().addElement();
2797//        ed.setPath("Bundle.entry.fullUrl");
2798//        ed.setMin(1);
2799//        ed = sd.getDifferential().addElement();
2800//        ed.setPath("Bundle.entry.resource");
2801//        ed.setMin(1);
2802//        ed.addType().setCode(pn.getProfileProperty().getStructure().getType()).setProfile(pn.getProfileProperty().getStructure().getUrl());
2803//      }
2804      return pn;
2805    } else {
2806      assert (!Utilities.noString(element));
2807      Property pvb = var.getProperty().getBaseProperty();
2808      Property pvd = var.getProperty().getProfileProperty();
2809      Property pc = pvb.getChild(element, var.property.types);
2810      if (pc == null)
2811        throw new DefinitionException(
2812            "Unable to find a definition for " + pvb.getDefinition().getPath() + "." + element);
2813
2814      // the profile structure definition (derived)
2815      StructureDefinition sd = var.getProperty().profileProperty.getStructure();
2816      ElementDefinition ednew = sd.getDifferential().addElement();
2817      ednew.setPath(var.getProperty().profileProperty.getDefinition().getPath() + "." + pc.getName());
2818      ednew.setUserData("slice-name", sliceName);
2819      ednew.setFixed(fixed);
2820      for (ProfiledType pt : type.getProfiledTypes()) {
2821        if (pt.hasBindings())
2822          ednew.setBinding(pt.getBindings().get(0));
2823        if (pt.getUri().startsWith("http://hl7.org/fhir/StructureDefinition/")) {
2824          String t = pt.getUri().substring(40);
2825          t = checkType(t, pc, pt.getProfiles());
2826          if (t != null) {
2827            if (pt.hasProfiles()) {
2828              for (String p : pt.getProfiles())
2829                if (t.equals("Reference"))
2830                  ednew.getType(t).addTargetProfile(p);
2831                else
2832                  ednew.getType(t).addProfile(p);
2833            } else
2834              ednew.getType(t);
2835          }
2836        }
2837      }
2838
2839      return new PropertyWithType(var.property.path + "." + element, pc, new Property(worker, ednew, sd), type);
2840    }
2841  }
2842
2843  private String checkType(String t, Property pvb, List<String> profiles) throws FHIRException {
2844    if (pvb.getDefinition().getType().size() == 1
2845        && isCompatibleType(t, pvb.getDefinition().getType().get(0).getWorkingCode())
2846        && profilesMatch(profiles, pvb.getDefinition().getType().get(0).getProfile()))
2847      return null;
2848    for (TypeRefComponent tr : pvb.getDefinition().getType()) {
2849      if (isCompatibleType(t, tr.getWorkingCode()))
2850        return tr.getWorkingCode(); // note what is returned - the base type, not the inferred mapping type
2851    }
2852    throw new FHIRException(
2853        "The type " + t + " is not compatible with the allowed types for " + pvb.getDefinition().getPath());
2854  }
2855
2856  private boolean profilesMatch(List<String> profiles, List<CanonicalType> profile) {
2857    return profiles == null || profiles.size() == 0 || profile.size() == 0
2858        || (profiles.size() == 1 && profiles.get(0).equals(profile.get(0).getValue()));
2859  }
2860
2861  private boolean isCompatibleType(String t, String code) {
2862    if (t.equals(code))
2863      return true;
2864    if (t.equals("string")) {
2865      StructureDefinition sd = worker.fetchTypeDefinition(code);
2866      if (sd != null && sd.getBaseDefinition().equals("http://hl7.org/fhir/StructureDefinition/string"))
2867        return true;
2868    }
2869    return false;
2870  }
2871
2872  private TypeDetails analyseTransform(TransformContext context, StructureMap map,
2873      StructureMapGroupRuleTargetComponent tgt, VariableForProfiling var, VariablesForProfiling vars)
2874      throws FHIRException {
2875    switch (tgt.getTransform()) {
2876    case CREATE:
2877      String p = getParamString(vars, tgt.getParameter().get(0));
2878      return new TypeDetails(CollectionStatus.SINGLETON, p);
2879    case COPY:
2880      return getParam(vars, tgt.getParameter().get(0));
2881    case EVALUATE:
2882      ExpressionNode expr = (ExpressionNode) tgt.getUserData(MAP_EXPRESSION);
2883      if (expr == null) {
2884        expr = fpe.parse(getParamString(vars, tgt.getParameter().get(tgt.getParameter().size() - 1)));
2885        tgt.setUserData(MAP_WHERE_EXPRESSION, expr);
2886      }
2887      return fpe.check(vars, "Resource", null, expr);
2888
2889////case TRUNCATE : 
2890////  String src = getParamString(vars, tgt.getParameter().get(0));
2891////  String len = getParamString(vars, tgt.getParameter().get(1));
2892////  if (Utilities.isInteger(len)) {
2893////    int l = Integer.parseInt(len);
2894////    if (src.length() > l)
2895////      src = src.substring(0, l);
2896////  }
2897////  return new StringType(src);
2898////case ESCAPE : 
2899////  throw new Error("Transform "+tgt.getTransform().toCode()+" not supported yet");
2900////case CAST :
2901////  throw new Error("Transform "+tgt.getTransform().toCode()+" not supported yet");
2902////case APPEND : 
2903////  throw new Error("Transform "+tgt.getTransform().toCode()+" not supported yet");
2904    case TRANSLATE:
2905      return new TypeDetails(CollectionStatus.SINGLETON, "CodeableConcept");
2906    case CC:
2907      ProfiledType res = new ProfiledType("CodeableConcept");
2908      if (tgt.getParameter().size() >= 2 && isParamId(vars, tgt.getParameter().get(1))) {
2909        TypeDetails td = vars.get(null, getParamId(vars, tgt.getParameter().get(1))).property.types;
2910        if (td != null && td.hasBinding())
2911          // todo: do we need to check that there's no implicit translation her? I don't
2912          // think we do...
2913          res.addBinding(td.getBinding());
2914      }
2915      return new TypeDetails(CollectionStatus.SINGLETON, res);
2916    case C:
2917      return new TypeDetails(CollectionStatus.SINGLETON, "Coding");
2918    case QTY:
2919      return new TypeDetails(CollectionStatus.SINGLETON, "Quantity");
2920    case REFERENCE:
2921      VariableForProfiling vrs = vars.get(VariableMode.OUTPUT, getParamId(vars, tgt.getParameterFirstRep()));
2922      if (vrs == null)
2923        throw new FHIRException("Unable to resolve variable \"" + getParamId(vars, tgt.getParameterFirstRep()) + "\"");
2924      String profile = vrs.property.getProfileProperty().getStructure().getUrl();
2925      TypeDetails td = new TypeDetails(CollectionStatus.SINGLETON);
2926      td.addType("Reference", profile);
2927      return td;
2928////case DATEOP :
2929////  throw new Error("Transform "+tgt.getTransform().toCode()+" not supported yet");
2930////case UUID :
2931////  return new IdType(UUID.randomUUID().toString());
2932////case POINTER :
2933////  Base b = getParam(vars, tgt.getParameter().get(0));
2934////  if (b instanceof Resource)
2935////    return new UriType("urn:uuid:"+((Resource) b).getId());
2936////  else
2937////    throw new FHIRException("Transform engine cannot point at an element of type "+b.fhirType());
2938    default:
2939      throw new Error("Transform Unknown or not handled yet: " + tgt.getTransform().toCode());
2940    }
2941  }
2942
2943  private String getParamString(VariablesForProfiling vars, StructureMapGroupRuleTargetParameterComponent parameter) {
2944    Type p = parameter.getValue();
2945    if (p == null || p instanceof IdType)
2946      return null;
2947    if (!p.hasPrimitiveValue())
2948      return null;
2949    return p.primitiveValue();
2950  }
2951
2952  private String getParamId(VariablesForProfiling vars, StructureMapGroupRuleTargetParameterComponent parameter) {
2953    Type p = parameter.getValue();
2954    if (p == null || !(p instanceof IdType))
2955      return null;
2956    return p.primitiveValue();
2957  }
2958
2959  private boolean isParamId(VariablesForProfiling vars, StructureMapGroupRuleTargetParameterComponent parameter) {
2960    Type p = parameter.getValue();
2961    if (p == null || !(p instanceof IdType))
2962      return false;
2963    return vars.get(null, p.primitiveValue()) != null;
2964  }
2965
2966  private TypeDetails getParam(VariablesForProfiling vars, StructureMapGroupRuleTargetParameterComponent parameter)
2967      throws DefinitionException {
2968    Type p = parameter.getValue();
2969    if (!(p instanceof IdType))
2970      return new TypeDetails(CollectionStatus.SINGLETON,
2971          ProfileUtilities.sdNs(p.fhirType(), worker.getOverrideVersionNs()));
2972    else {
2973      String n = ((IdType) p).asStringValue();
2974      VariableForProfiling b = vars.get(VariableMode.INPUT, n);
2975      if (b == null)
2976        b = vars.get(VariableMode.OUTPUT, n);
2977      if (b == null)
2978        throw new DefinitionException("Variable " + n + " not found (" + vars.summary() + ")");
2979      return b.getProperty().getTypes();
2980    }
2981  }
2982
2983  private PropertyWithType createProfile(StructureMap map, List<StructureDefinition> profiles, PropertyWithType prop,
2984      String sliceName, Base ctxt) throws FHIRException {
2985    if (prop.getBaseProperty().getDefinition().getPath().contains("."))
2986      throw new DefinitionException("Unable to process entry point");
2987
2988    String type = prop.getBaseProperty().getDefinition().getPath();
2989    String suffix = "";
2990    if (ids.containsKey(type)) {
2991      int id = ids.get(type);
2992      id++;
2993      ids.put(type, id);
2994      suffix = "-" + Integer.toString(id);
2995    } else
2996      ids.put(type, 0);
2997
2998    StructureDefinition profile = new StructureDefinition();
2999    profiles.add(profile);
3000    profile.setDerivation(TypeDerivationRule.CONSTRAINT);
3001    profile.setType(type);
3002    profile.setBaseDefinition(prop.getBaseProperty().getStructure().getUrl());
3003    profile.setName("Profile for " + profile.getType() + " for " + sliceName);
3004    profile.setUrl(map.getUrl().replace("StructureMap", "StructureDefinition") + "-" + profile.getType() + suffix);
3005    ctxt.setUserData("profile", profile.getUrl()); // then we can easily assign this profile url for validation later
3006                                                   // when we actually transform
3007    profile.setId(map.getId() + "-" + profile.getType() + suffix);
3008    profile.setStatus(map.getStatus());
3009    profile.setExperimental(map.getExperimental());
3010    profile.setDescription("Generated automatically from the mapping by the Java Reference Implementation");
3011    for (ContactDetail c : map.getContact()) {
3012      ContactDetail p = profile.addContact();
3013      p.setName(c.getName());
3014      for (ContactPoint cc : c.getTelecom())
3015        p.addTelecom(cc);
3016    }
3017    profile.setDate(map.getDate());
3018    profile.setCopyright(map.getCopyright());
3019    profile.setFhirVersion(FHIRVersion.fromCode(Constants.VERSION));
3020    profile.setKind(prop.getBaseProperty().getStructure().getKind());
3021    profile.setAbstract(false);
3022    ElementDefinition ed = profile.getDifferential().addElement();
3023    ed.setPath(profile.getType());
3024    prop.profileProperty = new Property(worker, ed, profile);
3025    return prop;
3026  }
3027
3028  private PropertyWithType resolveType(StructureMap map, String type, StructureMapInputMode mode) throws FHIRException {
3029    for (StructureMapStructureComponent imp : map.getStructure()) {
3030      if ((imp.getMode() == StructureMapModelMode.SOURCE && mode == StructureMapInputMode.SOURCE)
3031          || (imp.getMode() == StructureMapModelMode.TARGET && mode == StructureMapInputMode.TARGET)) {
3032        StructureDefinition sd = worker.fetchResource(StructureDefinition.class, imp.getUrl());
3033        if (sd == null)
3034          throw new FHIRException("Import " + imp.getUrl() + " cannot be resolved");
3035        if (sd.getId().equals(type)) {
3036          return new PropertyWithType(sd.getType(), new Property(worker, sd.getSnapshot().getElement().get(0), sd),
3037              null, new TypeDetails(CollectionStatus.SINGLETON, sd.getUrl()));
3038        }
3039      }
3040    }
3041    throw new FHIRException("Unable to find structure definition for " + type + " in imports");
3042  }
3043
3044  public StructureMap generateMapFromMappings(StructureDefinition sd) throws IOException, FHIRException {
3045    String id = getLogicalMappingId(sd);
3046    if (id == null)
3047      return null;
3048    String prefix = ToolingExtensions.readStringExtension(sd, ToolingExtensions.EXT_MAPPING_PREFIX);
3049    String suffix = ToolingExtensions.readStringExtension(sd, ToolingExtensions.EXT_MAPPING_SUFFIX);
3050    if (prefix == null || suffix == null)
3051      return null;
3052    // we build this by text. Any element that has a mapping, we put it's mappings
3053    // inside it....
3054    StringBuilder b = new StringBuilder();
3055    b.append(prefix);
3056
3057    ElementDefinition root = sd.getSnapshot().getElementFirstRep();
3058    String m = getMapping(root, id);
3059    if (m != null)
3060      b.append(m + "\r\n");
3061    addChildMappings(b, id, "", sd, root, false);
3062    b.append("\r\n");
3063    b.append(suffix);
3064    b.append("\r\n");
3065    StructureMap map = parse(b.toString(), sd.getUrl());
3066    map.setId(tail(map.getUrl()));
3067    if (!map.hasStatus())
3068      map.setStatus(PublicationStatus.DRAFT);
3069    map.getText().setStatus(NarrativeStatus.GENERATED);
3070    map.getText().setDiv(new XhtmlNode(NodeType.Element, "div"));
3071    map.getText().getDiv().addTag("pre").addText(render(map));
3072    return map;
3073  }
3074
3075  private String tail(String url) {
3076    return url.substring(url.lastIndexOf("/") + 1);
3077  }
3078
3079  private void addChildMappings(StringBuilder b, String id, String indent, StructureDefinition sd, ElementDefinition ed,
3080      boolean inner) throws DefinitionException {
3081    boolean first = true;
3082    List<ElementDefinition> children = ProfileUtilities.getChildMap(sd, ed);
3083    for (ElementDefinition child : children) {
3084      if (first && inner) {
3085        b.append(" then {\r\n");
3086        first = false;
3087      }
3088      String map = getMapping(child, id);
3089      if (map != null) {
3090        b.append(indent + "  " + child.getPath() + ": " + map);
3091        addChildMappings(b, id, indent + "  ", sd, child, true);
3092        b.append("\r\n");
3093      }
3094    }
3095    if (!first && inner)
3096      b.append(indent + "}");
3097
3098  }
3099
3100  private String getMapping(ElementDefinition ed, String id) {
3101    for (ElementDefinitionMappingComponent map : ed.getMapping())
3102      if (id.equals(map.getIdentity()))
3103        return map.getMap();
3104    return null;
3105  }
3106
3107  private String getLogicalMappingId(StructureDefinition sd) {
3108    String id = null;
3109    for (StructureDefinitionMappingComponent map : sd.getMapping()) {
3110      if ("http://hl7.org/fhir/logical".equals(map.getUri()))
3111        return map.getIdentity();
3112    }
3113    return null;
3114  }
3115
3116  public TerminologyServiceOptions getTerminologyServiceOptions() {
3117    return terminologyServiceOptions;
3118  }
3119
3120  public void setTerminologyServiceOptions(TerminologyServiceOptions terminologyServiceOptions) {
3121    this.terminologyServiceOptions = terminologyServiceOptions;
3122  }
3123
3124}