001package org.hl7.fhir.r5.conformance;
002
003/*-
004 * #%L
005 * org.hl7.fhir.r5
006 * %%
007 * Copyright (C) 2014 - 2019 Health Level 7
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 * 
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 * 
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023import java.io.IOException;
024import java.io.OutputStream;
025import java.util.ArrayList;
026import java.util.Collections;
027import java.util.Comparator;
028import java.util.HashMap;
029import java.util.HashSet;
030import java.util.Iterator;
031import java.util.List;
032import java.util.Map;
033import java.util.Set;
034
035import org.apache.commons.lang3.StringUtils;
036import org.hl7.fhir.exceptions.DefinitionException;
037import org.hl7.fhir.exceptions.FHIRException;
038import org.hl7.fhir.exceptions.FHIRFormatError;
039import org.hl7.fhir.r5.conformance.ProfileUtilities.ProfileKnowledgeProvider.BindingResolution;
040import org.hl7.fhir.r5.context.IWorkerContext;
041import org.hl7.fhir.r5.context.IWorkerContext.ValidationResult;
042import org.hl7.fhir.r5.elementmodel.ObjectConverter;
043import org.hl7.fhir.r5.elementmodel.Property;
044import org.hl7.fhir.r5.formats.IParser;
045import org.hl7.fhir.r5.model.Base;
046import org.hl7.fhir.r5.model.BooleanType;
047import org.hl7.fhir.r5.model.CanonicalType;
048import org.hl7.fhir.r5.model.CodeType;
049import org.hl7.fhir.r5.model.CodeableConcept;
050import org.hl7.fhir.r5.model.Coding;
051import org.hl7.fhir.r5.model.Element;
052import org.hl7.fhir.r5.model.ElementDefinition;
053import org.hl7.fhir.r5.model.ElementDefinition.AggregationMode;
054import org.hl7.fhir.r5.model.ElementDefinition.DiscriminatorType;
055import org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionBaseComponent;
056import org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionBindingComponent;
057import org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionConstraintComponent;
058import org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionExampleComponent;
059import org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionMappingComponent;
060import org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionSlicingComponent;
061import org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionSlicingDiscriminatorComponent;
062import org.hl7.fhir.r5.model.ElementDefinition.PropertyRepresentation;
063import org.hl7.fhir.r5.model.ElementDefinition.SlicingRules;
064import org.hl7.fhir.r5.model.ElementDefinition.TypeRefComponent;
065import org.hl7.fhir.r5.model.Enumeration;
066import org.hl7.fhir.r5.model.Enumerations.BindingStrength;
067import org.hl7.fhir.r5.model.Enumerations.FHIRVersion;
068import org.hl7.fhir.r5.model.Extension;
069import org.hl7.fhir.r5.model.IdType;
070import org.hl7.fhir.r5.model.IntegerType;
071import org.hl7.fhir.r5.model.PrimitiveType;
072import org.hl7.fhir.r5.model.Quantity;
073import org.hl7.fhir.r5.model.Resource;
074import org.hl7.fhir.r5.model.StringType;
075import org.hl7.fhir.r5.model.StructureDefinition;
076import org.hl7.fhir.r5.model.StructureDefinition.ExtensionContextType;
077import org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionContextComponent;
078import org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionDifferentialComponent;
079import org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionKind;
080import org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionMappingComponent;
081import org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionSnapshotComponent;
082import org.hl7.fhir.r5.model.StructureDefinition.TypeDerivationRule;
083import org.hl7.fhir.r5.model.Type;
084import org.hl7.fhir.r5.model.UriType;
085import org.hl7.fhir.r5.model.ValueSet;
086import org.hl7.fhir.r5.model.ValueSet.ValueSetExpansionComponent;
087import org.hl7.fhir.r5.model.ValueSet.ValueSetExpansionContainsComponent;
088import org.hl7.fhir.r5.terminologies.ValueSetExpander.ValueSetExpansionOutcome;
089import org.hl7.fhir.r5.utils.NarrativeGenerator;
090import org.hl7.fhir.r5.utils.ToolingExtensions;
091import org.hl7.fhir.r5.utils.TranslatingUtilities;
092import org.hl7.fhir.r5.utils.formats.CSVWriter;
093import org.hl7.fhir.r5.utils.formats.XLSXWriter;
094import org.hl7.fhir.utilities.CommaSeparatedStringBuilder;
095import org.hl7.fhir.utilities.TerminologyServiceOptions;
096import org.hl7.fhir.utilities.Utilities;
097import org.hl7.fhir.utilities.validation.ValidationMessage;
098import org.hl7.fhir.utilities.validation.ValidationMessage.Source;
099import org.hl7.fhir.utilities.xhtml.HierarchicalTableGenerator;
100import org.hl7.fhir.utilities.xhtml.HierarchicalTableGenerator.Cell;
101import org.hl7.fhir.utilities.xhtml.HierarchicalTableGenerator.Piece;
102import org.hl7.fhir.utilities.xhtml.HierarchicalTableGenerator.Row;
103import org.hl7.fhir.utilities.xhtml.HierarchicalTableGenerator.TableModel;
104import org.hl7.fhir.utilities.xhtml.XhtmlNode;
105import org.hl7.fhir.utilities.xml.SchematronWriter;
106import org.hl7.fhir.utilities.xml.SchematronWriter.Rule;
107import org.hl7.fhir.utilities.xml.SchematronWriter.SchematronType;
108import org.hl7.fhir.utilities.xml.SchematronWriter.Section;
109
110/** 
111 * This class provides a set of utility operations for working with Profiles.
112 * Key functionality:
113 *  * getChildMap --?
114 *  * getChildList
115 *  * generateSnapshot: Given a base (snapshot) profile structure, and a differential profile, generate a new snapshot profile
116 *  * closeDifferential: fill out a differential by excluding anything not mentioned
117 *  * generateExtensionsTable: generate the HTML for a hierarchical table presentation of the extensions
118 *  * generateTable: generate  the HTML for a hierarchical table presentation of a structure
119 *  * generateSpanningTable: generate the HTML for a table presentation of a network of structures, starting at a nominated point
120 *  * summarize: describe the contents of a profile
121 *  
122 * note to maintainers: Do not make modifications to the snapshot generation without first changing the snapshot generation test cases to demonstrate the grounds for your change
123 *  
124 * @author Grahame
125 *
126 */
127public class ProfileUtilities extends TranslatingUtilities {
128
129  public class ElementRedirection {
130
131    private String path;
132    private ElementDefinition element;
133
134    public ElementRedirection(ElementDefinition element, String path) {
135      this.path = path;
136      this.element = element;
137    }
138
139    public ElementDefinition getElement() {
140      return element;
141    }
142
143    @Override
144    public String toString() {
145      return element.toString() + " : "+path;
146    }
147
148    public String getPath() {
149      return path;
150    }
151
152  }
153  
154  public class TypeSlice {
155    private ElementDefinition defn;
156    private String type;
157    public TypeSlice(ElementDefinition defn, String type) {
158      super();
159      this.defn = defn;
160      this.type = type;
161    }
162    public ElementDefinition getDefn() {
163      return defn;
164    }
165    public String getType() {
166      return type;
167    }
168    
169  }
170  private static final int MAX_RECURSION_LIMIT = 10;
171  
172  public class ExtensionContext {
173
174    private ElementDefinition element;
175    private StructureDefinition defn;
176
177    public ExtensionContext(StructureDefinition ext, ElementDefinition ed) {
178      this.defn = ext;
179      this.element = ed;
180    }
181
182    public ElementDefinition getElement() {
183      return element;
184    }
185
186    public StructureDefinition getDefn() {
187      return defn;
188    }
189
190    public String getUrl() {
191      if (element == defn.getSnapshot().getElement().get(0))
192        return defn.getUrl();
193      else
194        return element.getSliceName();
195    }
196
197    public ElementDefinition getExtensionValueDefinition() {
198      int i = defn.getSnapshot().getElement().indexOf(element)+1;
199      while (i < defn.getSnapshot().getElement().size()) {
200        ElementDefinition ed = defn.getSnapshot().getElement().get(i);
201        if (ed.getPath().equals(element.getPath()))
202          return null;
203        if (ed.getPath().startsWith(element.getPath()+".value"))
204          return ed;
205        i++;
206      }
207      return null;
208    }
209  }
210
211  private static final String ROW_COLOR_ERROR = "#ffcccc";
212  private static final String ROW_COLOR_FATAL = "#ff9999";
213  private static final String ROW_COLOR_WARNING = "#ffebcc";
214  private static final String ROW_COLOR_HINT = "#ebf5ff";
215  private static final String ROW_COLOR_NOT_MUST_SUPPORT = "#d6eaf8";
216  public static final int STATUS_OK = 0;
217  public static final int STATUS_HINT = 1;
218  public static final int STATUS_WARNING = 2;
219  public static final int STATUS_ERROR = 3;
220  public static final int STATUS_FATAL = 4;
221
222
223  private static final String DERIVATION_EQUALS = "derivation.equals";
224  public static final String DERIVATION_POINTER = "derived.pointer";
225  public static final String IS_DERIVED = "derived.fact";
226  public static final String UD_ERROR_STATUS = "error-status";
227  private static final String GENERATED_IN_SNAPSHOT = "profileutilities.snapshot.processed";
228  private final boolean ADD_REFERENCE_TO_TABLE = true;
229
230  private boolean useTableForFixedValues = true;
231  private boolean debug;
232
233  // note that ProfileUtilities are used re-entrantly internally, so nothing with process state can be here
234  private final IWorkerContext context;
235  private List<ValidationMessage> messages;
236  private List<String> snapshotStack = new ArrayList<String>();
237  private ProfileKnowledgeProvider pkp;
238  private boolean igmode;
239  private boolean exception;
240  private TerminologyServiceOptions terminologyServiceOptions = new TerminologyServiceOptions();
241  private boolean newSlicingProcessing;
242  private String defWebRoot;
243
244  public ProfileUtilities(IWorkerContext context, List<ValidationMessage> messages, ProfileKnowledgeProvider pkp) {
245    super();
246    this.context = context;
247    this.messages = messages;
248    this.pkp = pkp;
249  }
250
251  private class UnusedTracker {
252    private boolean used;
253  }
254
255  public boolean isIgmode() {
256    return igmode;
257  }
258
259
260  public void setIgmode(boolean igmode) {
261    this.igmode = igmode;
262  }
263
264  public interface ProfileKnowledgeProvider {
265    public class BindingResolution {
266      public String display;
267      public String url;
268    }
269    public boolean isDatatype(String typeSimple);
270    public boolean isResource(String typeSimple);
271    public boolean hasLinkFor(String typeSimple);
272    public String getLinkFor(String corePath, String typeSimple);
273    public BindingResolution resolveBinding(StructureDefinition def, ElementDefinitionBindingComponent binding, String path) throws FHIRException;
274    public BindingResolution resolveBinding(StructureDefinition def, String url, String path) throws FHIRException;
275    public String getLinkForProfile(StructureDefinition profile, String url);
276    public boolean prependLinks();
277    public String getLinkForUrl(String corePath, String s);
278  }
279
280
281
282  public static List<ElementDefinition> getChildMap(StructureDefinition profile, ElementDefinition element) throws DefinitionException {
283    if (element.getContentReference()!=null) {
284      for (ElementDefinition e : profile.getSnapshot().getElement()) {
285        if (element.getContentReference().equals("#"+e.getId()))
286          return getChildMap(profile, e);
287      }
288      throw new DefinitionException("Unable to resolve name reference "+element.getContentReference()+" at path "+element.getPath());
289
290    } else {
291      List<ElementDefinition> res = new ArrayList<ElementDefinition>();
292      List<ElementDefinition> elements = profile.getSnapshot().getElement();
293      String path = element.getPath();
294      for (int index = elements.indexOf(element) + 1; index < elements.size(); index++) {
295        ElementDefinition e = elements.get(index);
296        if (e.getPath().startsWith(path + ".")) {
297          // We only want direct children, not all descendants
298          if (!e.getPath().substring(path.length()+1).contains("."))
299            res.add(e);
300        } else
301          break;
302      }
303      return res;
304    }
305  }
306
307
308  public static List<ElementDefinition> getSliceList(StructureDefinition profile, ElementDefinition element) throws DefinitionException {
309    if (!element.hasSlicing())
310      throw new Error("getSliceList should only be called when the element has slicing");
311
312    List<ElementDefinition> res = new ArrayList<ElementDefinition>();
313    List<ElementDefinition> elements = profile.getSnapshot().getElement();
314    String path = element.getPath();
315    for (int index = elements.indexOf(element) + 1; index < elements.size(); index++) {
316      ElementDefinition e = elements.get(index);
317      if (e.getPath().startsWith(path + ".") || e.getPath().equals(path)) {
318        // We want elements with the same path (until we hit an element that doesn't start with the same path)
319        if (e.getPath().equals(element.getPath()))
320          res.add(e);
321      } else
322        break;
323    }
324    return res;
325  }
326
327
328  /**
329   * Given a Structure, navigate to the element given by the path and return the direct children of that element
330   *
331   * @param structure The structure to navigate into
332   * @param path The path of the element within the structure to get the children for
333   * @return A List containing the element children (all of them are Elements)
334   */
335  public static List<ElementDefinition> getChildList(StructureDefinition profile, String path, String id) {
336    return getChildList(profile, path, id, false);
337  }
338  
339  public static List<ElementDefinition> getChildList(StructureDefinition profile, String path, String id, boolean diff) {
340    List<ElementDefinition> res = new ArrayList<ElementDefinition>();
341
342    boolean capturing = id==null;
343    if (id==null && !path.contains("."))
344      capturing = true;
345  
346    List<ElementDefinition> list = diff ? profile.getDifferential().getElement() : profile.getSnapshot().getElement();
347    for (ElementDefinition e : list) {
348      if (e == null)
349        throw new Error("element = null: "+profile.getUrl());
350      if (e.getId() == null)
351        throw new Error("element id = null: "+e.toString()+" on "+profile.getUrl());
352      
353      if (!capturing && id!=null && e.getId().equals(id)) {
354        capturing = true;
355      }
356      
357      // If our element is a slice, stop capturing children as soon as we see the next slice
358      if (capturing && e.hasId() && id!= null && !e.getId().equals(id) && e.getPath().equals(path))
359        break;
360      
361      if (capturing) {
362        String p = e.getPath();
363  
364        if (!Utilities.noString(e.getContentReference()) && path.startsWith(p)) {
365          if (path.length() > p.length())
366            return getChildList(profile, e.getContentReference()+"."+path.substring(p.length()+1), null, diff);
367          else
368            return getChildList(profile, e.getContentReference(), null, diff);
369          
370        } else if (p.startsWith(path+".") && !p.equals(path)) {
371          String tail = p.substring(path.length()+1);
372          if (!tail.contains(".")) {
373            res.add(e);
374          }
375        }
376      }
377    }
378
379    return res;
380  }
381
382  public static List<ElementDefinition> getChildList(StructureDefinition structure, ElementDefinition element, boolean diff) {
383    return getChildList(structure, element.getPath(), element.getId(), diff);
384  }
385
386  public static List<ElementDefinition> getChildList(StructureDefinition structure, ElementDefinition element) {
387    return getChildList(structure, element.getPath(), element.getId(), false);
388        }
389
390  public void updateMaps(StructureDefinition base, StructureDefinition derived) throws DefinitionException {
391    if (base == null)
392        throw new DefinitionException("no base profile provided");
393    if (derived == null)
394      throw new DefinitionException("no derived structure provided");
395    
396    for (StructureDefinitionMappingComponent baseMap : base.getMapping()) {
397      boolean found = false;
398      for (StructureDefinitionMappingComponent derivedMap : derived.getMapping()) {
399        if (derivedMap.getUri() != null && derivedMap.getUri().equals(baseMap.getUri())) {
400          found = true;
401          break;
402        }
403      }
404      if (!found)
405        derived.getMapping().add(baseMap);
406    }
407  }
408  
409  /**
410   * Given a base (snapshot) profile structure, and a differential profile, generate a new snapshot profile
411   *
412   * @param base - the base structure on which the differential will be applied
413   * @param differential - the differential to apply to the base
414   * @param url - where the base has relative urls for profile references, these need to be converted to absolutes by prepending this URL (e.g. the canonical URL)
415   * @param webUrl - where the base has relative urls in markdown, these need to be converted to absolutes by prepending this URL (this is not the same as the canonical URL)
416   * @param trimDifferential - if this is true, then the snap short generator will remove any material in the element definitions that is not different to the base
417   * @return
418   * @throws FHIRException 
419   * @throws DefinitionException 
420   * @throws Exception
421   */
422  public void generateSnapshot(StructureDefinition base, StructureDefinition derived, String url, String webUrl, String profileName) throws DefinitionException, FHIRException {
423    if (base == null)
424      throw new DefinitionException("no base profile provided");
425    if (derived == null)
426      throw new DefinitionException("no derived structure provided");
427
428    if (!base.hasType())
429      throw new DefinitionException("Base profile "+base.getUrl()+" has no type");
430    if (!derived.hasType())
431      throw new DefinitionException("Derived profile "+derived.getUrl()+" has no type");
432    if (!base.getType().equals(derived.getType()) && derived.getDerivation().equals(TypeDerivationRule.CONSTRAINT))
433      throw new DefinitionException("Base & Derived profiles have different types ("+base.getUrl()+" = "+base.getType()+" vs "+derived.getUrl()+" = "+derived.getType()+")");
434      
435    if (snapshotStack.contains(derived.getUrl()))
436      throw new DefinitionException("Circular snapshot references detected; cannot generate snapshot (stack = "+snapshotStack.toString()+")");
437    snapshotStack.add(derived.getUrl());
438
439    if (!Utilities.noString(webUrl) && !webUrl.endsWith("/"))
440      webUrl = webUrl + '/';
441
442    if (defWebRoot == null)
443      defWebRoot = webUrl;
444    derived.setSnapshot(new StructureDefinitionSnapshotComponent());
445
446    try {
447      // so we have two lists - the base list, and the differential list
448      // the differential list is only allowed to include things that are in the base list, but
449      // is allowed to include them multiple times - thereby slicing them
450
451      // our approach is to walk through the base list, and see whether the differential
452      // says anything about them.
453      int baseCursor = 0;
454      int diffCursor = 0; // we need a diff cursor because we can only look ahead, in the bound scoped by longer paths
455
456      if (derived.hasDifferential() && !derived.getDifferential().getElementFirstRep().getPath().contains(".") && !derived.getDifferential().getElementFirstRep().getType().isEmpty())
457        throw new Error("type on first differential element!");
458
459      for (ElementDefinition e : derived.getDifferential().getElement()) 
460        e.clearUserData(GENERATED_IN_SNAPSHOT);
461
462      // we actually delegate the work to a subroutine so we can re-enter it with a different cursors
463      StructureDefinitionDifferentialComponent diff = cloneDiff(derived.getDifferential()); // we make a copy here because we're sometimes going to hack the differential while processing it. Have to migrate user data back afterwards
464      StructureDefinitionSnapshotComponent baseSnapshot  = base.getSnapshot(); 
465      if (derived.getDerivation().equals(TypeDerivationRule.SPECIALIZATION)) {
466        baseSnapshot = cloneSnapshot(baseSnapshot, base.getType(), derived.getType());
467      }
468      processPaths("", derived.getSnapshot(), baseSnapshot, diff, baseCursor, diffCursor, baseSnapshot.getElement().size()-1, 
469          derived.getDifferential().hasElement() ? derived.getDifferential().getElement().size()-1 : -1, url, webUrl, derived.present(), null, null, false, base.getUrl(), null, false, new ArrayList<ElementRedirection>(), base);
470      if (derived.getDerivation().equals(TypeDerivationRule.SPECIALIZATION)) {
471        for (ElementDefinition e : diff.getElement()) {
472          if (!e.hasUserData(GENERATED_IN_SNAPSHOT)) {
473            ElementDefinition outcome = updateURLs(url, webUrl, e.copy());
474            e.setUserData(GENERATED_IN_SNAPSHOT, outcome);
475            derived.getSnapshot().addElement(outcome);
476          }
477        }
478      }
479      
480      if (!derived.getSnapshot().getElementFirstRep().getType().isEmpty())
481        throw new Error("type on first snapshot element for "+derived.getSnapshot().getElementFirstRep().getPath()+" in "+derived.getUrl()+" from "+base.getUrl());
482      updateMaps(base, derived);
483
484      if (debug) {
485        System.out.println("Differential: ");
486        for (ElementDefinition ed : derived.getDifferential().getElement())
487          System.out.println("  "+ed.getPath()+" : "+typeSummaryWithProfile(ed)+"["+ed.getMin()+".."+ed.getMax()+"]"+sliceSummary(ed)+"  id = "+ed.getId()+" "+constraintSummary(ed));
488        System.out.println("Snapshot: ");
489        for (ElementDefinition ed : derived.getSnapshot().getElement())
490          System.out.println("  "+ed.getPath()+" : "+typeSummaryWithProfile(ed)+"["+ed.getMin()+".."+ed.getMax()+"]"+sliceSummary(ed)+"  id = "+ed.getId()+" "+constraintSummary(ed));
491      }
492      setIds(derived, false);
493      //Check that all differential elements have a corresponding snapshot element
494      for (ElementDefinition e : diff.getElement()) {
495        if (!e.hasUserData("diff-source"))
496          throw new Error("Unxpected internal condition - no source on diff element");
497        else {
498          if (e.hasUserData(DERIVATION_EQUALS))
499            ((Base) e.getUserData("diff-source")).setUserData(DERIVATION_EQUALS, e.getUserData(DERIVATION_EQUALS));
500          if (e.hasUserData(DERIVATION_POINTER))
501            ((Base) e.getUserData("diff-source")).setUserData(DERIVATION_POINTER, e.getUserData(DERIVATION_POINTER));
502        }
503        if (!e.hasUserData(GENERATED_IN_SNAPSHOT)) {
504          System.out.println("Error in snapshot generation: Differential for "+derived.getUrl()+" has an element " + (e.hasId() ? "id: "+e.getId() : "path: "+e.getPath())+" that is not marked with a snapshot match - check validity of differential (including order)");
505          if (exception)
506            throw new DefinitionException("Snapshot for "+derived.getUrl()+" does not contain an element that matches an existing differential element that has "+(e.hasId() ? "id: "+e.getId() : "path: "+e.getPath()));
507          else
508            messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.VALUE, url, "Snapshot for "+derived.getUrl()+" does not contain an element that matches an existing differential element that has id: " + e.getId(), ValidationMessage.IssueSeverity.ERROR));
509        }
510      }
511      if (derived.getDerivation() == TypeDerivationRule.SPECIALIZATION) {
512        for (ElementDefinition ed : derived.getSnapshot().getElement()) {
513          if (!ed.hasBase()) {
514            ed.getBase().setPath(ed.getPath()).setMin(ed.getMin()).setMax(ed.getMax());
515          }
516        }
517      }
518    } catch (Exception e) {
519      // if we had an exception generating the snapshot, make sure we don't leave any half generated snapshot behind
520      derived.setSnapshot(null);
521      throw e;
522    }
523  }
524
525  private StructureDefinitionDifferentialComponent cloneDiff(StructureDefinitionDifferentialComponent source) {
526    StructureDefinitionDifferentialComponent diff = new StructureDefinitionDifferentialComponent();
527    for (ElementDefinition sed : source.getElement()) {
528      ElementDefinition ted = sed.copy();
529      diff.getElement().add(ted);
530      ted.setUserData("diff-source", sed);
531    }
532    return diff;
533  }
534
535  private StructureDefinitionSnapshotComponent cloneSnapshot(StructureDefinitionSnapshotComponent source, String baseType, String derivedType) {
536        StructureDefinitionSnapshotComponent diff = new StructureDefinitionSnapshotComponent();
537    for (ElementDefinition sed : source.getElement()) {
538      ElementDefinition ted = sed.copy();
539      ted.setId(ted.getId().replaceFirst(baseType,derivedType));
540      ted.setPath(ted.getPath().replaceFirst(baseType,derivedType));
541      diff.getElement().add(ted);
542    }
543    return diff;
544  }
545
546  private String constraintSummary(ElementDefinition ed) {
547    CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
548    if (ed.hasPattern())
549      b.append("pattern="+ed.getPattern().fhirType());
550    if (ed.hasFixed())
551      b.append("fixed="+ed.getFixed().fhirType());
552    if (ed.hasConstraint())
553      b.append("constraints="+ed.getConstraint().size());
554    return b.toString();
555  }
556
557
558  private String sliceSummary(ElementDefinition ed) {
559    if (!ed.hasSlicing() && !ed.hasSliceName())
560      return "";
561    if (ed.hasSliceName())
562      return " (slicename = "+ed.getSliceName()+")";
563    
564    StringBuilder b = new StringBuilder();
565    boolean first = true;
566    for (ElementDefinitionSlicingDiscriminatorComponent d : ed.getSlicing().getDiscriminator()) {
567      if (first) 
568        first = false;
569      else
570        b.append("|");
571      b.append(d.getPath());
572    }
573    return " (slicing by "+b.toString()+")";
574  }
575
576
577  private String typeSummary(ElementDefinition ed) {
578    StringBuilder b = new StringBuilder();
579    boolean first = true;
580    for (TypeRefComponent tr : ed.getType()) {
581      if (first) 
582        first = false;
583      else
584        b.append("|");
585      b.append(tr.getWorkingCode());
586    }
587    return b.toString();
588  }
589
590  private String typeSummaryWithProfile(ElementDefinition ed) {
591    StringBuilder b = new StringBuilder();
592    boolean first = true;
593    for (TypeRefComponent tr : ed.getType()) {
594      if (first) 
595        first = false;
596      else
597        b.append("|");
598      b.append(tr.getWorkingCode());
599      if (tr.hasProfile()) {
600        b.append("(");
601        b.append(tr.getProfile());
602        b.append(")");
603        
604      }
605    }
606    return b.toString();
607  }
608
609
610  private boolean findMatchingElement(String id, List<ElementDefinition> list) {
611    for (ElementDefinition ed : list) {
612      if (ed.getId().equals(id))
613        return true;
614      if (id.endsWith("[x]")) {
615        if (ed.getId().startsWith(id.substring(0, id.length()-3)) && !ed.getId().substring(id.length()-3).contains("."))
616          return true;
617      }
618    }
619    return false;
620  }
621
622
623  /**
624   * @param trimDifferential
625   * @param srcSD 
626   * @throws DefinitionException, FHIRException 
627   * @throws Exception
628   */
629  private ElementDefinition processPaths(String indent, StructureDefinitionSnapshotComponent result, StructureDefinitionSnapshotComponent base, StructureDefinitionDifferentialComponent differential, int baseCursor, int diffCursor, int baseLimit,
630      int diffLimit, String url, String webUrl, String profileName, String contextPathSrc, String contextPathDst, boolean trimDifferential, String contextName, String resultPathBase, boolean slicingDone, List<ElementRedirection> redirector, StructureDefinition srcSD) throws DefinitionException, FHIRException {
631    if (debug) 
632      System.out.println(indent+"PP @ "+resultPathBase+" / "+contextPathSrc+" : base = "+baseCursor+" to "+baseLimit+", diff = "+diffCursor+" to "+diffLimit+" (slicing = "+slicingDone+", redirector = "+(redirector == null ? "null" : redirector.toString())+")");
633    ElementDefinition res = null; 
634    List<TypeSlice> typeList = new ArrayList<>();
635    // just repeat processing entries until we run out of our allowed scope (1st entry, the allowed scope is all the entries)
636    while (baseCursor <= baseLimit) {
637      // get the current focus of the base, and decide what to do
638      ElementDefinition currentBase = base.getElement().get(baseCursor);
639      String cpath = fixedPathSource(contextPathSrc, currentBase.getPath(), redirector);
640      if (debug) 
641        System.out.println(indent+" - "+cpath+": base = "+baseCursor+" ("+descED(base.getElement(),baseCursor)+") to "+baseLimit+" ("+descED(base.getElement(),baseLimit)+"), diff = "+diffCursor+" ("+descED(differential.getElement(),diffCursor)+") to "+diffLimit+" ("+descED(differential.getElement(),diffLimit)+") "+
642           "(slicingDone = "+slicingDone+") (diffpath= "+(differential.getElement().size() > diffCursor ? differential.getElement().get(diffCursor).getPath() : "n/a")+")");
643      List<ElementDefinition> diffMatches = getDiffMatches(differential, cpath, diffCursor, diffLimit, profileName); // get a list of matching elements in scope
644
645      // in the simple case, source is not sliced.
646      if (!currentBase.hasSlicing()) {
647        if (diffMatches.isEmpty()) { // the differential doesn't say anything about this item
648          // so we just copy it in
649          ElementDefinition outcome = updateURLs(url, webUrl, currentBase.copy());
650          outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
651          updateFromBase(outcome, currentBase);
652          markDerived(outcome);
653          if (resultPathBase == null)
654            resultPathBase = outcome.getPath();
655          else if (!outcome.getPath().startsWith(resultPathBase))
656            throw new DefinitionException("Adding wrong path");
657          result.getElement().add(outcome);
658          if (hasInnerDiffMatches(differential, cpath, diffCursor, diffLimit, base.getElement(), true)) {
659            // well, the profile walks into this, so we need to as well
660            // did we implicitly step into a new type?
661            if (baseHasChildren(base, currentBase)) { // not a new type here
662              processPaths(indent+"  ", result, base, differential, baseCursor+1, diffCursor, baseLimit, diffLimit, url, webUrl, profileName, contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, false, redirector, srcSD);
663              baseCursor = indexOfFirstNonChild(base, currentBase, baseCursor+1, baseLimit);
664            } else {
665              if (outcome.getType().size() == 0) {
666                throw new DefinitionException(diffMatches.get(0).getPath()+" has no children ("+differential.getElement().get(diffCursor).getPath()+") and no types in profile "+profileName);
667              }
668              if (outcome.getType().size() > 1) {
669                for (TypeRefComponent t : outcome.getType()) {
670                  if (!t.getWorkingCode().equals("Reference"))
671                    throw new DefinitionException(diffMatches.get(0).getPath()+" has children ("+differential.getElement().get(diffCursor).getPath()+") and multiple types ("+typeCode(outcome.getType())+") in profile "+profileName);
672                }
673              }
674              StructureDefinition dt = getProfileForDataType(outcome.getType().get(0));
675              if (dt == null)
676                throw new DefinitionException("Unknown type "+outcome.getType().get(0)+" at "+diffMatches.get(0).getPath());
677              contextName = dt.getUrl();
678              int start = diffCursor;
679              while (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), cpath+"."))
680                diffCursor++;
681              processPaths(indent+"  ", result, dt.getSnapshot(), differential, 1 /* starting again on the data type, but skip the root */, start, dt.getSnapshot().getElement().size()-1,
682                  diffCursor-1, url, getWebUrl(dt, webUrl, indent), profileName, cpath, outcome.getPath(), trimDifferential, contextName, resultPathBase, false, redirector, srcSD);
683            }
684          }
685          baseCursor++;
686        } else if (diffMatches.size() == 1 && (slicingDone || (!isImplicitSlicing(diffMatches.get(0), cpath) && !(diffMatches.get(0).hasSlicing() || (isExtension(diffMatches.get(0)) && diffMatches.get(0).hasSliceName()))))) {// one matching element in the differential
687          ElementDefinition template = null;
688          if (diffMatches.get(0).hasType() && diffMatches.get(0).getType().size() == 1 && diffMatches.get(0).getType().get(0).hasProfile() && !"Reference".equals(diffMatches.get(0).getType().get(0).getWorkingCode())) {
689            CanonicalType p = diffMatches.get(0).getType().get(0).getProfile().get(0);
690            StructureDefinition sd = context.fetchResource(StructureDefinition.class, p.getValue());
691            if (sd != null) {
692              if (!sd.hasSnapshot()) {
693                StructureDefinition sdb = context.fetchResource(StructureDefinition.class, sd.getBaseDefinition());
694                if (sdb == null)
695                  throw new DefinitionException("Unable to find base "+sd.getBaseDefinition()+" for "+sd.getUrl());
696                generateSnapshot(sdb, sd, sd.getUrl(), (sdb.hasUserData("path")) ? Utilities.extractBaseUrl(sdb.getUserString("path")) : webUrl, sd.getName());
697              }
698              ElementDefinition src;
699              if (p.hasExtension(ToolingExtensions.EXT_PROFILE_ELEMENT)) {
700                 src = null;
701                 String eid = p.getExtensionString(ToolingExtensions.EXT_PROFILE_ELEMENT);
702                 for (ElementDefinition t : sd.getSnapshot().getElement()) {
703                   if (eid.equals(t.getId()))
704                     src = t;
705                 }
706                 if (src == null)
707                   throw new DefinitionException("Unable to find element "+eid+" in "+p.getValue());
708              } else 
709                src = sd.getSnapshot().getElement().get(0);
710              template = src.copy().setPath(currentBase.getPath());
711              template.setSliceName(null);
712              // temporary work around
713              if (!"Extension".equals(diffMatches.get(0).getType().get(0).getCode())) {
714                template.setMin(currentBase.getMin());
715                template.setMax(currentBase.getMax());
716              }
717            }
718          } 
719          if (template == null)
720            template = currentBase.copy();
721          else
722            // some of what's in currentBase overrides template
723            template = fillOutFromBase(template, currentBase);
724          
725          ElementDefinition outcome = updateURLs(url, webUrl, template);
726          outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
727          if (res == null)
728            res = outcome;
729          updateFromBase(outcome, currentBase);
730          if (diffMatches.get(0).hasSliceName())
731            outcome.setSliceName(diffMatches.get(0).getSliceName());
732          updateFromDefinition(outcome, diffMatches.get(0), profileName, trimDifferential, url, srcSD);
733          removeStatusExtensions(outcome);
734//          if (outcome.getPath().endsWith("[x]") && outcome.getType().size() == 1 && !outcome.getType().get(0).getCode().equals("*") && !diffMatches.get(0).hasSlicing()) // if the base profile allows multiple types, but the profile only allows one, rename it
735//            outcome.setPath(outcome.getPath().substring(0, outcome.getPath().length()-3)+Utilities.capitalize(outcome.getType().get(0).getCode()));
736          outcome.setSlicing(null);
737          if (resultPathBase == null)
738            resultPathBase = outcome.getPath();
739          else if (!outcome.getPath().startsWith(resultPathBase))
740            throw new DefinitionException("Adding wrong path");
741          result.getElement().add(outcome);
742          baseCursor++;
743          diffCursor = differential.getElement().indexOf(diffMatches.get(0))+1;
744          if (diffLimit >= diffCursor && outcome.getPath().contains(".") && (isDataType(outcome.getType()) || outcome.hasContentReference())) {  // don't want to do this for the root, since that's base, and we're already processing it
745            if (pathStartsWith(differential.getElement().get(diffCursor).getPath(), diffMatches.get(0).getPath()+".") && !baseWalksInto(base.getElement(), baseCursor)) {
746              if (outcome.getType().size() > 1) {
747                if (outcome.getPath().endsWith("[x]") && !diffMatches.get(0).getPath().endsWith("[x]")) {
748                  String en = tail(outcome.getPath());
749                  String tn = tail(diffMatches.get(0).getPath());
750                  String t = tn.substring(en.length()-3);
751                  if (isPrimitive(Utilities.uncapitalize(t)))
752                    t = Utilities.uncapitalize(t);
753                  List<TypeRefComponent> ntr = getByTypeName(outcome.getType(), t); // keep any additional information
754                  if (ntr.isEmpty()) 
755                    ntr.add(new TypeRefComponent().setCode(t));
756                  outcome.getType().clear();
757                  outcome.getType().addAll(ntr);
758                }
759                if (outcome.getType().size() > 1)
760                  for (TypeRefComponent t : outcome.getType()) {
761                    if (!t.getCode().equals("Reference")) {
762                      boolean nonExtension = false;
763                      for (ElementDefinition ed : diffMatches)
764                        if (ed != diffMatches.get(0) && !ed.getPath().endsWith(".extension"))
765                          nonExtension = true;
766                      if (nonExtension)
767                        throw new DefinitionException(diffMatches.get(0).getPath()+" has children ("+differential.getElement().get(diffCursor).getPath()+") and multiple types ("+typeCode(outcome.getType())+") in profile "+profileName);
768                    }
769                }
770              }
771              int start = diffCursor;
772              while (diffCursor <= diffLimit && differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), diffMatches.get(0).getPath()+"."))
773                diffCursor++;
774              if (outcome.hasContentReference()) {
775                ElementDefinition tgt = getElementById(base.getElement(), outcome.getContentReference());
776                if (tgt == null)
777                  throw new DefinitionException("Unable to resolve reference to "+outcome.getContentReference());
778                replaceFromContentReference(outcome, tgt);
779                int nbc = base.getElement().indexOf(tgt)+1;
780                int nbl = nbc;
781                while (nbl < base.getElement().size() && base.getElement().get(nbl).getPath().startsWith(tgt.getPath()+"."))
782                  nbl++;
783                processPaths(indent+"  ", result, base, differential, nbc, start - 1, nbl-1, diffCursor - 1, url, webUrl, profileName, tgt.getPath(), diffMatches.get(0).getPath(), trimDifferential, contextName, resultPathBase, false, redirectorStack(redirector, outcome, cpath), srcSD);
784              } else {
785                StructureDefinition dt = outcome.getType().size() == 1 ? getProfileForDataType(outcome.getType().get(0)) : getProfileForDataType("Element");
786                if (dt == null)
787                  throw new DefinitionException(diffMatches.get(0).getPath()+" has children ("+differential.getElement().get(diffCursor).getPath()+") for type "+typeCode(outcome.getType())+" in profile "+profileName+", but can't find type");
788                contextName = dt.getUrl();
789                processPaths(indent+"  ", result, dt.getSnapshot(), differential, 1 /* starting again on the data type, but skip the root */, start, dt.getSnapshot().getElement().size()-1,
790                    diffCursor - 1, url, getWebUrl(dt, webUrl, indent), profileName+pathTail(diffMatches, 0), diffMatches.get(0).getPath(), outcome.getPath(), trimDifferential, contextName, resultPathBase, false, new ArrayList<ElementRedirection>(), srcSD);
791              }
792            }
793          }
794        } else if (diffsConstrainTypes(diffMatches, cpath, typeList)) {
795          int start = 0;
796          int nbl = findEndOfElement(base, baseCursor);
797          int ndc = differential.getElement().indexOf(diffMatches.get(0));
798          ElementDefinition elementToRemove = null;
799          boolean shortCut = typeList.get(0).type != null;
800          // we come here whether they are sliced in the diff, or whether the short cut is used. 
801          if (shortCut) {
802            // this is the short cut method, we've just dived in and specified a type slice. 
803            // in R3 (and unpatched R4, as a workaround right now...
804            if (!FHIRVersion.isR4Plus(context.getVersion()) || !newSlicingProcessing) { // newSlicingProcessing is a work around for editorial loop dependency
805              // we insert a cloned element with the right types at the start of the diffMatches
806              ElementDefinition ed = new ElementDefinition();
807              ed.setPath(determineTypeSlicePath(diffMatches.get(0).getPath(), cpath));
808              for (TypeSlice ts : typeList) 
809                ed.addType().setCode(ts.type);
810              ed.setSlicing(new ElementDefinitionSlicingComponent());
811              ed.getSlicing().addDiscriminator().setType(DiscriminatorType.TYPE).setPath("$this");
812              ed.getSlicing().setRules(SlicingRules.CLOSED);
813              ed.getSlicing().setOrdered(false);
814              diffMatches.add(0, ed);
815              differential.getElement().add(ndc, ed);
816              elementToRemove = ed;
817            } else {
818              // as of R4, this changed; if there's no slice, there's no constraint on the slice types, only one the type. 
819              // so the element we insert specifies no types (= all types) allowed in the base, not just the listed type. 
820              // see also discussion here: https://chat.fhir.org/#narrow/stream/179177-conformance/topic/Slicing.20a.20non-repeating.20element             
821              ElementDefinition ed = new ElementDefinition();
822              ed.setPath(determineTypeSlicePath(diffMatches.get(0).getPath(), cpath));
823              ed.setSlicing(new ElementDefinitionSlicingComponent());
824              ed.getSlicing().addDiscriminator().setType(DiscriminatorType.TYPE).setPath("$this");
825              ed.getSlicing().setRules(SlicingRules.CLOSED);
826              ed.getSlicing().setOrdered(false);
827              diffMatches.add(0, ed);
828              differential.getElement().add(ndc, ed);
829              elementToRemove = ed;
830            }
831          }
832          int ndl = findEndOfElement(differential, ndc);
833          // the first element is setting up the slicing
834          if (diffMatches.get(0).getSlicing().hasRules())
835            if (diffMatches.get(0).getSlicing().getRules() != SlicingRules.CLOSED)
836              throw new FHIRException("Error at path "+cpath+" in "+url+": Type slicing with slicing.rules != closed");
837          if (diffMatches.get(0).getSlicing().hasOrdered())
838            if (diffMatches.get(0).getSlicing().getOrdered())
839              throw new FHIRException("Error at path "+cpath+" in "+url+": Type slicing with slicing.ordered = true");
840          if (diffMatches.get(0).getSlicing().hasDiscriminator()) {
841            if (diffMatches.get(0).getSlicing().getDiscriminator().size() != 1)
842              throw new FHIRException("Error at path "+cpath+" in "+url+": Type slicing with slicing.discriminator.count() > 1");
843            if (!"$this".equals(diffMatches.get(0).getSlicing().getDiscriminatorFirstRep().getPath()))
844              throw new FHIRException("Error at path "+cpath+" in "+url+": Type slicing with slicing.discriminator.path != '$this'");
845            if (diffMatches.get(0).getSlicing().getDiscriminatorFirstRep().getType() != DiscriminatorType.TYPE)
846              throw new FHIRException("Error at path "+cpath+" in "+url+": Type slicing with slicing.discriminator.type != 'type'");
847          }
848          // check the slice names too while we're at it...
849          for (TypeSlice ts : typeList)
850            if (ts.type != null) {
851              String tn = rootName(cpath)+Utilities.capitalize(ts.type);
852              if (!ts.defn.hasSliceName())
853                ts.defn.setSliceName(tn);
854              else if (!ts.defn.getSliceName().equals(tn))
855                throw new FHIRException("Error at path "+(!Utilities.noString(contextPathSrc) ? contextPathSrc : cpath)+": Slice name must be '"+tn+"' but is '"+ts.defn.getSliceName()+"'"); 
856              if (!ts.defn.hasType())
857                ts.defn.addType().setCode(ts.type);
858              else if (ts.defn.getType().size() > 1)
859                throw new FHIRException("Error at path "+(!Utilities.noString(contextPathSrc) ? contextPathSrc : cpath)+": Slice for type '"+tn+"' has more than one type '"+ts.defn.typeSummary()+"'"); 
860              else if (!ts.defn.getType().get(0).getCode().equals(ts.type))
861                throw new FHIRException("Error at path "+(!Utilities.noString(contextPathSrc) ? contextPathSrc : cpath)+": Slice for type '"+tn+"' has wrong type '"+ts.defn.typeSummary()+"'"); 
862            }
863
864          // ok passed the checks. 
865          // copy the root diff, and then process any children it has
866          ElementDefinition e = processPaths(indent+"  ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName+pathTail(diffMatches, 0), contextPathSrc, contextPathDst, 
867              trimDifferential, contextName, resultPathBase, true, redirector, srcSD);
868          if (e==null)
869            throw new FHIRException("Did not find type root: " + diffMatches.get(0).getPath());
870          // now set up slicing on the e (cause it was wiped by what we called.
871          e.setSlicing(new ElementDefinitionSlicingComponent());
872          e.getSlicing().addDiscriminator().setType(DiscriminatorType.TYPE).setPath("$this");
873          e.getSlicing().setRules(SlicingRules.CLOSED);
874          e.getSlicing().setOrdered(false);
875          start++;
876
877          // now process the siblings, which should each be type constrained - and may also have their own children
878          // now we process the base scope repeatedly for each instance of the item in the differential list
879          for (int i = start; i < diffMatches.size(); i++) {
880            // our processing scope for the differential is the item in the list, and all the items before the next one in the list
881            ndc = differential.getElement().indexOf(diffMatches.get(i));
882            ndl = findEndOfElement(differential, ndc);
883            processPaths(indent+"  ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName+pathTail(diffMatches, i), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, true, redirector, srcSD);
884          }
885          if (elementToRemove != null) {
886            differential.getElement().remove(elementToRemove);
887            ndl--;
888          }
889          
890          // ok, done with that - next in the base list
891          baseCursor = nbl+1;
892          diffCursor = ndl+1;
893          
894        } else {
895          // ok, the differential slices the item. Let's check our pre-conditions to ensure that this is correct
896          if (!unbounded(currentBase) && !isSlicedToOneOnly(diffMatches.get(0)))
897            // you can only slice an element that doesn't repeat if the sum total of your slices is limited to 1
898            // (but you might do that in order to split up constraints by type)
899            throw new DefinitionException("Attempt to a slice an element that does not repeat: "+currentBase.getPath()+"/"+currentBase.getPath()+" from "+contextName+" in "+url);
900          if (!diffMatches.get(0).hasSlicing() && !isExtension(currentBase)) // well, the diff has set up a slice, but hasn't defined it. this is an error
901            throw new DefinitionException("Differential does not have a slice: "+currentBase.getPath()+"/ (b:"+baseCursor+" of "+ baseLimit+" / "+ diffCursor +"/ "+diffLimit+") in profile "+url);
902
903          // well, if it passed those preconditions then we slice the dest.
904          int start = 0;
905          int nbl = findEndOfElement(base, baseCursor);
906//          if (diffMatches.size() > 1 && diffMatches.get(0).hasSlicing() && differential.getElement().indexOf(diffMatches.get(1)) > differential.getElement().indexOf(diffMatches.get(0))+1) {
907          if (diffMatches.size() > 1 && diffMatches.get(0).hasSlicing() && (nbl > baseCursor || differential.getElement().indexOf(diffMatches.get(1)) > differential.getElement().indexOf(diffMatches.get(0))+1)) { // there's a default set before the slices
908            int ndc = differential.getElement().indexOf(diffMatches.get(0));
909            int ndl = findEndOfElement(differential, ndc);
910            ElementDefinition e = processPaths(indent+"  ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName+pathTail(diffMatches, 0), contextPathSrc, contextPathDst, 
911                trimDifferential, contextName, resultPathBase, true, redirector, srcSD);
912            if (e==null)
913              throw new FHIRException("Did not find single slice: " + diffMatches.get(0).getPath());
914            e.setSlicing(diffMatches.get(0).getSlicing());
915            start++;
916          } else {
917            // we're just going to accept the differential slicing at face value
918            ElementDefinition outcome = updateURLs(url, webUrl, currentBase.copy());
919            outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
920            updateFromBase(outcome, currentBase);
921
922            if (!diffMatches.get(0).hasSlicing())
923              outcome.setSlicing(makeExtensionSlicing());
924            else
925              outcome.setSlicing(diffMatches.get(0).getSlicing().copy());
926            if (!outcome.getPath().startsWith(resultPathBase))
927              throw new DefinitionException("Adding wrong path");
928            result.getElement().add(outcome);
929
930            // differential - if the first one in the list has a name, we'll process it. Else we'll treat it as the base definition of the slice.
931            if (!diffMatches.get(0).hasSliceName()) {
932              updateFromDefinition(outcome, diffMatches.get(0), profileName, trimDifferential, url, srcSD);
933              removeStatusExtensions(outcome);
934              if (!outcome.hasContentReference() && !outcome.hasType()) {
935                throw new DefinitionException("not done yet");
936              }
937              start++;
938              // result.getElement().remove(result.getElement().size()-1);
939            } else 
940              checkExtensionDoco(outcome);
941          }
942          // now, for each entry in the diff matches, we're going to process the base item
943          // our processing scope for base is all the children of the current path
944          int ndc = diffCursor;
945          int ndl = diffCursor;
946          for (int i = start; i < diffMatches.size(); i++) {
947            // our processing scope for the differential is the item in the list, and all the items before the next one in the list
948            ndc = differential.getElement().indexOf(diffMatches.get(i));
949            ndl = findEndOfElement(differential, ndc);
950/*            if (skipSlicingElement && i == 0) {
951              ndc = ndc + 1;
952              if (ndc > ndl)
953                continue;
954            }*/
955            // now we process the base scope repeatedly for each instance of the item in the differential list
956            processPaths(indent+"  ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName+pathTail(diffMatches, i), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, true, redirector, srcSD);
957          }
958          // ok, done with that - next in the base list
959          baseCursor = nbl+1;
960          diffCursor = ndl+1;
961        }
962      } else {
963        // the item is already sliced in the base profile.
964        // here's the rules
965        //  1. irrespective of whether the slicing is ordered or not, the definition order must be maintained
966        //  2. slice element names have to match.
967        //  3. new slices must be introduced at the end
968        // corallory: you can't re-slice existing slices. is that ok?
969
970        // we're going to need this:
971        String path = currentBase.getPath();
972        ElementDefinition original = currentBase;
973
974        if (diffMatches.isEmpty()) {
975          if (hasInnerDiffMatches(differential, path, diffCursor, diffLimit, base.getElement(), true)) {
976            // so we just copy it in
977            ElementDefinition outcome = updateURLs(url, webUrl, currentBase.copy());
978            outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
979            updateFromBase(outcome, currentBase);
980            markDerived(outcome);
981            if (resultPathBase == null)
982              resultPathBase = outcome.getPath();
983            else if (!outcome.getPath().startsWith(resultPathBase))
984              throw new DefinitionException("Adding wrong path");
985            result.getElement().add(outcome);
986            // the profile walks into this, so we need to as well
987            // did we implicitly step into a new type?
988            if (baseHasChildren(base, currentBase)) { // not a new type here
989              processPaths(indent+"  ", result, base, differential, baseCursor+1, diffCursor, baseLimit, diffLimit, url, webUrl, profileName, contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, false, redirector, srcSD);
990              baseCursor = indexOfFirstNonChild(base, currentBase, baseCursor, baseLimit);
991            } else {
992              if (outcome.getType().size() == 0) {
993                throw new DefinitionException(diffMatches.get(0).getPath()+" has no children ("+differential.getElement().get(diffCursor).getPath()+") and no types in profile "+profileName);
994              }
995              if (outcome.getType().size() > 1) {
996                for (TypeRefComponent t : outcome.getType()) {
997                  if (!t.getWorkingCode().equals("Reference"))
998                    throw new DefinitionException(diffMatches.get(0).getPath()+" has children ("+differential.getElement().get(diffCursor).getPath()+") and multiple types ("+typeCode(outcome.getType())+") in profile "+profileName);
999                }
1000              }
1001              StructureDefinition dt = getProfileForDataType(outcome.getType().get(0));
1002              if (dt == null)
1003                throw new DefinitionException("Unknown type "+outcome.getType().get(0)+" at "+diffMatches.get(0).getPath());
1004              contextName = dt.getUrl();
1005              int start = diffCursor;
1006              while (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), cpath+"."))
1007                diffCursor++;
1008              processPaths(indent+"  ", result, dt.getSnapshot(), differential, 1 /* starting again on the data type, but skip the root */, start, dt.getSnapshot().getElement().size()-1,
1009                  diffCursor-1, url, getWebUrl(dt, webUrl, indent), profileName, cpath, outcome.getPath(), trimDifferential, contextName, resultPathBase, false, redirector, srcSD);
1010            }
1011            baseCursor++;
1012          } else {
1013            // the differential doesn't say anything about this item
1014            // copy across the currentbase, and all of its children and siblings
1015            while (baseCursor < base.getElement().size() && base.getElement().get(baseCursor).getPath().startsWith(path)) {
1016              ElementDefinition outcome = updateURLs(url, webUrl, base.getElement().get(baseCursor).copy());
1017              outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
1018              if (!outcome.getPath().startsWith(resultPathBase))
1019                throw new DefinitionException("Adding wrong path in profile " + profileName + ": "+outcome.getPath()+" vs " + resultPathBase);
1020              result.getElement().add(outcome); // so we just copy it in
1021              baseCursor++;
1022            }
1023          }
1024        } else {
1025          // first - check that the slicing is ok
1026          boolean closed = currentBase.getSlicing().getRules() == SlicingRules.CLOSED;
1027          int diffpos = 0;
1028          boolean isExtension = cpath.endsWith(".extension") || cpath.endsWith(".modifierExtension");
1029          if (diffMatches.get(0).hasSlicing()) { // it might be null if the differential doesn't want to say anything about slicing
1030//            if (!isExtension)
1031//              diffpos++; // if there's a slice on the first, we'll ignore any content it has
1032            ElementDefinitionSlicingComponent dSlice = diffMatches.get(0).getSlicing();
1033            ElementDefinitionSlicingComponent bSlice = currentBase.getSlicing();
1034            if (dSlice.hasOrderedElement() && bSlice.hasOrderedElement() && !orderMatches(dSlice.getOrderedElement(), bSlice.getOrderedElement()))
1035              throw new DefinitionException("Slicing rules on differential ("+summarizeSlicing(dSlice)+") do not match those on base ("+summarizeSlicing(bSlice)+") - order @ "+path+" ("+contextName+")");
1036            if (!discriminatorMatches(dSlice.getDiscriminator(), bSlice.getDiscriminator()))
1037             throw new DefinitionException("Slicing rules on differential ("+summarizeSlicing(dSlice)+") do not match those on base ("+summarizeSlicing(bSlice)+") - disciminator @ "+path+" ("+contextName+")");
1038            if (!ruleMatches(dSlice.getRules(), bSlice.getRules()))
1039             throw new DefinitionException("Slicing rules on differential ("+summarizeSlicing(dSlice)+") do not match those on base ("+summarizeSlicing(bSlice)+") - rule @ "+path+" ("+contextName+")");
1040          }
1041          ElementDefinition outcome = updateURLs(url, webUrl, currentBase.copy());
1042          outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
1043          updateFromBase(outcome, currentBase);
1044          if (diffMatches.get(0).hasSlicing() || !diffMatches.get(0).hasSliceName()) {
1045            updateFromSlicing(outcome.getSlicing(), diffMatches.get(0).getSlicing());
1046            updateFromDefinition(outcome, diffMatches.get(0), profileName, closed, url, srcSD); // if there's no slice, we don't want to update the unsliced description
1047            removeStatusExtensions(outcome);
1048          } else if (!diffMatches.get(0).hasSliceName())
1049            diffMatches.get(0).setUserData(GENERATED_IN_SNAPSHOT, outcome); // because of updateFromDefinition isn't called 
1050          
1051          result.getElement().add(outcome);
1052
1053          if (!diffMatches.get(0).hasSliceName()) { // it's not real content, just the slice
1054            diffpos++; 
1055          }
1056          if (hasInnerDiffMatches(differential, cpath, diffpos, diffLimit, base.getElement(), false)) {
1057            int nbl = findEndOfElement(base, baseCursor);
1058            int ndc = differential.getElement().indexOf(diffMatches.get(0))+1;
1059            int ndl = findEndOfElement(differential, ndc);
1060            processPaths(indent+"  ", result, base, differential, baseCursor+1, ndc, nbl, ndl, url, webUrl, profileName+pathTail(diffMatches, 0), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, false, null, srcSD);
1061//            throw new Error("Not done yet");
1062//          } else if (currentBase.getType().get(0).getCode().equals("BackboneElement") && diffMatches.size() > 0 && diffMatches.get(0).hasSliceName()) {
1063          } else if (currentBase.getType().get(0).getCode().equals("BackboneElement")) {
1064            // We need to copy children of the backbone element before we start messing around with slices
1065            int nbl = findEndOfElement(base, baseCursor);
1066            for (int i = baseCursor+1; i<=nbl; i++) {
1067              outcome = updateURLs(url, webUrl, base.getElement().get(i).copy());
1068              result.getElement().add(outcome);
1069            }
1070          }
1071
1072          // now, we have two lists, base and diff. we're going to work through base, looking for matches in diff.
1073          List<ElementDefinition> baseMatches = getSiblings(base.getElement(), currentBase);
1074          for (ElementDefinition baseItem : baseMatches) {
1075            baseCursor = base.getElement().indexOf(baseItem);
1076            outcome = updateURLs(url, webUrl, baseItem.copy());
1077            updateFromBase(outcome, currentBase);
1078            outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
1079            outcome.setSlicing(null);
1080            if (!outcome.getPath().startsWith(resultPathBase))
1081              throw new DefinitionException("Adding wrong path");
1082            if (diffpos < diffMatches.size() && diffMatches.get(diffpos).getSliceName().equals(outcome.getSliceName())) {
1083              // if there's a diff, we update the outcome with diff
1084              // no? updateFromDefinition(outcome, diffMatches.get(diffpos), profileName, closed, url);
1085              //then process any children
1086              int nbl = findEndOfElement(base, baseCursor);
1087              int ndc = differential.getElement().indexOf(diffMatches.get(diffpos));
1088              int ndl = findEndOfElement(differential, ndc);
1089              // now we process the base scope repeatedly for each instance of the item in the differential list
1090              processPaths(indent+"  ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName+pathTail(diffMatches, diffpos), contextPathSrc, contextPathDst, closed, contextName, resultPathBase, true, redirector, srcSD);
1091              // ok, done with that - now set the cursors for if this is the end
1092              baseCursor = nbl;
1093              diffCursor = ndl+1;
1094              diffpos++;
1095            } else {
1096              result.getElement().add(outcome);
1097              baseCursor++;
1098              // just copy any children on the base
1099              while (baseCursor < base.getElement().size() && base.getElement().get(baseCursor).getPath().startsWith(path) && !base.getElement().get(baseCursor).getPath().equals(path)) {
1100                outcome = updateURLs(url, webUrl, base.getElement().get(baseCursor).copy());
1101                outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
1102                if (!outcome.getPath().startsWith(resultPathBase))
1103                  throw new DefinitionException("Adding wrong path");
1104                result.getElement().add(outcome);
1105                baseCursor++;
1106              }
1107              //Lloyd - add this for test T15
1108              baseCursor--;
1109            }
1110          }
1111          // finally, we process any remaining entries in diff, which are new (and which are only allowed if the base wasn't closed
1112          if (closed && diffpos < diffMatches.size())
1113            throw new DefinitionException("The base snapshot marks a slicing as closed, but the differential tries to extend it in "+profileName+" at "+path+" ("+cpath+")");
1114          if (diffpos == diffMatches.size()) {
1115//Lloyd This was causing problems w/ Telus
1116//            diffCursor++;
1117          } else {
1118            while (diffpos < diffMatches.size()) {
1119              ElementDefinition diffItem = diffMatches.get(diffpos);
1120              for (ElementDefinition baseItem : baseMatches)
1121                if (baseItem.getSliceName().equals(diffItem.getSliceName()))
1122                  throw new DefinitionException("Named items are out of order in the slice");
1123              outcome = updateURLs(url, webUrl, currentBase.copy());
1124              //            outcome = updateURLs(url, diffItem.copy());
1125              outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
1126              updateFromBase(outcome, currentBase);
1127              outcome.setSlicing(null);
1128              if (!outcome.getPath().startsWith(resultPathBase))
1129                throw new DefinitionException("Adding wrong path");
1130              result.getElement().add(outcome);
1131              updateFromDefinition(outcome, diffItem, profileName, trimDifferential, url, srcSD);
1132              removeStatusExtensions(outcome);
1133              // --- LM Added this
1134              diffCursor = differential.getElement().indexOf(diffItem)+1;
1135              if (!outcome.getType().isEmpty() && (/*outcome.getType().get(0).getCode().equals("Extension") || */differential.getElement().size() > diffCursor) && outcome.getPath().contains(".") && isDataType(outcome.getType())) {  // don't want to do this for the root, since that's base, and we're already processing it
1136                if (!baseWalksInto(base.getElement(), baseCursor)) {
1137                  if (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), diffMatches.get(0).getPath()+".")) {
1138                    if (outcome.getType().size() > 1)
1139                      for (TypeRefComponent t : outcome.getType()) {
1140                        if (!t.getCode().equals("Reference"))
1141                          throw new DefinitionException(diffMatches.get(0).getPath()+" has children ("+differential.getElement().get(diffCursor).getPath()+") and multiple types ("+typeCode(outcome.getType())+") in profile "+profileName);
1142                      }
1143                    TypeRefComponent t = outcome.getType().get(0);
1144                    if (t.getCode().equals("BackboneElement")) {
1145                      int baseStart = base.getElement().indexOf(currentBase)+1;
1146                      int baseMax = baseStart + 1;
1147                      while (baseMax < base.getElement().size() && base.getElement().get(baseMax).getPath().startsWith(currentBase.getPath()+"."))
1148                       baseMax++;
1149                      int start = diffCursor;
1150                      while (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), diffMatches.get(0).getPath()+"."))
1151                        diffCursor++;
1152                      processPaths(indent+"  ", result, base, differential, baseStart, start-1, baseMax-1,
1153                          diffCursor - 1, url, webUrl, profileName+pathTail(diffMatches, 0), base.getElement().get(0).getPath(), base.getElement().get(0).getPath(), trimDifferential, contextName, resultPathBase, false, redirector, srcSD);
1154                      
1155                    } else {
1156                      StructureDefinition dt = getProfileForDataType(outcome.getType().get(0));
1157                      //                if (t.getCode().equals("Extension") && t.hasProfile() && !t.getProfile().contains(":")) {
1158                      // lloydfix                  dt = 
1159                      //                }
1160                      if (dt == null)
1161                        throw new DefinitionException(diffMatches.get(0).getPath()+" has children ("+differential.getElement().get(diffCursor).getPath()+") for type "+typeCode(outcome.getType())+" in profile "+profileName+", but can't find type");
1162                      contextName = dt.getUrl();
1163                      int start = diffCursor;
1164                      while (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), diffMatches.get(0).getPath()+"."))
1165                        diffCursor++;
1166                      processPaths(indent+"  ", result, dt.getSnapshot(), differential, 1 /* starting again on the data type, but skip the root */, start-1, dt.getSnapshot().getElement().size()-1,
1167                          diffCursor - 1, url, getWebUrl(dt, webUrl, indent), profileName+pathTail(diffMatches, 0), diffMatches.get(0).getPath(), outcome.getPath(), trimDifferential, contextName, resultPathBase, false, redirector, srcSD);
1168                    }
1169                  }
1170                }
1171              }
1172              // ---
1173              diffpos++;
1174            }
1175          }
1176          baseCursor++;
1177        }
1178      }
1179    }
1180    
1181    int i = 0;
1182    for (ElementDefinition e : result.getElement()) {
1183      i++;
1184      if (e.hasMinElement() && e.getMinElement().getValue()==null)
1185        throw new Error("null min");
1186    }
1187    return res;
1188  }
1189
1190
1191  private String getWebUrl(StructureDefinition dt, String webUrl, String indent) {
1192    if (dt.hasUserData("path")) {
1193      // this is a hack, but it works for now, since we don't have deep folders
1194      String url = dt.getUserString("path");
1195      int i = url.lastIndexOf("/");
1196      if (i < 1) {
1197        return defWebRoot;
1198      } else {
1199        return url.substring(0, i+1);
1200      }
1201    } else {  
1202      return webUrl;
1203    }
1204  }
1205
1206
1207  private void removeStatusExtensions(ElementDefinition outcome) {
1208    outcome.removeExtension(ToolingExtensions.EXT_FMM_LEVEL);
1209    outcome.removeExtension(ToolingExtensions.EXT_STANDARDS_STATUS);
1210    outcome.removeExtension(ToolingExtensions.EXT_NORMATIVE_VERSION);
1211    outcome.removeExtension(ToolingExtensions.EXT_WORKGROUP);    
1212  }
1213
1214
1215  private String descED(List<ElementDefinition> list, int index) {
1216    return index >=0 && index < list.size() ? list.get(index).present() : "X";
1217  }
1218
1219
1220  private boolean baseHasChildren(StructureDefinitionSnapshotComponent base, ElementDefinition ed) {
1221    int index = base.getElement().indexOf(ed);
1222    if (index == -1 || index >= base.getElement().size()-1)
1223      return false;
1224    String p = base.getElement().get(index+1).getPath();
1225    return isChildOf(p, ed.getPath());
1226  }
1227
1228
1229  private boolean isChildOf(String sub, String focus) {
1230    if (focus.endsWith("[x]")) {
1231      focus = focus.substring(0, focus.length()-3);
1232      return sub.startsWith(focus);
1233    } else 
1234      return sub.startsWith(focus+".");
1235  }
1236
1237
1238  private int indexOfFirstNonChild(StructureDefinitionSnapshotComponent base, ElementDefinition currentBase, int i, int baseLimit) {
1239    return baseLimit+1;
1240  }
1241
1242
1243  private String rootName(String cpath) {
1244    String t = tail(cpath);
1245    return t.replace("[x]", "");
1246  }
1247
1248
1249  private String determineTypeSlicePath(String path, String cpath) {
1250    String headP = path.substring(0, path.lastIndexOf("."));
1251//    String tailP = path.substring(path.lastIndexOf(".")+1);
1252    String tailC = cpath.substring(cpath.lastIndexOf(".")+1);
1253    return headP+"."+tailC;
1254  }
1255
1256
1257  private boolean isImplicitSlicing(ElementDefinition ed, String path) {
1258    if (ed == null || ed.getPath() == null || path == null)
1259      return false;
1260    if (path.equals(ed.getPath()))
1261      return false;
1262    boolean ok = path.endsWith("[x]") && ed.getPath().startsWith(path.substring(0, path.length()-3));
1263    return ok;
1264  }
1265
1266
1267  private boolean diffsConstrainTypes(List<ElementDefinition> diffMatches, String cPath, List<TypeSlice> typeList) {
1268//    if (diffMatches.size() < 2)
1269//      return false;
1270    String p = diffMatches.get(0).getPath();
1271    if (!p.endsWith("[x]") && !cPath.endsWith("[x]"))
1272      return false;
1273    typeList.clear();
1274    String rn = tail(cPath);
1275    rn = rn.substring(0, rn.length()-3);
1276    for (int i = 0; i < diffMatches.size(); i++) {
1277      ElementDefinition ed = diffMatches.get(i);
1278      String n = tail(ed.getPath());
1279      if (!n.startsWith(rn))
1280        return false;
1281      String s = n.substring(rn.length());
1282      if (!s.contains(".")) {
1283        if (ed.hasSliceName() && ed.getType().size() == 1) {
1284          typeList.add(new TypeSlice(ed, ed.getTypeFirstRep().getWorkingCode()));
1285        } else if (!ed.hasSliceName() && !s.equals("[x]")) {
1286          if (isDataType(s))
1287            typeList.add(new TypeSlice(ed, s));
1288          else if (isConstrainedDataType(s))
1289            typeList.add(new TypeSlice(ed, baseType(s)));
1290          else if (isPrimitive(Utilities.uncapitalize(s)))
1291            typeList.add(new TypeSlice(ed, Utilities.uncapitalize(s)));
1292        } else if (!ed.hasSliceName() && s.equals("[x]"))
1293          typeList.add(new TypeSlice(ed, null));
1294      }
1295    }
1296    return true;
1297  }
1298
1299
1300  private List<ElementRedirection> redirectorStack(List<ElementRedirection> redirector, ElementDefinition outcome, String path) {
1301    List<ElementRedirection> result = new ArrayList<ElementRedirection>();
1302    result.addAll(redirector);
1303    result.add(new ElementRedirection(outcome, path));
1304    return result;
1305  }
1306
1307
1308  private List<TypeRefComponent> getByTypeName(List<TypeRefComponent> type, String t) {
1309    List<TypeRefComponent> res = new ArrayList<TypeRefComponent>();
1310    for (TypeRefComponent tr : type) {
1311      if (t.equals(tr.getWorkingCode()))
1312          res.add(tr);
1313    }
1314    return res;
1315  }
1316
1317
1318  private void replaceFromContentReference(ElementDefinition outcome, ElementDefinition tgt) {
1319    outcome.setContentReference(null);
1320    outcome.getType().clear(); // though it should be clear anyway
1321    outcome.getType().addAll(tgt.getType());    
1322  }
1323
1324
1325  private boolean baseWalksInto(List<ElementDefinition> elements, int cursor) {
1326    if (cursor >= elements.size())
1327      return false;
1328    String path = elements.get(cursor).getPath();
1329    String prevPath = elements.get(cursor - 1).getPath();
1330    return path.startsWith(prevPath + ".");
1331  }
1332
1333
1334  private ElementDefinition fillOutFromBase(ElementDefinition profile, ElementDefinition usage) throws FHIRFormatError {
1335    ElementDefinition res = profile.copy();
1336    if (!res.hasSliceName())
1337      res.setSliceName(usage.getSliceName());
1338    if (!res.hasLabel())
1339      res.setLabel(usage.getLabel());
1340    for (Coding c : usage.getCode())
1341      if (!res.hasCode(c))
1342        res.addCode(c);
1343    
1344    if (!res.hasDefinition())
1345      res.setDefinition(usage.getDefinition());
1346    if (!res.hasShort() && usage.hasShort())
1347      res.setShort(usage.getShort());
1348    if (!res.hasComment() && usage.hasComment())
1349      res.setComment(usage.getComment());
1350    if (!res.hasRequirements() && usage.hasRequirements())
1351      res.setRequirements(usage.getRequirements());
1352    for (StringType c : usage.getAlias())
1353      if (!res.hasAlias(c.getValue()))
1354        res.addAlias(c.getValue());
1355    if (!res.hasMin() && usage.hasMin())
1356      res.setMin(usage.getMin());
1357    if (!res.hasMax() && usage.hasMax())
1358      res.setMax(usage.getMax());
1359     
1360    if (!res.hasFixed() && usage.hasFixed())
1361      res.setFixed(usage.getFixed());
1362    if (!res.hasPattern() && usage.hasPattern())
1363      res.setPattern(usage.getPattern());
1364    if (!res.hasExample() && usage.hasExample())
1365      res.setExample(usage.getExample());
1366    if (!res.hasMinValue() && usage.hasMinValue())
1367      res.setMinValue(usage.getMinValue());
1368    if (!res.hasMaxValue() && usage.hasMaxValue())
1369      res.setMaxValue(usage.getMaxValue());     
1370    if (!res.hasMaxLength() && usage.hasMaxLength())
1371      res.setMaxLength(usage.getMaxLength());
1372    if (!res.hasMustSupport() && usage.hasMustSupport())
1373      res.setMustSupport(usage.getMustSupport());
1374    if (!res.hasBinding() && usage.hasBinding())
1375      res.setBinding(usage.getBinding().copy());
1376    for (ElementDefinitionConstraintComponent c : usage.getConstraint())
1377      if (!res.hasConstraint(c.getKey()))
1378        res.addConstraint(c);
1379    for (Extension e : usage.getExtension()) {
1380      if (!res.hasExtension(e.getUrl()))
1381        res.addExtension(e.copy());
1382    }
1383    
1384    return res;
1385  }
1386
1387
1388  private boolean checkExtensionDoco(ElementDefinition base) {
1389    // see task 3970. For an extension, there's no point copying across all the underlying definitional stuff
1390    boolean isExtension = base.getPath().equals("Extension") || base.getPath().endsWith(".extension") || base.getPath().endsWith(".modifierExtension");
1391    if (isExtension) {
1392      base.setDefinition("An Extension");
1393      base.setShort("Extension");
1394      base.setCommentElement(null);
1395      base.setRequirementsElement(null);
1396      base.getAlias().clear();
1397      base.getMapping().clear();
1398    }
1399    return isExtension;
1400  }
1401
1402
1403  private String pathTail(List<ElementDefinition> diffMatches, int i) {
1404    
1405    ElementDefinition d = diffMatches.get(i);
1406    String s = d.getPath().contains(".") ? d.getPath().substring(d.getPath().lastIndexOf(".")+1) : d.getPath();
1407    return "."+s + (d.hasType() && d.getType().get(0).hasProfile() ? "["+d.getType().get(0).getProfile()+"]" : "");
1408  }
1409
1410
1411  private void markDerived(ElementDefinition outcome) {
1412    for (ElementDefinitionConstraintComponent inv : outcome.getConstraint())
1413      inv.setUserData(IS_DERIVED, true);
1414  }
1415
1416
1417  public static String summarizeSlicing(ElementDefinitionSlicingComponent slice) {
1418    StringBuilder b = new StringBuilder();
1419    boolean first = true;
1420    for (ElementDefinitionSlicingDiscriminatorComponent d : slice.getDiscriminator()) {
1421      if (first)
1422        first = false;
1423      else
1424        b.append(", ");
1425      b.append(d.getType().toCode()+":"+d.getPath());
1426    }
1427    b.append(" (");
1428    if (slice.hasOrdered())
1429      b.append(slice.getOrdered() ? "ordered" : "unordered");
1430    b.append("/");
1431    if (slice.hasRules())
1432      b.append(slice.getRules().toCode());
1433    b.append(")");
1434    if (slice.hasDescription()) {
1435      b.append(" \"");
1436      b.append(slice.getDescription());
1437      b.append("\"");
1438    }
1439    return b.toString();
1440  }
1441
1442
1443  private void updateFromBase(ElementDefinition derived, ElementDefinition base) {
1444    if (base.hasBase()) {
1445      if (!derived.hasBase())
1446        derived.setBase(new ElementDefinitionBaseComponent());
1447      derived.getBase().setPath(base.getBase().getPath());
1448      derived.getBase().setMin(base.getBase().getMin());
1449      derived.getBase().setMax(base.getBase().getMax());
1450    } else {
1451      if (!derived.hasBase())
1452        derived.setBase(new ElementDefinitionBaseComponent());
1453      derived.getBase().setPath(base.getPath());
1454      derived.getBase().setMin(base.getMin());
1455      derived.getBase().setMax(base.getMax());
1456    }
1457  }
1458
1459
1460  private boolean pathStartsWith(String p1, String p2) {
1461    return p1.startsWith(p2) || (p2.endsWith("[x].") && p1.startsWith(p2.substring(0, p2.length()-4)));
1462  }
1463
1464  private boolean pathMatches(String p1, String p2) {
1465    return p1.equals(p2) || (p2.endsWith("[x]") && p1.startsWith(p2.substring(0, p2.length()-3)) && !p1.substring(p2.length()-3).contains("."));
1466  }
1467
1468
1469  private String fixedPathSource(String contextPath, String pathSimple, List<ElementRedirection> redirector) {
1470    if (contextPath == null)
1471      return pathSimple;
1472//    String ptail = pathSimple.substring(contextPath.length() + 1);
1473    if (redirector.size() > 0) {
1474      String ptail = pathSimple.substring(contextPath.length()+1);
1475      return redirector.get(redirector.size()-1).getPath()+"."+ptail;
1476//      return contextPath+"."+tail(redirector.getPath())+"."+ptail.substring(ptail.indexOf(".")+1);
1477    } else {
1478      String ptail = pathSimple.substring(pathSimple.indexOf(".")+1);
1479      return contextPath+"."+ptail;
1480    }
1481  }
1482  
1483  private String fixedPathDest(String contextPath, String pathSimple, List<ElementRedirection> redirector, String redirectSource) {
1484    String s;
1485    if (contextPath == null)
1486      s = pathSimple;
1487    else {
1488      if (redirector.size() > 0) {
1489        String ptail = pathSimple.substring(redirectSource.length() + 1);
1490  //      ptail = ptail.substring(ptail.indexOf(".")+1);
1491        s = contextPath+"."+/*tail(redirector.getPath())+"."+*/ptail;
1492      } else {
1493        String ptail = pathSimple.substring(pathSimple.indexOf(".")+1);
1494        s = contextPath+"."+ptail;
1495      }
1496    }
1497    return s;
1498  }  
1499
1500  private StructureDefinition getProfileForDataType(TypeRefComponent type)  {
1501    StructureDefinition sd = null;
1502    if (type.hasProfile()) {
1503      sd = context.fetchResource(StructureDefinition.class, type.getProfile().get(0).getValue());
1504      if (sd == null)
1505        System.out.println("Failed to find referenced profile: " + type.getProfile());
1506    }
1507    if (sd == null)
1508      sd = context.fetchTypeDefinition(type.getWorkingCode());
1509    if (sd == null)
1510      System.out.println("XX: failed to find profle for type: " + type.getWorkingCode()); // debug GJM
1511    return sd;
1512  }
1513
1514  private StructureDefinition getProfileForDataType(String type)  {
1515    StructureDefinition sd = context.fetchTypeDefinition(type);
1516    if (sd == null)
1517      System.out.println("XX: failed to find profle for type: " + type); // debug GJM
1518    return sd;
1519  }
1520
1521
1522  public static String typeCode(List<TypeRefComponent> types) {
1523    StringBuilder b = new StringBuilder();
1524    boolean first = true;
1525    for (TypeRefComponent type : types) {
1526      if (first) first = false; else b.append(", ");
1527      b.append(type.getWorkingCode());
1528      if (type.hasTargetProfile())
1529        b.append("{"+type.getTargetProfile()+"}");
1530      else if (type.hasProfile())
1531        b.append("{"+type.getProfile()+"}");
1532    }
1533    return b.toString();
1534  }
1535
1536
1537  private boolean isDataType(List<TypeRefComponent> types) {
1538    if (types.isEmpty())
1539      return false;
1540    for (TypeRefComponent type : types) {
1541      String t = type.getWorkingCode();
1542      if (!isDataType(t) && !isPrimitive(t))
1543        return false;
1544    }
1545    return true;
1546  }
1547
1548
1549  /**
1550   * Finds internal references in an Element's Binding and StructureDefinition references (in TypeRef) and bases them on the given url
1551   * @param url - the base url to use to turn internal references into absolute references
1552   * @param element - the Element to update
1553   * @return - the updated Element
1554   */
1555  private ElementDefinition updateURLs(String url, String webUrl, ElementDefinition element) {
1556    if (element != null) {
1557      ElementDefinition defn = element;
1558      if (defn.hasBinding() && defn.getBinding().hasValueSet() && defn.getBinding().getValueSet().startsWith("#"))
1559        defn.getBinding().setValueSet(url+defn.getBinding().getValueSet());
1560      for (TypeRefComponent t : defn.getType()) {
1561        for (UriType u : t.getProfile()) {
1562          if (u.getValue().startsWith("#"))
1563            u.setValue(url+t.getProfile());
1564        }
1565        for (UriType u : t.getTargetProfile()) {
1566          if (u.getValue().startsWith("#"))
1567            u.setValue(url+t.getTargetProfile());
1568        }
1569      }
1570      if (webUrl != null) {
1571        // also, must touch up the markdown
1572        if (element.hasDefinition())
1573          element.setDefinition(processRelativeUrls(element.getDefinition(), webUrl));
1574        if (element.hasComment())
1575          element.setComment(processRelativeUrls(element.getComment(), webUrl));
1576        if (element.hasRequirements())
1577          element.setRequirements(processRelativeUrls(element.getRequirements(), webUrl));
1578        if (element.hasMeaningWhenMissing())
1579          element.setMeaningWhenMissing(processRelativeUrls(element.getMeaningWhenMissing(), webUrl));
1580      }
1581    }
1582    return element;
1583  }
1584
1585  private String processRelativeUrls(String markdown, String webUrl) {
1586    StringBuilder b = new StringBuilder();
1587    int i = 0;
1588    while (i < markdown.length()) {
1589      if (i < markdown.length()-3 && markdown.substring(i, i+2).equals("](")) {
1590         int j = i + 2;
1591        while (j < markdown.length() && markdown.charAt(j) != ')')
1592          j++;
1593        if (j < markdown.length()) {
1594          String url = markdown.substring(i+2, j);
1595          if (!Utilities.isAbsoluteUrl(url) && !url.startsWith("..")) {
1596            b.append("](");
1597            b.append(webUrl);
1598            i = i + 1;
1599          } else
1600            b.append(markdown.charAt(i));
1601        } else 
1602          b.append(markdown.charAt(i));
1603      } else {
1604        b.append(markdown.charAt(i));
1605      }
1606      i++;
1607    }
1608    return b.toString();
1609  }
1610
1611
1612  private List<ElementDefinition> getSiblings(List<ElementDefinition> list, ElementDefinition current) {
1613    List<ElementDefinition> result = new ArrayList<ElementDefinition>();
1614    String path = current.getPath();
1615    int cursor = list.indexOf(current)+1;
1616    while (cursor < list.size() && list.get(cursor).getPath().length() >= path.length()) {
1617      if (pathMatches(list.get(cursor).getPath(), path))
1618        result.add(list.get(cursor));
1619      cursor++;
1620    }
1621    return result;
1622  }
1623
1624  private void updateFromSlicing(ElementDefinitionSlicingComponent dst, ElementDefinitionSlicingComponent src) {
1625    if (src.hasOrderedElement())
1626      dst.setOrderedElement(src.getOrderedElement().copy());
1627    if (src.hasDiscriminator()) {
1628      //    dst.getDiscriminator().addAll(src.getDiscriminator());  Can't use addAll because it uses object equality, not string equality
1629      for (ElementDefinitionSlicingDiscriminatorComponent s : src.getDiscriminator()) {
1630        boolean found = false;
1631        for (ElementDefinitionSlicingDiscriminatorComponent d : dst.getDiscriminator()) {
1632          if (matches(d, s)) {
1633            found = true;
1634            break;
1635          }
1636        }
1637        if (!found)
1638          dst.getDiscriminator().add(s);
1639      }
1640    }
1641    if (src.hasRulesElement())
1642      dst.setRulesElement(src.getRulesElement().copy());
1643  }
1644
1645  private boolean orderMatches(BooleanType diff, BooleanType base) {
1646    return (diff == null) || (base == null) || (diff.getValue() == base.getValue());
1647  }
1648
1649  private boolean discriminatorMatches(List<ElementDefinitionSlicingDiscriminatorComponent> diff, List<ElementDefinitionSlicingDiscriminatorComponent> base) {
1650    if (diff.isEmpty() || base.isEmpty())
1651        return true;
1652    if (diff.size() != base.size())
1653        return false;
1654    for (int i = 0; i < diff.size(); i++)
1655        if (!matches(diff.get(i), base.get(i)))
1656                return false;
1657    return true;
1658  }
1659
1660  private boolean matches(ElementDefinitionSlicingDiscriminatorComponent c1, ElementDefinitionSlicingDiscriminatorComponent c2) {
1661    return c1.getType().equals(c2.getType()) && c1.getPath().equals(c2.getPath());
1662  }
1663
1664
1665  private boolean ruleMatches(SlicingRules diff, SlicingRules base) {
1666    return (diff == null) || (base == null) || (diff == base) || (base == SlicingRules.OPEN) ||
1667        ((diff == SlicingRules.OPENATEND && base == SlicingRules.CLOSED));
1668  }
1669
1670  private boolean isSlicedToOneOnly(ElementDefinition e) {
1671    return (e.hasSlicing() && e.hasMaxElement() && e.getMax().equals("1"));
1672  }
1673
1674  private ElementDefinitionSlicingComponent makeExtensionSlicing() {
1675        ElementDefinitionSlicingComponent slice = new ElementDefinitionSlicingComponent();
1676    slice.addDiscriminator().setPath("url").setType(DiscriminatorType.VALUE);
1677    slice.setOrdered(false);
1678    slice.setRules(SlicingRules.OPEN);
1679    return slice;
1680  }
1681
1682  private boolean isExtension(ElementDefinition currentBase) {
1683    return currentBase.getPath().endsWith(".extension") || currentBase.getPath().endsWith(".modifierExtension");
1684  }
1685
1686  private boolean hasInnerDiffMatches(StructureDefinitionDifferentialComponent context, String path, int start, int end, List<ElementDefinition> base, boolean allowSlices) throws DefinitionException {
1687    end = Math.min(context.getElement().size(), end);
1688    start = Math.max(0,  start);
1689    
1690    for (int i = start; i <= end; i++) {
1691      String statedPath = context.getElement().get(i).getPath();
1692      if (statedPath.startsWith(path+".")) {
1693        return true;
1694      } else if (path.endsWith("[x]") && statedPath.startsWith(path.substring(0, path.length() -3))) {
1695        return true;
1696      } else if (!statedPath.endsWith(path))
1697        break;
1698    }
1699    return false;
1700  }
1701
1702  private List<ElementDefinition> getDiffMatches(StructureDefinitionDifferentialComponent context, String path, int start, int end, String profileName) throws DefinitionException {
1703    List<ElementDefinition> result = new ArrayList<ElementDefinition>();
1704    String[] p = path.split("\\.");
1705    for (int i = start; i <= end; i++) {
1706      String statedPath = context.getElement().get(i).getPath();
1707      String[] sp = statedPath.split("\\.");
1708      boolean ok = sp.length == p.length;
1709      for (int j = 0; j < p.length; j++) {
1710        ok = ok && sp.length > j && (p[j].equals(sp[j]) || (p[j].endsWith("[x]") && sp[j].startsWith(p[j].substring(0, p[j].length()-3))));
1711      }
1712      if (ok != (statedPath.equals(path) || (path.endsWith("[x]") && statedPath.length() > path.length() - 2 && 
1713            statedPath.substring(0, path.length()-3).equals(path.substring(0, path.length()-3)) && 
1714            (statedPath.length() < path.length() || !statedPath.substring(path.length()).contains("."))))) {
1715        System.out.println("mismatch in paths: "+statedPath +" vs " +path);
1716      }
1717      if (ok) {
1718        /* 
1719         * Commenting this out because it raises warnings when profiling inherited elements.  For example,
1720         * Error: unknown element 'Bundle.meta.profile' (or it is out of order) in profile ... (looking for 'Bundle.entry')
1721         * Not sure we have enough information here to do the check properly.  Might be better done when we're sorting the profile?
1722
1723        if (i != start && result.isEmpty() && !path.startsWith(context.getElement().get(start).getPath()))
1724          messages.add(new ValidationMessage(Source.ProfileValidator, IssueType.VALUE, "StructureDefinition.differential.element["+Integer.toString(start)+"]", "Error: unknown element '"+context.getElement().get(start).getPath()+"' (or it is out of order) in profile '"+url+"' (looking for '"+path+"')", IssueSeverity.WARNING));
1725
1726         */
1727        result.add(context.getElement().get(i));
1728      }
1729    }
1730    return result;
1731  }
1732
1733  private int findEndOfElement(StructureDefinitionDifferentialComponent context, int cursor) {
1734            int result = cursor;
1735            if (cursor >= context.getElement().size())
1736              return result;
1737            String path = context.getElement().get(cursor).getPath()+".";
1738            while (result < context.getElement().size()- 1 && context.getElement().get(result+1).getPath().startsWith(path))
1739              result++;
1740            return result;
1741          }
1742
1743  private int findEndOfElement(StructureDefinitionSnapshotComponent context, int cursor) {
1744            int result = cursor;
1745            String path = context.getElement().get(cursor).getPath()+".";
1746            while (result < context.getElement().size()- 1 && context.getElement().get(result+1).getPath().startsWith(path))
1747              result++;
1748            return result;
1749          }
1750
1751  private boolean unbounded(ElementDefinition definition) {
1752    StringType max = definition.getMaxElement();
1753    if (max == null)
1754      return false; // this is not valid
1755    if (max.getValue().equals("1"))
1756      return false;
1757    if (max.getValue().equals("0"))
1758      return false;
1759    return true;
1760  }
1761
1762  private void updateFromDefinition(ElementDefinition dest, ElementDefinition source, String pn, boolean trimDifferential, String purl, StructureDefinition srcSD) throws DefinitionException, FHIRException {
1763    source.setUserData(GENERATED_IN_SNAPSHOT, dest);
1764    // we start with a clone of the base profile ('dest') and we copy from the profile ('source')
1765    // over the top for anything the source has
1766    ElementDefinition base = dest;
1767    ElementDefinition derived = source;
1768    derived.setUserData(DERIVATION_POINTER, base);
1769    boolean isExtension = checkExtensionDoco(base);
1770
1771
1772    // Before applying changes, apply them to what's in the profile
1773    // TODO: follow Chris's rules - Done by Lloyd
1774    StructureDefinition profile = null;
1775    if (base.hasSliceName())
1776      profile = base.getType().size() == 1 && base.getTypeFirstRep().hasProfile() ? context.fetchResource(StructureDefinition.class, base.getTypeFirstRep().getProfile().get(0).getValue()) : null;
1777    if (profile==null)
1778      profile = source.getType().size() == 1 && source.getTypeFirstRep().hasProfile() ? context.fetchResource(StructureDefinition.class, source.getTypeFirstRep().getProfile().get(0).getValue()) : null;
1779    if (profile != null) {
1780      ElementDefinition e = profile.getSnapshot().getElement().get(0);
1781      base.setDefinition(e.getDefinition());
1782      base.setShort(e.getShort());
1783      if (e.hasCommentElement())
1784        base.setCommentElement(e.getCommentElement());
1785      if (e.hasRequirementsElement())
1786        base.setRequirementsElement(e.getRequirementsElement());
1787      base.getAlias().clear();
1788      base.getAlias().addAll(e.getAlias());
1789      base.getMapping().clear();
1790      base.getMapping().addAll(e.getMapping());
1791    } 
1792    if (derived != null) {
1793      if (derived.hasSliceName()) {
1794        base.setSliceName(derived.getSliceName());
1795      }
1796      
1797      if (derived.hasShortElement()) {
1798        if (!Base.compareDeep(derived.getShortElement(), base.getShortElement(), false))
1799          base.setShortElement(derived.getShortElement().copy());
1800        else if (trimDifferential)
1801          derived.setShortElement(null);
1802        else if (derived.hasShortElement())
1803          derived.getShortElement().setUserData(DERIVATION_EQUALS, true);
1804      }
1805
1806      if (derived.hasDefinitionElement()) {
1807        if (derived.getDefinition().startsWith("..."))
1808          base.setDefinition(base.getDefinition()+"\r\n"+derived.getDefinition().substring(3));
1809        else if (!Base.compareDeep(derived.getDefinitionElement(), base.getDefinitionElement(), false))
1810          base.setDefinitionElement(derived.getDefinitionElement().copy());
1811        else if (trimDifferential)
1812          derived.setDefinitionElement(null);
1813        else if (derived.hasDefinitionElement())
1814          derived.getDefinitionElement().setUserData(DERIVATION_EQUALS, true);
1815      }
1816
1817      if (derived.hasCommentElement()) {
1818        if (derived.getComment().startsWith("..."))
1819          base.setComment(base.getComment()+"\r\n"+derived.getComment().substring(3));
1820        else if (derived.hasCommentElement()!= base.hasCommentElement() || !Base.compareDeep(derived.getCommentElement(), base.getCommentElement(), false))
1821          base.setCommentElement(derived.getCommentElement().copy());
1822        else if (trimDifferential)
1823          base.setCommentElement(derived.getCommentElement().copy());
1824        else if (derived.hasCommentElement())
1825          derived.getCommentElement().setUserData(DERIVATION_EQUALS, true);
1826      }
1827
1828      if (derived.hasLabelElement()) {
1829        if (derived.getLabel().startsWith("..."))
1830          base.setLabel(base.getLabel()+"\r\n"+derived.getLabel().substring(3));
1831        else if (!base.hasLabelElement() || !Base.compareDeep(derived.getLabelElement(), base.getLabelElement(), false))
1832          base.setLabelElement(derived.getLabelElement().copy());
1833        else if (trimDifferential)
1834          base.setLabelElement(derived.getLabelElement().copy());
1835        else if (derived.hasLabelElement())
1836          derived.getLabelElement().setUserData(DERIVATION_EQUALS, true);
1837      }
1838
1839      if (derived.hasRequirementsElement()) {
1840        if (derived.getRequirements().startsWith("..."))
1841          base.setRequirements(base.getRequirements()+"\r\n"+derived.getRequirements().substring(3));
1842        else if (!base.hasRequirementsElement() || !Base.compareDeep(derived.getRequirementsElement(), base.getRequirementsElement(), false))
1843          base.setRequirementsElement(derived.getRequirementsElement().copy());
1844        else if (trimDifferential)
1845          base.setRequirementsElement(derived.getRequirementsElement().copy());
1846        else if (derived.hasRequirementsElement())
1847          derived.getRequirementsElement().setUserData(DERIVATION_EQUALS, true);
1848      }
1849      // sdf-9
1850      if (derived.hasRequirements() && !base.getPath().contains("."))
1851        derived.setRequirements(null);
1852      if (base.hasRequirements() && !base.getPath().contains("."))
1853        base.setRequirements(null);
1854
1855      if (derived.hasAlias()) {
1856        if (!Base.compareDeep(derived.getAlias(), base.getAlias(), false))
1857          for (StringType s : derived.getAlias()) {
1858            if (!base.hasAlias(s.getValue()))
1859              base.getAlias().add(s.copy());
1860          }
1861        else if (trimDifferential)
1862          derived.getAlias().clear();
1863        else
1864          for (StringType t : derived.getAlias())
1865            t.setUserData(DERIVATION_EQUALS, true);
1866      }
1867
1868      if (derived.hasMinElement()) {
1869        if (!Base.compareDeep(derived.getMinElement(), base.getMinElement(), false)) {
1870          if (derived.getMin() < base.getMin() && !derived.hasSliceName()) // in a slice, minimum cardinality rules do not apply 
1871            messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn+"."+source.getPath(), "Element "+base.getPath()+": derived min ("+Integer.toString(derived.getMin())+") cannot be less than base min ("+Integer.toString(base.getMin())+")", ValidationMessage.IssueSeverity.ERROR));
1872          base.setMinElement(derived.getMinElement().copy());
1873        } else if (trimDifferential)
1874          derived.setMinElement(null);
1875        else
1876          derived.getMinElement().setUserData(DERIVATION_EQUALS, true);
1877      }
1878
1879      if (derived.hasMaxElement()) {
1880        if (!Base.compareDeep(derived.getMaxElement(), base.getMaxElement(), false)) {
1881          if (isLargerMax(derived.getMax(), base.getMax()))
1882            messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn+"."+source.getPath(), "Element "+base.getPath()+": derived max ("+derived.getMax()+") cannot be greater than base max ("+base.getMax()+")", ValidationMessage.IssueSeverity.ERROR));
1883          base.setMaxElement(derived.getMaxElement().copy());
1884        } else if (trimDifferential)
1885          derived.setMaxElement(null);
1886        else
1887          derived.getMaxElement().setUserData(DERIVATION_EQUALS, true);
1888      }
1889
1890      if (derived.hasFixed()) {
1891        if (!Base.compareDeep(derived.getFixed(), base.getFixed(), true)) {
1892          base.setFixed(derived.getFixed().copy());
1893        } else if (trimDifferential)
1894          derived.setFixed(null);
1895        else
1896          derived.getFixed().setUserData(DERIVATION_EQUALS, true);
1897      }
1898
1899      if (derived.hasPattern()) {
1900        if (!Base.compareDeep(derived.getPattern(), base.getPattern(), false)) {
1901          base.setPattern(derived.getPattern().copy());
1902        } else
1903          if (trimDifferential)
1904            derived.setPattern(null);
1905          else
1906            derived.getPattern().setUserData(DERIVATION_EQUALS, true);
1907      }
1908
1909      for (ElementDefinitionExampleComponent ex : derived.getExample()) {
1910        boolean found = false;
1911        for (ElementDefinitionExampleComponent exS : base.getExample())
1912          if (Base.compareDeep(ex, exS, false))
1913            found = true;
1914        if (!found)
1915          base.addExample(ex.copy());
1916        else if (trimDifferential)
1917          derived.getExample().remove(ex);
1918        else
1919          ex.setUserData(DERIVATION_EQUALS, true);
1920      }
1921
1922      if (derived.hasMaxLengthElement()) {
1923        if (!Base.compareDeep(derived.getMaxLengthElement(), base.getMaxLengthElement(), false))
1924          base.setMaxLengthElement(derived.getMaxLengthElement().copy());
1925        else if (trimDifferential)
1926          derived.setMaxLengthElement(null);
1927        else
1928          derived.getMaxLengthElement().setUserData(DERIVATION_EQUALS, true);
1929      }
1930
1931      // todo: what to do about conditions?
1932      // condition : id 0..*
1933
1934      if (derived.hasMustSupportElement()) {
1935        if (!(base.hasMustSupportElement() && Base.compareDeep(derived.getMustSupportElement(), base.getMustSupportElement(), false)))
1936          base.setMustSupportElement(derived.getMustSupportElement().copy());
1937        else if (trimDifferential)
1938          derived.setMustSupportElement(null);
1939        else
1940          derived.getMustSupportElement().setUserData(DERIVATION_EQUALS, true);
1941      }
1942
1943
1944      // profiles cannot change : isModifier, defaultValue, meaningWhenMissing
1945      // but extensions can change isModifier
1946      if (isExtension) {
1947        if (derived.hasIsModifierElement() && !(base.hasIsModifierElement() && Base.compareDeep(derived.getIsModifierElement(), base.getIsModifierElement(), false)))
1948          base.setIsModifierElement(derived.getIsModifierElement().copy());
1949        else if (trimDifferential)
1950          derived.setIsModifierElement(null);
1951        else if (derived.hasIsModifierElement())
1952          derived.getIsModifierElement().setUserData(DERIVATION_EQUALS, true);
1953        if (derived.hasIsModifierReasonElement() && !(base.hasIsModifierReasonElement() && Base.compareDeep(derived.getIsModifierReasonElement(), base.getIsModifierReasonElement(), false)))
1954          base.setIsModifierReasonElement(derived.getIsModifierReasonElement().copy());
1955        else if (trimDifferential)
1956          derived.setIsModifierReasonElement(null);
1957        else if (derived.hasIsModifierReasonElement())
1958          derived.getIsModifierReasonElement().setUserData(DERIVATION_EQUALS, true);
1959      }
1960
1961      if (derived.hasBinding()) {
1962        if (!base.hasBinding() || !Base.compareDeep(derived.getBinding(), base.getBinding(), false)) {
1963          if (base.hasBinding() && base.getBinding().getStrength() == BindingStrength.REQUIRED && derived.getBinding().getStrength() != BindingStrength.REQUIRED)
1964            messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn+"."+derived.getPath(), "illegal attempt to change the binding on "+derived.getPath()+" from "+base.getBinding().getStrength().toCode()+" to "+derived.getBinding().getStrength().toCode(), ValidationMessage.IssueSeverity.ERROR));
1965//            throw new DefinitionException("StructureDefinition "+pn+" at "+derived.getPath()+": illegal attempt to change a binding from "+base.getBinding().getStrength().toCode()+" to "+derived.getBinding().getStrength().toCode());
1966          else if (base.hasBinding() && derived.hasBinding() && base.getBinding().getStrength() == BindingStrength.REQUIRED && base.getBinding().hasValueSet() && derived.getBinding().hasValueSet()) {
1967            ValueSet baseVs = context.fetchResource(ValueSet.class, base.getBinding().getValueSet());
1968            ValueSet contextVs = context.fetchResource(ValueSet.class, derived.getBinding().getValueSet());
1969            if (baseVs == null) {
1970              messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn+"."+base.getPath(), "Binding "+base.getBinding().getValueSet()+" could not be located", ValidationMessage.IssueSeverity.WARNING));
1971            } else if (contextVs == null) {
1972              messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn+"."+derived.getPath(), "Binding "+derived.getBinding().getValueSet()+" could not be located", ValidationMessage.IssueSeverity.WARNING));
1973            } else {
1974              ValueSetExpansionOutcome expBase = context.expandVS(baseVs, true, false);
1975              ValueSetExpansionOutcome expDerived = context.expandVS(contextVs, true, false);
1976              if (expBase.getValueset() == null)
1977                messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn+"."+base.getPath(), "Binding "+base.getBinding().getValueSet()+" could not be expanded", ValidationMessage.IssueSeverity.WARNING));
1978              else if (expDerived.getValueset() == null)
1979                messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn+"."+derived.getPath(), "Binding "+derived.getBinding().getValueSet()+" could not be expanded", ValidationMessage.IssueSeverity.WARNING));
1980              else if (!isSubset(expBase.getValueset(), expDerived.getValueset()))
1981                messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn+"."+derived.getPath(), "Binding "+derived.getBinding().getValueSet()+" is not a subset of binding "+base.getBinding().getValueSet(), ValidationMessage.IssueSeverity.ERROR));
1982
1983            }
1984          }
1985          base.setBinding(derived.getBinding().copy());
1986        } else if (trimDifferential)
1987          derived.setBinding(null);
1988        else
1989          derived.getBinding().setUserData(DERIVATION_EQUALS, true);
1990      } // else if (base.hasBinding() && doesn't have bindable type )
1991        //  base
1992
1993      if (derived.hasIsSummaryElement()) {
1994        if (!Base.compareDeep(derived.getIsSummaryElement(), base.getIsSummaryElement(), false)) {
1995          if (base.hasIsSummary())
1996            throw new Error("Error in profile "+pn+" at "+derived.getPath()+": Base isSummary = "+base.getIsSummaryElement().asStringValue()+", derived isSummary = "+derived.getIsSummaryElement().asStringValue());
1997          base.setIsSummaryElement(derived.getIsSummaryElement().copy());
1998        } else if (trimDifferential)
1999          derived.setIsSummaryElement(null);
2000        else
2001          derived.getIsSummaryElement().setUserData(DERIVATION_EQUALS, true);
2002      }
2003
2004      if (derived.hasType()) {
2005        if (!Base.compareDeep(derived.getType(), base.getType(), false)) {
2006          if (base.hasType()) {
2007            for (TypeRefComponent ts : derived.getType()) {
2008//              if (!ts.hasCode()) { // ommitted in the differential; copy it over....
2009//                if (base.getType().size() > 1) 
2010//                  throw new DefinitionException("StructureDefinition "+pn+" at "+derived.getPath()+": constrained type code must be present if there are multiple types ("+base.typeSummary()+")");
2011//                if (base.getType().get(0).getCode() != null)
2012//                  ts.setCode(base.getType().get(0).getCode());
2013//              }
2014              boolean ok = false;
2015              CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
2016              String t = ts.getWorkingCode();
2017              for (TypeRefComponent td : base.getType()) {;
2018                String tt = td.getWorkingCode();
2019                b.append(tt);
2020                if (td.hasCode() && (tt.equals(t) || "Extension".equals(tt) || (t.equals("uri") && tt.equals("string"))  || // work around for old badly generated SDs
2021                    "Element".equals(tt) || "*".equals(tt) ||
2022                    (("Resource".equals(tt) || ("DomainResource".equals(tt)) && pkp.isResource(t)))))
2023                  ok = true;
2024              }
2025              if (!ok)
2026                throw new DefinitionException("StructureDefinition "+purl+" at "+derived.getPath()+": illegal constrained type "+t+" from "+b.toString()+" in "+srcSD.getUrl());
2027            }
2028          }
2029          base.getType().clear();
2030          for (TypeRefComponent t : derived.getType()) {
2031            TypeRefComponent tt = t.copy();
2032//            tt.setUserData(DERIVATION_EQUALS, true);
2033            base.getType().add(tt);
2034          }
2035        }
2036        else if (trimDifferential)
2037          derived.getType().clear();
2038        else
2039          for (TypeRefComponent t : derived.getType())
2040            t.setUserData(DERIVATION_EQUALS, true);
2041      }
2042
2043      if (derived.hasMapping()) {
2044        // todo: mappings are not cumulative - one replaces another
2045        if (!Base.compareDeep(derived.getMapping(), base.getMapping(), false)) {
2046          for (ElementDefinitionMappingComponent s : derived.getMapping()) {
2047            boolean found = false;
2048            for (ElementDefinitionMappingComponent d : base.getMapping()) {
2049              found = found || (d.getIdentity().equals(s.getIdentity()) && d.getMap().equals(s.getMap()));
2050            }
2051            if (!found)
2052              base.getMapping().add(s);
2053          }
2054        }
2055        else if (trimDifferential)
2056          derived.getMapping().clear();
2057        else
2058          for (ElementDefinitionMappingComponent t : derived.getMapping())
2059            t.setUserData(DERIVATION_EQUALS, true);
2060      }
2061
2062      // todo: constraints are cumulative. there is no replacing
2063      for (ElementDefinitionConstraintComponent s : base.getConstraint()) { 
2064        s.setUserData(IS_DERIVED, true);
2065        if (!s.hasSource())
2066          s.setSource(srcSD.getUrl());
2067      }
2068      if (derived.hasConstraint()) {
2069        for (ElementDefinitionConstraintComponent s : derived.getConstraint()) {
2070          if (!base.hasConstraint(s.getKey())) {
2071            ElementDefinitionConstraintComponent inv = s.copy();
2072            base.getConstraint().add(inv);
2073          }
2074        }
2075      }
2076      for (IdType id : derived.getCondition()) {
2077        if (!base.hasCondition(id))
2078          base.getCondition().add(id);
2079      }
2080      
2081      // now, check that we still have a bindable type; if not, delete the binding - see task 8477
2082      if (dest.hasBinding() && !hasBindableType(dest))
2083        dest.setBinding(null);
2084        
2085      // finally, we copy any extensions from source to dest
2086      for (Extension ex : derived.getExtension()) {
2087        StructureDefinition sd  = context.fetchResource(StructureDefinition.class, ex.getUrl());
2088        if (sd == null || sd.getSnapshot() == null || sd.getSnapshot().getElementFirstRep().getMax().equals("1"))
2089          ToolingExtensions.removeExtension(dest, ex.getUrl());
2090        dest.addExtension(ex.copy());
2091      }
2092    }
2093  }
2094
2095  private boolean hasBindableType(ElementDefinition ed) {
2096    for (TypeRefComponent tr : ed.getType()) {
2097      if (Utilities.existsInList(tr.getWorkingCode(), "Coding", "CodeableConcept", "Quantity", "uri", "string", "code"))
2098        return true;
2099    }
2100    return false;
2101  }
2102
2103
2104  private boolean isLargerMax(String derived, String base) {
2105    if ("*".equals(base))
2106      return false;
2107    if ("*".equals(derived))
2108      return true;
2109    return Integer.parseInt(derived) > Integer.parseInt(base);
2110  }
2111
2112
2113  private boolean isSubset(ValueSet expBase, ValueSet expDerived) {
2114    return codesInExpansion(expDerived.getExpansion().getContains(), expBase.getExpansion());
2115  }
2116
2117
2118  private boolean codesInExpansion(List<ValueSetExpansionContainsComponent> contains, ValueSetExpansionComponent expansion) {
2119    for (ValueSetExpansionContainsComponent cc : contains) {
2120      if (!inExpansion(cc, expansion.getContains()))
2121        return false;
2122      if (!codesInExpansion(cc.getContains(), expansion))
2123        return false;
2124    }
2125    return true;
2126  }
2127
2128
2129  private boolean inExpansion(ValueSetExpansionContainsComponent cc, List<ValueSetExpansionContainsComponent> contains) {
2130    for (ValueSetExpansionContainsComponent cc1 : contains) {
2131      if (cc.getSystem().equals(cc1.getSystem()) && cc.getCode().equals(cc1.getCode()))
2132        return true;
2133      if (inExpansion(cc,  cc1.getContains()))
2134        return true;
2135    }
2136    return false;
2137  }
2138
2139  public void closeDifferential(StructureDefinition base, StructureDefinition derived) throws FHIRException {
2140    for (ElementDefinition edb : base.getSnapshot().getElement()) {
2141      if (isImmediateChild(edb) && !edb.getPath().endsWith(".id")) {
2142        ElementDefinition edm = getMatchInDerived(edb, derived.getDifferential().getElement());
2143        if (edm == null) {
2144          ElementDefinition edd = derived.getDifferential().addElement();
2145          edd.setPath(edb.getPath());
2146          edd.setMax("0");
2147        } else if (edb.hasSlicing()) {
2148          closeChildren(base, edb, derived, edm);
2149        }
2150      }
2151    }
2152    sortDifferential(base, derived, derived.getName(), new ArrayList<String>());
2153  }
2154
2155  private void closeChildren(StructureDefinition base, ElementDefinition edb, StructureDefinition derived, ElementDefinition edm) {
2156    String path = edb.getPath()+".";
2157    int baseStart = base.getSnapshot().getElement().indexOf(edb);
2158    int baseEnd = findEnd(base.getSnapshot().getElement(), edb, baseStart+1);
2159    int diffStart = derived.getDifferential().getElement().indexOf(edm);
2160    int diffEnd = findEnd(derived.getDifferential().getElement(), edm, diffStart+1);
2161    
2162    for (int cBase = baseStart; cBase < baseEnd; cBase++) {
2163      ElementDefinition edBase = base.getSnapshot().getElement().get(cBase);
2164      if (isImmediateChild(edBase, edb)) {
2165        ElementDefinition edMatch = getMatchInDerived(edBase, derived.getDifferential().getElement(), diffStart, diffEnd);
2166        if (edMatch == null) {
2167          ElementDefinition edd = derived.getDifferential().addElement();
2168          edd.setPath(edBase.getPath());
2169          edd.setMax("0");
2170        } else {
2171          closeChildren(base, edBase, derived, edMatch);
2172        }        
2173      }
2174    }
2175  }
2176
2177
2178
2179
2180  private int findEnd(List<ElementDefinition> list, ElementDefinition ed, int cursor) {
2181    String path = ed.getPath()+".";
2182    while (cursor < list.size() && list.get(cursor).getPath().startsWith(path))
2183      cursor++;
2184    return cursor;
2185  }
2186
2187
2188  private ElementDefinition getMatchInDerived(ElementDefinition ed, List<ElementDefinition> list) {
2189    for (ElementDefinition t : list)
2190      if (t.getPath().equals(ed.getPath()))
2191        return t;
2192    return null;
2193  }
2194
2195  private ElementDefinition getMatchInDerived(ElementDefinition ed, List<ElementDefinition> list, int start, int end) {
2196    for (int i = start; i < end; i++) {
2197      ElementDefinition t = list.get(i);
2198      if (t.getPath().equals(ed.getPath()))
2199        return t;
2200    }
2201    return null;
2202  }
2203
2204
2205  private boolean isImmediateChild(ElementDefinition ed) {
2206    String p = ed.getPath();
2207    if (!p.contains("."))
2208      return false;
2209    p = p.substring(p.indexOf(".")+1);
2210    return !p.contains(".");
2211  }
2212
2213  private boolean isImmediateChild(ElementDefinition candidate, ElementDefinition base) {
2214    String p = candidate.getPath();
2215    if (!p.contains("."))
2216      return false;
2217    if (!p.startsWith(base.getPath()+"."))
2218      return false;
2219    p = p.substring(base.getPath().length()+1);
2220    return !p.contains(".");
2221  }
2222
2223  public XhtmlNode generateExtensionTable(String defFile, StructureDefinition ed, String imageFolder, boolean inlineGraphics, boolean full, String corePath, String imagePath, Set<String> outputTracker) throws IOException, FHIRException {
2224    HierarchicalTableGenerator gen = new HierarchicalTableGenerator(imageFolder, inlineGraphics, true);
2225    gen.setTranslator(getTranslator());
2226    TableModel model = gen.initNormalTable(corePath, false, true);
2227
2228    boolean deep = false;
2229    String m = "";
2230    boolean vdeep = false;
2231    if (ed.getSnapshot().getElementFirstRep().getIsModifier())
2232      m = "modifier_";
2233    for (ElementDefinition eld : ed.getSnapshot().getElement()) {
2234      deep = deep || eld.getPath().contains("Extension.extension.");
2235      vdeep = vdeep || eld.getPath().contains("Extension.extension.extension.");
2236    }
2237    Row r = gen.new Row();
2238    model.getRows().add(r);
2239    String en;
2240    if (!full)
2241      en = ed.getName();
2242    else if (ed.getSnapshot().getElement().get(0).getIsModifier())
2243      en = "modifierExtension";
2244    else 
2245      en = "extension";
2246    
2247    r.getCells().add(gen.new Cell(null, defFile == null ? "" : defFile+"-definitions.html#extension."+ed.getName(), en, null, null));
2248    r.getCells().add(gen.new Cell());
2249    r.getCells().add(gen.new Cell(null, null, describeCardinality(ed.getSnapshot().getElement().get(0), null, new UnusedTracker()), null, null));
2250
2251    ElementDefinition ved = null;
2252    if (full || vdeep) {
2253      r.getCells().add(gen.new Cell("", "", "Extension", null, null));
2254
2255      r.setIcon(deep ? "icon_"+m+"extension_complex.png" : "icon_extension_simple.png", deep ? HierarchicalTableGenerator.TEXT_ICON_EXTENSION_COMPLEX : HierarchicalTableGenerator.TEXT_ICON_EXTENSION_SIMPLE);
2256      List<ElementDefinition> children = getChildren(ed.getSnapshot().getElement(), ed.getSnapshot().getElement().get(0));
2257      for (ElementDefinition child : children)
2258        if (!child.getPath().endsWith(".id"))
2259          genElement(defFile == null ? "" : defFile+"-definitions.html#extension.", gen, r.getSubRows(), child, ed.getSnapshot().getElement(), null, true, defFile, true, full, corePath, imagePath, true, false, false, false, null);
2260    } else if (deep) {
2261      List<ElementDefinition> children = new ArrayList<ElementDefinition>();
2262      for (ElementDefinition ted : ed.getSnapshot().getElement()) {
2263        if (ted.getPath().equals("Extension.extension"))
2264          children.add(ted);
2265      }
2266
2267      r.getCells().add(gen.new Cell("", "", "Extension", null, null));
2268      r.setIcon("icon_"+m+"extension_complex.png", HierarchicalTableGenerator.TEXT_ICON_EXTENSION_COMPLEX);
2269      
2270      for (ElementDefinition c : children) {
2271        ved = getValueFor(ed, c);
2272        ElementDefinition ued = getUrlFor(ed, c);
2273        if (ved != null && ued != null) {
2274          Row r1 = gen.new Row();
2275          r.getSubRows().add(r1);
2276          r1.getCells().add(gen.new Cell(null, defFile == null ? "" : defFile+"-definitions.html#extension."+ed.getName(), ((UriType) ued.getFixed()).getValue(), null, null));
2277          r1.getCells().add(gen.new Cell());
2278          r1.getCells().add(gen.new Cell(null, null, describeCardinality(c, null, new UnusedTracker()), null, null));
2279          genTypes(gen, r1, ved, defFile, ed, corePath, imagePath);
2280          Cell cell = gen.new Cell();
2281          cell.addMarkdown(c.getDefinition());
2282          r1.getCells().add(cell);
2283          r1.setIcon("icon_"+m+"extension_simple.png", HierarchicalTableGenerator.TEXT_ICON_EXTENSION_SIMPLE);      
2284        }
2285      }
2286    } else  {
2287      for (ElementDefinition ted : ed.getSnapshot().getElement()) {
2288        if (ted.getPath().startsWith("Extension.value"))
2289          ved = ted;
2290      }
2291
2292      genTypes(gen, r, ved, defFile, ed, corePath, imagePath);
2293
2294      r.setIcon("icon_"+m+"extension_simple.png", HierarchicalTableGenerator.TEXT_ICON_EXTENSION_SIMPLE);      
2295    }
2296    Cell c = gen.new Cell("", "", "URL = "+ed.getUrl(), null, null);
2297    Piece cc = gen.new Piece(null, ed.getName()+": ", null);
2298    c.addPiece(gen.new Piece("br")).addPiece(cc);
2299    c.addMarkdown(ed.getDescription());
2300    
2301    if (!full && !(deep || vdeep) && ved != null && ved.hasBinding()) {  
2302        c.addPiece(gen.new Piece("br"));
2303      BindingResolution br = pkp.resolveBinding(ed, ved.getBinding(), ved.getPath());
2304      c.getPieces().add(checkForNoChange(ved.getBinding(), gen.new Piece(null, translate("sd.table", "Binding")+": ", null).addStyle("font-weight:bold")));
2305      c.getPieces().add(checkForNoChange(ved.getBinding(), gen.new Piece(br.url == null ? null : Utilities.isAbsoluteUrl(br.url) || !pkp.prependLinks() ? br.url : corePath+br.url, br.display, null)));
2306      if (ved.getBinding().hasStrength()) {
2307        c.getPieces().add(checkForNoChange(ved.getBinding(), gen.new Piece(null, " (", null)));
2308        c.getPieces().add(checkForNoChange(ved.getBinding(), gen.new Piece(corePath+"terminologies.html#"+ved.getBinding().getStrength().toCode(), egt(ved.getBinding().getStrengthElement()), ved.getBinding().getStrength().getDefinition())));              
2309        c.getPieces().add(gen.new Piece(null, ")", null));
2310      }
2311    }
2312    c.addPiece(gen.new Piece("br")).addPiece(gen.new Piece(null, describeExtensionContext(ed), null));
2313    r.getCells().add(c);
2314    
2315    try {
2316      return gen.generate(model, corePath, 0, outputTracker);
2317        } catch (org.hl7.fhir.exceptions.FHIRException e) {
2318                throw new FHIRException(e.getMessage(), e);
2319        }
2320  }
2321
2322  private ElementDefinition getUrlFor(StructureDefinition ed, ElementDefinition c) {
2323    int i = ed.getSnapshot().getElement().indexOf(c) + 1;
2324    while (i < ed.getSnapshot().getElement().size() && ed.getSnapshot().getElement().get(i).getPath().startsWith(c.getPath()+".")) {
2325      if (ed.getSnapshot().getElement().get(i).getPath().equals(c.getPath()+".url"))
2326        return ed.getSnapshot().getElement().get(i);
2327      i++;
2328    }
2329    return null;
2330  }
2331
2332  private ElementDefinition getValueFor(StructureDefinition ed, ElementDefinition c) {
2333    int i = ed.getSnapshot().getElement().indexOf(c) + 1;
2334    while (i < ed.getSnapshot().getElement().size() && ed.getSnapshot().getElement().get(i).getPath().startsWith(c.getPath()+".")) {
2335      if (ed.getSnapshot().getElement().get(i).getPath().startsWith(c.getPath()+".value"))
2336        return ed.getSnapshot().getElement().get(i);
2337      i++;
2338    }
2339    return null;
2340  }
2341
2342  private static final int AGG_NONE = 0;
2343  private static final int AGG_IND = 1;
2344  private static final int AGG_GR = 2;
2345  private static final boolean TABLE_FORMAT_FOR_FIXED_VALUES = false;
2346  
2347  private Cell genTypes(HierarchicalTableGenerator gen, Row r, ElementDefinition e, String profileBaseFileName, StructureDefinition profile, String corePath, String imagePath) {
2348    Cell c = gen.new Cell();
2349    r.getCells().add(c);
2350    List<TypeRefComponent> types = e.getType();
2351    if (!e.hasType()) {
2352      if (e.hasContentReference()) {
2353        return c;
2354      } else {
2355        ElementDefinition d = (ElementDefinition) e.getUserData(DERIVATION_POINTER);
2356        if (d != null && d.hasType()) {
2357          types = new ArrayList<ElementDefinition.TypeRefComponent>();
2358          for (TypeRefComponent tr : d.getType()) {
2359            TypeRefComponent tt = tr.copy();
2360            tt.setUserData(DERIVATION_EQUALS, true);
2361            types.add(tt);
2362          }
2363        } else {
2364          return c;
2365        }
2366      }
2367    }
2368
2369    boolean first = true;
2370
2371    TypeRefComponent tl = null;
2372    for (TypeRefComponent t : types) {
2373      if (first) {
2374        first = false;
2375      } else {
2376        c.addPiece(checkForNoChange(tl, gen.new Piece(null,", ", null)));
2377      }
2378      tl = t;
2379      if (t.hasTarget()) {
2380        c.getPieces().add(gen.new Piece(corePath+"references.html", t.getWorkingCode(), null));
2381        c.getPieces().add(gen.new Piece(null, "(", null));
2382        boolean tfirst = true;
2383        for (UriType u : t.getTargetProfile()) {
2384          if (tfirst)
2385            tfirst = false;
2386          else
2387            c.addPiece(gen.new Piece(null, " | ", null));
2388          genTargetLink(gen, profileBaseFileName, corePath, c, t, u.getValue());
2389        }
2390        c.getPieces().add(gen.new Piece(null, ")", null));
2391        if (t.getAggregation().size() > 0) {
2392          c.getPieces().add(gen.new Piece(corePath+"valueset-resource-aggregation-mode.html", " {", null));
2393          boolean firstA = true;
2394          for (Enumeration<AggregationMode> a : t.getAggregation()) {
2395            if (firstA = true)
2396              firstA = false;
2397            else
2398              c.getPieces().add(gen.new Piece(corePath+"valueset-resource-aggregation-mode.html", ", ", null));
2399            c.getPieces().add(gen.new Piece(corePath+"valueset-resource-aggregation-mode.html", codeForAggregation(a.getValue()), hintForAggregation(a.getValue())));
2400          }
2401          c.getPieces().add(gen.new Piece(corePath+"valueset-resource-aggregation-mode.html", "}", null));
2402        }
2403      } else if (t.hasProfile() && (!t.getWorkingCode().equals("Extension") || isProfiledType(t.getProfile()))) { // a profiled type
2404        String ref;
2405        ref = pkp.getLinkForProfile(profile, t.getProfile().get(0).getValue());
2406        if (ref != null) {
2407          String[] parts = ref.split("\\|");
2408          if (parts[0].startsWith("http:") || parts[0].startsWith("https:")) {
2409//            c.addPiece(checkForNoChange(t, gen.new Piece(parts[0], "<" + parts[1] + ">", t.getCode()))); Lloyd
2410            c.addPiece(checkForNoChange(t, gen.new Piece(parts[0], parts[1], t.getWorkingCode())));
2411          } else {
2412//            c.addPiece(checkForNoChange(t, gen.new Piece((t.getProfile().startsWith(corePath)? corePath: "")+parts[0], "<" + parts[1] + ">", t.getCode())));
2413            c.addPiece(checkForNoChange(t, gen.new Piece((t.getProfile().get(0).getValue().startsWith(corePath+"StructureDefinition")? corePath: "")+parts[0], parts[1], t.getWorkingCode())));
2414          }
2415        } else
2416          c.addPiece(checkForNoChange(t, gen.new Piece((t.getProfile().get(0).getValue().startsWith(corePath)? corePath: "")+ref, t.getWorkingCode(), null)));
2417      } else {
2418        String tc = t.getWorkingCode();
2419        if (pkp != null && pkp.hasLinkFor(tc)) {
2420          c.addPiece(checkForNoChange(t, gen.new Piece(pkp.getLinkFor(corePath, tc), tc, null)));
2421        } else
2422          c.addPiece(checkForNoChange(t, gen.new Piece(null, tc, null)));
2423      }
2424    }
2425    return c;
2426  }
2427
2428
2429  public void genTargetLink(HierarchicalTableGenerator gen, String profileBaseFileName, String corePath, Cell c, TypeRefComponent t, String u) {
2430    if (u.startsWith("http://hl7.org/fhir/StructureDefinition/")) {
2431      StructureDefinition sd = context.fetchResource(StructureDefinition.class, u);
2432      if (sd != null) {
2433        String disp = sd.hasTitle() ? sd.getTitle() : sd.getName();
2434        c.addPiece(checkForNoChange(t, gen.new Piece(checkPrepend(corePath, sd.getUserString("path")), disp, null)));
2435      } else {
2436        String rn = u.substring(40);
2437        c.addPiece(checkForNoChange(t, gen.new Piece(pkp.getLinkFor(corePath, rn), rn, null)));
2438      }
2439    } else if (Utilities.isAbsoluteUrl(u)) {
2440      StructureDefinition sd = context.fetchResource(StructureDefinition.class, u);
2441      if (sd != null) {
2442        String disp = sd.hasTitle() ? sd.getTitle() : sd.getName();
2443        String ref = pkp.getLinkForProfile(null, sd.getUrl());
2444        if (ref != null && ref.contains("|"))
2445          ref = ref.substring(0,  ref.indexOf("|"));
2446        c.addPiece(checkForNoChange(t, gen.new Piece(ref, disp, null)));
2447      } else
2448        c.addPiece(checkForNoChange(t, gen.new Piece(null, u, null)));        
2449    } else if (t.hasTargetProfile() && u.startsWith("#"))
2450      c.addPiece(checkForNoChange(t, gen.new Piece(corePath+profileBaseFileName+"."+u.substring(1).toLowerCase()+".html", u, null)));
2451  }
2452
2453  private boolean isProfiledType(List<CanonicalType> theProfile) {
2454    for (CanonicalType next : theProfile){
2455      if (StringUtils.defaultString(next.getValueAsString()).contains(":")) {
2456        return true;
2457      }
2458    }
2459    return false;
2460  }
2461
2462
2463  private String codeForAggregation(AggregationMode a) {
2464    switch (a) {
2465    case BUNDLED : return "b";
2466    case CONTAINED : return "c";
2467    case REFERENCED: return "r";
2468    default: return "?";
2469    }
2470  }
2471
2472  private String hintForAggregation(AggregationMode a) {
2473    if (a != null)
2474      return a.getDefinition();
2475    else 
2476      return null;
2477  }
2478
2479
2480  private String checkPrepend(String corePath, String path) {
2481    if (pkp.prependLinks() && !(path.startsWith("http:") || path.startsWith("https:")))
2482      return corePath+path;
2483    else 
2484      return path;
2485  }
2486
2487
2488  private ElementDefinition getElementByName(List<ElementDefinition> elements, String contentReference) {
2489    for (ElementDefinition ed : elements)
2490      if (ed.hasSliceName() && ("#"+ed.getSliceName()).equals(contentReference))
2491        return ed;
2492    return null;
2493  }
2494
2495  private ElementDefinition getElementById(List<ElementDefinition> elements, String contentReference) {
2496    for (ElementDefinition ed : elements)
2497      if (ed.hasId() && ("#"+ed.getId()).equals(contentReference))
2498        return ed;
2499    return null;
2500  }
2501
2502
2503  public static String describeExtensionContext(StructureDefinition ext) {
2504    StringBuilder b = new StringBuilder();
2505    b.append("Use on ");
2506    for (int i = 0; i < ext.getContext().size(); i++) {
2507      StructureDefinitionContextComponent ec = ext.getContext().get(i);
2508      if (i > 0) 
2509        b.append(i < ext.getContext().size() - 1 ? ", " : " or ");
2510      b.append(ec.getType().getDisplay());
2511      b.append(" ");
2512      b.append(ec.getExpression());
2513    }
2514    if (ext.hasContextInvariant()) {
2515      b.append(", with <a href=\"structuredefinition-definitions.html#StructureDefinition.contextInvariant\">Context Invariant</a> = ");
2516      boolean first = true;
2517      for (StringType s : ext.getContextInvariant()) {
2518        if (first)
2519          first = false;
2520        else
2521          b.append(", ");
2522        b.append("<code>"+s.getValue()+"</code>");
2523      }
2524    }
2525    return b.toString(); 
2526  }
2527
2528  private String describeCardinality(ElementDefinition definition, ElementDefinition fallback, UnusedTracker tracker) {
2529    IntegerType min = definition.hasMinElement() ? definition.getMinElement() : new IntegerType();
2530    StringType max = definition.hasMaxElement() ? definition.getMaxElement() : new StringType();
2531    if (min.isEmpty() && fallback != null)
2532      min = fallback.getMinElement();
2533    if (max.isEmpty() && fallback != null)
2534      max = fallback.getMaxElement();
2535
2536    tracker.used = !max.isEmpty() && !max.getValue().equals("0");
2537
2538    if (min.isEmpty() && max.isEmpty())
2539      return null;
2540    else
2541      return (!min.hasValue() ? "" : Integer.toString(min.getValue())) + ".." + (!max.hasValue() ? "" : max.getValue());
2542  }
2543
2544  private void genCardinality(HierarchicalTableGenerator gen, ElementDefinition definition, Row row, boolean hasDef, UnusedTracker tracker, ElementDefinition fallback) {
2545    IntegerType min = !hasDef ? new IntegerType() : definition.hasMinElement() ? definition.getMinElement() : new IntegerType();
2546    StringType max = !hasDef ? new StringType() : definition.hasMaxElement() ? definition.getMaxElement() : new StringType();
2547    if (min.isEmpty() && definition.getUserData(DERIVATION_POINTER) != null) {
2548      ElementDefinition base = (ElementDefinition) definition.getUserData(DERIVATION_POINTER);
2549      if (base.hasMinElement()) {
2550        min = base.getMinElement().copy();
2551        min.setUserData(DERIVATION_EQUALS, true);
2552      }
2553    }
2554    if (max.isEmpty() && definition.getUserData(DERIVATION_POINTER) != null) {
2555      ElementDefinition base = (ElementDefinition) definition.getUserData(DERIVATION_POINTER);
2556      if (base.hasMaxElement()) {
2557        max = base.getMaxElement().copy();
2558        max.setUserData(DERIVATION_EQUALS, true);
2559      }
2560    }
2561    if (min.isEmpty() && fallback != null)
2562      min = fallback.getMinElement();
2563    if (max.isEmpty() && fallback != null)
2564      max = fallback.getMaxElement();
2565
2566    if (!max.isEmpty())
2567      tracker.used = !max.getValue().equals("0");
2568
2569    Cell cell = gen.new Cell(null, null, null, null, null);
2570    row.getCells().add(cell);
2571    if (!min.isEmpty() || !max.isEmpty()) {
2572      cell.addPiece(checkForNoChange(min, gen.new Piece(null, !min.hasValue() ? "" : Integer.toString(min.getValue()), null)));
2573      cell.addPiece(checkForNoChange(min, max, gen.new Piece(null, "..", null)));
2574      cell.addPiece(checkForNoChange(min, gen.new Piece(null, !max.hasValue() ? "" : max.getValue(), null)));
2575    }
2576  }
2577
2578
2579  private Piece checkForNoChange(Element source, Piece piece) {
2580    if (source.hasUserData(DERIVATION_EQUALS)) {
2581      piece.addStyle("opacity: 0.4");
2582    }
2583    return piece;
2584  }
2585
2586  private Piece checkForNoChange(Element src1, Element src2, Piece piece) {
2587    if (src1.hasUserData(DERIVATION_EQUALS) && src2.hasUserData(DERIVATION_EQUALS)) {
2588      piece.addStyle("opacity: 0.5");
2589    }
2590    return piece;
2591  }
2592
2593  public XhtmlNode generateTable(String defFile, StructureDefinition profile, boolean diff, String imageFolder, boolean inlineGraphics, String profileBaseFileName, boolean snapshot, String corePath, String imagePath, boolean logicalModel, boolean allInvariants, Set<String> outputTracker) throws IOException, FHIRException {
2594    assert(diff != snapshot);// check it's ok to get rid of one of these
2595    HierarchicalTableGenerator gen = new HierarchicalTableGenerator(imageFolder, inlineGraphics, true);
2596    gen.setTranslator(getTranslator());
2597    TableModel model = gen.initNormalTable(corePath, false, true);
2598    List<ElementDefinition> list = new ArrayList<>();
2599    if (diff)
2600      list.addAll(profile.getDifferential().getElement());
2601    else
2602      list.addAll(profile.getSnapshot().getElement());
2603    List<StructureDefinition> profiles = new ArrayList<StructureDefinition>();
2604    profiles.add(profile);
2605    if (list.isEmpty()) {
2606      ElementDefinition root = new ElementDefinition().setPath(profile.getType());
2607      root.setId(profile.getType());
2608      list.add(root);
2609    } else {
2610      if (list.get(0).getPath().contains(".")) {
2611        ElementDefinition root = new ElementDefinition().setPath(profile.getType());
2612        root.setId(profile.getType());
2613        list.add(0, root);
2614      }
2615    }
2616    if (diff)
2617      insertMissingSparseElements(list);
2618    genElement(defFile == null ? null : defFile+"#", gen, model.getRows(), list.get(0), list, profiles, diff, profileBaseFileName, null, snapshot, corePath, imagePath, true, logicalModel, profile.getDerivation() == TypeDerivationRule.CONSTRAINT && usesMustSupport(list), allInvariants, null);
2619    try {
2620      return gen.generate(model, imagePath, 0, outputTracker);
2621        } catch (org.hl7.fhir.exceptions.FHIRException e) {
2622                throw new FHIRException("Error generating table for profile " + profile.getUrl() + ": " + e.getMessage(), e);
2623        }
2624  }
2625
2626
2627  private void insertMissingSparseElements(List<ElementDefinition> list) {
2628    int i = 1;
2629    while (i < list.size()) {
2630      String[] pathCurrent = list.get(i).getPath().split("\\.");
2631      String[] pathLast = list.get(i-1).getPath().split("\\.");
2632      int firstDiff = 0; // the first entry must be a match 
2633      while (firstDiff < pathCurrent.length && firstDiff < pathLast.length && pathCurrent[firstDiff].equals(pathLast[firstDiff])) {
2634        firstDiff++;
2635      }
2636      if (!(isSibling(pathCurrent, pathLast, firstDiff) || isChild(pathCurrent, pathLast, firstDiff))) {
2637        // now work backwards down to lastMatch inserting missing path nodes
2638        for (int index = pathCurrent.length-2; index >= firstDiff; index--) {
2639          ElementDefinition root = new ElementDefinition().setPath(makePath(pathCurrent, index));
2640          root.setId(root.getPath());
2641          list.add(i, root);
2642        }
2643      } 
2644      i++;
2645    }
2646  }
2647
2648  private boolean isSibling(String[] pathCurrent, String[] pathLast, int firstDiff) {
2649    return pathCurrent.length == pathLast.length && firstDiff == pathCurrent.length-1;
2650  }
2651
2652
2653  private boolean isChild(String[] pathCurrent, String[] pathLast, int firstDiff) {
2654    return pathCurrent.length == pathLast.length+1 && firstDiff == pathLast.length;
2655  }
2656
2657
2658  private String makePath(String[] pathCurrent, int index) {
2659    CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder(".");
2660    for (int i = 0; i <= index; i++) {
2661      b.append(pathCurrent[i]);
2662    }
2663    return b.toString();
2664  }
2665
2666
2667  public XhtmlNode generateGrid(String defFile, StructureDefinition profile, String imageFolder, boolean inlineGraphics, String profileBaseFileName, String corePath, String imagePath, Set<String> outputTracker) throws IOException, FHIRException {
2668    HierarchicalTableGenerator gen = new HierarchicalTableGenerator(imageFolder, inlineGraphics, true);
2669    gen.setTranslator(getTranslator());
2670    TableModel model = gen.initGridTable(corePath);
2671    List<ElementDefinition> list = profile.getSnapshot().getElement();
2672    List<StructureDefinition> profiles = new ArrayList<StructureDefinition>();
2673    profiles.add(profile);
2674    genGridElement(defFile == null ? null : defFile+"#", gen, model.getRows(), list.get(0), list, profiles, true, profileBaseFileName, null, corePath, imagePath, true, profile.getDerivation() == TypeDerivationRule.CONSTRAINT && usesMustSupport(list));
2675    try {
2676      return gen.generate(model, imagePath, 1, outputTracker);
2677    } catch (org.hl7.fhir.exceptions.FHIRException e) {
2678      throw new FHIRException(e.getMessage(), e);
2679    }
2680  }
2681
2682
2683  private boolean usesMustSupport(List<ElementDefinition> list) {
2684    for (ElementDefinition ed : list)
2685      if (ed.hasMustSupport() && ed.getMustSupport())
2686        return true;
2687    return false;
2688  }
2689
2690
2691  private Row genElement(String defPath, HierarchicalTableGenerator gen, List<Row> rows, ElementDefinition element, List<ElementDefinition> all, List<StructureDefinition> profiles, boolean showMissing, String profileBaseFileName, Boolean extensions, boolean snapshot, String corePath, String imagePath, boolean root, boolean logicalModel, boolean isConstraintMode, boolean allInvariants, Row slicingRow) throws IOException, FHIRException {
2692    Row originalRow = slicingRow;
2693    StructureDefinition profile = profiles == null ? null : profiles.get(profiles.size()-1);
2694    String s = tail(element.getPath());
2695    if (element.hasSliceName())
2696      s = s +":"+element.getSliceName();
2697    Row typesRow = null;
2698    
2699    List<ElementDefinition> children = getChildren(all, element);
2700    boolean isExtension = (s.equals("extension") || s.equals("modifierExtension"));
2701//    if (!snapshot && isExtension && extensions != null && extensions != isExtension)
2702//      return;
2703
2704    if (!onlyInformationIsMapping(all, element)) {
2705      Row row = gen.new Row();
2706      row.setAnchor(element.getPath());
2707      row.setColor(getRowColor(element, isConstraintMode));
2708      if (element.hasSlicing())
2709        row.setLineColor(1);
2710      else if (element.hasSliceName())
2711        row.setLineColor(2);
2712      else
2713        row.setLineColor(0);
2714      boolean hasDef = element != null;
2715      boolean ext = false;
2716      if (tail(element.getPath()).equals("extension")) {
2717        if (element.hasType() && element.getType().get(0).hasProfile() && extensionIsComplex(element.getType().get(0).getProfile().get(0).getValue()))
2718          row.setIcon("icon_extension_complex.png", HierarchicalTableGenerator.TEXT_ICON_EXTENSION_COMPLEX);
2719        else
2720          row.setIcon("icon_extension_simple.png", HierarchicalTableGenerator.TEXT_ICON_EXTENSION_SIMPLE);
2721        ext = true;
2722      } else if (tail(element.getPath()).equals("modifierExtension")) {
2723        if (element.hasType() && element.getType().get(0).hasProfile() && extensionIsComplex(element.getType().get(0).getProfile().get(0).getValue()))
2724          row.setIcon("icon_modifier_extension_complex.png", HierarchicalTableGenerator.TEXT_ICON_EXTENSION_COMPLEX);
2725        else
2726          row.setIcon("icon_modifier_extension_simple.png", HierarchicalTableGenerator.TEXT_ICON_EXTENSION_SIMPLE);
2727      } else if (!hasDef || element.getType().size() == 0)
2728        row.setIcon("icon_element.gif", HierarchicalTableGenerator.TEXT_ICON_ELEMENT);
2729      else if (hasDef && element.getType().size() > 1) {
2730        if (allAreReference(element.getType()))
2731          row.setIcon("icon_reference.png", HierarchicalTableGenerator.TEXT_ICON_REFERENCE);
2732        else {
2733          row.setIcon("icon_choice.gif", HierarchicalTableGenerator.TEXT_ICON_CHOICE);
2734          typesRow = row;
2735        }
2736      } else if (hasDef && element.getType().get(0).getWorkingCode() != null && element.getType().get(0).getWorkingCode().startsWith("@"))
2737        row.setIcon("icon_reuse.png", HierarchicalTableGenerator.TEXT_ICON_REUSE);
2738      else if (hasDef && isPrimitive(element.getType().get(0).getWorkingCode()))
2739        row.setIcon("icon_primitive.png", HierarchicalTableGenerator.TEXT_ICON_PRIMITIVE);
2740      else if (hasDef && element.getType().get(0).hasTarget())
2741        row.setIcon("icon_reference.png", HierarchicalTableGenerator.TEXT_ICON_REFERENCE);
2742      else if (hasDef && isDataType(element.getType().get(0).getWorkingCode()))
2743        row.setIcon("icon_datatype.gif", HierarchicalTableGenerator.TEXT_ICON_DATATYPE);
2744      else
2745        row.setIcon("icon_resource.png", HierarchicalTableGenerator.TEXT_ICON_RESOURCE);
2746      String ref = defPath == null ? null : defPath + element.getId();
2747      UnusedTracker used = new UnusedTracker();
2748      used.used = true;
2749      if (logicalModel && element.hasRepresentation(PropertyRepresentation.XMLATTR))
2750        s = "@"+s;
2751      Cell left = gen.new Cell(null, ref, s, (element.hasSliceName() ? translate("sd.table", "Slice")+" "+element.getSliceName() : "")+(hasDef && element.hasSliceName() ? ": " : "")+(!hasDef ? null : gt(element.getDefinitionElement())), null);
2752      row.getCells().add(left);
2753      Cell gc = gen.new Cell();
2754      row.getCells().add(gc);
2755      if (element != null && element.getIsModifier())
2756        checkForNoChange(element.getIsModifierElement(), gc.addStyledText(translate("sd.table", "This element is a modifier element"), "?!", null, null, null, false));
2757      if (element != null && element.getMustSupport())
2758        checkForNoChange(element.getMustSupportElement(), gc.addStyledText(translate("sd.table", "This element must be supported"), "S", "white", "red", null, false));
2759      if (element != null && element.getIsSummary())
2760        checkForNoChange(element.getIsSummaryElement(), gc.addStyledText(translate("sd.table", "This element is included in summaries"), "\u03A3", null, null, null, false));
2761      if (element != null && (!element.getConstraint().isEmpty() || !element.getCondition().isEmpty()))
2762        gc.addStyledText(translate("sd.table", "This element has or is affected by some invariants ("+listConstraintsAndConditions(element)+")"), "I", null, null, null, false);
2763
2764      ExtensionContext extDefn = null;
2765      if (ext) {
2766        if (element != null && element.getType().size() == 1 && element.getType().get(0).hasProfile()) {
2767          String eurl = element.getType().get(0).getProfile().get(0).getValue();
2768          extDefn = locateExtension(StructureDefinition.class, eurl);
2769          if (extDefn == null) {
2770            genCardinality(gen, element, row, hasDef, used, null);
2771            row.getCells().add(gen.new Cell(null, null, "?? "+element.getType().get(0).getProfile(), null, null));
2772            generateDescription(gen, row, element, null, used.used, profile.getUrl(), eurl, profile, corePath, imagePath, root, logicalModel, allInvariants, snapshot);
2773          } else {
2774            String name = urltail(eurl);
2775            left.getPieces().get(0).setText(name);
2776            // left.getPieces().get(0).setReference((String) extDefn.getExtensionStructure().getTag("filename"));
2777            left.getPieces().get(0).setHint(translate("sd.table", "Extension URL")+" = "+extDefn.getUrl());
2778            genCardinality(gen, element, row, hasDef, used, extDefn.getElement());
2779            ElementDefinition valueDefn = extDefn.getExtensionValueDefinition();
2780            if (valueDefn != null && !"0".equals(valueDefn.getMax()))
2781               genTypes(gen, row, valueDefn, profileBaseFileName, profile, corePath, imagePath);
2782             else // if it's complex, we just call it nothing
2783                // genTypes(gen, row, extDefn.getSnapshot().getElement().get(0), profileBaseFileName, profile);
2784              row.getCells().add(gen.new Cell(null, null, "("+translate("sd.table", "Complex")+")", null, null));
2785            generateDescription(gen, row, element, extDefn.getElement(), used.used, null, extDefn.getUrl(), profile, corePath, imagePath, root, logicalModel, allInvariants, valueDefn, snapshot);
2786          }
2787        } else {
2788          genCardinality(gen, element, row, hasDef, used, null);
2789          if ("0".equals(element.getMax()))
2790            row.getCells().add(gen.new Cell());            
2791          else
2792            genTypes(gen, row, element, profileBaseFileName, profile, corePath, imagePath);
2793          generateDescription(gen, row, element, null, used.used, null, null, profile, corePath, imagePath, root, logicalModel, allInvariants, snapshot);
2794        }
2795      } else {
2796        genCardinality(gen, element, row, hasDef, used, null);
2797        if (element.hasSlicing())
2798          row.getCells().add(gen.new Cell(null, corePath+"profiling.html#slicing", "(Slice Definition)", null, null));
2799        else if (hasDef && !"0".equals(element.getMax()) && typesRow == null)
2800          genTypes(gen, row, element, profileBaseFileName, profile, corePath, imagePath);
2801        else
2802          row.getCells().add(gen.new Cell());
2803        generateDescription(gen, row, element, null, used.used, null, null, profile, corePath, imagePath, root, logicalModel, allInvariants, snapshot);
2804      }
2805      if (element.hasSlicing()) {
2806        if (standardExtensionSlicing(element)) {
2807          used.used = true; // doesn't matter whether we have a type, we're used if we're setting up slicing ... element.hasType() && element.getType().get(0).hasProfile();
2808          showMissing = false; //?
2809        } else {
2810          row.setIcon("icon_slice.png", HierarchicalTableGenerator.TEXT_ICON_SLICE);
2811          slicingRow = row;
2812          for (Cell cell : row.getCells())
2813            for (Piece p : cell.getPieces()) {
2814              p.addStyle("font-style: italic");
2815            }
2816        }
2817      } else if (element.hasSliceName()) {
2818        row.setIcon("icon_slice_item.png", HierarchicalTableGenerator.TEXT_ICON_SLICE_ITEM);
2819      }
2820      if (used.used || showMissing)
2821        rows.add(row);
2822      if (!used.used && !element.hasSlicing()) {
2823        for (Cell cell : row.getCells())
2824          for (Piece p : cell.getPieces()) {
2825            p.setStyle("text-decoration:line-through");
2826            p.setReference(null);
2827          }
2828      } else {
2829        if (slicingRow != originalRow && !children.isEmpty()) {
2830          // we've entered a slice; we're going to create a holder row for the slice children
2831          Row hrow = gen.new Row();
2832          hrow.setAnchor(element.getPath());
2833          hrow.setColor(getRowColor(element, isConstraintMode));
2834          hrow.setLineColor(1);
2835          hrow.setIcon("icon_element.gif", HierarchicalTableGenerator.TEXT_ICON_ELEMENT);
2836          hrow.getCells().add(gen.new Cell(null, null, s+":All Slices", "", null));
2837          hrow.getCells().add(gen.new Cell());
2838          hrow.getCells().add(gen.new Cell());
2839          hrow.getCells().add(gen.new Cell());
2840          hrow.getCells().add(gen.new Cell(null, null, "Content/Rules for all slices", "", null));
2841          row.getSubRows().add(hrow);
2842          row = hrow;
2843        }
2844        if (typesRow != null && !children.isEmpty()) {
2845          // we've entered a typing slice; we're going to create a holder row for the all types children
2846          Row hrow = gen.new Row();
2847          hrow.setAnchor(element.getPath());
2848          hrow.setColor(getRowColor(element, isConstraintMode));
2849          hrow.setLineColor(1);
2850          hrow.setIcon("icon_element.gif", HierarchicalTableGenerator.TEXT_ICON_ELEMENT);
2851          hrow.getCells().add(gen.new Cell(null, null, s+":All Types", "", null));
2852          hrow.getCells().add(gen.new Cell());
2853          hrow.getCells().add(gen.new Cell());
2854          hrow.getCells().add(gen.new Cell());
2855          hrow.getCells().add(gen.new Cell(null, null, "Content/Rules for all Types", "", null));
2856          row.getSubRows().add(hrow);
2857          row = hrow;
2858        }
2859          
2860        Row currRow = row; 
2861        for (ElementDefinition child : children) {
2862          if (!child.hasSliceName())
2863            currRow = row; 
2864          if (logicalModel || !child.getPath().endsWith(".id") || (child.getPath().endsWith(".id") && (profile != null) && (profile.getDerivation() == TypeDerivationRule.CONSTRAINT)))  
2865            currRow = genElement(defPath, gen, currRow.getSubRows(), child, all, profiles, showMissing, profileBaseFileName, isExtension, snapshot, corePath, imagePath, false, logicalModel, isConstraintMode, allInvariants, currRow);
2866        }
2867//        if (!snapshot && (extensions == null || !extensions))
2868//          for (ElementDefinition child : children)
2869//            if (child.getPath().endsWith(".extension") || child.getPath().endsWith(".modifierExtension"))
2870//              genElement(defPath, gen, row.getSubRows(), child, all, profiles, showMissing, profileBaseFileName, true, false, corePath, imagePath, false, logicalModel, isConstraintMode, allInvariants);
2871      }
2872      if (typesRow != null) {
2873        makeChoiceRows(typesRow.getSubRows(), element, gen, corePath, profileBaseFileName);
2874      }
2875    }
2876    return slicingRow;
2877  }
2878
2879  private String listConstraintsAndConditions(ElementDefinition element) {
2880    CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
2881    for (ElementDefinitionConstraintComponent con : element.getConstraint()) {
2882      b.append(con.getKey());
2883    }
2884    for (IdType id : element.getCondition()) {
2885      b.append(id.asStringValue());
2886    }
2887    return b.toString();
2888  }
2889
2890
2891  private void makeChoiceRows(List<Row> subRows, ElementDefinition element, HierarchicalTableGenerator gen, String corePath, String profileBaseFileName) {
2892    // create a child for each choice
2893    for (TypeRefComponent tr : element.getType()) {
2894      Row choicerow = gen.new Row();
2895      String t = tr.getWorkingCode();
2896      if (isReference(t)) {
2897        choicerow.getCells().add(gen.new Cell(null, null, tail(element.getPath()).replace("[x]", Utilities.capitalize(t)), null, null));
2898        choicerow.getCells().add(gen.new Cell());
2899        choicerow.getCells().add(gen.new Cell(null, null, "", null, null));
2900        choicerow.setIcon("icon_reference.png", HierarchicalTableGenerator.TEXT_ICON_REFERENCE);
2901        Cell c = gen.new Cell();
2902        choicerow.getCells().add(c);
2903        if (ADD_REFERENCE_TO_TABLE) {
2904          if (tr.getWorkingCode().equals("canonical"))
2905            c.getPieces().add(gen.new Piece(corePath+"datatypes.html#canonical", "canonical", null));
2906          else
2907            c.getPieces().add(gen.new Piece(corePath+"references.html#Reference", "Reference", null));
2908          c.getPieces().add(gen.new Piece(null, "(", null));
2909        }
2910        boolean first = true;
2911        for (CanonicalType rt : tr.getTargetProfile()) {
2912          if (!first)
2913            c.getPieces().add(gen.new Piece(null, " | ", null));
2914          genTargetLink(gen, profileBaseFileName, corePath, c, tr, rt.getValue());
2915          first = false;
2916        }
2917        if (first)
2918          c.getPieces().add(gen.new Piece(null, "Any", null));
2919          
2920        if (ADD_REFERENCE_TO_TABLE) 
2921          c.getPieces().add(gen.new Piece(null, ")", null));
2922        
2923      } else {
2924        StructureDefinition sd = context.fetchTypeDefinition(t);
2925        if (sd.getKind() == StructureDefinitionKind.PRIMITIVETYPE) {
2926          choicerow.getCells().add(gen.new Cell(null, null, tail(element.getPath()).replace("[x]",  Utilities.capitalize(t)), sd.getDescription(), null));
2927          choicerow.getCells().add(gen.new Cell());
2928          choicerow.getCells().add(gen.new Cell(null, null, "", null, null));
2929          choicerow.setIcon("icon_primitive.png", HierarchicalTableGenerator.TEXT_ICON_PRIMITIVE);
2930          choicerow.getCells().add(gen.new Cell(null, corePath+"datatypes.html#"+t, t, null, null));
2931          //      } else if (definitions.getConstraints().contthnsKey(t)) {
2932          //        ProfiledType pt = definitions.getConstraints().get(t);
2933          //        choicerow.getCells().add(gen.new Cell(null, null, e.getName().replace("[x]", Utilities.capitalize(pt.getBaseType())), definitions.getTypes().containsKey(t) ? definitions.getTypes().get(t).getDefinition() : null, null));
2934          //        choicerow.getCells().add(gen.new Cell());
2935          //        choicerow.getCells().add(gen.new Cell(null, null, "", null, null));
2936          //        choicerow.setIcon("icon_datatype.gif", HierarchicalTableGenerator.TEXT_ICON_DATATYPE);
2937          //        choicerow.getCells().add(gen.new Cell(null, definitions.getSrcFile(t)+".html#"+t.replace("*", "open"), t, null, null));
2938        } else {
2939          choicerow.getCells().add(gen.new Cell(null, null, tail(element.getPath()).replace("[x]",  Utilities.capitalize(t)), sd.getDescription(), null));
2940          choicerow.getCells().add(gen.new Cell());
2941          choicerow.getCells().add(gen.new Cell(null, null, "", null, null));
2942          choicerow.setIcon("icon_datatype.gif", HierarchicalTableGenerator.TEXT_ICON_DATATYPE);
2943          choicerow.getCells().add(gen.new Cell(null, pkp.getLinkFor(corePath, t), t, null, null));
2944        }
2945        if (tr.hasProfile()) {
2946          Cell typeCell = choicerow.getCells().get(3);
2947          typeCell.addPiece(gen.new Piece(null, "(", null));
2948          boolean first = true;
2949          for (CanonicalType pt : tr.getProfile()) {
2950            if (first) first = false; else typeCell.addPiece(gen.new Piece(null, " | ", null));
2951            StructureDefinition psd = context.fetchResource(StructureDefinition.class, pt.getValue());
2952            if (psd == null)
2953              typeCell.addPiece(gen.new Piece(null, "??", null));
2954            else
2955              typeCell.addPiece(gen.new Piece(psd.getUserString("path"), psd.getName(), psd.present()));
2956            
2957          }
2958          typeCell.addPiece(gen.new Piece(null, ")", null));
2959        }
2960      }    
2961      choicerow.getCells().add(gen.new Cell());
2962      subRows.add(choicerow);
2963    }
2964  }
2965
2966  private boolean isReference(String t) {
2967    return t.equals("Reference") || t.equals("canonical"); 
2968  }  
2969
2970
2971
2972  private void genGridElement(String defPath, HierarchicalTableGenerator gen, List<Row> rows, ElementDefinition element, List<ElementDefinition> all, List<StructureDefinition> profiles, boolean showMissing, String profileBaseFileName, Boolean extensions, String corePath, String imagePath, boolean root, boolean isConstraintMode) throws IOException, FHIRException {
2973    StructureDefinition profile = profiles == null ? null : profiles.get(profiles.size()-1);
2974    String s = tail(element.getPath());
2975    List<ElementDefinition> children = getChildren(all, element);
2976    boolean isExtension = (s.equals("extension") || s.equals("modifierExtension"));
2977
2978    if (!onlyInformationIsMapping(all, element)) {
2979      Row row = gen.new Row();
2980      row.setAnchor(element.getPath());
2981      row.setColor(getRowColor(element, isConstraintMode));
2982      if (element.hasSlicing())
2983        row.setLineColor(1);
2984      else if (element.hasSliceName())
2985        row.setLineColor(2);
2986      else
2987        row.setLineColor(0);
2988      boolean hasDef = element != null;
2989      String ref = defPath == null ? null : defPath + element.getId();
2990      UnusedTracker used = new UnusedTracker();
2991      used.used = true;
2992      Cell left = gen.new Cell();
2993      if (element.getType().size() == 1 && element.getType().get(0).isPrimitive())
2994        left.getPieces().add(gen.new Piece(ref, "\u00A0\u00A0" + s, !hasDef ? null : gt(element.getDefinitionElement())).addStyle("font-weight:bold"));
2995      else
2996        left.getPieces().add(gen.new Piece(ref, "\u00A0\u00A0" + s, !hasDef ? null : gt(element.getDefinitionElement())));
2997      if (element.hasSliceName()) {
2998        left.getPieces().add(gen.new Piece("br"));
2999        String indent = StringUtils.repeat('\u00A0', 1+2*(element.getPath().split("\\.").length));
3000        left.getPieces().add(gen.new Piece(null, indent + "("+element.getSliceName() + ")", null));
3001      }
3002      row.getCells().add(left);
3003
3004      ExtensionContext extDefn = null;
3005      genCardinality(gen, element, row, hasDef, used, null);
3006      if (hasDef && !"0".equals(element.getMax()))
3007        genTypes(gen, row, element, profileBaseFileName, profile, corePath, imagePath);
3008      else
3009        row.getCells().add(gen.new Cell());
3010      generateGridDescription(gen, row, element, null, used.used, null, null, profile, corePath, imagePath, root, null);
3011/*      if (element.hasSlicing()) {
3012        if (standardExtensionSlicing(element)) {
3013          used.used = element.hasType() && element.getType().get(0).hasProfile();
3014          showMissing = false;
3015        } else {
3016          row.setIcon("icon_slice.png", HierarchicalTableGenerator.TEXT_ICON_SLICE);
3017          row.getCells().get(2).getPieces().clear();
3018          for (Cell cell : row.getCells())
3019            for (Piece p : cell.getPieces()) {
3020              p.addStyle("font-style: italic");
3021            }
3022        }
3023      }*/
3024      rows.add(row);
3025      for (ElementDefinition child : children)
3026        if (child.getMustSupport())
3027          genGridElement(defPath, gen, row.getSubRows(), child, all, profiles, showMissing, profileBaseFileName, isExtension, corePath, imagePath, false, isConstraintMode);
3028    }
3029  }
3030
3031
3032  private ExtensionContext locateExtension(Class<StructureDefinition> class1, String value)  {
3033    if (value.contains("#")) {
3034      StructureDefinition ext = context.fetchResource(StructureDefinition.class, value.substring(0, value.indexOf("#")));
3035      if (ext == null)
3036        return null;
3037      String tail = value.substring(value.indexOf("#")+1);
3038      ElementDefinition ed = null;
3039      for (ElementDefinition ted : ext.getSnapshot().getElement()) {
3040        if (tail.equals(ted.getSliceName())) {
3041          ed = ted;
3042          return new ExtensionContext(ext, ed);
3043        }
3044      }
3045      return null;
3046    } else {
3047      StructureDefinition ext = context.fetchResource(StructureDefinition.class, value);
3048      if (ext == null)
3049        return null;
3050      else 
3051        return new ExtensionContext(ext, ext.getSnapshot().getElement().get(0));
3052    }
3053  }
3054
3055
3056  private boolean extensionIsComplex(String value) {
3057    if (value.contains("#")) {
3058      StructureDefinition ext = context.fetchResource(StructureDefinition.class, value.substring(0, value.indexOf("#")));
3059    if (ext == null)
3060      return false;
3061      String tail = value.substring(value.indexOf("#")+1);
3062      ElementDefinition ed = null;
3063      for (ElementDefinition ted : ext.getSnapshot().getElement()) {
3064        if (tail.equals(ted.getSliceName())) {
3065          ed = ted;
3066          break;
3067        }
3068      }
3069      if (ed == null)
3070        return false;
3071      int i = ext.getSnapshot().getElement().indexOf(ed);
3072      int j = i+1;
3073      while (j < ext.getSnapshot().getElement().size() && !ext.getSnapshot().getElement().get(j).getPath().equals(ed.getPath()))
3074        j++;
3075      return j - i > 5;
3076    } else {
3077      StructureDefinition ext = context.fetchResource(StructureDefinition.class, value);
3078      return ext != null && ext.getSnapshot().getElement().size() > 5;
3079    }
3080  }
3081
3082
3083  private String getRowColor(ElementDefinition element, boolean isConstraintMode) {
3084    switch (element.getUserInt(UD_ERROR_STATUS)) {
3085    case STATUS_HINT: return ROW_COLOR_HINT;
3086    case STATUS_WARNING: return ROW_COLOR_WARNING;
3087    case STATUS_ERROR: return ROW_COLOR_ERROR;
3088    case STATUS_FATAL: return ROW_COLOR_FATAL;
3089    }
3090    if (isConstraintMode && !element.getMustSupport() && !element.getIsModifier() && element.getPath().contains("."))
3091      return null; // ROW_COLOR_NOT_MUST_SUPPORT;
3092    else
3093      return null;
3094  }
3095
3096
3097  private String urltail(String path) {
3098    if (path.contains("#"))
3099      return path.substring(path.lastIndexOf('#')+1);
3100    if (path.contains("/"))
3101      return path.substring(path.lastIndexOf('/')+1);
3102    else
3103      return path;
3104
3105  }
3106
3107  private boolean standardExtensionSlicing(ElementDefinition element) {
3108    String t = tail(element.getPath());
3109    return (t.equals("extension") || t.equals("modifierExtension"))
3110          && element.getSlicing().getRules() != SlicingRules.CLOSED && element.getSlicing().getDiscriminator().size() == 1 && element.getSlicing().getDiscriminator().get(0).getPath().equals("url") && element.getSlicing().getDiscriminator().get(0).getType().equals(DiscriminatorType.VALUE);
3111  }
3112
3113  private Cell generateDescription(HierarchicalTableGenerator gen, Row row, ElementDefinition definition, ElementDefinition fallback, boolean used, String baseURL, String url, StructureDefinition profile, String corePath, String imagePath, boolean root, boolean logicalModel, boolean allInvariants, boolean snapshot) throws IOException, FHIRException {
3114    return generateDescription(gen, row, definition, fallback, used, baseURL, url, profile, corePath, imagePath, root, logicalModel, allInvariants, null, snapshot);
3115  }
3116  
3117  private Cell generateDescription(HierarchicalTableGenerator gen, Row row, ElementDefinition definition, ElementDefinition fallback, boolean used, String baseURL, String url, StructureDefinition profile, String corePath, String imagePath, boolean root, boolean logicalModel, boolean allInvariants, ElementDefinition valueDefn, boolean snapshot) throws IOException, FHIRException {
3118    Cell c = gen.new Cell();
3119    row.getCells().add(c);
3120
3121    if (used) {
3122      if (logicalModel && ToolingExtensions.hasExtension(profile, "http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace")) {
3123        if (root) {
3124          c.getPieces().add(gen.new Piece(null, translate("sd.table", "XML Namespace")+": ", null).addStyle("font-weight:bold"));
3125          c.getPieces().add(gen.new Piece(null, ToolingExtensions.readStringExtension(profile, "http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace"), null));        
3126        } else if (!root && ToolingExtensions.hasExtension(definition, "http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace") && 
3127            !ToolingExtensions.readStringExtension(definition, "http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace").equals(ToolingExtensions.readStringExtension(profile, "http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace"))) {
3128          c.getPieces().add(gen.new Piece(null, translate("sd.table", "XML Namespace")+": ", null).addStyle("font-weight:bold"));
3129          c.getPieces().add(gen.new Piece(null, ToolingExtensions.readStringExtension(definition, "http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace"), null));        
3130        }
3131      }
3132      
3133      if (definition.hasContentReference()) {
3134        ElementDefinition ed = getElementByName(profile.getSnapshot().getElement(), definition.getContentReference());
3135        if (ed == null)
3136          c.getPieces().add(gen.new Piece(null, translate("sd.table", "Unknown reference to %s", definition.getContentReference()), null));
3137        else
3138          c.getPieces().add(gen.new Piece("#"+ed.getPath(), translate("sd.table", "See %s", ed.getPath()), null));
3139      }
3140      if (definition.getPath().endsWith("url") && definition.hasFixed()) {
3141        c.getPieces().add(checkForNoChange(definition.getFixed(), gen.new Piece(null, "\""+buildJson(definition.getFixed())+"\"", null).addStyle("color: darkgreen")));
3142      } else {
3143        if (definition != null && definition.hasShort()) {
3144          if (!c.getPieces().isEmpty()) c.addPiece(gen.new Piece("br"));
3145          c.addPiece(checkForNoChange(definition.getShortElement(), gen.new Piece(null, gt(definition.getShortElement()), null)));
3146        } else if (fallback != null && fallback.hasShort()) {
3147          if (!c.getPieces().isEmpty()) c.addPiece(gen.new Piece("br"));
3148          c.addPiece(checkForNoChange(fallback.getShortElement(), gen.new Piece(null, gt(fallback.getShortElement()), null)));
3149        }
3150        if (url != null) {
3151          if (!c.getPieces().isEmpty()) 
3152            c.addPiece(gen.new Piece("br"));
3153          String fullUrl = url.startsWith("#") ? baseURL+url : url;
3154          StructureDefinition ed = context.fetchResource(StructureDefinition.class, url);
3155          String ref = null;
3156          String ref2 = null;
3157          String fixedUrl = null;
3158          if (ed != null) {
3159            String p = ed.getUserString("path");
3160            if (p != null) {
3161              ref = p.startsWith("http:") || igmode ? p : Utilities.pathURL(corePath, p);
3162            }             
3163            fixedUrl = getFixedUrl(ed);
3164            if (fixedUrl != null) {// if its null, we guess that it's not a profiled extension? 
3165              if (fixedUrl.equals(url))
3166                fixedUrl = null;
3167              else {
3168                StructureDefinition ed2 = context.fetchResource(StructureDefinition.class, fixedUrl);
3169                if (ed2 != null) {
3170                  String p2 = ed2.getUserString("path");
3171                  if (p2 != null) {
3172                    ref2 = p2.startsWith("http:") || igmode ? p2 : Utilities.pathURL(corePath, p2);
3173                  }                              
3174                }
3175              }
3176            }
3177          }
3178          if (fixedUrl == null) {
3179            c.getPieces().add(gen.new Piece(null, translate("sd.table", "URL")+": ", null).addStyle("font-weight:bold"));
3180            c.getPieces().add(gen.new Piece(ref, fullUrl, null));
3181          } else { 
3182            // reference to a profile take on the extension show the base URL
3183            c.getPieces().add(gen.new Piece(null, translate("sd.table", "URL")+": ", null).addStyle("font-weight:bold"));
3184            c.getPieces().add(gen.new Piece(ref2, fixedUrl, null));
3185            c.getPieces().add(gen.new Piece(null, translate("sd.table", " profiled by ")+" ", null).addStyle("font-weight:bold"));
3186            c.getPieces().add(gen.new Piece(ref, fullUrl, null));
3187          
3188          }
3189        }
3190
3191        if (definition.hasSlicing()) {
3192          if (!c.getPieces().isEmpty()) c.addPiece(gen.new Piece("br"));
3193          c.getPieces().add(gen.new Piece(null, translate("sd.table", "Slice")+": ", null).addStyle("font-weight:bold"));
3194          c.getPieces().add(gen.new Piece(null, describeSlice(definition.getSlicing()), null));
3195        }
3196        if (definition != null) {
3197          ElementDefinitionBindingComponent binding = null;
3198          if (valueDefn != null && valueDefn.hasBinding() && !valueDefn.getBinding().isEmpty())
3199            binding = valueDefn.getBinding();
3200          else if (definition.hasBinding())
3201            binding = definition.getBinding();
3202          if (binding!=null && !binding.isEmpty()) {
3203            if (!c.getPieces().isEmpty()) 
3204              c.addPiece(gen.new Piece("br"));
3205            BindingResolution br = pkp.resolveBinding(profile, binding, definition.getPath());
3206            c.getPieces().add(checkForNoChange(binding, gen.new Piece(null, translate("sd.table", "Binding")+": ", null).addStyle("font-weight:bold")));
3207            c.getPieces().add(checkForNoChange(binding, gen.new Piece(br.url == null ? null : Utilities.isAbsoluteUrl(br.url) || !pkp.prependLinks() ? br.url : corePath+br.url, br.display, null)));
3208            if (binding.hasStrength()) {
3209              c.getPieces().add(checkForNoChange(binding, gen.new Piece(null, " (", null)));
3210              c.getPieces().add(checkForNoChange(binding, gen.new Piece(corePath+"terminologies.html#"+binding.getStrength().toCode(), egt(binding.getStrengthElement()), binding.getStrength().getDefinition())));
3211              
3212              c.getPieces().add(gen.new Piece(null, ")", null));
3213            }
3214            if (binding.hasExtension(ToolingExtensions.EXT_MAX_VALUESET)) {
3215              br = pkp.resolveBinding(profile, ToolingExtensions.readStringExtension(binding, ToolingExtensions.EXT_MAX_VALUESET), definition.getPath());
3216              c.addPiece(gen.new Piece("br"));
3217              c.getPieces().add(checkForNoChange(binding, gen.new Piece(corePath+"extension-elementdefinition-maxvalueset.html", translate("sd.table", "Max Binding")+": ", "Max Value Set Extension").addStyle("font-weight:bold")));             
3218              c.getPieces().add(checkForNoChange(binding, gen.new Piece(br.url == null ? null : Utilities.isAbsoluteUrl(br.url) || !pkp.prependLinks() ? br.url : corePath+br.url, br.display, null)));
3219            }
3220            if (binding.hasExtension(ToolingExtensions.EXT_MIN_VALUESET)) {
3221              br = pkp.resolveBinding(profile, ToolingExtensions.readStringExtension(binding, ToolingExtensions.EXT_MIN_VALUESET), definition.getPath());
3222              c.addPiece(gen.new Piece("br"));
3223              c.getPieces().add(checkForNoChange(binding, gen.new Piece(corePath+"extension-elementdefinition-minvalueset.html", translate("sd.table", "Min Binding")+": ", "Min Value Set Extension").addStyle("font-weight:bold")));             
3224              c.getPieces().add(checkForNoChange(binding, gen.new Piece(br.url == null ? null : Utilities.isAbsoluteUrl(br.url) || !pkp.prependLinks() ? br.url : corePath+br.url, br.display, null)));
3225            }
3226          }
3227          for (ElementDefinitionConstraintComponent inv : definition.getConstraint()) {
3228            if (!inv.hasSource() || allInvariants) {
3229              if (!c.getPieces().isEmpty()) 
3230                c.addPiece(gen.new Piece("br"));
3231              c.getPieces().add(checkForNoChange(inv, gen.new Piece(null, inv.getKey()+": ", null).addStyle("font-weight:bold")));
3232              c.getPieces().add(checkForNoChange(inv, gen.new Piece(null, gt(inv.getHumanElement()), null)));
3233            }
3234          }
3235          if ((definition.hasBase() && definition.getBase().getMax().equals("*")) || (definition.hasMax() && definition.getMax().equals("*"))) {
3236            if (c.getPieces().size() > 0)
3237              c.addPiece(gen.new Piece("br"));
3238            if (definition.hasOrderMeaning()) {
3239              c.getPieces().add(gen.new Piece(null, "This repeating element order: "+definition.getOrderMeaning(), null));
3240            } else {
3241              // don't show this, this it's important: c.getPieces().add(gen.new Piece(null, "This repeating element has no defined order", null));
3242            }           
3243          }
3244
3245          if (definition.hasFixed()) {
3246            if (!c.getPieces().isEmpty()) c.addPiece(gen.new Piece("br"));
3247            c.getPieces().add(checkForNoChange(definition.getFixed(), gen.new Piece(null, translate("sd.table", "Fixed Value")+": ", null).addStyle("font-weight:bold")));
3248            if (!useTableForFixedValues || definition.getFixed().isPrimitive()) {
3249              String s = buildJson(definition.getFixed());
3250              String link = null;
3251              if (Utilities.isAbsoluteUrl(s))
3252                link = pkp.getLinkForUrl(corePath, s);
3253              c.getPieces().add(checkForNoChange(definition.getFixed(), gen.new Piece(link, s, null).addStyle("color: darkgreen")));
3254            } else {
3255              c.getPieces().add(checkForNoChange(definition.getFixed(), gen.new Piece(null, "As shown", null).addStyle("color: darkgreen")));
3256              genFixedValue(gen, row, definition.getFixed(), snapshot, false, corePath);              
3257            }
3258            if (isCoded(definition.getFixed()) && !hasDescription(definition.getFixed())) {
3259              Piece p = describeCoded(gen, definition.getFixed());
3260              if (p != null)
3261                c.getPieces().add(p);
3262            }
3263          } else if (definition.hasPattern()) {
3264            if (!c.getPieces().isEmpty()) c.addPiece(gen.new Piece("br"));
3265            c.getPieces().add(checkForNoChange(definition.getPattern(), gen.new Piece(null, translate("sd.table", "Required Pattern")+": ", null).addStyle("font-weight:bold")));
3266            if (!useTableForFixedValues || definition.getPattern().isPrimitive())
3267              c.getPieces().add(checkForNoChange(definition.getPattern(), gen.new Piece(null, buildJson(definition.getPattern()), null).addStyle("color: darkgreen")));
3268            else {
3269              c.getPieces().add(checkForNoChange(definition.getPattern(), gen.new Piece(null, "At least the following", null).addStyle("color: darkgreen")));
3270              genFixedValue(gen, row, definition.getPattern(), snapshot, true, corePath);
3271            }
3272          } else if (definition.hasExample()) {
3273            for (ElementDefinitionExampleComponent ex : definition.getExample()) {
3274              if (!c.getPieces().isEmpty()) c.addPiece(gen.new Piece("br"));
3275              c.getPieces().add(checkForNoChange(ex, gen.new Piece(null, translate("sd.table", "Example")+("".equals("General")? "" : " "+ex.getLabel())+": ", null).addStyle("font-weight:bold")));
3276              c.getPieces().add(checkForNoChange(ex, gen.new Piece(null, buildJson(ex.getValue()), null).addStyle("color: darkgreen")));
3277            }
3278          }
3279          if (definition.hasMaxLength() && definition.getMaxLength()!=0) {
3280            if (!c.getPieces().isEmpty()) c.addPiece(gen.new Piece("br"));
3281            c.getPieces().add(checkForNoChange(definition.getMaxLengthElement(), gen.new Piece(null, "Max Length: ", null).addStyle("font-weight:bold")));
3282            c.getPieces().add(checkForNoChange(definition.getMaxLengthElement(), gen.new Piece(null, Integer.toString(definition.getMaxLength()), null).addStyle("color: darkgreen")));
3283          }
3284          if (profile != null) {
3285            for (StructureDefinitionMappingComponent md : profile.getMapping()) {
3286              if (md.hasExtension(ToolingExtensions.EXT_TABLE_NAME)) {
3287                ElementDefinitionMappingComponent map = null;
3288                for (ElementDefinitionMappingComponent m : definition.getMapping()) 
3289                  if (m.getIdentity().equals(md.getIdentity()))
3290                    map = m;
3291                if (map != null) {
3292                  for (int i = 0; i<definition.getMapping().size(); i++){
3293                    c.addPiece(gen.new Piece("br"));
3294                    c.getPieces().add(gen.new Piece(null, ToolingExtensions.readStringExtension(md, ToolingExtensions.EXT_TABLE_NAME)+": " + map.getMap(), null));
3295                  }
3296                }
3297              }
3298            }
3299          }
3300        }
3301      }
3302    }
3303    return c;
3304  }
3305
3306  private void genFixedValue(HierarchicalTableGenerator gen, Row erow, Type value, boolean snapshot, boolean pattern, String corePath) {
3307    String ref = pkp.getLinkFor(corePath, value.fhirType());
3308    if (ref != null) {
3309      ref = ref.substring(0, ref.indexOf(".html"))+"-definitions.html#";
3310    } else {
3311      ref = "??";
3312    }
3313    StructureDefinition sd = context.fetchTypeDefinition(value.fhirType());
3314    
3315    for (org.hl7.fhir.r5.model.Property t : value.children()) {
3316      if (t.getValues().size() > 0 || snapshot) {
3317        ElementDefinition ed = findElementDefinition(sd, t.getName());
3318        if (t.getValues().size() == 0 || (t.getValues().size() == 1 && t.getValues().get(0).isEmpty())) {
3319          Row row = gen.new Row();
3320          erow.getSubRows().add(row);
3321          Cell c = gen.new Cell();
3322          row.getCells().add(c);
3323          c.addPiece(gen.new Piece((ed.getBase().getPath().equals(ed.getPath()) ? ref+ed.getPath() : corePath+"element-definitions.html#"+ed.getBase().getPath()), t.getName(), null));
3324          c = gen.new Cell();
3325          row.getCells().add(c);
3326          c.addPiece(gen.new Piece(null, null, null));
3327          c = gen.new Cell();
3328          row.getCells().add(c);
3329          if (!pattern) {
3330            c.addPiece(gen.new Piece(null, "0..0", null));
3331            row.setIcon("icon_fixed.gif", "Fixed Value" /*HierarchicalTableGenerator.TEXT_ICON_FIXED*/);
3332          } else if (isPrimitive(t.getTypeCode())) {
3333            row.setIcon("icon_primitive.png", HierarchicalTableGenerator.TEXT_ICON_PRIMITIVE);
3334            c.addPiece(gen.new Piece(null, "0.."+(t.getMaxCardinality() == 2147483647 ? "*": Integer.toString(t.getMaxCardinality())), null));
3335          } else if (isReference(t.getTypeCode())) { 
3336            row.setIcon("icon_reference.png", HierarchicalTableGenerator.TEXT_ICON_REFERENCE);
3337            c.addPiece(gen.new Piece(null, "0.."+(t.getMaxCardinality() == 2147483647 ? "*": Integer.toString(t.getMaxCardinality())), null));
3338          } else { 
3339            row.setIcon("icon_datatype.gif", HierarchicalTableGenerator.TEXT_ICON_DATATYPE);
3340            c.addPiece(gen.new Piece(null, "0.."+(t.getMaxCardinality() == 2147483647 ? "*": Integer.toString(t.getMaxCardinality())), null));
3341          }
3342          c = gen.new Cell();
3343          row.getCells().add(c);
3344          if (t.getTypeCode().contains("(")) {
3345            String tc = t.getTypeCode();
3346            String tn = tc.substring(0, tc.indexOf("("));
3347            c.addPiece(gen.new Piece(pkp.getLinkFor(corePath, tn), tn, null));
3348            c.addPiece(gen.new Piece(null, "(", null));
3349            String[] p = tc.substring(tc.indexOf("(")+1, tc.indexOf(")")).split("\\|");
3350            for (String s : p) {
3351              c.addPiece(gen.new Piece(pkp.getLinkFor(corePath, s), s, null));
3352            }
3353            c.addPiece(gen.new Piece(null, ")", null));            
3354          } else {
3355            c.addPiece(gen.new Piece(pkp.getLinkFor(corePath, t.getTypeCode()), t.getTypeCode(), null));
3356          }
3357          c = gen.new Cell();
3358          c.addPiece(gen.new Piece(null, ed.getShort(), null));
3359          row.getCells().add(c);
3360        } else {
3361          for (Base b : t.getValues()) {
3362            Row row = gen.new Row();
3363            erow.getSubRows().add(row);
3364            row.setIcon("icon_fixed.gif", "Fixed Value" /*HierarchicalTableGenerator.TEXT_ICON_FIXED*/);
3365
3366            Cell c = gen.new Cell();
3367            row.getCells().add(c);
3368            c.addPiece(gen.new Piece((ed.getBase().getPath().equals(ed.getPath()) ? ref+ed.getPath() : corePath+"element-definitions.html#"+ed.getBase().getPath()), t.getName(), null));
3369
3370            c = gen.new Cell();
3371            row.getCells().add(c);
3372            c.addPiece(gen.new Piece(null, null, null));
3373
3374            c = gen.new Cell();
3375            row.getCells().add(c);
3376            if (pattern)
3377              c.addPiece(gen.new Piece(null, "1.."+(t.getMaxCardinality() == 2147483647 ? "*" : Integer.toString(t.getMaxCardinality())), null));
3378            else
3379              c.addPiece(gen.new Piece(null, "1..1", null));
3380
3381            c = gen.new Cell();
3382            row.getCells().add(c);
3383            if (b.fhirType().contains("(")) {
3384              String tc = b.fhirType();
3385              String tn = tc.substring(0, tc.indexOf("("));
3386              c.addPiece(gen.new Piece(pkp.getLinkFor(corePath, tn), tn, null));
3387              c.addPiece(gen.new Piece(null, "(", null));
3388              String[] p = tc.substring(tc.indexOf("(")+1, tc.indexOf(")")).split("\\|");
3389              for (String s : p) {
3390                c.addPiece(gen.new Piece(pkp.getLinkFor(corePath, s), s, null));
3391              }
3392              c.addPiece(gen.new Piece(null, ")", null));            
3393            } else {
3394              c.addPiece(gen.new Piece(pkp.getLinkFor(corePath, b.fhirType()), b.fhirType(), null));
3395            }
3396
3397            if (b.isPrimitive()) {
3398              c = gen.new Cell();
3399              row.getCells().add(c);
3400              c.addPiece(gen.new Piece(null, ed.getShort(), null));
3401              c.addPiece(gen.new Piece("br"));
3402              c.getPieces().add(gen.new Piece(null, "Fixed Value: ", null).addStyle("font-weight: bold"));
3403              String s = b.primitiveValue();
3404              // ok. let's see if we can find a relevant link for this
3405              String link = null;
3406              if (Utilities.isAbsoluteUrl(s))
3407                link = pkp.getLinkForUrl(corePath, s);
3408              c.getPieces().add(gen.new Piece(link, s, null).addStyle("color: darkgreen"));
3409            } else {
3410              c = gen.new Cell();
3411              row.getCells().add(c);
3412              c.addPiece(gen.new Piece(null, ed.getShort(), null));
3413              c.addPiece(gen.new Piece("br"));
3414              c.getPieces().add(gen.new Piece(null, "Fixed Value: ", null).addStyle("font-weight: bold"));
3415              c.getPieces().add(gen.new Piece(null, "(complex)", null).addStyle("color: darkgreen"));
3416              genFixedValue(gen, row, (Type) b, snapshot, pattern, corePath);
3417            }
3418          }
3419        }
3420      }
3421    }
3422  }
3423
3424
3425  private ElementDefinition findElementDefinition(StructureDefinition sd, String name) {
3426    String path = sd.getType()+"."+name;
3427    for (ElementDefinition ed : sd.getSnapshot().getElement()) {
3428      if (ed.getPath().equals(path))
3429        return ed;
3430    }
3431    throw new FHIRException("Unable to find element "+path);
3432  }
3433
3434
3435  private String getFixedUrl(StructureDefinition sd) {
3436    for (ElementDefinition ed : sd.getSnapshot().getElement()) {
3437      if (ed.getPath().equals("Extension.url")) {
3438        if (ed.hasFixed() && ed.getFixed() instanceof UriType)
3439          return ed.getFixed().primitiveValue();
3440      }
3441    }
3442    return null;
3443  }
3444
3445
3446  private Piece describeCoded(HierarchicalTableGenerator gen, Type fixed) {
3447    if (fixed instanceof Coding) {
3448      Coding c = (Coding) fixed;
3449      ValidationResult vr = context.validateCode(terminologyServiceOptions , c.getSystem(), c.getCode(), c.getDisplay());
3450      if (vr.getDisplay() != null)
3451        return gen.new Piece(null, " ("+vr.getDisplay()+")", null).addStyle("color: darkgreen");
3452    } else if (fixed instanceof CodeableConcept) {
3453      CodeableConcept cc = (CodeableConcept) fixed;
3454      for (Coding c : cc.getCoding()) {
3455        ValidationResult vr = context.validateCode(terminologyServiceOptions, c.getSystem(), c.getCode(), c.getDisplay());
3456        if (vr.getDisplay() != null)
3457          return gen.new Piece(null, " ("+vr.getDisplay()+")", null).addStyle("color: darkgreen");
3458      }
3459    }
3460    return null;
3461  }
3462
3463
3464  private boolean hasDescription(Type fixed) {
3465    if (fixed instanceof Coding) {
3466      return ((Coding) fixed).hasDisplay();
3467    } else if (fixed instanceof CodeableConcept) {
3468      CodeableConcept cc = (CodeableConcept) fixed;
3469      if (cc.hasText())
3470        return true;
3471      for (Coding c : cc.getCoding())
3472        if (c.hasDisplay())
3473         return true;
3474    } // (fixed instanceof CodeType) || (fixed instanceof Quantity);
3475    return false;
3476  }
3477
3478
3479  private boolean isCoded(Type fixed) {
3480    return (fixed instanceof Coding) || (fixed instanceof CodeableConcept) || (fixed instanceof CodeType) || (fixed instanceof Quantity);
3481  }
3482
3483
3484  private Cell generateGridDescription(HierarchicalTableGenerator gen, Row row, ElementDefinition definition, ElementDefinition fallback, boolean used, String baseURL, String url, StructureDefinition profile, String corePath, String imagePath, boolean root, ElementDefinition valueDefn) throws IOException, FHIRException {
3485    Cell c = gen.new Cell();
3486    row.getCells().add(c);
3487
3488    if (used) {
3489      if (definition.hasContentReference()) {
3490        ElementDefinition ed = getElementByName(profile.getSnapshot().getElement(), definition.getContentReference());
3491        if (ed == null)
3492          c.getPieces().add(gen.new Piece(null, "Unknown reference to "+definition.getContentReference(), null));
3493        else
3494          c.getPieces().add(gen.new Piece("#"+ed.getPath(), "See "+ed.getPath(), null));
3495      }
3496      if (definition.getPath().endsWith("url") && definition.hasFixed()) {
3497        c.getPieces().add(checkForNoChange(definition.getFixed(), gen.new Piece(null, "\""+buildJson(definition.getFixed())+"\"", null).addStyle("color: darkgreen")));
3498      } else {
3499        if (url != null) {
3500          if (!c.getPieces().isEmpty()) 
3501            c.addPiece(gen.new Piece("br"));
3502          String fullUrl = url.startsWith("#") ? baseURL+url : url;
3503          StructureDefinition ed = context.fetchResource(StructureDefinition.class, url);
3504          String ref = null;
3505          if (ed != null) {
3506            String p = ed.getUserString("path");
3507            if (p != null) {
3508              ref = p.startsWith("http:") || igmode ? p : Utilities.pathURL(corePath, p);
3509            }
3510          }
3511          c.getPieces().add(gen.new Piece(null, "URL: ", null).addStyle("font-weight:bold"));
3512          c.getPieces().add(gen.new Piece(ref, fullUrl, null));
3513        }
3514
3515        if (definition.hasSlicing()) {
3516          if (!c.getPieces().isEmpty()) c.addPiece(gen.new Piece("br"));
3517          c.getPieces().add(gen.new Piece(null, "Slice: ", null).addStyle("font-weight:bold"));
3518          c.getPieces().add(gen.new Piece(null, describeSlice(definition.getSlicing()), null));
3519        }
3520        if (definition != null) {
3521          ElementDefinitionBindingComponent binding = null;
3522          if (valueDefn != null && valueDefn.hasBinding() && !valueDefn.getBinding().isEmpty())
3523            binding = valueDefn.getBinding();
3524          else if (definition.hasBinding())
3525            binding = definition.getBinding();
3526          if (binding!=null && !binding.isEmpty()) {
3527            if (!c.getPieces().isEmpty()) 
3528              c.addPiece(gen.new Piece("br"));
3529            BindingResolution br = pkp.resolveBinding(profile, binding, definition.getPath());
3530            c.getPieces().add(checkForNoChange(binding, gen.new Piece(null, "Binding: ", null).addStyle("font-weight:bold")));
3531            c.getPieces().add(checkForNoChange(binding, gen.new Piece(br.url == null ? null : Utilities.isAbsoluteUrl(br.url) || !pkp.prependLinks() ? br.url : corePath+br.url, br.display, null)));
3532            if (binding.hasStrength()) {
3533              c.getPieces().add(checkForNoChange(binding, gen.new Piece(null, " (", null)));
3534              c.getPieces().add(checkForNoChange(binding, gen.new Piece(corePath+"terminologies.html#"+binding.getStrength().toCode(), binding.getStrength().toCode(), binding.getStrength().getDefinition())));              c.getPieces().add(gen.new Piece(null, ")", null));
3535            }
3536          }
3537          for (ElementDefinitionConstraintComponent inv : definition.getConstraint()) {
3538            if (!c.getPieces().isEmpty()) c.addPiece(gen.new Piece("br"));
3539            c.getPieces().add(checkForNoChange(inv, gen.new Piece(null, inv.getKey()+": ", null).addStyle("font-weight:bold")));
3540            c.getPieces().add(checkForNoChange(inv, gen.new Piece(null, inv.getHuman(), null)));
3541          }
3542          if (definition.hasFixed()) {
3543            if (!c.getPieces().isEmpty()) c.addPiece(gen.new Piece("br"));
3544            c.getPieces().add(checkForNoChange(definition.getFixed(), gen.new Piece(null, "Fixed Value: ", null).addStyle("font-weight:bold")));
3545            String s = buildJson(definition.getFixed());
3546            String link = null;
3547            if (Utilities.isAbsoluteUrl(s))
3548              link = pkp.getLinkForUrl(corePath, s);
3549            c.getPieces().add(checkForNoChange(definition.getFixed(), gen.new Piece(link, s, null).addStyle("color: darkgreen")));
3550          } else if (definition.hasPattern()) {
3551            if (!c.getPieces().isEmpty()) c.addPiece(gen.new Piece("br"));
3552            c.getPieces().add(checkForNoChange(definition.getPattern(), gen.new Piece(null, "Required Pattern: ", null).addStyle("font-weight:bold")));
3553            c.getPieces().add(checkForNoChange(definition.getPattern(), gen.new Piece(null, buildJson(definition.getPattern()), null).addStyle("color: darkgreen")));
3554          } else if (definition.hasExample()) {
3555            for (ElementDefinitionExampleComponent ex : definition.getExample()) {
3556              if (!c.getPieces().isEmpty()) c.addPiece(gen.new Piece("br"));
3557              c.getPieces().add(checkForNoChange(ex, gen.new Piece(null, "Example'"+("".equals("General")? "" : " "+ex.getLabel()+"'")+": ", null).addStyle("font-weight:bold")));
3558              c.getPieces().add(checkForNoChange(ex, gen.new Piece(null, buildJson(ex.getValue()), null).addStyle("color: darkgreen")));
3559            }
3560          }
3561          if (definition.hasMaxLength() && definition.getMaxLength()!=0) {
3562            if (!c.getPieces().isEmpty()) c.addPiece(gen.new Piece("br"));
3563            c.getPieces().add(checkForNoChange(definition.getMaxLengthElement(), gen.new Piece(null, "Max Length: ", null).addStyle("font-weight:bold")));
3564            c.getPieces().add(checkForNoChange(definition.getMaxLengthElement(), gen.new Piece(null, Integer.toString(definition.getMaxLength()), null).addStyle("color: darkgreen")));
3565          }
3566          if (profile != null) {
3567            for (StructureDefinitionMappingComponent md : profile.getMapping()) {
3568              if (md.hasExtension(ToolingExtensions.EXT_TABLE_NAME)) {
3569                ElementDefinitionMappingComponent map = null;
3570                for (ElementDefinitionMappingComponent m : definition.getMapping()) 
3571                  if (m.getIdentity().equals(md.getIdentity()))
3572                    map = m;
3573                if (map != null) {
3574                  for (int i = 0; i<definition.getMapping().size(); i++){
3575                    c.addPiece(gen.new Piece("br"));
3576                    c.getPieces().add(gen.new Piece(null, ToolingExtensions.readStringExtension(md, ToolingExtensions.EXT_TABLE_NAME)+": " + map.getMap(), null));
3577                  }
3578                }
3579              }
3580            }
3581          }
3582          if (definition.hasDefinition()) {
3583            if (!c.getPieces().isEmpty()) c.addPiece(gen.new Piece("br"));
3584            c.getPieces().add(gen.new Piece(null, "Definition: ", null).addStyle("font-weight:bold"));
3585            c.addPiece(gen.new Piece("br"));
3586            c.addMarkdown(definition.getDefinition());
3587//            c.getPieces().add(checkForNoChange(definition.getCommentElement(), gen.new Piece(null, definition.getComment(), null)));
3588          }
3589          if (definition.getComment()!=null) {
3590            if (!c.getPieces().isEmpty()) c.addPiece(gen.new Piece("br"));
3591            c.getPieces().add(gen.new Piece(null, "Comments: ", null).addStyle("font-weight:bold"));
3592            c.addPiece(gen.new Piece("br"));
3593            c.addMarkdown(definition.getComment());
3594//            c.getPieces().add(checkForNoChange(definition.getCommentElement(), gen.new Piece(null, definition.getComment(), null)));
3595          }
3596        }
3597      }
3598    }
3599    return c;
3600  }
3601
3602
3603
3604  private String buildJson(Type value) throws IOException {
3605    if (value instanceof PrimitiveType)
3606      return ((PrimitiveType) value).asStringValue();
3607
3608    IParser json = context.newJsonParser();
3609    return json.composeString(value, null);
3610  }
3611
3612
3613  public String describeSlice(ElementDefinitionSlicingComponent slicing) {
3614    return translate("sd.table", "%s, %s by %s", slicing.getOrdered() ? translate("sd.table", "Ordered") : translate("sd.table", "Unordered"), describe(slicing.getRules()), commas(slicing.getDiscriminator()));
3615  }
3616
3617  private String commas(List<ElementDefinitionSlicingDiscriminatorComponent> list) {
3618    CommaSeparatedStringBuilder c = new CommaSeparatedStringBuilder();
3619    for (ElementDefinitionSlicingDiscriminatorComponent id : list)
3620      c.append(id.getType().toCode()+":"+id.getPath());
3621    return c.toString();
3622  }
3623
3624
3625  private String describe(SlicingRules rules) {
3626    if (rules == null)
3627      return translate("sd.table", "Unspecified");
3628    switch (rules) {
3629    case CLOSED : return translate("sd.table", "Closed");
3630    case OPEN : return translate("sd.table", "Open");
3631    case OPENATEND : return translate("sd.table", "Open At End");
3632    default:
3633      return "??";
3634    }
3635  }
3636
3637  private boolean onlyInformationIsMapping(List<ElementDefinition> list, ElementDefinition e) {
3638    return (!e.hasSliceName() && !e.hasSlicing() && (onlyInformationIsMapping(e))) &&
3639        getChildren(list, e).isEmpty();
3640  }
3641
3642  private boolean onlyInformationIsMapping(ElementDefinition d) {
3643    return !d.hasShort() && !d.hasDefinition() &&
3644        !d.hasRequirements() && !d.getAlias().isEmpty() && !d.hasMinElement() &&
3645        !d.hasMax() && !d.getType().isEmpty() && !d.hasContentReference() &&
3646        !d.hasExample() && !d.hasFixed() && !d.hasMaxLengthElement() &&
3647        !d.getCondition().isEmpty() && !d.getConstraint().isEmpty() && !d.hasMustSupportElement() &&
3648        !d.hasBinding();
3649  }
3650
3651  private boolean allAreReference(List<TypeRefComponent> types) {
3652    for (TypeRefComponent t : types) {
3653      if (!t.hasTarget())
3654        return false;
3655    }
3656    return true;
3657  }
3658
3659  private List<ElementDefinition> getChildren(List<ElementDefinition> all, ElementDefinition element) {
3660    List<ElementDefinition> result = new ArrayList<ElementDefinition>();
3661    int i = all.indexOf(element)+1;
3662    while (i < all.size() && all.get(i).getPath().length() > element.getPath().length()) {
3663      if ((all.get(i).getPath().substring(0, element.getPath().length()+1).equals(element.getPath()+".")) && !all.get(i).getPath().substring(element.getPath().length()+1).contains("."))
3664        result.add(all.get(i));
3665      i++;
3666    }
3667    return result;
3668  }
3669
3670  private String tail(String path) {
3671    if (path.contains("."))
3672      return path.substring(path.lastIndexOf('.')+1);
3673    else
3674      return path;
3675  }
3676
3677  private boolean isDataType(String value) {
3678    StructureDefinition sd = context.fetchTypeDefinition(value);
3679    if (sd == null) // might be running before all SDs are available
3680      return Utilities.existsInList(value, "Address", "Age", "Annotation", "Attachment", "CodeableConcept", "Coding", "ContactPoint", "Count", "Distance", "Duration", "HumanName", "Identifier", "Money", "Period", "Quantity", "Range", "Ratio", "Reference", "SampledData", "Signature", "Timing", 
3681            "ContactDetail", "Contributor", "DataRequirement", "Expression", "ParameterDefinition", "RelatedArtifact", "TriggerDefinition", "UsageContext");
3682    else 
3683      return sd.getKind() == StructureDefinitionKind.COMPLEXTYPE && sd.getDerivation() == TypeDerivationRule.SPECIALIZATION;
3684  }
3685
3686  private boolean isConstrainedDataType(String value) {
3687    StructureDefinition sd = context.fetchTypeDefinition(value);
3688    if (sd == null) // might be running before all SDs are available
3689      return Utilities.existsInList(value, "SimpleQuantity", "MoneyQuantity");
3690    else 
3691      return sd.getKind() == StructureDefinitionKind.COMPLEXTYPE && sd.getDerivation() == TypeDerivationRule.CONSTRAINT;
3692  }
3693
3694  private String baseType(String value) {
3695    StructureDefinition sd = context.fetchTypeDefinition(value);
3696    if (sd != null) // might be running before all SDs are available
3697      return sd.getType();
3698    if (Utilities.existsInList(value, "SimpleQuantity", "MoneyQuantity"))
3699      return "Quantity";
3700     throw new Error("Internal error -  type not known "+value);
3701  }
3702
3703
3704  public boolean isPrimitive(String value) {
3705    StructureDefinition sd = context.fetchTypeDefinition(value);
3706    if (sd == null) // might be running before all SDs are available
3707      return Utilities.existsInList(value, "base64Binary", "boolean", "canonical", "code", "date", "dateTime", "decimal", "id", "instant", "integer", "markdown", "oid", "positiveInt", "string", "time", "unsignedInt", "uri", "url", "uuid");
3708    else 
3709      return sd.getKind() == StructureDefinitionKind.PRIMITIVETYPE;
3710  }
3711
3712//  private static String listStructures(StructureDefinition p) {
3713//    StringBuilder b = new StringBuilder();
3714//    boolean first = true;
3715//    for (ProfileStructureComponent s : p.getStructure()) {
3716//      if (first)
3717//        first = false;
3718//      else
3719//        b.append(", ");
3720//      if (pkp != null && pkp.hasLinkFor(s.getType()))
3721//        b.append("<a href=\""+pkp.getLinkFor(s.getType())+"\">"+s.getType()+"</a>");
3722//      else
3723//        b.append(s.getType());
3724//    }
3725//    return b.toString();
3726//  }
3727
3728
3729  public StructureDefinition getProfile(StructureDefinition source, String url) {
3730        StructureDefinition profile = null;
3731        String code = null;
3732        if (url.startsWith("#")) {
3733                profile = source;
3734                code = url.substring(1);
3735        } else if (context != null) {
3736                String[] parts = url.split("\\#");
3737                profile = context.fetchResource(StructureDefinition.class, parts[0]);
3738      code = parts.length == 1 ? null : parts[1];
3739        }         
3740        if (profile == null)
3741                return null;
3742        if (code == null)
3743                return profile;
3744        for (Resource r : profile.getContained()) {
3745                if (r instanceof StructureDefinition && r.getId().equals(code))
3746                        return (StructureDefinition) r;
3747        }
3748        return null;
3749  }
3750
3751
3752
3753  public static class ElementDefinitionHolder {
3754    private String name;
3755    private ElementDefinition self;
3756    private int baseIndex = 0;
3757    private List<ElementDefinitionHolder> children;
3758    private boolean placeHolder = false;
3759
3760    public ElementDefinitionHolder(ElementDefinition self, boolean isPlaceholder) {
3761      super();
3762      this.self = self;
3763      this.name = self.getPath();
3764      this.placeHolder = isPlaceholder;
3765      children = new ArrayList<ElementDefinitionHolder>();      
3766    }
3767
3768    public ElementDefinitionHolder(ElementDefinition self) {
3769      this(self, false);
3770    }
3771
3772    public ElementDefinition getSelf() {
3773      return self;
3774    }
3775
3776    public List<ElementDefinitionHolder> getChildren() {
3777      return children;
3778    }
3779
3780    public int getBaseIndex() {
3781      return baseIndex;
3782    }
3783
3784    public void setBaseIndex(int baseIndex) {
3785      this.baseIndex = baseIndex;
3786    }
3787
3788    public boolean isPlaceHolder() {
3789      return this.placeHolder;
3790    }
3791
3792    @Override
3793    public String toString() {
3794      if (self.hasSliceName())
3795        return self.getPath()+"("+self.getSliceName()+")";
3796      else
3797        return self.getPath();
3798    }
3799  }
3800
3801  public static class ElementDefinitionComparer implements Comparator<ElementDefinitionHolder> {
3802
3803    private boolean inExtension;
3804    private List<ElementDefinition> snapshot;
3805    private int prefixLength;
3806    private String base;
3807    private String name;
3808    private Set<String> errors = new HashSet<String>();
3809
3810    public ElementDefinitionComparer(boolean inExtension, List<ElementDefinition> snapshot, String base, int prefixLength, String name) {
3811      this.inExtension = inExtension;
3812      this.snapshot = snapshot;
3813      this.prefixLength = prefixLength;
3814      this.base = base;
3815      this.name = name;
3816    }
3817
3818    @Override
3819    public int compare(ElementDefinitionHolder o1, ElementDefinitionHolder o2) {
3820      if (o1.getBaseIndex() == 0)
3821        o1.setBaseIndex(find(o1.getSelf().getPath()));
3822      if (o2.getBaseIndex() == 0)
3823        o2.setBaseIndex(find(o2.getSelf().getPath()));
3824      return o1.getBaseIndex() - o2.getBaseIndex();
3825    }
3826
3827    private int find(String path) {
3828      String op = path;
3829      int lc = 0;
3830      String actual = base+path.substring(prefixLength);
3831      for (int i = 0; i < snapshot.size(); i++) {
3832        String p = snapshot.get(i).getPath();
3833        if (p.equals(actual)) {
3834          return i;
3835        }
3836        if (p.endsWith("[x]") && actual.startsWith(p.substring(0, p.length()-3)) && !(actual.endsWith("[x]")) && !actual.substring(p.length()-3).contains(".")) {
3837          return i;
3838        }
3839        if (path.startsWith(p+".") && snapshot.get(i).hasContentReference()) {
3840          String ref = snapshot.get(i).getContentReference();
3841          if (ref.substring(1, 2).toUpperCase().equals(ref.substring(1,2))) {
3842            actual = base+(ref.substring(1)+"."+path.substring(p.length()+1)).substring(prefixLength);
3843            path = actual;
3844          } else {
3845            // Older versions of FHIR (e.g. 2016May) had reference of the style #parameter instead of #Parameters.parameter, so we have to handle that
3846            actual = base+(path.substring(0,  path.indexOf(".")+1) + ref.substring(1)+"."+path.substring(p.length()+1)).substring(prefixLength);
3847            path = actual;
3848          }
3849            
3850          i = 0;
3851          lc++;
3852          if (lc > MAX_RECURSION_LIMIT)
3853            throw new Error("Internal recursion detection: find() loop path recursion > "+MAX_RECURSION_LIMIT+" - check paths are valid (for path "+path+"/"+op+")");
3854        }
3855      }
3856      if (prefixLength == 0)
3857        errors.add("Differential contains path "+path+" which is not found in the base");
3858      else
3859        errors.add("Differential contains path "+path+" which is actually "+actual+", which is not found in the base");
3860      return 0;
3861    }
3862
3863    public void checkForErrors(List<String> errorList) {
3864      if (errors.size() > 0) {
3865//        CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
3866//        for (String s : errors)
3867//          b.append("StructureDefinition "+name+": "+s);
3868//        throw new DefinitionException(b.toString());
3869        for (String s : errors)
3870          if (s.startsWith("!"))
3871            errorList.add("!StructureDefinition "+name+": "+s.substring(1));
3872          else
3873            errorList.add("StructureDefinition "+name+": "+s);
3874      }
3875    }
3876  }
3877
3878
3879  public void sortDifferential(StructureDefinition base, StructureDefinition diff, String name, List<String> errors) throws FHIRException  {
3880    final List<ElementDefinition> diffList = diff.getDifferential().getElement();
3881    int lastCount = diffList.size();
3882    // first, we move the differential elements into a tree
3883    if (diffList.isEmpty())
3884      return;
3885    
3886    ElementDefinitionHolder edh = null;
3887    int i = 0;
3888    if (diffList.get(0).getPath().contains(".")) {
3889      String newPath = diffList.get(0).getPath().split("\\.")[0];
3890      ElementDefinition e = new ElementDefinition(new StringType(newPath));
3891      edh = new ElementDefinitionHolder(e, true);
3892    } else {
3893      edh = new ElementDefinitionHolder(diffList.get(0));
3894      i = 1;
3895    }
3896
3897    boolean hasSlicing = false;
3898    List<String> paths = new ArrayList<String>(); // in a differential, slicing may not be stated explicitly
3899    for(ElementDefinition elt : diffList) {
3900      if (elt.hasSlicing() || paths.contains(elt.getPath())) {
3901        hasSlicing = true;
3902        break;
3903      }
3904      paths.add(elt.getPath());
3905    }
3906    if(!hasSlicing) {
3907      // if Differential does not have slicing then safe to pre-sort the list
3908      // so elements and subcomponents are together
3909      Collections.sort(diffList, new ElementNameCompare());
3910    }
3911
3912    processElementsIntoTree(edh, i, diff.getDifferential().getElement());
3913
3914    // now, we sort the siblings throughout the tree
3915    ElementDefinitionComparer cmp = new ElementDefinitionComparer(true, base.getSnapshot().getElement(), "", 0, name);
3916    sortElements(edh, cmp, errors);
3917
3918    // now, we serialise them back to a list
3919    diffList.clear();
3920    writeElements(edh, diffList);
3921    
3922    if (lastCount != diffList.size())
3923      errors.add("Sort failed: counts differ; at least one of the paths in the differential is illegal");
3924  }
3925
3926  private int processElementsIntoTree(ElementDefinitionHolder edh, int i, List<ElementDefinition> list) {
3927    String path = edh.getSelf().getPath();
3928    final String prefix = path + ".";
3929    while (i < list.size() && list.get(i).getPath().startsWith(prefix)) {
3930      if (list.get(i).getPath().substring(prefix.length()+1).contains(".")) {
3931        String newPath = prefix + list.get(i).getPath().substring(prefix.length()).split("\\.")[0];
3932        ElementDefinition e = new ElementDefinition(new StringType(newPath));
3933        ElementDefinitionHolder child = new ElementDefinitionHolder(e, true);
3934        edh.getChildren().add(child);
3935        i = processElementsIntoTree(child, i, list);
3936        
3937      } else {
3938        ElementDefinitionHolder child = new ElementDefinitionHolder(list.get(i));
3939        edh.getChildren().add(child);
3940        i = processElementsIntoTree(child, i+1, list);
3941      }
3942    }
3943    return i;
3944  }
3945
3946  private void sortElements(ElementDefinitionHolder edh, ElementDefinitionComparer cmp, List<String> errors) throws FHIRException {
3947    if (edh.getChildren().size() == 1)
3948      // special case - sort needsto allocate base numbers, but there'll be no sort if there's only 1 child. So in that case, we just go ahead and allocated base number directly
3949      edh.getChildren().get(0).baseIndex = cmp.find(edh.getChildren().get(0).getSelf().getPath());
3950    else
3951      Collections.sort(edh.getChildren(), cmp);
3952    cmp.checkForErrors(errors);
3953
3954    for (ElementDefinitionHolder child : edh.getChildren()) {
3955      if (child.getChildren().size() > 0) {
3956        ElementDefinitionComparer ccmp = getComparer(cmp, child);
3957        if (ccmp != null)
3958        sortElements(child, ccmp, errors);
3959      }
3960    }
3961  }
3962
3963
3964  public ElementDefinitionComparer getComparer(ElementDefinitionComparer cmp, ElementDefinitionHolder child) throws FHIRException, Error {
3965    // what we have to check for here is running off the base profile into a data type profile
3966    ElementDefinition ed = cmp.snapshot.get(child.getBaseIndex());
3967    ElementDefinitionComparer ccmp;
3968    if (ed.getType().isEmpty() || isAbstract(ed.getType().get(0).getWorkingCode()) || ed.getType().get(0).getWorkingCode().equals(ed.getPath())) {
3969      ccmp = new ElementDefinitionComparer(true, cmp.snapshot, cmp.base, cmp.prefixLength, cmp.name);
3970    } else if (ed.getType().get(0).getWorkingCode().equals("Extension") && child.getSelf().getType().size() == 1 && child.getSelf().getType().get(0).hasProfile()) {
3971      StructureDefinition profile = context.fetchResource(StructureDefinition.class, child.getSelf().getType().get(0).getProfile().get(0).getValue());
3972      if (profile==null)
3973        ccmp = null; // this might happen before everything is loaded. And we don't so much care about sot order in this case
3974      else
3975      ccmp = new ElementDefinitionComparer(true, profile.getSnapshot().getElement(), ed.getType().get(0).getWorkingCode(), child.getSelf().getPath().length(), cmp.name);
3976    } else if (ed.getType().size() == 1 && !ed.getType().get(0).getWorkingCode().equals("*")) {
3977      StructureDefinition profile = context.fetchResource(StructureDefinition.class, sdNs(ed.getType().get(0).getWorkingCode()));
3978      if (profile==null)
3979        throw new FHIRException("Unable to resolve profile " + sdNs(ed.getType().get(0).getWorkingCode()) + " in element " + ed.getPath());
3980      ccmp = new ElementDefinitionComparer(false, profile.getSnapshot().getElement(), ed.getType().get(0).getWorkingCode(), child.getSelf().getPath().length(), cmp.name);
3981    } else if (child.getSelf().getType().size() == 1) {
3982      StructureDefinition profile = context.fetchResource(StructureDefinition.class, sdNs(child.getSelf().getType().get(0).getWorkingCode()));
3983      if (profile==null)
3984        throw new FHIRException("Unable to resolve profile " + sdNs(ed.getType().get(0).getWorkingCode()) + " in element " + ed.getPath());
3985      ccmp = new ElementDefinitionComparer(false, profile.getSnapshot().getElement(), child.getSelf().getType().get(0).getWorkingCode(), child.getSelf().getPath().length(), cmp.name);
3986    } else if (ed.getPath().endsWith("[x]") && !child.getSelf().getPath().endsWith("[x]")) {
3987      String edLastNode = ed.getPath().replaceAll("(.*\\.)*(.*)", "$2");
3988      String childLastNode = child.getSelf().getPath().replaceAll("(.*\\.)*(.*)", "$2");
3989      String p = childLastNode.substring(edLastNode.length()-3);
3990      if (isPrimitive(Utilities.uncapitalize(p)))
3991        p = Utilities.uncapitalize(p);
3992      StructureDefinition sd = context.fetchResource(StructureDefinition.class, sdNs(p));
3993      if (sd == null)
3994        throw new Error("Unable to find profile '"+p+"' at "+ed.getId());
3995      ccmp = new ElementDefinitionComparer(false, sd.getSnapshot().getElement(), p, child.getSelf().getPath().length(), cmp.name);
3996    } else if (child.getSelf().hasType() && child.getSelf().getType().get(0).getWorkingCode().equals("Reference")) {
3997      for (TypeRefComponent t: child.getSelf().getType()) {
3998        if (!t.getWorkingCode().equals("Reference")) {
3999          throw new Error("Can't have children on an element with a polymorphic type - you must slice and constrain the types first (sortElements: "+ed.getPath()+":"+typeCode(ed.getType())+")");
4000        }
4001      }
4002      StructureDefinition profile = context.fetchResource(StructureDefinition.class, sdNs(ed.getType().get(0).getWorkingCode()));
4003      ccmp = new ElementDefinitionComparer(false, profile.getSnapshot().getElement(), ed.getType().get(0).getWorkingCode(), child.getSelf().getPath().length(), cmp.name);
4004    } else if (!child.getSelf().hasType() && ed.getType().get(0).getWorkingCode().equals("Reference")) {
4005      for (TypeRefComponent t: ed.getType()) {
4006        if (!t.getWorkingCode().equals("Reference")) {
4007          throw new Error("Not handled yet (sortElements: "+ed.getPath()+":"+typeCode(ed.getType())+")");
4008        }
4009      }
4010      StructureDefinition profile = context.fetchResource(StructureDefinition.class, sdNs(ed.getType().get(0).getWorkingCode()));
4011      ccmp = new ElementDefinitionComparer(false, profile.getSnapshot().getElement(), ed.getType().get(0).getWorkingCode(), child.getSelf().getPath().length(), cmp.name);
4012    } else {
4013      // this is allowed if we only profile the extensions
4014      StructureDefinition profile = context.fetchResource(StructureDefinition.class, sdNs("Element"));
4015      if (profile==null)
4016        throw new FHIRException("Unable to resolve profile " + sdNs(ed.getType().get(0).getWorkingCode()) + " in element " + ed.getPath());
4017      ccmp = new ElementDefinitionComparer(false, profile.getSnapshot().getElement(), "Element", child.getSelf().getPath().length(), cmp.name);
4018//      throw new Error("Not handled yet (sortElements: "+ed.getPath()+":"+typeCode(ed.getType())+")");
4019    }
4020    return ccmp;
4021  }
4022
4023  private static String sdNs(String type) {
4024    return sdNs(type, null);
4025  }
4026  
4027  public static String sdNs(String type, String overrideVersionNs) {
4028    if (Utilities.isAbsoluteUrl(type))
4029      return type;
4030    else if (overrideVersionNs != null)
4031      return Utilities.pathURL(overrideVersionNs, type);
4032    else
4033      return "http://hl7.org/fhir/StructureDefinition/"+type;
4034  }
4035
4036
4037  private boolean isAbstract(String code) {
4038    return code.equals("Element") || code.equals("BackboneElement") || code.equals("Resource") || code.equals("DomainResource");
4039  }
4040
4041
4042  private void writeElements(ElementDefinitionHolder edh, List<ElementDefinition> list) {
4043    if (!edh.isPlaceHolder())
4044      list.add(edh.getSelf());
4045    for (ElementDefinitionHolder child : edh.getChildren()) {
4046      writeElements(child, list);
4047    }
4048  }
4049
4050  /**
4051   * First compare element by path then by name if same
4052   */
4053  private static class ElementNameCompare implements Comparator<ElementDefinition> {
4054
4055    @Override
4056    public int compare(ElementDefinition o1, ElementDefinition o2) {
4057      String path1 = normalizePath(o1);
4058      String path2 = normalizePath(o2);
4059      int cmp = path1.compareTo(path2);
4060      if (cmp == 0) {
4061        String name1 = o1.hasSliceName() ? o1.getSliceName() : "";
4062        String name2 = o2.hasSliceName() ? o2.getSliceName() : "";
4063        cmp = name1.compareTo(name2);
4064      }
4065      return cmp;
4066    }
4067
4068    private static String normalizePath(ElementDefinition e) {
4069      if (!e.hasPath()) return "";
4070      String path = e.getPath();
4071      // if sorting element names make sure onset[x] appears before onsetAge, onsetDate, etc.
4072      // so strip off the [x] suffix when comparing the path names.
4073      if (path.endsWith("[x]")) {
4074        path = path.substring(0, path.length()-3);
4075      }
4076      return path;
4077    }
4078
4079  }
4080
4081
4082  // generate schematrons for the rules in a structure definition
4083  public void generateSchematrons(OutputStream dest, StructureDefinition structure) throws IOException, DefinitionException {
4084    if (structure.getDerivation() != TypeDerivationRule.CONSTRAINT)
4085      throw new DefinitionException("not the right kind of structure to generate schematrons for");
4086    if (!structure.hasSnapshot())
4087      throw new DefinitionException("needs a snapshot");
4088
4089        StructureDefinition base = context.fetchResource(StructureDefinition.class, structure.getBaseDefinition());
4090
4091        if (base != null) {
4092          SchematronWriter sch = new SchematronWriter(dest, SchematronType.PROFILE, base.getName());
4093
4094          ElementDefinition ed = structure.getSnapshot().getElement().get(0);
4095          generateForChildren(sch, "f:"+ed.getPath(), ed, structure, base);
4096          sch.dump();
4097        }
4098  }
4099
4100  // generate a CSV representation of the structure definition
4101  public void generateCsvs(OutputStream dest, StructureDefinition structure, boolean asXml) throws IOException, DefinitionException, Exception {
4102    if (!structure.hasSnapshot())
4103      throw new DefinitionException("needs a snapshot");
4104
4105    CSVWriter csv = new CSVWriter(dest, structure, asXml);
4106
4107    for (ElementDefinition child : structure.getSnapshot().getElement()) {
4108      csv.processElement(child);
4109    }
4110    csv.dump();
4111  }
4112  
4113  // generate an Excel representation of the structure definition
4114  public void generateXlsx(OutputStream dest, StructureDefinition structure, boolean asXml, boolean hideMustSupportFalse) throws IOException, DefinitionException, Exception {
4115    if (!structure.hasSnapshot())
4116      throw new DefinitionException("needs a snapshot");
4117
4118    XLSXWriter xlsx = new XLSXWriter(dest, structure, asXml, hideMustSupportFalse);
4119
4120    for (ElementDefinition child : structure.getSnapshot().getElement()) {
4121      xlsx.processElement(child);
4122    }
4123    xlsx.dump();
4124    xlsx.close();
4125  }
4126  
4127  private class Slicer extends ElementDefinitionSlicingComponent {
4128    String criteria = "";
4129    String name = "";   
4130    boolean check;
4131    public Slicer(boolean cantCheck) {
4132      super();
4133      this.check = cantCheck;
4134    }
4135  }
4136  
4137  private Slicer generateSlicer(ElementDefinition child, ElementDefinitionSlicingComponent slicing, StructureDefinition structure) {
4138    // given a child in a structure, it's sliced. figure out the slicing xpath
4139    if (child.getPath().endsWith(".extension")) {
4140      ElementDefinition ued = getUrlFor(structure, child);
4141      if ((ued == null || !ued.hasFixed()) && !(child.hasType() && (child.getType().get(0).hasProfile())))
4142        return new Slicer(false);
4143      else {
4144      Slicer s = new Slicer(true);
4145      String url = (ued == null || !ued.hasFixed()) ? child.getType().get(0).getProfile().get(0).getValue() : ((UriType) ued.getFixed()).asStringValue();
4146      s.name = " with URL = '"+url+"'";
4147      s.criteria = "[@url = '"+url+"']";
4148      return s;
4149      }
4150    } else
4151      return new Slicer(false);
4152  }
4153
4154  private void generateForChildren(SchematronWriter sch, String xpath, ElementDefinition ed, StructureDefinition structure, StructureDefinition base) throws IOException {
4155    //    generateForChild(txt, structure, child);
4156    List<ElementDefinition> children = getChildList(structure, ed);
4157    String sliceName = null;
4158    ElementDefinitionSlicingComponent slicing = null;
4159    for (ElementDefinition child : children) {
4160      String name = tail(child.getPath());
4161      if (child.hasSlicing()) {
4162        sliceName = name;
4163        slicing = child.getSlicing();        
4164      } else if (!name.equals(sliceName))
4165        slicing = null;
4166      
4167      ElementDefinition based = getByPath(base, child.getPath());
4168      boolean doMin = (child.getMin() > 0) && (based == null || (child.getMin() != based.getMin()));
4169      boolean doMax = child.hasMax() && !child.getMax().equals("*") && (based == null || (!child.getMax().equals(based.getMax())));
4170      Slicer slicer = slicing == null ? new Slicer(true) : generateSlicer(child, slicing, structure);
4171      if (slicer.check) {
4172        if (doMin || doMax) {
4173          Section s = sch.section(xpath);
4174          Rule r = s.rule(xpath);
4175          if (doMin) 
4176            r.assrt("count(f:"+name+slicer.criteria+") >= "+Integer.toString(child.getMin()), name+slicer.name+": minimum cardinality of '"+name+"' is "+Integer.toString(child.getMin()));
4177          if (doMax) 
4178            r.assrt("count(f:"+name+slicer.criteria+") <= "+child.getMax(), name+slicer.name+": maximum cardinality of '"+name+"' is "+child.getMax());
4179          }
4180        }
4181      }
4182    for (ElementDefinitionConstraintComponent inv : ed.getConstraint()) {
4183      if (inv.hasXpath()) {
4184        Section s = sch.section(ed.getPath());
4185        Rule r = s.rule(xpath);
4186        r.assrt(inv.getXpath(), (inv.hasId() ? inv.getId()+": " : "")+inv.getHuman()+(inv.hasUserData(IS_DERIVED) ? " (inherited)" : ""));
4187      }
4188    }
4189    for (ElementDefinition child : children) {
4190      String name = tail(child.getPath());
4191      generateForChildren(sch, xpath+"/f:"+name, child, structure, base);
4192    }
4193  }
4194
4195
4196
4197
4198  private ElementDefinition getByPath(StructureDefinition base, String path) {
4199                for (ElementDefinition ed : base.getSnapshot().getElement()) {
4200                        if (ed.getPath().equals(path))
4201                                return ed;
4202                        if (ed.getPath().endsWith("[x]") && ed.getPath().length() <= path.length()-3 &&  ed.getPath().substring(0, ed.getPath().length()-3).equals(path.substring(0, ed.getPath().length()-3)))
4203                                return ed;
4204    }
4205          return null;
4206  }
4207
4208
4209  public void setIds(StructureDefinition sd, boolean checkFirst) throws DefinitionException  {
4210    if (!checkFirst || !sd.hasDifferential() || hasMissingIds(sd.getDifferential().getElement())) {
4211      if (!sd.hasDifferential())
4212        sd.setDifferential(new StructureDefinitionDifferentialComponent());
4213      generateIds(sd.getDifferential().getElement(), sd.getUrl());
4214    }
4215    if (!checkFirst || !sd.hasSnapshot() || hasMissingIds(sd.getSnapshot().getElement())) {
4216      if (!sd.hasSnapshot())
4217        sd.setSnapshot(new StructureDefinitionSnapshotComponent());
4218      generateIds(sd.getSnapshot().getElement(), sd.getUrl());
4219    }
4220  }
4221
4222
4223  private boolean hasMissingIds(List<ElementDefinition> list) {
4224    for (ElementDefinition ed : list) {
4225      if (!ed.hasId())
4226        return true;
4227    }    
4228    return false;
4229  }
4230
4231  public class SliceList {
4232
4233    private Map<String, String> slices = new HashMap<>();
4234    
4235    public void seeElement(ElementDefinition ed) {
4236      Iterator<Map.Entry<String,String>> iter = slices.entrySet().iterator();
4237      while (iter.hasNext()) {
4238        Map.Entry<String,String> entry = iter.next();
4239        if (entry.getKey().length() > ed.getPath().length() || entry.getKey().equals(ed.getPath()))
4240          iter.remove();
4241      }
4242      
4243      if (ed.hasSliceName()) 
4244        slices.put(ed.getPath(), ed.getSliceName());
4245    }
4246
4247    public String[] analyse(List<String> paths) {
4248      String s = paths.get(0);
4249      String[] res = new String[paths.size()];
4250      res[0] = null;
4251      for (int i = 1; i < paths.size(); i++) {
4252        s = s + "."+paths.get(i);
4253        if (slices.containsKey(s)) 
4254          res[i] = slices.get(s);
4255        else
4256          res[i] = null;
4257      }
4258      return res;
4259    }
4260
4261  }
4262
4263  private void generateIds(List<ElementDefinition> list, String name) throws DefinitionException  {
4264    if (list.isEmpty())
4265      return;
4266    
4267    Map<String, String> idMap = new HashMap<String, String>();
4268    Map<String, String> idList = new HashMap<String, String>();
4269    
4270    SliceList sliceInfo = new SliceList();
4271    // first pass, update the element ids
4272    for (ElementDefinition ed : list) {
4273      List<String> paths = new ArrayList<String>();
4274      if (!ed.hasPath())
4275        throw new DefinitionException("No path on element Definition "+Integer.toString(list.indexOf(ed))+" in "+name);
4276      sliceInfo.seeElement(ed);
4277      String[] pl = ed.getPath().split("\\.");
4278      for (int i = paths.size(); i < pl.length; i++) // -1 because the last path is in focus
4279        paths.add(pl[i]);
4280      String slices[] = sliceInfo.analyse(paths);
4281      
4282      StringBuilder b = new StringBuilder();
4283      b.append(paths.get(0));
4284      for (int i = 1; i < paths.size(); i++) {
4285        b.append(".");
4286        String s = paths.get(i);
4287        String p = slices[i];
4288        b.append(fixChars(s));
4289        if (p != null) {
4290          b.append(":");
4291          b.append(p);
4292        }
4293      }
4294      String bs = b.toString();
4295      idMap.put(ed.hasId() ? ed.getId() : ed.getPath(), bs);
4296      ed.setId(bs);
4297      if (idList.containsKey(bs)) {
4298        if (exception || messages == null)
4299          throw new DefinitionException("Same id '"+bs+"'on multiple elements "+idList.get(bs)+"/"+ed.getPath()+" in "+name);
4300        else
4301          messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, name+"."+bs, "Duplicate Element id "+bs, ValidationMessage.IssueSeverity.ERROR));
4302      }
4303      idList.put(bs, ed.getPath());
4304      if (ed.hasContentReference()) {
4305        String s = ed.getContentReference().substring(1);
4306        if (idMap.containsKey(s))
4307          ed.setContentReference("#"+idMap.get(s));
4308        
4309      }
4310    }  
4311    // second path - fix up any broken path based id references
4312    
4313  }
4314
4315
4316  private Object fixChars(String s) {
4317    return s.replace("_", "-");
4318  }
4319
4320
4321//  private String describeExtension(ElementDefinition ed) {
4322//    if (!ed.hasType() || !ed.getTypeFirstRep().hasProfile())
4323//      return "";
4324//    return "$"+urlTail(ed.getTypeFirstRep().getProfile());
4325//  }
4326//
4327
4328  private String urlTail(String profile) {
4329    return profile.contains("/") ? profile.substring(profile.lastIndexOf("/")+1) : profile;
4330  }
4331
4332
4333  private String checkName(String name) {
4334//    if (name.contains("."))
4335////      throw new Exception("Illegal name "+name+": no '.'");
4336//    if (name.contains(" "))
4337//      throw new Exception("Illegal name "+name+": no spaces");
4338    StringBuilder b = new StringBuilder();
4339    for (char c : name.toCharArray()) {
4340      if (!Utilities.existsInList(c, '.', ' ', ':', '"', '\'', '(', ')', '&', '[', ']'))
4341        b.append(c);
4342    }
4343    return b.toString().toLowerCase();
4344  }
4345
4346
4347  private int charCount(String path, char t) {
4348    int res = 0;
4349    for (char ch : path.toCharArray()) {
4350      if (ch == t)
4351        res++;
4352    }
4353    return res;
4354  }
4355
4356//
4357//private void generateForChild(TextStreamWriter txt,
4358//    StructureDefinition structure, ElementDefinition child) {
4359//  // TODO Auto-generated method stub
4360//
4361//}
4362
4363  private interface ExampleValueAccessor {
4364    Type getExampleValue(ElementDefinition ed);
4365    String getId();
4366  }
4367
4368  private class BaseExampleValueAccessor implements ExampleValueAccessor {
4369    @Override
4370    public Type getExampleValue(ElementDefinition ed) {
4371      if (ed.hasFixed())
4372        return ed.getFixed();
4373      if (ed.hasExample())
4374        return ed.getExample().get(0).getValue();
4375      else
4376        return null;
4377    }
4378
4379    @Override
4380    public String getId() {
4381      return "-genexample";
4382    }
4383  }
4384  
4385  private class ExtendedExampleValueAccessor implements ExampleValueAccessor {
4386    private String index;
4387
4388    public ExtendedExampleValueAccessor(String index) {
4389      this.index = index;
4390    }
4391    @Override
4392    public Type getExampleValue(ElementDefinition ed) {
4393      if (ed.hasFixed())
4394        return ed.getFixed();
4395      for (Extension ex : ed.getExtension()) {
4396       String ndx = ToolingExtensions.readStringExtension(ex, "index");
4397       Type value = ToolingExtensions.getExtension(ex, "exValue").getValue();
4398       if (index.equals(ndx) && value != null)
4399         return value;
4400      }
4401      return null;
4402    }
4403    @Override
4404    public String getId() {
4405      return "-genexample-"+index;
4406    }
4407  }
4408  
4409  public List<org.hl7.fhir.r5.elementmodel.Element> generateExamples(StructureDefinition sd, boolean evenWhenNoExamples) throws FHIRException {
4410    List<org.hl7.fhir.r5.elementmodel.Element> examples = new ArrayList<org.hl7.fhir.r5.elementmodel.Element>();
4411    if (sd.hasSnapshot()) {
4412      if (evenWhenNoExamples || hasAnyExampleValues(sd)) 
4413        examples.add(generateExample(sd, new BaseExampleValueAccessor()));
4414      for (int i = 1; i <= 50; i++) {
4415        if (hasAnyExampleValues(sd, Integer.toString(i))) 
4416          examples.add(generateExample(sd, new ExtendedExampleValueAccessor(Integer.toString(i))));
4417      }
4418    }
4419    return examples;
4420  }
4421
4422  private org.hl7.fhir.r5.elementmodel.Element generateExample(StructureDefinition profile, ExampleValueAccessor accessor) throws FHIRException {
4423    ElementDefinition ed = profile.getSnapshot().getElementFirstRep();
4424    org.hl7.fhir.r5.elementmodel.Element r = new org.hl7.fhir.r5.elementmodel.Element(ed.getPath(), new Property(context, ed, profile));
4425    List<ElementDefinition> children = getChildMap(profile, ed);
4426    for (ElementDefinition child : children) {
4427      if (child.getPath().endsWith(".id")) {
4428        org.hl7.fhir.r5.elementmodel.Element id = new org.hl7.fhir.r5.elementmodel.Element("id", new Property(context, child, profile));
4429        id.setValue(profile.getId()+accessor.getId());
4430        r.getChildren().add(id);
4431      } else { 
4432        org.hl7.fhir.r5.elementmodel.Element e = createExampleElement(profile, child, accessor);
4433        if (e != null)
4434          r.getChildren().add(e);
4435      }
4436    }
4437    return r;
4438  }
4439
4440  private org.hl7.fhir.r5.elementmodel.Element createExampleElement(StructureDefinition profile, ElementDefinition ed, ExampleValueAccessor accessor) throws FHIRException {
4441    Type v = accessor.getExampleValue(ed);
4442    if (v != null) {
4443      return new ObjectConverter(context).convert(new Property(context, ed, profile), v);
4444    } else {
4445      org.hl7.fhir.r5.elementmodel.Element res = new org.hl7.fhir.r5.elementmodel.Element(tail(ed.getPath()), new Property(context, ed, profile));
4446      boolean hasValue = false;
4447      List<ElementDefinition> children = getChildMap(profile, ed);
4448      for (ElementDefinition child : children) {
4449        if (!child.hasContentReference()) {
4450        org.hl7.fhir.r5.elementmodel.Element e = createExampleElement(profile, child, accessor);
4451        if (e != null) {
4452          hasValue = true;
4453          res.getChildren().add(e);
4454        }
4455      }
4456      }
4457      if (hasValue)
4458        return res;
4459      else
4460        return null;
4461    }
4462  }
4463
4464  private boolean hasAnyExampleValues(StructureDefinition sd, String index) {
4465    for (ElementDefinition ed : sd.getSnapshot().getElement())
4466      for (Extension ex : ed.getExtension()) {
4467        String ndx = ToolingExtensions.readStringExtension(ex, "index");
4468        Extension exv = ToolingExtensions.getExtension(ex, "exValue");
4469        if (exv != null) {
4470          Type value = exv.getValue();
4471        if (index.equals(ndx) && value != null)
4472          return true;
4473        }
4474       }
4475    return false;
4476  }
4477
4478
4479  private boolean hasAnyExampleValues(StructureDefinition sd) {
4480    for (ElementDefinition ed : sd.getSnapshot().getElement())
4481      if (ed.hasExample())
4482        return true;
4483    return false;
4484  }
4485
4486
4487  public void populateLogicalSnapshot(StructureDefinition sd) throws FHIRException {
4488    sd.getSnapshot().getElement().add(sd.getDifferential().getElementFirstRep().copy());
4489    
4490    if (sd.hasBaseDefinition()) {
4491    StructureDefinition base = context.fetchResource(StructureDefinition.class, sd.getBaseDefinition());
4492    if (base == null)
4493      throw new FHIRException("Unable to find base definition for logical model: "+sd.getBaseDefinition()+" from "+sd.getUrl());
4494    copyElements(sd, base.getSnapshot().getElement());
4495    }
4496    copyElements(sd, sd.getDifferential().getElement());
4497  }
4498
4499
4500  private void copyElements(StructureDefinition sd, List<ElementDefinition> list) {
4501    for (ElementDefinition ed : list) {
4502      if (ed.getPath().contains(".")) {
4503        ElementDefinition n = ed.copy();
4504        n.setPath(sd.getSnapshot().getElementFirstRep().getPath()+"."+ed.getPath().substring(ed.getPath().indexOf(".")+1));
4505        sd.getSnapshot().addElement(n);
4506      }
4507    }
4508  }
4509
4510    
4511  public void cleanUpDifferential(StructureDefinition sd) {
4512    if (sd.getDifferential().getElement().size() > 1)
4513      cleanUpDifferential(sd, 1);
4514  }
4515  
4516  private void cleanUpDifferential(StructureDefinition sd, int start) {
4517    int level = Utilities.charCount(sd.getDifferential().getElement().get(start).getPath(), '.');
4518    int c = start;
4519    int len = sd.getDifferential().getElement().size();
4520    HashSet<String> paths = new HashSet<String>();
4521    while (c < len && Utilities.charCount(sd.getDifferential().getElement().get(c).getPath(), '.') == level) {
4522      ElementDefinition ed = sd.getDifferential().getElement().get(c);
4523      if (!paths.contains(ed.getPath())) {
4524        paths.add(ed.getPath());
4525        int ic = c+1; 
4526        while (ic < len && Utilities.charCount(sd.getDifferential().getElement().get(ic).getPath(), '.') > level) 
4527          ic++;
4528        ElementDefinition slicer = null;
4529        List<ElementDefinition> slices = new ArrayList<ElementDefinition>();
4530        slices.add(ed);
4531        while (ic < len && Utilities.charCount(sd.getDifferential().getElement().get(ic).getPath(), '.') == level) {
4532          ElementDefinition edi = sd.getDifferential().getElement().get(ic);
4533          if (ed.getPath().equals(edi.getPath())) {
4534            if (slicer == null) {
4535              slicer = new ElementDefinition();
4536              slicer.setPath(edi.getPath());
4537              slicer.getSlicing().setRules(SlicingRules.OPEN);
4538              sd.getDifferential().getElement().add(c, slicer);
4539              c++;
4540              ic++;
4541            }
4542            slices.add(edi);
4543          }
4544          ic++;
4545          while (ic < len && Utilities.charCount(sd.getDifferential().getElement().get(ic).getPath(), '.') > level) 
4546            ic++;
4547        }
4548        // now we're at the end, we're going to figure out the slicing discriminator
4549        if (slicer != null)
4550          determineSlicing(slicer, slices);
4551      }
4552      c++;
4553      if (c < len && Utilities.charCount(sd.getDifferential().getElement().get(c).getPath(), '.') > level) {
4554        cleanUpDifferential(sd, c);
4555        c++;
4556        while (c < len && Utilities.charCount(sd.getDifferential().getElement().get(c).getPath(), '.') > level) 
4557          c++;
4558      }
4559  }
4560  }
4561
4562
4563  private void determineSlicing(ElementDefinition slicer, List<ElementDefinition> slices) {
4564    // first, name them
4565    int i = 0;
4566    for (ElementDefinition ed : slices) {
4567      if (ed.hasUserData("slice-name")) {
4568        ed.setSliceName(ed.getUserString("slice-name"));
4569      } else {
4570        i++;
4571        ed.setSliceName("slice-"+Integer.toString(i));
4572      }
4573    }
4574    // now, the hard bit, how are they differentiated? 
4575    // right now, we hard code this...
4576    if (slicer.getPath().endsWith(".extension") || slicer.getPath().endsWith(".modifierExtension"))
4577      slicer.getSlicing().addDiscriminator().setType(DiscriminatorType.VALUE).setPath("url");
4578    else if (slicer.getPath().equals("DiagnosticReport.result"))
4579      slicer.getSlicing().addDiscriminator().setType(DiscriminatorType.VALUE).setPath("reference.code");
4580    else if (slicer.getPath().equals("Observation.related"))
4581      slicer.getSlicing().addDiscriminator().setType(DiscriminatorType.VALUE).setPath("target.reference.code");
4582    else if (slicer.getPath().equals("Bundle.entry"))
4583      slicer.getSlicing().addDiscriminator().setType(DiscriminatorType.VALUE).setPath("resource.@profile");
4584    else  
4585      throw new Error("No slicing for "+slicer.getPath()); 
4586  }
4587
4588  public class SpanEntry {
4589    private List<SpanEntry> children = new ArrayList<SpanEntry>();
4590    private boolean profile;
4591    private String id;
4592    private String name;
4593    private String resType;
4594    private String cardinality;
4595    private String description;
4596    private String profileLink;
4597    private String resLink;
4598    private String type;
4599    
4600    public String getName() {
4601      return name;
4602    }
4603    public void setName(String name) {
4604      this.name = name;
4605    }
4606    public String getResType() {
4607      return resType;
4608    }
4609    public void setResType(String resType) {
4610      this.resType = resType;
4611    }
4612    public String getCardinality() {
4613      return cardinality;
4614    }
4615    public void setCardinality(String cardinality) {
4616      this.cardinality = cardinality;
4617    }
4618    public String getDescription() {
4619      return description;
4620    }
4621    public void setDescription(String description) {
4622      this.description = description;
4623    }
4624    public String getProfileLink() {
4625      return profileLink;
4626    }
4627    public void setProfileLink(String profileLink) {
4628      this.profileLink = profileLink;
4629    }
4630    public String getResLink() {
4631      return resLink;
4632    }
4633    public void setResLink(String resLink) {
4634      this.resLink = resLink;
4635    }
4636    public String getId() {
4637      return id;
4638    }
4639    public void setId(String id) {
4640      this.id = id;
4641    }
4642    public boolean isProfile() {
4643      return profile;
4644    }
4645    public void setProfile(boolean profile) {
4646      this.profile = profile;
4647    }
4648    public List<SpanEntry> getChildren() {
4649      return children;
4650    }
4651    public String getType() {
4652      return type;
4653    }
4654    public void setType(String type) {
4655      this.type = type;
4656    }
4657    
4658  }
4659
4660  public XhtmlNode generateSpanningTable(StructureDefinition profile, String imageFolder, boolean onlyConstraints, String constraintPrefix, Set<String> outputTracker) throws IOException, FHIRException {
4661    HierarchicalTableGenerator gen = new HierarchicalTableGenerator(imageFolder, false, true);
4662    gen.setTranslator(getTranslator());
4663    TableModel model = initSpanningTable(gen, "", false);
4664    Set<String> processed = new HashSet<String>();
4665    SpanEntry span = buildSpanningTable("(focus)", "", profile, processed, onlyConstraints, constraintPrefix);
4666    
4667    genSpanEntry(gen, model.getRows(), span);
4668    return gen.generate(model, "", 0, outputTracker);
4669  }
4670
4671  private SpanEntry buildSpanningTable(String name, String cardinality, StructureDefinition profile, Set<String> processed, boolean onlyConstraints, String constraintPrefix) throws IOException {
4672    SpanEntry res = buildSpanEntryFromProfile(name, cardinality, profile);
4673    boolean wantProcess = !processed.contains(profile.getUrl());
4674    processed.add(profile.getUrl());
4675    if (wantProcess && profile.getDerivation() == TypeDerivationRule.CONSTRAINT) {
4676      for (ElementDefinition ed : profile.getSnapshot().getElement()) {
4677        if (!"0".equals(ed.getMax()) && ed.getType().size() > 0) {
4678          String card = getCardinality(ed, profile.getSnapshot().getElement());
4679          if (!card.endsWith(".0")) {
4680            List<String> refProfiles = listReferenceProfiles(ed);
4681            if (refProfiles.size() > 0) {
4682              String uri = refProfiles.get(0);
4683              if (uri != null) {
4684                StructureDefinition sd = context.fetchResource(StructureDefinition.class, uri);
4685                if (sd != null && (!onlyConstraints || (sd.getDerivation() == TypeDerivationRule.CONSTRAINT && (constraintPrefix == null || sd.getUrl().startsWith(constraintPrefix))))) {
4686                  res.getChildren().add(buildSpanningTable(nameForElement(ed), card, sd, processed, onlyConstraints, constraintPrefix));
4687                }
4688              }
4689            }
4690          }
4691        } 
4692      }
4693    }
4694    return res;
4695  }
4696
4697
4698  private String getCardinality(ElementDefinition ed, List<ElementDefinition> list) {
4699    int min = ed.getMin();
4700    int max = !ed.hasMax() || ed.getMax().equals("*") ? Integer.MAX_VALUE : Integer.parseInt(ed.getMax());
4701    while (ed != null && ed.getPath().contains(".")) {
4702      ed = findParent(ed, list);
4703      if (ed.getMax().equals("0"))
4704        max = 0;
4705      else if (!ed.getMax().equals("1") && !ed.hasSlicing())
4706        max = Integer.MAX_VALUE;
4707      if (ed.getMin() == 0)
4708        min = 0;
4709    }
4710    return Integer.toString(min)+".."+(max == Integer.MAX_VALUE ? "*" : Integer.toString(max));
4711  }
4712
4713
4714  private ElementDefinition findParent(ElementDefinition ed, List<ElementDefinition> list) {
4715    int i = list.indexOf(ed)-1;
4716    while (i >= 0 && !ed.getPath().startsWith(list.get(i).getPath()+"."))
4717      i--;
4718    if (i == -1)
4719      return null;
4720    else
4721      return list.get(i);
4722  }
4723
4724
4725  private List<String> listReferenceProfiles(ElementDefinition ed) {
4726    List<String> res = new ArrayList<String>();
4727    for (TypeRefComponent tr : ed.getType()) {
4728      // code is null if we're dealing with "value" and profile is null if we just have Reference()
4729      if (tr.hasTarget() && tr.hasTargetProfile())
4730        for (UriType u : tr.getTargetProfile())
4731          res.add(u.getValue());
4732    }
4733    return res;
4734  }
4735
4736
4737  private String nameForElement(ElementDefinition ed) {
4738    return ed.getPath().substring(ed.getPath().indexOf(".")+1);
4739  }
4740
4741
4742  private SpanEntry buildSpanEntryFromProfile(String name, String cardinality, StructureDefinition profile) throws IOException {
4743    SpanEntry res = new SpanEntry();
4744    res.setName(name);
4745    res.setCardinality(cardinality);
4746    res.setProfileLink(profile.getUserString("path"));
4747    res.setResType(profile.getType());
4748    StructureDefinition base = context.fetchResource(StructureDefinition.class, res.getResType());
4749    if (base != null)
4750      res.setResLink(base.getUserString("path"));
4751    res.setId(profile.getId());
4752    res.setProfile(profile.getDerivation() == TypeDerivationRule.CONSTRAINT);
4753    StringBuilder b = new StringBuilder();
4754    b.append(res.getResType());
4755    boolean first = true;
4756    boolean open = false;
4757    if (profile.getDerivation() == TypeDerivationRule.CONSTRAINT) {
4758      res.setDescription(profile.getName());
4759      for (ElementDefinition ed : profile.getSnapshot().getElement()) {
4760        if (isKeyProperty(ed.getBase().getPath()) && ed.hasFixed()) {
4761          if (first) {
4762            open = true;
4763            first = false;
4764            b.append("[");
4765          } else {
4766            b.append(", ");
4767          }
4768          b.append(tail(ed.getBase().getPath()));
4769          b.append("=");
4770          b.append(summarize(ed.getFixed()));
4771        }
4772      }
4773      if (open)
4774        b.append("]");
4775    } else
4776      res.setDescription("Base FHIR "+profile.getName());
4777    res.setType(b.toString());
4778    return res ;
4779  }
4780
4781
4782  private String summarize(Type value) throws IOException {
4783    if (value instanceof Coding)
4784      return summarizeCoding((Coding) value);
4785    else if (value instanceof CodeableConcept)
4786      return summarizeCodeableConcept((CodeableConcept) value);
4787    else
4788      return buildJson(value);
4789  }
4790
4791
4792  private String summarizeCoding(Coding value) {
4793    String uri = value.getSystem();
4794    String system = NarrativeGenerator.describeSystem(uri);
4795    if (Utilities.isURL(system)) {
4796      if (system.equals("http://cap.org/protocols"))
4797        system = "CAP Code";
4798    }
4799    return system+" "+value.getCode();
4800  }
4801
4802
4803  private String summarizeCodeableConcept(CodeableConcept value) {
4804    if (value.hasCoding())
4805      return summarizeCoding(value.getCodingFirstRep());
4806    else
4807      return value.getText();
4808  }
4809
4810
4811  private boolean isKeyProperty(String path) {
4812    return Utilities.existsInList(path, "Observation.code");
4813  }
4814
4815
4816  public TableModel initSpanningTable(HierarchicalTableGenerator gen, String prefix, boolean isLogical) {
4817    TableModel model = gen.new TableModel();
4818    
4819    model.setDocoImg(prefix+"help16.png");
4820    model.setDocoRef(prefix+"formats.html#table"); // todo: change to graph definition
4821    model.getTitles().add(gen.new Title(null, model.getDocoRef(), "Property", "A profiled resource", null, 0));
4822    model.getTitles().add(gen.new Title(null, model.getDocoRef(), "Card.", "Minimum and Maximum # of times the the element can appear in the instance", null, 0));
4823    model.getTitles().add(gen.new Title(null, model.getDocoRef(), "Content", "What goes here", null, 0));
4824    model.getTitles().add(gen.new Title(null, model.getDocoRef(), "Description", "Description of the profile", null, 0));
4825    return model;
4826  }
4827
4828  private void genSpanEntry(HierarchicalTableGenerator gen, List<Row> rows, SpanEntry span) throws IOException {
4829    Row row = gen.new Row();
4830    rows.add(row);
4831    row.setAnchor(span.getId());
4832    //row.setColor(..?);
4833    if (span.isProfile()) 
4834      row.setIcon("icon_profile.png", HierarchicalTableGenerator.TEXT_ICON_PROFILE);
4835    else
4836      row.setIcon("icon_resource.png", HierarchicalTableGenerator.TEXT_ICON_RESOURCE);
4837    
4838    row.getCells().add(gen.new Cell(null, null, span.getName(), null, null));
4839    row.getCells().add(gen.new Cell(null, null, span.getCardinality(), null, null));
4840    row.getCells().add(gen.new Cell(null, span.getProfileLink(), span.getType(), null, null));
4841    row.getCells().add(gen.new Cell(null, null, span.getDescription(), null, null));
4842
4843    for (SpanEntry child : span.getChildren())
4844      genSpanEntry(gen, row.getSubRows(), child);
4845  }
4846
4847
4848  public static ElementDefinitionSlicingDiscriminatorComponent interpretR2Discriminator(String discriminator, boolean isExists) {
4849    if (discriminator.endsWith("@pattern"))
4850      return makeDiscriminator(DiscriminatorType.PATTERN, discriminator.length() == 8 ? "" : discriminator.substring(0,discriminator.length()-9)); 
4851    if (discriminator.endsWith("@profile"))
4852      return makeDiscriminator(DiscriminatorType.PROFILE, discriminator.length() == 8 ? "" : discriminator.substring(0,discriminator.length()-9)); 
4853    if (discriminator.endsWith("@type")) 
4854      return makeDiscriminator(DiscriminatorType.TYPE, discriminator.length() == 5 ? "" : discriminator.substring(0,discriminator.length()-6));
4855    if (discriminator.endsWith("@exists"))
4856      return makeDiscriminator(DiscriminatorType.EXISTS, discriminator.length() == 7 ? "" : discriminator.substring(0,discriminator.length()-8)); 
4857    if (isExists)
4858      return makeDiscriminator(DiscriminatorType.EXISTS, discriminator); 
4859    return new ElementDefinitionSlicingDiscriminatorComponent().setType(DiscriminatorType.VALUE).setPath(discriminator);
4860  }
4861
4862
4863  private static ElementDefinitionSlicingDiscriminatorComponent makeDiscriminator(DiscriminatorType dType, String str) {
4864    return new ElementDefinitionSlicingDiscriminatorComponent().setType(dType).setPath(Utilities.noString(str)? "$this" : str);
4865  }
4866
4867
4868  public static String buildR2Discriminator(ElementDefinitionSlicingDiscriminatorComponent t) throws FHIRException {
4869    switch (t.getType()) {
4870    case PROFILE: return t.getPath()+"/@profile";
4871    case PATTERN: return t.getPath()+"/@pattern";
4872    case TYPE: return t.getPath()+"/@type";
4873    case VALUE: return t.getPath();
4874    case EXISTS: return t.getPath(); // determination of value vs. exists is based on whether there's only 2 slices - one with minOccurs=1 and other with maxOccur=0
4875    default: throw new FHIRException("Unable to represent "+t.getType().toCode()+":"+t.getPath()+" in R2");    
4876    }
4877  }
4878
4879
4880  public static StructureDefinition makeExtensionForVersionedURL(IWorkerContext context, String url) {
4881    String epath = url.substring(54);
4882    if (!epath.contains("."))
4883      return null;
4884    String type = epath.substring(0, epath.indexOf("."));
4885    StructureDefinition sd = context.fetchTypeDefinition(type);
4886    if (sd == null)
4887      return null;
4888    ElementDefinition ed = null;
4889    for (ElementDefinition t : sd.getSnapshot().getElement()) {
4890      if (t.getPath().equals(epath)) {
4891        ed = t;
4892        break;
4893      }
4894    }
4895    if (ed == null)
4896      return null;
4897    if ("Element".equals(ed.typeSummary()) || "BackboneElement".equals(ed.typeSummary())) {
4898      return null;
4899    } else {
4900      StructureDefinition template = context.fetchResource(StructureDefinition.class, "http://fhir-registry.smarthealthit.org/StructureDefinition/capabilities");
4901      StructureDefinition ext = template.copy();
4902      ext.setUrl(url);
4903      ext.setId("extension-"+epath);
4904      ext.setName("Extension-"+epath);
4905      ext.setTitle("Extension for r4 "+epath);
4906      ext.setStatus(sd.getStatus());
4907      ext.setDate(sd.getDate());
4908      ext.getContact().clear();
4909      ext.getContact().addAll(sd.getContact());
4910      ext.setFhirVersion(sd.getFhirVersion());
4911      ext.setDescription(ed.getDefinition());
4912      ext.getContext().clear();
4913      ext.addContext().setType(ExtensionContextType.ELEMENT).setExpression(epath.substring(0, epath.lastIndexOf(".")));
4914      ext.getDifferential().getElement().clear();
4915      ext.getSnapshot().getElement().get(3).setFixed(new UriType(url));
4916      ext.getSnapshot().getElement().set(4, ed.copy());
4917      ext.getSnapshot().getElement().get(4).setPath("Extension.value"+Utilities.capitalize(ed.typeSummary()));
4918      return ext;      
4919    }
4920
4921  }
4922
4923
4924  public boolean isThrowException() {
4925    return exception;
4926  }
4927
4928
4929  public void setThrowException(boolean exception) {
4930    this.exception = exception;
4931  }
4932
4933
4934  public TerminologyServiceOptions getTerminologyServiceOptions() {
4935    return terminologyServiceOptions;
4936  }
4937
4938
4939  public void setTerminologyServiceOptions(TerminologyServiceOptions terminologyServiceOptions) {
4940    this.terminologyServiceOptions = terminologyServiceOptions;
4941  }
4942
4943
4944  public boolean isNewSlicingProcessing() {
4945    return newSlicingProcessing;
4946  }
4947
4948
4949  public void setNewSlicingProcessing(boolean newSlicingProcessing) {
4950    this.newSlicingProcessing = newSlicingProcessing;
4951  }
4952
4953
4954  public boolean isDebug() {
4955    return debug;
4956  }
4957
4958
4959  public void setDebug(boolean debug) {
4960    this.debug = debug;
4961  }
4962
4963
4964  public String getDefWebRoot() {
4965    return defWebRoot;
4966  }
4967
4968
4969  public void setDefWebRoot(String defWebRoot) {
4970    this.defWebRoot = defWebRoot;
4971    if (!this.defWebRoot.endsWith("/"))
4972      this.defWebRoot = this.defWebRoot + '/';
4973  }
4974
4975
4976
4977  
4978}