Search in sources :

Example 31 with TS

use of org.hl7.v3.TS in project kindling by HL7.

the class PageProcessor method orgDT.

private String orgDT(String name, String xml, String tree, String uml1, String uml2, String ref, String ts, String json, String ttl, String diff) {
    StringBuilder b = new StringBuilder();
    b.append("<div id=\"tabs-").append(name).append("\">\r\n");
    b.append(" <ul>\r\n");
    b.append("  <li><a href=\"#tabs-" + name + "-struc\">Structure</a></li>\r\n");
    b.append("  <li><a href=\"#tabs-" + name + "-uml\">UML</a></li>\r\n");
    b.append("  <li><a href=\"#tabs-" + name + "-xml\">XML</a></li>\r\n");
    b.append("  <li><a href=\"#tabs-" + name + "-json\">JSON</a></li>\r\n");
    b.append("  <li><a href=\"#tabs-" + name + "-ttl\">Turtle</a></li>\r\n");
    b.append("  <li><a href=\"#tabs-" + name + "-diff\">R3 Diff</a></li>\r\n");
    b.append("  <li><a href=\"#tabs-" + name + "-all\">All</a></li>\r\n");
    b.append(" </ul>\r\n");
    b.append(" <div id=\"tabs-" + name + "-struc\">\r\n");
    b.append("  <div id=\"tbl\">\r\n");
    b.append("   <p><b>Structure</b></p>\r\n");
    b.append("   <div id=\"tbl-inner\">\r\n");
    b.append("    " + tree + "\r\n");
    b.append("   </div>\r\n");
    b.append("  </div>\r\n");
    b.append(" </div>\r\n");
    b.append("\r\n");
    b.append(" <div id=\"tabs-" + name + "-uml\">\r\n");
    b.append("  <div id=\"uml\">\r\n");
    b.append("   <p><b>UML Diagram</b> (<a href=\"formats.html#uml\">Legend</a>)</p>\r\n");
    b.append("   <div id=\"uml-inner\">\r\n");
    b.append("    " + uml1 + "\r\n");
    b.append("   </div>\r\n");
    b.append("  </div>\r\n");
    b.append(" </div>\r\n");
    b.append("\r\n");
    b.append(" <div id=\"tabs-" + name + "-xml\">\r\n");
    b.append("  <div id=\"xml\">\r\n");
    b.append("   <p><b>XML Template</b></p>\r\n");
    b.append("   <div id=\"xml-inner\">\r\n");
    b.append("    " + xml + "\r\n");
    b.append("   </div>\r\n");
    b.append("  </div>\r\n");
    b.append(" </div>\r\n");
    b.append("\r\n");
    b.append(" <div id=\"tabs-" + name + "-json\">\r\n");
    b.append("  <div id=\"json\">\r\n");
    b.append("   <p><b>JSON Template</b></p>\r\n");
    b.append("   <div id=\"json-inner\">\r\n");
    b.append("    " + json + "\r\n");
    b.append("   </div>\r\n");
    b.append("  </div>\r\n");
    b.append(" </div>\r\n");
    b.append("\r\n");
    b.append(" <div id=\"tabs-" + name + "-ttl\">\r\n");
    b.append("  <div id=\"ttl\">\r\n");
    b.append("   <p><b>Turtle Template</b></p>\r\n");
    b.append("   <div id=\"ttl-inner\">\r\n");
    b.append("    " + ttl + "\r\n");
    b.append("   </div>\r\n");
    b.append("  </div>\r\n");
    b.append(" </div>\r\n");
    b.append("\r\n");
    b.append(" <div id=\"tabs-" + name + "-diff\">\r\n");
    b.append("  <div id=\"diff\">\r\n");
    b.append("   <p><b>Changes since Release 3</b></p>\r\n");
    b.append("   <div id=\"diff-inner\">\r\n");
    b.append("    " + diff + "\r\n");
    b.append("   </div>\r\n");
    b.append("  </div>\r\n");
    b.append(" </div>\r\n");
    b.append("\r\n");
    b.append(" <div id=\"tabs-" + name + "-all\">\r\n");
    b.append("  <div id=\"tbla\">\r\n");
    b.append("   <a name=\"tbl-" + name + "\"> </a>\r\n");
    b.append("   <p><b>Structure</b></p>\r\n");
    b.append("   <div id=\"tbl-inner\">\r\n");
    b.append("    " + tree + "\r\n");
    b.append("   </div>\r\n");
    b.append("  </div>\r\n");
    b.append("\r\n");
    b.append("  <div id=\"umla\">\r\n");
    b.append("   <a name=\"uml-" + name + "\"> </a>\r\n");
    b.append("   <p><b>UML Diagram</b> (<a href=\"formats.html#uml\">Legend</a>)</p>\r\n");
    b.append("   <div id=\"uml-inner\">\r\n");
    b.append("    " + uml2 + "\r\n");
    b.append("   </div>\r\n");
    b.append("  </div>\r\n");
    b.append("\r\n");
    b.append("  <div id=\"xmla\">\r\n");
    b.append("   <a name=\"xml-" + name + "\"> </a>\r\n");
    b.append("   <p><b>XML Template</b></p>\r\n");
    b.append("   <div id=\"xml-inner\">\r\n");
    b.append("     " + xml + "\r\n");
    b.append("   </div>\r\n");
    b.append("  </div>\r\n");
    b.append("\r\n");
    b.append("  <div id=\"jsona\">\r\n");
    b.append("   <a name=\"json-" + name + "\"> </a>\r\n");
    b.append("   <p><b>JSON Template</b></p>\r\n");
    b.append("   <div id=\"json-inner\">\r\n");
    b.append("     " + json + "\r\n");
    b.append("   </div>\r\n");
    b.append("  </div>\r\n");
    b.append("  <div id=\"ttla\">\r\n");
    b.append("   <a name=\"ttl-" + name + "\"> </a>\r\n");
    b.append("   <p><b>Turtle Template</b></p>\r\n");
    b.append("   <div id=\"ttl-inner\">\r\n");
    b.append("     " + ttl + "\r\n");
    b.append("   </div>\r\n");
    b.append("  </div>\r\n");
    b.append("  <div id=\"diffa\">\r\n");
    b.append("   <a name=\"diff-" + name + "\"> </a>\r\n");
    b.append("   <p><b>Changes since Release 3</b></p>\r\n");
    b.append("   <div id=\"diff-inner\">\r\n");
    b.append("     " + diff + "\r\n");
    b.append("   </div>\r\n");
    b.append("  </div>\r\n");
    b.append(" </div>\r\n");
    b.append("</div>\r\n");
    return b.toString();
}
Also used : CommaSeparatedStringBuilder(org.hl7.fhir.utilities.CommaSeparatedStringBuilder)

Example 32 with TS

use of org.hl7.v3.TS in project org.hl7.fhir.core by hapifhir.

the class ProfileUtilities method processPaths.

/**
 * @param trimDifferential
 * @param srcSD
 * @throws DefinitionException, FHIRException
 * @throws Exception
 */
private ElementDefinition processPaths(String indent, StructureDefinitionSnapshotComponent result, StructureDefinitionSnapshotComponent base, StructureDefinitionDifferentialComponent differential, int baseCursor, int diffCursor, int baseLimit, int diffLimit, String url, String webUrl, String profileName, String contextPathSrc, String contextPathDst, boolean trimDifferential, String contextName, String resultPathBase, boolean slicingDone, ElementDefinition slicer, String typeSlicingPath, List<ElementRedirection> redirector, StructureDefinition srcSD) throws DefinitionException, FHIRException {
    if (debug) {
        System.out.println(indent + "PP @ " + resultPathBase + " / " + contextPathSrc + " : base = " + baseCursor + " to " + baseLimit + ", diff = " + diffCursor + " to " + diffLimit + " (slicing = " + slicingDone + ", k " + (redirector == null ? "null" : redirector.toString()) + ")");
    }
    ElementDefinition res = null;
    List<TypeSlice> typeList = new ArrayList<>();
    // just repeat processing entries until we run out of our allowed scope (1st entry, the allowed scope is all the entries)
    while (baseCursor <= baseLimit) {
        // get the current focus of the base, and decide what to do
        ElementDefinition currentBase = base.getElement().get(baseCursor);
        String cpath = fixedPathSource(contextPathSrc, currentBase.getPath(), redirector);
        if (debug) {
            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) + ") " + "(slicingDone = " + slicingDone + ") (diffpath= " + (differential.getElement().size() > diffCursor ? differential.getElement().get(diffCursor).getPath() : "n/a") + ")");
        }
        // get a list of matching elements in scope
        List<ElementDefinition> diffMatches = getDiffMatches(differential, cpath, diffCursor, diffLimit, profileName);
        // in the simple case, source is not sliced.
        if (!currentBase.hasSlicing() || cpath.equals(typeSlicingPath)) {
            if (diffMatches.isEmpty()) {
                // the differential doesn't say anything about this item
                // so we just copy it in
                ElementDefinition outcome = updateURLs(url, webUrl, currentBase.copy());
                outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
                updateFromBase(outcome, currentBase);
                updateConstraintSources(outcome, srcSD.getUrl());
                markDerived(outcome);
                if (resultPathBase == null)
                    resultPathBase = outcome.getPath();
                else if (!outcome.getPath().startsWith(resultPathBase))
                    throw new DefinitionException(context.formatMessage(I18nConstants.ADDING_WRONG_PATH__OUTCOMEGETPATH___RESULTPATHBASE__, outcome.getPath(), resultPathBase));
                result.getElement().add(outcome);
                if (hasInnerDiffMatches(differential, cpath, diffCursor, diffLimit, base.getElement(), true)) {
                    // did we implicitly step into a new type?
                    if (baseHasChildren(base, currentBase)) {
                        // not a new type here
                        processPaths(indent + "  ", result, base, differential, baseCursor + 1, diffCursor, baseLimit, diffLimit, url, webUrl, profileName, contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, false, null, null, redirector, srcSD);
                        baseCursor = indexOfFirstNonChild(base, currentBase, baseCursor + 1, baseLimit);
                    } else {
                        if (outcome.getType().size() == 0 && !outcome.hasContentReference()) {
                            throw new DefinitionException(context.formatMessage(I18nConstants._HAS_NO_CHILDREN__AND_NO_TYPES_IN_PROFILE_, cpath, differential.getElement().get(diffCursor).getPath(), profileName));
                        }
                        boolean nonExtension = false;
                        if (outcome.getType().size() > 1) {
                            for (TypeRefComponent t : outcome.getType()) {
                                if (!t.getWorkingCode().equals("Reference")) {
                                    for (ElementDefinition ed : diffMatches) {
                                        if (ed != diffMatches.get(0) && !ed.getPath().endsWith(".extension")) {
                                            nonExtension = true;
                                        }
                                    }
                                }
                            }
                        }
                        int start = diffCursor;
                        while (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), cpath + ".")) diffCursor++;
                        if (nonExtension) {
                            throw new DefinitionException(context.formatMessage(I18nConstants._HAS_CHILDREN__AND_MULTIPLE_TYPES__IN_PROFILE_, cpath, differential.getElement().get(diffCursor).getPath(), typeCode(outcome.getType()), profileName));
                        }
                        if (outcome.hasContentReference()) {
                            ElementDefinitionResolution tgt = getElementById(srcSD, base.getElement(), outcome.getContentReference());
                            if (tgt == null)
                                throw new DefinitionException(context.formatMessage(I18nConstants.UNABLE_TO_RESOLVE_REFERENCE_TO_, outcome.getContentReference()));
                            replaceFromContentReference(outcome, tgt.getElement());
                            if (tgt.getSource() != srcSD) {
                                base = tgt.getSource().getSnapshot();
                                int nbc = base.getElement().indexOf(tgt.getElement()) + 1;
                                int nbl = nbc;
                                while (nbl < base.getElement().size() && base.getElement().get(nbl).getPath().startsWith(tgt.getElement().getPath() + ".")) nbl++;
                                processPaths(indent + "  ", result, base, differential, nbc, start - 1, nbl - 1, diffCursor - 1, url, webUrl, profileName, tgt.getElement().getPath(), diffMatches.get(0).getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirectorStack(redirector, outcome, cpath), tgt.getSource());
                            } else {
                                int nbc = base.getElement().indexOf(tgt.getElement()) + 1;
                                int nbl = nbc;
                                while (nbl < base.getElement().size() && base.getElement().get(nbl).getPath().startsWith(tgt.getElement().getPath() + ".")) nbl++;
                                System.out.println("Test!");
                                processPaths(indent + "  ", result, base, differential, nbc, start, nbl - 1, diffCursor - 1, url, webUrl, profileName, tgt.getElement().getPath(), outcome.getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirectorStack(redirector, outcome, cpath), srcSD);
                            }
                        } else {
                            StructureDefinition dt = outcome.getType().size() > 1 ? context.fetchTypeDefinition("Element") : getProfileForDataType(outcome.getType().get(0), webUrl);
                            if (dt == null) {
                                throw new DefinitionException(context.formatMessage(I18nConstants.UNKNOWN_TYPE__AT_, outcome.getType().get(0), cpath));
                            }
                            contextName = dt.getUrl();
                            if (redirector.isEmpty()) {
                                processPaths(indent + "  ", result, dt.getSnapshot(), differential, 1, /* starting again on the data type, but skip the root */
                                start, dt.getSnapshot().getElement().size() - 1, diffCursor - 1, url, getWebUrl(dt, webUrl, indent), profileName, cpath, outcome.getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirector, srcSD);
                            } else {
                                processPaths(indent + "  ", result, dt.getSnapshot(), differential, 1, /* starting again on the data type, but skip the root */
                                start, dt.getSnapshot().getElement().size() - 1, diffCursor - 1, url, getWebUrl(dt, webUrl, indent), profileName, cpath, outcome.getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirectorStack(redirector, currentBase, cpath), srcSD);
                            }
                        }
                    }
                }
                baseCursor++;
            } 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
                ElementDefinition template = null;
                if (diffMatches.get(0).hasType() && "Reference".equals(diffMatches.get(0).getType().get(0).getWorkingCode()) && !isValidType(diffMatches.get(0).getType().get(0), currentBase)) {
                    throw new DefinitionException(context.formatMessage(I18nConstants.VALIDATION_VAL_ILLEGAL_TYPE_CONSTRAINT, url, diffMatches.get(0).getPath(), diffMatches.get(0).getType().get(0), currentBase.typeSummary()));
                }
                String id = diffMatches.get(0).getId();
                String lid = tail(id);
                if (lid.contains("/")) {
                    // the template comes from the snapshot of the base
                    generateIds(result.getElement(), url, srcSD.getType());
                    // this is wrong if there's more than one reslice (todo: one thing at a time)
                    String baseId = id.substring(0, id.length() - lid.length()) + lid.substring(0, lid.indexOf("/"));
                    template = getById(result.getElement(), baseId);
                } else 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())) {
                    CanonicalType p = diffMatches.get(0).getType().get(0).getProfile().get(0);
                    StructureDefinition sd = context.fetchResource(StructureDefinition.class, p.getValue());
                    if (sd == null && xver != null && xver.matchingUrl(p.getValue())) {
                        switch(xver.status(p.getValue())) {
                            case BadVersion:
                                throw new FHIRException("Reference to invalid version in extension url " + p.getValue());
                            case Invalid:
                                throw new FHIRException("Reference to invalid extension " + p.getValue());
                            case Unknown:
                                throw new FHIRException("Reference to unknown extension " + p.getValue());
                            case Valid:
                                sd = xver.makeDefinition(p.getValue());
                                generateSnapshot(context.fetchTypeDefinition("Extension"), sd, sd.getUrl(), webUrl, sd.getName());
                        }
                    }
                    if (sd != null) {
                        if (!isMatchingType(sd, diffMatches.get(0).getType(), p.getExtensionString(ToolingExtensions.EXT_PROFILE_ELEMENT))) {
                            throw new DefinitionException(context.formatMessage(I18nConstants.VALIDATION_VAL_PROFILE_WRONGTYPE2, sd.getUrl(), diffMatches.get(0).getPath(), sd.getType(), p.getValue(), diffMatches.get(0).getType().get(0).getWorkingCode()));
                        }
                        if (isGenerating(sd)) {
                            // but we check anyway
                            if (sd.getSnapshot().getElementFirstRep().isEmpty()) {
                                throw new FHIRException(context.formatMessage(I18nConstants.ATTEMPT_TO_USE_A_SNAPSHOT_ON_PROFILE__AS__BEFORE_IT_IS_GENERATED, sd.getUrl(), "Source for first element"));
                            }
                        } else if (!sd.hasSnapshot()) {
                            StructureDefinition sdb = context.fetchResource(StructureDefinition.class, sd.getBaseDefinition());
                            if (sdb == null)
                                throw new DefinitionException(context.formatMessage(I18nConstants.UNABLE_TO_FIND_BASE__FOR_, sd.getBaseDefinition(), sd.getUrl()));
                            checkNotGenerating(sdb, "an extension base");
                            generateSnapshot(sdb, sd, sd.getUrl(), (sdb.hasUserData("path")) ? Utilities.extractBaseUrl(sdb.getUserString("path")) : webUrl, sd.getName());
                        }
                        ElementDefinition src;
                        if (p.hasExtension(ToolingExtensions.EXT_PROFILE_ELEMENT)) {
                            src = null;
                            String eid = p.getExtensionString(ToolingExtensions.EXT_PROFILE_ELEMENT);
                            for (ElementDefinition t : sd.getSnapshot().getElement()) {
                                if (eid.equals(t.getId()))
                                    src = t;
                            }
                            if (src == null)
                                throw new DefinitionException(context.formatMessage(I18nConstants.UNABLE_TO_FIND_ELEMENT__IN_, eid, p.getValue()));
                        } else
                            src = sd.getSnapshot().getElement().get(0);
                        template = src.copy().setPath(currentBase.getPath());
                        template.setSliceName(null);
                        // temporary work around
                        if (!"Extension".equals(diffMatches.get(0).getType().get(0).getCode())) {
                            template.setMin(currentBase.getMin());
                            template.setMax(currentBase.getMax());
                        }
                    }
                }
                if (template == null)
                    template = currentBase.copy();
                else
                    // some of what's in currentBase overrides template
                    template = fillOutFromBase(template, currentBase);
                ElementDefinition outcome = updateURLs(url, webUrl, template);
                outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
                if (res == null)
                    res = outcome;
                updateFromBase(outcome, currentBase);
                if (diffMatches.get(0).hasSliceName()) {
                    outcome.setSliceName(diffMatches.get(0).getSliceName());
                    if (!diffMatches.get(0).hasMin() && (diffMatches.size() > 1 || slicer == null || slicer.getSlicing().getRules() != SlicingRules.CLOSED) && !currentBase.hasSliceName()) {
                        if (!cpath.endsWith("xtension.value[x]")) {
                            // hack work around for problems with snapshots in official releases
                            outcome.setMin(0);
                        }
                    }
                }
                updateFromDefinition(outcome, diffMatches.get(0), profileName, trimDifferential, url, srcSD);
                removeStatusExtensions(outcome);
                // 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
                // outcome.setPath(outcome.getPath().substring(0, outcome.getPath().length()-3)+Utilities.capitalize(outcome.getType().get(0).getCode()));
                outcome.setSlicing(null);
                if (resultPathBase == null)
                    resultPathBase = outcome.getPath();
                else if (!outcome.getPath().startsWith(resultPathBase))
                    throw new DefinitionException(context.formatMessage(I18nConstants.ADDING_WRONG_PATH));
                result.getElement().add(outcome);
                baseCursor++;
                diffCursor = differential.getElement().indexOf(diffMatches.get(0)) + 1;
                if (diffLimit >= diffCursor && outcome.getPath().contains(".") && (isDataType(outcome.getType()) || isBaseResource(outcome.getType()) || outcome.hasContentReference())) {
                    // don't want to do this for the root, since that's base, and we're already processing it
                    if (pathStartsWith(differential.getElement().get(diffCursor).getPath(), diffMatches.get(0).getPath() + ".") && !baseWalksInto(base.getElement(), baseCursor)) {
                        if (outcome.getType().size() > 1) {
                            if (outcome.getPath().endsWith("[x]") && !diffMatches.get(0).getPath().endsWith("[x]")) {
                                String en = tail(outcome.getPath());
                                String tn = tail(diffMatches.get(0).getPath());
                                String t = tn.substring(en.length() - 3);
                                if (isPrimitive(Utilities.uncapitalize(t)))
                                    t = Utilities.uncapitalize(t);
                                // keep any additional information
                                List<TypeRefComponent> ntr = getByTypeName(outcome.getType(), t);
                                if (ntr.isEmpty())
                                    ntr.add(new TypeRefComponent().setCode(t));
                                outcome.getType().clear();
                                outcome.getType().addAll(ntr);
                            }
                            if (outcome.getType().size() > 1)
                                for (TypeRefComponent t : outcome.getType()) {
                                    if (!t.getCode().equals("Reference")) {
                                        boolean nonExtension = false;
                                        for (ElementDefinition ed : diffMatches) if (ed != diffMatches.get(0) && !ed.getPath().endsWith(".extension"))
                                            nonExtension = true;
                                        if (nonExtension)
                                            throw new DefinitionException(context.formatMessage(I18nConstants._HAS_CHILDREN__AND_MULTIPLE_TYPES__IN_PROFILE_, diffMatches.get(0).getPath(), differential.getElement().get(diffCursor).getPath(), typeCode(outcome.getType()), profileName));
                                    }
                                }
                        }
                        int start = diffCursor;
                        while (diffCursor <= diffLimit && differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), diffMatches.get(0).getPath() + ".")) diffCursor++;
                        if (outcome.hasContentReference()) {
                            ElementDefinitionResolution tgt = getElementById(srcSD, base.getElement(), outcome.getContentReference());
                            if (tgt == null)
                                throw new DefinitionException(context.formatMessage(I18nConstants.UNABLE_TO_RESOLVE_REFERENCE_TO_, outcome.getContentReference()));
                            replaceFromContentReference(outcome, tgt.getElement());
                            if (tgt.getSource() != srcSD) {
                                base = tgt.getSource().getSnapshot();
                                int nbc = base.getElement().indexOf(tgt.getElement()) + 1;
                                int nbl = nbc;
                                while (nbl < base.getElement().size() && base.getElement().get(nbl).getPath().startsWith(tgt.getElement().getPath() + ".")) nbl++;
                                processPaths(indent + "  ", result, base, differential, nbc, start - 1, nbl - 1, diffCursor - 1, url, webUrl, profileName, tgt.getElement().getPath(), diffMatches.get(0).getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirectorStack(redirector, outcome, cpath), tgt.getSource());
                            } else {
                                int nbc = base.getElement().indexOf(tgt.getElement()) + 1;
                                int nbl = nbc;
                                while (nbl < base.getElement().size() && base.getElement().get(nbl).getPath().startsWith(tgt.getElement().getPath() + ".")) nbl++;
                                processPaths(indent + "  ", result, base, differential, nbc, start - 1, nbl - 1, diffCursor - 1, url, webUrl, profileName, tgt.getElement().getPath(), diffMatches.get(0).getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirectorStack(redirector, outcome, cpath), srcSD);
                            }
                        } else {
                            StructureDefinition dt = outcome.getType().size() == 1 ? getProfileForDataType(outcome.getType().get(0), webUrl) : getProfileForDataType("Element");
                            if (dt == null)
                                throw new DefinitionException(context.formatMessage(I18nConstants._HAS_CHILDREN__FOR_TYPE__IN_PROFILE__BUT_CANT_FIND_TYPE, diffMatches.get(0).getPath(), differential.getElement().get(diffCursor).getPath(), typeCode(outcome.getType()), profileName));
                            contextName = dt.getUrl();
                            processPaths(indent + "  ", result, dt.getSnapshot(), differential, 1, /* starting again on the data type, but skip the root */
                            start, dt.getSnapshot().getElement().size() - 1, diffCursor - 1, url, getWebUrl(dt, webUrl, indent), profileName + pathTail(diffMatches, 0), diffMatches.get(0).getPath(), outcome.getPath(), trimDifferential, contextName, resultPathBase, false, null, null, new ArrayList<ElementRedirection>(), srcSD);
                        }
                    }
                }
            } else if (diffsConstrainTypes(diffMatches, cpath, typeList)) {
                int start = 0;
                int nbl = findEndOfElement(base, baseCursor);
                int ndc = differential.getElement().indexOf(diffMatches.get(0));
                ElementDefinition elementToRemove = null;
                boolean shortCut = !typeList.isEmpty() && typeList.get(0).type != null;
                // we come here whether they are sliced in the diff, or whether the short cut is used.
                if (shortCut) {
                    // in R3 (and unpatched R4, as a workaround right now...
                    if (!FHIRVersion.isR4Plus(context.getVersion()) || !newSlicingProcessing) {
                        // newSlicingProcessing is a work around for editorial loop dependency
                        // we insert a cloned element with the right types at the start of the diffMatches
                        ElementDefinition ed = new ElementDefinition();
                        ed.setPath(determineTypeSlicePath(diffMatches.get(0).getPath(), cpath));
                        for (TypeSlice ts : typeList) ed.addType().setCode(ts.type);
                        ed.setSlicing(new ElementDefinitionSlicingComponent());
                        ed.getSlicing().addDiscriminator().setType(DiscriminatorType.TYPE).setPath("$this");
                        ed.getSlicing().setRules(SlicingRules.CLOSED);
                        ed.getSlicing().setOrdered(false);
                        diffMatches.add(0, ed);
                        differential.getElement().add(ndc, ed);
                        elementToRemove = ed;
                    } else {
                        // as of R4, this changed; if there's no slice, there's no constraint on the slice types, only one the type.
                        // so the element we insert specifies no types (= all types) allowed in the base, not just the listed type.
                        // see also discussion here: https://chat.fhir.org/#narrow/stream/179177-conformance/topic/Slicing.20a.20non-repeating.20element
                        ElementDefinition ed = new ElementDefinition();
                        ed.setPath(determineTypeSlicePath(diffMatches.get(0).getPath(), cpath));
                        ed.setSlicing(new ElementDefinitionSlicingComponent());
                        ed.getSlicing().addDiscriminator().setType(DiscriminatorType.TYPE).setPath("$this");
                        ed.getSlicing().setRules(SlicingRules.CLOSED);
                        ed.getSlicing().setOrdered(false);
                        diffMatches.add(0, ed);
                        differential.getElement().add(ndc, ed);
                        elementToRemove = ed;
                    }
                }
                int ndl = findEndOfElement(differential, ndc);
                if (diffMatches.get(0).getSlicing().hasOrdered()) {
                    if (diffMatches.get(0).getSlicing().getOrdered()) {
                        throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__IN__TYPE_SLICING_WITH_SLICINGORDERED__TRUE, cpath, url));
                    }
                }
                if (diffMatches.get(0).getSlicing().hasDiscriminator()) {
                    if (diffMatches.get(0).getSlicing().getDiscriminator().size() != 1) {
                        throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__IN__TYPE_SLICING_WITH_SLICINGDISCRIMINATORCOUNT__1, cpath, url));
                    }
                    if (diffMatches.get(0).getSlicing().getDiscriminatorFirstRep().getType() != DiscriminatorType.TYPE) {
                        throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__IN__TYPE_SLICING_WITH_SLICINGDISCRIMINATORTYPE__TYPE, cpath, url));
                    }
                    if (!"$this".equals(diffMatches.get(0).getSlicing().getDiscriminatorFirstRep().getPath())) {
                        throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__IN__TYPE_SLICING_WITH_SLICINGDISCRIMINATORPATH__THIS, cpath, url));
                    }
                }
                // check the slice names too while we're at it...
                for (TypeSlice ts : typeList) {
                    if (ts.type != null) {
                        String tn = rootName(cpath) + Utilities.capitalize(ts.type);
                        if (!ts.defn.hasSliceName()) {
                            ts.defn.setSliceName(tn);
                        } else if (!ts.defn.getSliceName().equals(tn)) {
                            if (autoFixSliceNames) {
                                ts.defn.setSliceName(tn);
                            } else {
                                throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__SLICE_NAME_MUST_BE__BUT_IS_, (!Utilities.noString(contextPathSrc) ? contextPathSrc : cpath), tn, ts.defn.getSliceName()));
                            }
                        }
                        if (!ts.defn.hasType()) {
                            ts.defn.addType().setCode(ts.type);
                        } else if (ts.defn.getType().size() > 1) {
                            throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__SLICE_FOR_TYPE__HAS_MORE_THAN_ONE_TYPE_, (!Utilities.noString(contextPathSrc) ? contextPathSrc : cpath), tn, ts.defn.typeSummary()));
                        } else if (!ts.defn.getType().get(0).getCode().equals(ts.type)) {
                            throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__SLICE_FOR_TYPE__HAS_WRONG_TYPE_, (!Utilities.noString(contextPathSrc) ? contextPathSrc : cpath), tn, ts.defn.typeSummary()));
                        }
                    }
                }
                // ok passed the checks.
                // copy the root diff, and then process any children it has
                ElementDefinition e = processPaths(indent + "  ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName + pathTail(diffMatches, 0), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, true, null, null, redirector, srcSD);
                if (e == null)
                    throw new FHIRException(context.formatMessage(I18nConstants.DID_NOT_FIND_TYPE_ROOT_, diffMatches.get(0).getPath()));
                // now set up slicing on the e (cause it was wiped by what we called.
                e.setSlicing(new ElementDefinitionSlicingComponent());
                e.getSlicing().addDiscriminator().setType(DiscriminatorType.TYPE).setPath("$this");
                // type slicing is always closed; the differential might call it open, but that just means it's not constraining the slices it doesn't mention
                e.getSlicing().setRules(SlicingRules.CLOSED);
                e.getSlicing().setOrdered(false);
                start++;
                String fixedType = null;
                // now we process the base scope repeatedly for each instance of the item in the differential list
                for (int i = start; i < diffMatches.size(); i++) {
                    // our processing scope for the differential is the item in the list, and all the items before the next one in the list
                    if (diffMatches.get(i).getMin() > 0) {
                        if (diffMatches.size() > i + 1) {
                            throw new FHIRException(context.formatMessage(I18nConstants.INVALID_SLICING__THERE_IS_MORE_THAN_ONE_TYPE_SLICE_AT__BUT_ONE_OF_THEM__HAS_MIN__1_SO_THE_OTHER_SLICES_CANNOT_EXIST, diffMatches.get(i).getPath(), diffMatches.get(i).getSliceName()));
                        } else {
                            e.setMin(1);
                        }
                        fixedType = determineFixedType(diffMatches, fixedType, i);
                    }
                    ndc = differential.getElement().indexOf(diffMatches.get(i));
                    ndl = findEndOfElement(differential, ndc);
                    processPaths(indent + "  ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName + pathTail(diffMatches, i), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, true, e, null, redirector, srcSD);
                }
                if (elementToRemove != null) {
                    differential.getElement().remove(elementToRemove);
                    ndl--;
                }
                if (fixedType != null) {
                    for (Iterator<TypeRefComponent> iter = e.getType().iterator(); iter.hasNext(); ) {
                        TypeRefComponent tr = iter.next();
                        if (!tr.getCode().equals(fixedType)) {
                            iter.remove();
                        }
                    }
                }
                if (!"0".equals(e.getMax())) {
                    // check that there's a slice for each allowed types
                    Set<String> allowedTypes = getListOfTypes(e);
                    for (TypeSlice t : typeList) {
                        if (t.type != null) {
                            allowedTypes.remove(t.type);
                        } else if (t.getDefn().hasSliceName() && t.getDefn().getType().size() == 1) {
                            allowedTypes.remove(t.getDefn().getType().get(0).getCode());
                        }
                    }
                    if (!allowedTypes.isEmpty()) {
                        if (cpath.contains("xtension.value")) {
                            for (Iterator<TypeRefComponent> iter = e.getType().iterator(); iter.hasNext(); ) {
                                TypeRefComponent tr = iter.next();
                                if (allowedTypes.contains(tr.getCode())) {
                                    iter.remove();
                                }
                            }
                        // System.out.println("!!: Extension Error at "+cpath+": Allowed Types not sliced = "+allowedTypes+". !Extension!!");
                        // throw new Error("Extension Error at "+cpath+": Allowed Types not sliced = "+allowedTypes+". !Extension!!");
                        } else {
                            e.getSlicing().setRules(SlicingRules.OPEN);
                        }
                    }
                }
                // ok, done with that - next in the base list
                baseCursor = nbl + 1;
                diffCursor = ndl + 1;
            } else {
                // ok, the differential slices the item. Let's check our pre-conditions to ensure that this is correct
                if (!unbounded(currentBase) && !isSlicedToOneOnly(diffMatches.get(0)))
                    // (but you might do that in order to split up constraints by type)
                    throw new DefinitionException(context.formatMessage(I18nConstants.ATTEMPT_TO_A_SLICE_AN_ELEMENT_THAT_DOES_NOT_REPEAT__FROM__IN_, currentBase.getPath(), currentBase.getPath(), contextName, url, diffMatches.get(0).getId(), sliceNames(diffMatches)));
                if (// well, the diff has set up a slice, but hasn't defined it. this is an error
                !diffMatches.get(0).hasSlicing() && !isExtension(currentBase))
                    throw new DefinitionException(context.formatMessage(I18nConstants.DIFFERENTIAL_DOES_NOT_HAVE_A_SLICE__B_OF_____IN_PROFILE_, currentBase.getPath(), baseCursor, baseLimit, diffCursor, diffLimit, url, cpath));
                // well, if it passed those preconditions then we slice the dest.
                int start = 0;
                int nbl = findEndOfElement(base, baseCursor);
                // if (diffMatches.size() > 1 && diffMatches.get(0).hasSlicing() && differential.getElement().indexOf(diffMatches.get(1)) > differential.getElement().indexOf(diffMatches.get(0))+1) {
                ElementDefinition slicerElement;
                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
                    int ndc = differential.getElement().indexOf(diffMatches.get(0));
                    int ndl = findEndOfElement(differential, ndc);
                    ElementDefinition e = processPaths(indent + "  ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName + pathTail(diffMatches, 0), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, true, null, null, redirector, srcSD);
                    if (e == null)
                        throw new FHIRException(context.formatMessage(I18nConstants.DID_NOT_FIND_SINGLE_SLICE_, diffMatches.get(0).getPath()));
                    e.setSlicing(diffMatches.get(0).getSlicing());
                    slicerElement = e;
                    start++;
                } else {
                    // we're just going to accept the differential slicing at face value
                    ElementDefinition outcome = updateURLs(url, webUrl, currentBase.copy());
                    outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
                    updateFromBase(outcome, currentBase);
                    if (!diffMatches.get(0).hasSlicing())
                        outcome.setSlicing(makeExtensionSlicing());
                    else
                        outcome.setSlicing(diffMatches.get(0).getSlicing().copy());
                    if (!outcome.getPath().startsWith(resultPathBase))
                        throw new DefinitionException(context.formatMessage(I18nConstants.ADDING_WRONG_PATH));
                    result.getElement().add(outcome);
                    slicerElement = outcome;
                    // 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.
                    if (!diffMatches.get(0).hasSliceName()) {
                        updateFromDefinition(outcome, diffMatches.get(0), profileName, trimDifferential, url, srcSD);
                        removeStatusExtensions(outcome);
                        if (!outcome.hasContentReference() && !outcome.hasType()) {
                            throw new DefinitionException(context.formatMessage(I18nConstants.NOT_DONE_YET));
                        }
                        if (hasInnerDiffMatches(differential, currentBase.getPath(), diffCursor, diffLimit, base.getElement(), false)) {
                            if (baseHasChildren(base, currentBase)) {
                                // not a new type here
                                throw new Error("This situation is not yet handled (constrain slicing to 1..1 and fix base slice for inline structure - please report issue to grahame@fhir.org along with a test case that reproduces this error (@ " + cpath + " | " + currentBase.getPath() + ")");
                            } else {
                                StructureDefinition dt = getTypeForElement(differential, diffCursor, profileName, diffMatches, outcome, webUrl);
                                contextName = dt.getUrl();
                                diffCursor++;
                                start = diffCursor;
                                while (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), cpath + ".")) diffCursor++;
                                diffCursor--;
                                processPaths(indent + "  ", result, dt.getSnapshot(), differential, 1, /* starting again on the data type, but skip the root */
                                start, dt.getSnapshot().getElement().size() - 1, diffCursor, url, getWebUrl(dt, webUrl, indent), profileName, cpath, outcome.getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirector, srcSD);
                            }
                        }
                        start++;
                    // result.getElement().remove(result.getElement().size()-1);
                    } else
                        checkExtensionDoco(outcome);
                }
                // now, for each entry in the diff matches, we're going to process the base item
                // our processing scope for base is all the children of the current path
                int ndc = diffCursor;
                int ndl = diffCursor;
                for (int i = start; i < diffMatches.size(); i++) {
                    // our processing scope for the differential is the item in the list, and all the items before the next one in the list
                    ndc = differential.getElement().indexOf(diffMatches.get(i));
                    ndl = findEndOfElement(differential, ndc);
                    /*            if (skipSlicingElement && i == 0) {
              ndc = ndc + 1;
              if (ndc > ndl)
                continue;
            }*/
                    // now we process the base scope repeatedly for each instance of the item in the differential list
                    processPaths(indent + "  ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName + pathTail(diffMatches, i), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, true, slicerElement, null, redirector, srcSD);
                }
                // ok, done with that - next in the base list
                baseCursor = nbl + 1;
                diffCursor = ndl + 1;
            }
        } else {
            // the item is already sliced in the base profile.
            // here's the rules
            // 1. irrespective of whether the slicing is ordered or not, the definition order must be maintained
            // 2. slice element names have to match.
            // 3. new slices must be introduced at the end
            // corallory: you can't re-slice existing slices. is that ok?
            // we're going to need this:
            String path = currentBase.getPath();
            ElementDefinition original = currentBase;
            if (diffMatches.isEmpty()) {
                if (hasInnerDiffMatches(differential, path, diffCursor, diffLimit, base.getElement(), true)) {
                    // so we just copy it in
                    ElementDefinition outcome = updateURLs(url, webUrl, currentBase.copy());
                    outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
                    updateFromBase(outcome, currentBase);
                    markDerived(outcome);
                    if (resultPathBase == null)
                        resultPathBase = outcome.getPath();
                    else if (!outcome.getPath().startsWith(resultPathBase))
                        throw new DefinitionException(context.formatMessage(I18nConstants.ADDING_WRONG_PATH));
                    result.getElement().add(outcome);
                    // did we implicitly step into a new type?
                    if (baseHasChildren(base, currentBase)) {
                        // not a new type here
                        processPaths(indent + "  ", result, base, differential, baseCursor + 1, diffCursor, baseLimit, diffLimit, url, webUrl, profileName, contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, false, null, null, redirector, srcSD);
                        baseCursor = indexOfFirstNonChild(base, currentBase, baseCursor, baseLimit);
                    } else {
                        StructureDefinition dt = getTypeForElement(differential, diffCursor, profileName, diffMatches, outcome, webUrl);
                        contextName = dt.getUrl();
                        int start = diffCursor;
                        if (differential.getElement().get(diffCursor).getPath().equals(cpath)) {
                            diffCursor++;
                        }
                        while (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), cpath + ".")) {
                            diffCursor++;
                        }
                        if (diffCursor > start) {
                            processPaths(indent + "  ", result, dt.getSnapshot(), differential, 1, /* starting again on the data type, but skip the root */
                            start, dt.getSnapshot().getElement().size() - 1, diffCursor - 1, url, getWebUrl(dt, webUrl, indent), profileName, cpath, outcome.getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirector, srcSD);
                        }
                    }
                    baseCursor++;
                } else {
                    // copy across the currentbase, and all of its children and siblings
                    while (baseCursor < base.getElement().size() && base.getElement().get(baseCursor).getPath().startsWith(path)) {
                        ElementDefinition outcome = updateURLs(url, webUrl, base.getElement().get(baseCursor).copy());
                        outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
                        if (!outcome.getPath().startsWith(resultPathBase))
                            throw new DefinitionException(context.formatMessage(I18nConstants.ADDING_WRONG_PATH_IN_PROFILE___VS_, profileName, outcome.getPath(), resultPathBase));
                        // so we just copy it in
                        result.getElement().add(outcome);
                        baseCursor++;
                    }
                }
            } else if (diffsConstrainTypes(diffMatches, cpath, typeList)) {
                int start = 0;
                int nbl = findEndOfElement(base, baseCursor);
                int ndc = differential.getElement().indexOf(diffMatches.get(0));
                ElementDefinition elementToRemove = null;
                boolean shortCut = (!typeList.isEmpty() && typeList.get(0).type != null) || (diffMatches.get(0).hasSliceName() && !diffMatches.get(0).hasSlicing());
                // we come here whether they are sliced in the diff, or whether the short cut is used.
                if (shortCut) {
                    // in R3 (and unpatched R4, as a workaround right now...
                    if (!FHIRVersion.isR4Plus(context.getVersion()) || !newSlicingProcessing) {
                        // newSlicingProcessing is a work around for editorial loop dependency
                        // we insert a cloned element with the right types at the start of the diffMatches
                        ElementDefinition ed = new ElementDefinition();
                        ed.setPath(determineTypeSlicePath(diffMatches.get(0).getPath(), cpath));
                        for (TypeSlice ts : typeList) ed.addType().setCode(ts.type);
                        ed.setSlicing(new ElementDefinitionSlicingComponent());
                        ed.getSlicing().addDiscriminator().setType(DiscriminatorType.TYPE).setPath("$this");
                        ed.getSlicing().setRules(SlicingRules.CLOSED);
                        ed.getSlicing().setOrdered(false);
                        diffMatches.add(0, ed);
                        differential.getElement().add(ndc, ed);
                        elementToRemove = ed;
                    } else {
                        // as of R4, this changed; if there's no slice, there's no constraint on the slice types, only one the type.
                        // so the element we insert specifies no types (= all types) allowed in the base, not just the listed type.
                        // see also discussion here: https://chat.fhir.org/#narrow/stream/179177-conformance/topic/Slicing.20a.20non-repeating.20element
                        ElementDefinition ed = new ElementDefinition();
                        ed.setPath(determineTypeSlicePath(diffMatches.get(0).getPath(), cpath));
                        ed.setSlicing(new ElementDefinitionSlicingComponent());
                        ed.getSlicing().addDiscriminator().setType(DiscriminatorType.TYPE).setPath("$this");
                        ed.getSlicing().setRules(SlicingRules.CLOSED);
                        ed.getSlicing().setOrdered(false);
                        diffMatches.add(0, ed);
                        differential.getElement().add(ndc, ed);
                        elementToRemove = ed;
                    }
                }
                int ndl = findEndOfElement(differential, ndc);
                if (diffMatches.get(0).getSlicing().hasOrdered()) {
                    if (diffMatches.get(0).getSlicing().getOrdered()) {
                        throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__IN__TYPE_SLICING_WITH_SLICINGORDERED__TRUE, cpath, url));
                    }
                }
                if (diffMatches.get(0).getSlicing().hasDiscriminator()) {
                    if (diffMatches.get(0).getSlicing().getDiscriminator().size() != 1) {
                        throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__IN__TYPE_SLICING_WITH_SLICINGDISCRIMINATORCOUNT__1, cpath, url));
                    }
                    if (diffMatches.get(0).getSlicing().getDiscriminatorFirstRep().getType() != DiscriminatorType.TYPE) {
                        throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__IN__TYPE_SLICING_WITH_SLICINGDISCRIMINATORTYPE__TYPE, cpath, url));
                    }
                    if (!"$this".equals(diffMatches.get(0).getSlicing().getDiscriminatorFirstRep().getPath())) {
                        throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__IN__TYPE_SLICING_WITH_SLICINGDISCRIMINATORPATH__THIS, cpath, url));
                    }
                }
                // check the slice names too while we're at it...
                for (TypeSlice ts : typeList) {
                    if (ts.type != null) {
                        String tn = rootName(cpath) + Utilities.capitalize(ts.type);
                        if (!ts.defn.hasSliceName()) {
                            ts.defn.setSliceName(tn);
                        } else if (!ts.defn.getSliceName().equals(tn)) {
                            throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__SLICE_NAME_MUST_BE__BUT_IS_, (!Utilities.noString(contextPathSrc) ? contextPathSrc : cpath), tn, ts.defn.getSliceName()));
                        }
                        if (!ts.defn.hasType()) {
                            ts.defn.addType().setCode(ts.type);
                        } else if (ts.defn.getType().size() > 1) {
                            throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__SLICE_FOR_TYPE__HAS_MORE_THAN_ONE_TYPE_, (!Utilities.noString(contextPathSrc) ? contextPathSrc : cpath), tn, ts.defn.typeSummary()));
                        } else if (!ts.defn.getType().get(0).getCode().equals(ts.type)) {
                            throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__SLICE_FOR_TYPE__HAS_WRONG_TYPE_, (!Utilities.noString(contextPathSrc) ? contextPathSrc : cpath), tn, ts.defn.typeSummary()));
                        }
                    }
                }
                // ok passed the checks.
                // copy the root diff, and then process any children it has
                ElementDefinition e = processPaths(indent + "  ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName + pathTail(diffMatches, 0), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, true, null, cpath, redirector, srcSD);
                if (e == null)
                    throw new FHIRException(context.formatMessage(I18nConstants.DID_NOT_FIND_TYPE_ROOT_, diffMatches.get(0).getPath()));
                // now set up slicing on the e (cause it was wiped by what we called.
                e.setSlicing(new ElementDefinitionSlicingComponent());
                e.getSlicing().addDiscriminator().setType(DiscriminatorType.TYPE).setPath("$this");
                // type slicing is always closed; the differential might call it open, but that just means it's not constraining the slices it doesn't mention
                e.getSlicing().setRules(SlicingRules.CLOSED);
                e.getSlicing().setOrdered(false);
                start++;
                String fixedType = null;
                List<BaseTypeSlice> baseSlices = findBaseSlices(base, nbl);
                // now we process the base scope repeatedly for each instance of the item in the differential list
                for (int i = start; i < diffMatches.size(); i++) {
                    String type = determineFixedType(diffMatches, fixedType, i);
                    // our processing scope for the differential is the item in the list, and all the items before the next one in the list
                    if (diffMatches.get(i).getMin() > 0) {
                        if (diffMatches.size() > i + 1) {
                            throw new FHIRException(context.formatMessage(I18nConstants.INVALID_SLICING__THERE_IS_MORE_THAN_ONE_TYPE_SLICE_AT__BUT_ONE_OF_THEM__HAS_MIN__1_SO_THE_OTHER_SLICES_CANNOT_EXIST, diffMatches.get(i).getPath(), diffMatches.get(i).getSliceName()));
                        }
                        fixedType = type;
                    }
                    ndc = differential.getElement().indexOf(diffMatches.get(i));
                    ndl = findEndOfElement(differential, ndc);
                    int sStart = baseCursor;
                    int sEnd = nbl;
                    BaseTypeSlice bs = chooseMatchingBaseSlice(baseSlices, type);
                    if (bs != null) {
                        sStart = bs.start;
                        sEnd = bs.end;
                        bs.handled = true;
                    }
                    processPaths(indent + "  ", result, base, differential, sStart, ndc, sEnd, ndl, url, webUrl, profileName + pathTail(diffMatches, i), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, true, e, cpath, redirector, srcSD);
                }
                if (elementToRemove != null) {
                    differential.getElement().remove(elementToRemove);
                    ndl--;
                }
                if (fixedType != null) {
                    for (Iterator<TypeRefComponent> iter = e.getType().iterator(); iter.hasNext(); ) {
                        TypeRefComponent tr = iter.next();
                        if (!tr.getCode().equals(fixedType)) {
                            iter.remove();
                        }
                    }
                }
                for (BaseTypeSlice bs : baseSlices) {
                    if (!bs.handled) {
                        // ok we gimme up a fake differential that says nothing, and run that against the slice.
                        StructureDefinitionDifferentialComponent fakeDiff = new StructureDefinitionDifferentialComponent();
                        fakeDiff.getElementFirstRep().setPath(bs.defn.getPath());
                        processPaths(indent + "  ", result, base, fakeDiff, bs.start, 0, bs.end, 0, url, webUrl, profileName + tail(bs.defn.getPath()), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, true, e, cpath, redirector, srcSD);
                    }
                }
                // ok, done with that - next in the base list
                baseCursor = baseSlices.get(baseSlices.size() - 1).end + 1;
                diffCursor = ndl + 1;
            // throw new Error("not done yet - slicing / types @ "+cpath);
            } else {
                // first - check that the slicing is ok
                boolean closed = currentBase.getSlicing().getRules() == SlicingRules.CLOSED;
                int diffpos = 0;
                boolean isExtension = cpath.endsWith(".extension") || cpath.endsWith(".modifierExtension");
                if (diffMatches.get(0).hasSlicing()) {
                    // it might be null if the differential doesn't want to say anything about slicing
                    // if (!isExtension)
                    // diffpos++; // if there's a slice on the first, we'll ignore any content it has
                    ElementDefinitionSlicingComponent dSlice = diffMatches.get(0).getSlicing();
                    ElementDefinitionSlicingComponent bSlice = currentBase.getSlicing();
                    if (dSlice.hasOrderedElement() && bSlice.hasOrderedElement() && !orderMatches(dSlice.getOrderedElement(), bSlice.getOrderedElement()))
                        throw new DefinitionException(context.formatMessage(I18nConstants.SLICING_RULES_ON_DIFFERENTIAL__DO_NOT_MATCH_THOSE_ON_BASE___ORDER___, summarizeSlicing(dSlice), summarizeSlicing(bSlice), path, contextName));
                    if (!discriminatorMatches(dSlice.getDiscriminator(), bSlice.getDiscriminator()))
                        throw new DefinitionException(context.formatMessage(I18nConstants.SLICING_RULES_ON_DIFFERENTIAL__DO_NOT_MATCH_THOSE_ON_BASE___DISCIMINATOR___, summarizeSlicing(dSlice), summarizeSlicing(bSlice), path, contextName));
                    if (!currentBase.isChoice() && !ruleMatches(dSlice.getRules(), bSlice.getRules()))
                        throw new DefinitionException(context.formatMessage(I18nConstants.SLICING_RULES_ON_DIFFERENTIAL__DO_NOT_MATCH_THOSE_ON_BASE___RULE___, summarizeSlicing(dSlice), summarizeSlicing(bSlice), path, contextName));
                }
                ElementDefinition outcome = updateURLs(url, webUrl, currentBase.copy());
                outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
                updateFromBase(outcome, currentBase);
                if (diffMatches.get(0).hasSlicing() || !diffMatches.get(0).hasSliceName()) {
                    updateFromSlicing(outcome.getSlicing(), diffMatches.get(0).getSlicing());
                    // if there's no slice, we don't want to update the unsliced description
                    updateFromDefinition(outcome, diffMatches.get(0), profileName, closed, url, srcSD);
                    removeStatusExtensions(outcome);
                } else if (!diffMatches.get(0).hasSliceName()) {
                    // because of updateFromDefinition isn't called
                    diffMatches.get(0).setUserData(GENERATED_IN_SNAPSHOT, outcome);
                }
                result.getElement().add(outcome);
                if (!diffMatches.get(0).hasSliceName()) {
                    // it's not real content, just the slice
                    diffpos++;
                }
                if (hasInnerDiffMatches(differential, cpath, diffCursor, diffLimit, base.getElement(), false)) {
                    int nbl = findEndOfElement(base, baseCursor);
                    int ndx = differential.getElement().indexOf(diffMatches.get(0));
                    int ndc = ndx + (diffMatches.get(0).hasSlicing() ? 1 : 0);
                    int ndl = findEndOfElement(differential, ndx);
                    if (nbl == baseCursor) {
                        if (base.getElement().get(baseCursor).getType().size() != 1) {
                            throw new Error(context.formatMessage(I18nConstants.DIFFERENTIAL_WALKS_INTO____BUT_THE_BASE_DOES_NOT_AND_THERE_IS_NOT_A_SINGLE_FIXED_TYPE_THE_TYPE_IS__THIS_IS_NOT_HANDLED_YET, cpath, diffMatches.get(0).toString(), base.getElement().get(baseCursor).typeSummary()));
                        }
                        StructureDefinition dt = getProfileForDataType(base.getElement().get(baseCursor).getType().get(0), webUrl);
                        if (dt == null) {
                            throw new DefinitionException(context.formatMessage(I18nConstants.UNKNOWN_TYPE__AT_, outcome.getType().get(0), diffMatches.get(0).getPath()));
                        }
                        contextName = dt.getUrl();
                        while (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), cpath + ".")) diffCursor++;
                        processPaths(indent + "  ", result, dt.getSnapshot(), differential, 1, ndc, dt.getSnapshot().getElement().size() - 1, ndl, url, getWebUrl(dt, webUrl, indent), profileName, cpath, outcome.getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirector, srcSD);
                    } else {
                        processPaths(indent + "  ", result, base, differential, baseCursor + 1, ndc, nbl, ndl, url, webUrl, profileName + pathTail(diffMatches, 0), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, false, null, null, null, srcSD);
                    }
                // throw new Error("Not done yet");
                // } else if (currentBase.getType().get(0).getCode().equals("BackboneElement") && diffMatches.size() > 0 && diffMatches.get(0).hasSliceName()) {
                } else if (currentBase.getType().get(0).getCode().equals("BackboneElement")) {
                    // We need to copy children of the backbone element before we start messing around with slices
                    int nbl = findEndOfElement(base, baseCursor);
                    for (int i = baseCursor + 1; i <= nbl; i++) {
                        outcome = updateURLs(url, webUrl, base.getElement().get(i).copy());
                        result.getElement().add(outcome);
                    }
                }
                // now, we have two lists, base and diff. we're going to work through base, looking for matches in diff.
                List<ElementDefinition> baseMatches = getSiblings(base.getElement(), currentBase);
                for (ElementDefinition baseItem : baseMatches) {
                    baseCursor = base.getElement().indexOf(baseItem);
                    outcome = updateURLs(url, webUrl, baseItem.copy());
                    updateFromBase(outcome, currentBase);
                    outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
                    outcome.setSlicing(null);
                    if (!outcome.getPath().startsWith(resultPathBase))
                        throw new DefinitionException(context.formatMessage(I18nConstants.ADDING_WRONG_PATH));
                    if (diffpos < diffMatches.size() && diffMatches.get(diffpos).hasSliceName() && diffMatches.get(diffpos).getSliceName().equals(outcome.getSliceName())) {
                        // if there's a diff, we update the outcome with diff
                        // no? updateFromDefinition(outcome, diffMatches.get(diffpos), profileName, closed, url);
                        // then process any children
                        int nbl = findEndOfElement(base, baseCursor);
                        int ndc = differential.getElement().indexOf(diffMatches.get(diffpos));
                        int ndl = findEndOfElement(differential, ndc);
                        // now we process the base scope repeatedly for each instance of the item in the differential list
                        processPaths(indent + "  ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName + pathTail(diffMatches, diffpos), contextPathSrc, contextPathDst, closed, contextName, resultPathBase, true, null, null, redirector, srcSD);
                        // ok, done with that - now set the cursors for if this is the end
                        baseCursor = nbl;
                        diffCursor = ndl + 1;
                        diffpos++;
                    } else {
                        result.getElement().add(outcome);
                        baseCursor++;
                        // just copy any children on the base
                        while (baseCursor < base.getElement().size() && base.getElement().get(baseCursor).getPath().startsWith(path) && !base.getElement().get(baseCursor).getPath().equals(path)) {
                            outcome = updateURLs(url, webUrl, base.getElement().get(baseCursor).copy());
                            outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
                            if (!outcome.getPath().startsWith(resultPathBase))
                                throw new DefinitionException(context.formatMessage(I18nConstants.ADDING_WRONG_PATH));
                            result.getElement().add(outcome);
                            baseCursor++;
                        }
                        // Lloyd - add this for test T15
                        baseCursor--;
                    }
                }
                // finally, we process any remaining entries in diff, which are new (and which are only allowed if the base wasn't closed
                boolean checkImplicitTypes = false;
                if (closed && diffpos < diffMatches.size()) {
                    // this is a problem, unless we're on a polymorhpic type and we're going to constrain a slice that actually implicitly exists
                    if (currentBase.getPath().endsWith("[x]")) {
                        checkImplicitTypes = true;
                    } else {
                        throw new DefinitionException(context.formatMessage(I18nConstants.THE_BASE_SNAPSHOT_MARKS_A_SLICING_AS_CLOSED_BUT_THE_DIFFERENTIAL_TRIES_TO_EXTEND_IT_IN__AT__, profileName, path, cpath));
                    }
                }
                if (diffpos == diffMatches.size()) {
                // Lloyd This was causing problems w/ Telus
                // diffCursor++;
                } else {
                    while (diffpos < diffMatches.size()) {
                        ElementDefinition diffItem = diffMatches.get(diffpos);
                        for (ElementDefinition baseItem : baseMatches) if (baseItem.getSliceName().equals(diffItem.getSliceName()))
                            throw new DefinitionException(context.formatMessage(I18nConstants.NAMED_ITEMS_ARE_OUT_OF_ORDER_IN_THE_SLICE));
                        outcome = updateURLs(url, webUrl, currentBase.copy());
                        // outcome = updateURLs(url, diffItem.copy());
                        outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
                        updateFromBase(outcome, currentBase);
                        outcome.setSlicing(null);
                        // we're in a slice, so it's only a mandatory if it's explicitly marked so
                        outcome.setMin(0);
                        if (!outcome.getPath().startsWith(resultPathBase))
                            throw new DefinitionException(context.formatMessage(I18nConstants.ADDING_WRONG_PATH));
                        result.getElement().add(outcome);
                        updateFromDefinition(outcome, diffItem, profileName, trimDifferential, url, srcSD);
                        removeStatusExtensions(outcome);
                        // --- LM Added this
                        diffCursor = differential.getElement().indexOf(diffItem) + 1;
                        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
                            if (!baseWalksInto(base.getElement(), baseCursor)) {
                                if (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), diffMatches.get(0).getPath() + ".")) {
                                    if (outcome.getType().size() > 1)
                                        for (TypeRefComponent t : outcome.getType()) {
                                            if (!t.getCode().equals("Reference"))
                                                throw new DefinitionException(context.formatMessage(I18nConstants._HAS_CHILDREN__AND_MULTIPLE_TYPES__IN_PROFILE_, diffMatches.get(0).getPath(), differential.getElement().get(diffCursor).getPath(), typeCode(outcome.getType()), profileName));
                                        }
                                    TypeRefComponent t = outcome.getType().get(0);
                                    if (t.getCode().equals("BackboneElement")) {
                                        int baseStart = base.getElement().indexOf(currentBase) + 1;
                                        int baseMax = baseStart + 1;
                                        while (baseMax < base.getElement().size() && base.getElement().get(baseMax).getPath().startsWith(currentBase.getPath() + ".")) baseMax++;
                                        int start = diffCursor;
                                        while (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), diffMatches.get(0).getPath() + ".")) diffCursor++;
                                        processPaths(indent + "  ", result, base, differential, baseStart, start - 1, baseMax - 1, diffCursor - 1, url, webUrl, profileName + pathTail(diffMatches, 0), base.getElement().get(0).getPath(), base.getElement().get(0).getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirector, srcSD);
                                    } else {
                                        StructureDefinition dt = getProfileForDataType(outcome.getType().get(0), webUrl);
                                        // }
                                        if (dt == null)
                                            throw new DefinitionException(context.formatMessage(I18nConstants._HAS_CHILDREN__FOR_TYPE__IN_PROFILE__BUT_CANT_FIND_TYPE, diffMatches.get(0).getPath(), differential.getElement().get(diffCursor).getPath(), typeCode(outcome.getType()), profileName));
                                        contextName = dt.getUrl();
                                        int start = diffCursor;
                                        while (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), diffMatches.get(0).getPath() + ".")) diffCursor++;
                                        processPaths(indent + "  ", result, dt.getSnapshot(), differential, 1, /* starting again on the data type, but skip the root */
                                        start - 1, dt.getSnapshot().getElement().size() - 1, diffCursor - 1, url, getWebUrl(dt, webUrl, indent), profileName + pathTail(diffMatches, 0), diffMatches.get(0).getPath(), outcome.getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirector, srcSD);
                                    }
                                }
                            }
                        }
                        // ---
                        diffpos++;
                    }
                }
                baseCursor++;
            }
        }
    }
    int i = 0;
    for (ElementDefinition e : result.getElement()) {
        i++;
        if (e.hasMinElement() && e.getMinElement().getValue() == null)
            throw new Error(context.formatMessage(I18nConstants.NULL_MIN));
    }
    return res;
}
Also used : ArrayList(java.util.ArrayList) FHIRFormatError(org.hl7.fhir.exceptions.FHIRFormatError) CanonicalType(org.hl7.fhir.r4b.model.CanonicalType) FHIRException(org.hl7.fhir.exceptions.FHIRException) StructureDefinition(org.hl7.fhir.r4b.model.StructureDefinition) TypeRefComponent(org.hl7.fhir.r4b.model.ElementDefinition.TypeRefComponent) Iterator(java.util.Iterator) StructureDefinitionDifferentialComponent(org.hl7.fhir.r4b.model.StructureDefinition.StructureDefinitionDifferentialComponent) ElementDefinitionSlicingComponent(org.hl7.fhir.r4b.model.ElementDefinition.ElementDefinitionSlicingComponent) ArrayList(java.util.ArrayList) List(java.util.List) ElementDefinition(org.hl7.fhir.r4b.model.ElementDefinition) DefinitionException(org.hl7.fhir.exceptions.DefinitionException)

Example 33 with TS

use of org.hl7.v3.TS in project org.hl7.fhir.core by hapifhir.

the class ProfileUtilities method checkTypeDerivation.

public void checkTypeDerivation(String purl, StructureDefinition srcSD, ElementDefinition base, ElementDefinition derived, TypeRefComponent ts) {
    boolean ok = false;
    CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
    String t = ts.getWorkingCode();
    for (TypeRefComponent td : base.getType()) {
        ;
        String tt = td.getWorkingCode();
        b.append(tt);
        if (td.hasCode() && (tt.equals(t))) {
            ok = true;
        }
        if (!ok) {
            StructureDefinition sdt = context.fetchTypeDefinition(tt);
            if (sdt != null && (sdt.getAbstract() || sdt.getKind() == StructureDefinitionKind.LOGICAL)) {
                StructureDefinition sdb = context.fetchTypeDefinition(t);
                while (sdb != null && !ok) {
                    ok = sdb.getType().equals(sdt.getType());
                    sdb = context.fetchResource(StructureDefinition.class, sdb.getBaseDefinition());
                }
            }
        }
        // work around for old badly generated SDs
        if (DONT_DO_THIS && Utilities.existsInList(tt, "Extension", "uri", "string", "Element")) {
            ok = true;
        }
        if (DONT_DO_THIS && Utilities.existsInList(tt, "Resource", "DomainResource") && pkp.isResource(t)) {
            ok = true;
        }
        if (ok && ts.hasTargetProfile()) {
            // check that any derived target has a reference chain back to one of the base target profiles
            for (UriType u : ts.getTargetProfile()) {
                String url = u.getValue();
                boolean tgtOk = !td.hasTargetProfile() || td.hasTargetProfile(url);
                while (url != null && !tgtOk) {
                    StructureDefinition sd = context.fetchRawProfile(url);
                    if (sd == null) {
                        if (messages != null) {
                            messages.add(new ValidationMessage(Source.InstanceValidator, IssueType.BUSINESSRULE, purl + "#" + derived.getPath(), "Cannot check whether the target profile " + url + " is valid constraint on the base because it is not known", IssueSeverity.WARNING));
                        }
                        url = null;
                        // suppress error message
                        tgtOk = true;
                    } else {
                        url = sd.getBaseDefinition();
                        tgtOk = td.hasTargetProfile(url);
                    }
                }
                if (!tgtOk) {
                    if (messages == null) {
                        throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT__THE_TARGET_PROFILE__IS_NOT__VALID_CONSTRAINT_ON_THE_BASE_, purl, derived.getPath(), url, td.getTargetProfile()));
                    } else {
                        messages.add(new ValidationMessage(Source.InstanceValidator, IssueType.BUSINESSRULE, derived.getPath(), "The target profile " + u.getValue() + " is not a valid constraint on the base (" + td.getTargetProfile() + ") at " + derived.getPath(), IssueSeverity.ERROR));
                    }
                }
            }
        }
    }
    if (!ok) {
        throw new DefinitionException(context.formatMessage(I18nConstants.STRUCTUREDEFINITION__AT__ILLEGAL_CONSTRAINED_TYPE__FROM__IN_, purl, derived.getPath(), t, b.toString(), srcSD.getUrl()));
    }
}
Also used : StructureDefinition(org.hl7.fhir.r4b.model.StructureDefinition) ValidationMessage(org.hl7.fhir.utilities.validation.ValidationMessage) TypeRefComponent(org.hl7.fhir.r4b.model.ElementDefinition.TypeRefComponent) CommaSeparatedStringBuilder(org.hl7.fhir.utilities.CommaSeparatedStringBuilder) DefinitionException(org.hl7.fhir.exceptions.DefinitionException) FHIRException(org.hl7.fhir.exceptions.FHIRException) UriType(org.hl7.fhir.r4b.model.UriType)

Example 34 with TS

use of org.hl7.v3.TS in project org.hl7.fhir.core by hapifhir.

the class ProfileUtilities method processPaths.

/**
 * @param trimDifferential
 * @param srcSD
 * @throws DefinitionException, FHIRException
 * @throws Exception
 */
private ElementDefinition processPaths(String indent, StructureDefinitionSnapshotComponent result, StructureDefinitionSnapshotComponent base, StructureDefinitionDifferentialComponent differential, int baseCursor, int diffCursor, int baseLimit, int diffLimit, String url, String webUrl, String profileName, String contextPathSrc, String contextPathDst, boolean trimDifferential, String contextName, String resultPathBase, boolean slicingDone, ElementDefinition slicer, String typeSlicingPath, List<ElementRedirection> redirector, StructureDefinition srcSD) throws DefinitionException, FHIRException {
    if (debug) {
        System.out.println(indent + "PP @ " + resultPathBase + " / " + contextPathSrc + " : base = " + baseCursor + " to " + baseLimit + ", diff = " + diffCursor + " to " + diffLimit + " (slicing = " + slicingDone + ", k " + (redirector == null ? "null" : redirector.toString()) + ")");
    }
    ElementDefinition res = null;
    List<TypeSlice> typeList = new ArrayList<>();
    // just repeat processing entries until we run out of our allowed scope (1st entry, the allowed scope is all the entries)
    while (baseCursor <= baseLimit) {
        // get the current focus of the base, and decide what to do
        ElementDefinition currentBase = base.getElement().get(baseCursor);
        String cpath = fixedPathSource(contextPathSrc, currentBase.getPath(), redirector);
        if (debug) {
            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) + ") " + "(slicingDone = " + slicingDone + ") (diffpath= " + (differential.getElement().size() > diffCursor ? differential.getElement().get(diffCursor).getPath() : "n/a") + ")");
        }
        // get a list of matching elements in scope
        List<ElementDefinition> diffMatches = getDiffMatches(differential, cpath, diffCursor, diffLimit, profileName);
        // in the simple case, source is not sliced.
        if (!currentBase.hasSlicing() || cpath.equals(typeSlicingPath)) {
            if (diffMatches.isEmpty()) {
                // the differential doesn't say anything about this item
                // so we just copy it in
                ElementDefinition outcome = updateURLs(url, webUrl, currentBase.copy());
                outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
                updateFromBase(outcome, currentBase);
                updateConstraintSources(outcome, srcSD.getUrl());
                markDerived(outcome);
                if (resultPathBase == null)
                    resultPathBase = outcome.getPath();
                else if (!outcome.getPath().startsWith(resultPathBase))
                    throw new DefinitionException(context.formatMessage(I18nConstants.ADDING_WRONG_PATH__OUTCOMEGETPATH___RESULTPATHBASE__, outcome.getPath(), resultPathBase));
                result.getElement().add(outcome);
                if (hasInnerDiffMatches(differential, cpath, diffCursor, diffLimit, base.getElement(), true)) {
                    // did we implicitly step into a new type?
                    if (baseHasChildren(base, currentBase)) {
                        // not a new type here
                        processPaths(indent + "  ", result, base, differential, baseCursor + 1, diffCursor, baseLimit, diffLimit, url, webUrl, profileName, contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, false, null, null, redirector, srcSD);
                        baseCursor = indexOfFirstNonChild(base, currentBase, baseCursor + 1, baseLimit);
                    } else {
                        if (outcome.getType().size() == 0 && !outcome.hasContentReference()) {
                            throw new DefinitionException(context.formatMessage(I18nConstants._HAS_NO_CHILDREN__AND_NO_TYPES_IN_PROFILE_, cpath, differential.getElement().get(diffCursor).getPath(), profileName));
                        }
                        boolean nonExtension = false;
                        if (outcome.getType().size() > 1) {
                            for (TypeRefComponent t : outcome.getType()) {
                                if (!t.getWorkingCode().equals("Reference")) {
                                    for (ElementDefinition ed : diffMatches) {
                                        if (ed != diffMatches.get(0) && !ed.getPath().endsWith(".extension")) {
                                            nonExtension = true;
                                        }
                                    }
                                }
                            }
                        }
                        int start = diffCursor;
                        while (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), cpath + ".")) diffCursor++;
                        if (nonExtension) {
                            throw new DefinitionException(context.formatMessage(I18nConstants._HAS_CHILDREN__AND_MULTIPLE_TYPES__IN_PROFILE_, cpath, differential.getElement().get(diffCursor).getPath(), typeCode(outcome.getType()), profileName));
                        }
                        if (outcome.hasContentReference()) {
                            ElementDefinitionResolution tgt = getElementById(srcSD, base.getElement(), outcome.getContentReference());
                            if (tgt == null)
                                throw new DefinitionException(context.formatMessage(I18nConstants.UNABLE_TO_RESOLVE_REFERENCE_TO_, outcome.getContentReference()));
                            replaceFromContentReference(outcome, tgt.getElement());
                            if (tgt.getSource() != srcSD) {
                                base = tgt.getSource().getSnapshot();
                                int nbc = base.getElement().indexOf(tgt.getElement()) + 1;
                                int nbl = nbc;
                                while (nbl < base.getElement().size() && base.getElement().get(nbl).getPath().startsWith(tgt.getElement().getPath() + ".")) nbl++;
                                processPaths(indent + "  ", result, base, differential, nbc, start - 1, nbl - 1, diffCursor - 1, url, webUrl, profileName, tgt.getElement().getPath(), diffMatches.get(0).getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirectorStack(redirector, outcome, cpath), tgt.getSource());
                            } else {
                                int nbc = base.getElement().indexOf(tgt.getElement()) + 1;
                                int nbl = nbc;
                                while (nbl < base.getElement().size() && base.getElement().get(nbl).getPath().startsWith(tgt.getElement().getPath() + ".")) nbl++;
                                System.out.println("Test!");
                                processPaths(indent + "  ", result, base, differential, nbc, start, nbl - 1, diffCursor - 1, url, webUrl, profileName, tgt.getElement().getPath(), outcome.getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirectorStack(redirector, outcome, cpath), srcSD);
                            }
                        } else {
                            StructureDefinition dt = outcome.getType().size() > 1 ? context.fetchTypeDefinition("Element") : getProfileForDataType(outcome.getType().get(0), webUrl);
                            if (dt == null) {
                                throw new DefinitionException(context.formatMessage(I18nConstants.UNKNOWN_TYPE__AT_, outcome.getType().get(0), cpath));
                            }
                            contextName = dt.getUrl();
                            if (redirector.isEmpty()) {
                                processPaths(indent + "  ", result, dt.getSnapshot(), differential, 1, /* starting again on the data type, but skip the root */
                                start, dt.getSnapshot().getElement().size() - 1, diffCursor - 1, url, getWebUrl(dt, webUrl, indent), profileName, cpath, outcome.getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirector, srcSD);
                            } else {
                                processPaths(indent + "  ", result, dt.getSnapshot(), differential, 1, /* starting again on the data type, but skip the root */
                                start, dt.getSnapshot().getElement().size() - 1, diffCursor - 1, url, getWebUrl(dt, webUrl, indent), profileName, cpath, outcome.getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirectorStack(redirector, currentBase, cpath), srcSD);
                            }
                        }
                    }
                }
                baseCursor++;
            } 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
                ElementDefinition template = null;
                if (diffMatches.get(0).hasType() && "Reference".equals(diffMatches.get(0).getType().get(0).getWorkingCode()) && !isValidType(diffMatches.get(0).getType().get(0), currentBase)) {
                    throw new DefinitionException(context.formatMessage(I18nConstants.VALIDATION_VAL_ILLEGAL_TYPE_CONSTRAINT, url, diffMatches.get(0).getPath(), diffMatches.get(0).getType().get(0), currentBase.typeSummary()));
                }
                String id = diffMatches.get(0).getId();
                String lid = tail(id);
                if (lid.contains("/")) {
                    // the template comes from the snapshot of the base
                    generateIds(result.getElement(), url, srcSD.getType());
                    // this is wrong if there's more than one reslice (todo: one thing at a time)
                    String baseId = id.substring(0, id.length() - lid.length()) + lid.substring(0, lid.indexOf("/"));
                    template = getById(result.getElement(), baseId);
                } else 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())) {
                    CanonicalType p = diffMatches.get(0).getType().get(0).getProfile().get(0);
                    StructureDefinition sd = context.fetchResource(StructureDefinition.class, p.getValue());
                    if (sd == null && xver != null && xver.matchingUrl(p.getValue())) {
                        switch(xver.status(p.getValue())) {
                            case BadVersion:
                                throw new FHIRException("Reference to invalid version in extension url " + p.getValue());
                            case Invalid:
                                throw new FHIRException("Reference to invalid extension " + p.getValue());
                            case Unknown:
                                throw new FHIRException("Reference to unknown extension " + p.getValue());
                            case Valid:
                                sd = xver.makeDefinition(p.getValue());
                                generateSnapshot(context.fetchTypeDefinition("Extension"), sd, sd.getUrl(), webUrl, sd.getName());
                        }
                    }
                    if (sd != null) {
                        if (!isMatchingType(sd, diffMatches.get(0).getType(), p.getExtensionString(ToolingExtensions.EXT_PROFILE_ELEMENT))) {
                            throw new DefinitionException(context.formatMessage(I18nConstants.VALIDATION_VAL_PROFILE_WRONGTYPE2, sd.getUrl(), diffMatches.get(0).getPath(), sd.getType(), p.getValue(), diffMatches.get(0).getType().get(0).getWorkingCode()));
                        }
                        if (isGenerating(sd)) {
                            // but we check anyway
                            if (sd.getSnapshot().getElementFirstRep().isEmpty()) {
                                throw new FHIRException(context.formatMessage(I18nConstants.ATTEMPT_TO_USE_A_SNAPSHOT_ON_PROFILE__AS__BEFORE_IT_IS_GENERATED, sd.getUrl(), "Source for first element"));
                            }
                        } else if (!sd.hasSnapshot()) {
                            StructureDefinition sdb = context.fetchResource(StructureDefinition.class, sd.getBaseDefinition());
                            if (sdb == null)
                                throw new DefinitionException(context.formatMessage(I18nConstants.UNABLE_TO_FIND_BASE__FOR_, sd.getBaseDefinition(), sd.getUrl()));
                            checkNotGenerating(sdb, "an extension base");
                            generateSnapshot(sdb, sd, sd.getUrl(), (sdb.hasUserData("path")) ? Utilities.extractBaseUrl(sdb.getUserString("path")) : webUrl, sd.getName());
                        }
                        ElementDefinition src;
                        if (p.hasExtension(ToolingExtensions.EXT_PROFILE_ELEMENT)) {
                            src = null;
                            String eid = p.getExtensionString(ToolingExtensions.EXT_PROFILE_ELEMENT);
                            for (ElementDefinition t : sd.getSnapshot().getElement()) {
                                if (eid.equals(t.getId()))
                                    src = t;
                            }
                            if (src == null)
                                throw new DefinitionException(context.formatMessage(I18nConstants.UNABLE_TO_FIND_ELEMENT__IN_, eid, p.getValue()));
                        } else
                            src = sd.getSnapshot().getElement().get(0);
                        template = src.copy().setPath(currentBase.getPath());
                        template.setSliceName(null);
                        // temporary work around
                        if (!"Extension".equals(diffMatches.get(0).getType().get(0).getCode())) {
                            template.setMin(currentBase.getMin());
                            template.setMax(currentBase.getMax());
                        }
                    }
                }
                if (template == null)
                    template = currentBase.copy();
                else
                    // some of what's in currentBase overrides template
                    template = fillOutFromBase(template, currentBase);
                ElementDefinition outcome = updateURLs(url, webUrl, template);
                outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
                if (res == null)
                    res = outcome;
                updateFromBase(outcome, currentBase);
                if (diffMatches.get(0).hasSliceName()) {
                    outcome.setSliceName(diffMatches.get(0).getSliceName());
                    if (!diffMatches.get(0).hasMin() && (diffMatches.size() > 1 || slicer == null || slicer.getSlicing().getRules() != SlicingRules.CLOSED) && !currentBase.hasSliceName()) {
                        if (!cpath.endsWith("xtension.value[x]")) {
                            // hack work around for problems with snapshots in official releases
                            outcome.setMin(0);
                        }
                    }
                }
                updateFromDefinition(outcome, diffMatches.get(0), profileName, trimDifferential, url, srcSD);
                removeStatusExtensions(outcome);
                // 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
                // outcome.setPath(outcome.getPath().substring(0, outcome.getPath().length()-3)+Utilities.capitalize(outcome.getType().get(0).getCode()));
                outcome.setSlicing(null);
                if (resultPathBase == null)
                    resultPathBase = outcome.getPath();
                else if (!outcome.getPath().startsWith(resultPathBase))
                    throw new DefinitionException(context.formatMessage(I18nConstants.ADDING_WRONG_PATH));
                result.getElement().add(outcome);
                baseCursor++;
                diffCursor = differential.getElement().indexOf(diffMatches.get(0)) + 1;
                if (diffLimit >= diffCursor && outcome.getPath().contains(".") && (isDataType(outcome.getType()) || isBaseResource(outcome.getType()) || outcome.hasContentReference())) {
                    // don't want to do this for the root, since that's base, and we're already processing it
                    if (pathStartsWith(differential.getElement().get(diffCursor).getPath(), diffMatches.get(0).getPath() + ".") && !baseWalksInto(base.getElement(), baseCursor)) {
                        if (outcome.getType().size() > 1) {
                            if (outcome.getPath().endsWith("[x]") && !diffMatches.get(0).getPath().endsWith("[x]")) {
                                String en = tail(outcome.getPath());
                                String tn = tail(diffMatches.get(0).getPath());
                                String t = tn.substring(en.length() - 3);
                                if (isPrimitive(Utilities.uncapitalize(t)))
                                    t = Utilities.uncapitalize(t);
                                // keep any additional information
                                List<TypeRefComponent> ntr = getByTypeName(outcome.getType(), t);
                                if (ntr.isEmpty())
                                    ntr.add(new TypeRefComponent().setCode(t));
                                outcome.getType().clear();
                                outcome.getType().addAll(ntr);
                            }
                            if (outcome.getType().size() > 1)
                                for (TypeRefComponent t : outcome.getType()) {
                                    if (!t.getCode().equals("Reference")) {
                                        boolean nonExtension = false;
                                        for (ElementDefinition ed : diffMatches) if (ed != diffMatches.get(0) && !ed.getPath().endsWith(".extension"))
                                            nonExtension = true;
                                        if (nonExtension)
                                            throw new DefinitionException(context.formatMessage(I18nConstants._HAS_CHILDREN__AND_MULTIPLE_TYPES__IN_PROFILE_, diffMatches.get(0).getPath(), differential.getElement().get(diffCursor).getPath(), typeCode(outcome.getType()), profileName));
                                    }
                                }
                        }
                        int start = diffCursor;
                        while (diffCursor <= diffLimit && differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), diffMatches.get(0).getPath() + ".")) diffCursor++;
                        if (outcome.hasContentReference()) {
                            ElementDefinitionResolution tgt = getElementById(srcSD, base.getElement(), outcome.getContentReference());
                            if (tgt == null)
                                throw new DefinitionException(context.formatMessage(I18nConstants.UNABLE_TO_RESOLVE_REFERENCE_TO_, outcome.getContentReference()));
                            replaceFromContentReference(outcome, tgt.getElement());
                            if (tgt.getSource() != srcSD) {
                                base = tgt.getSource().getSnapshot();
                                int nbc = base.getElement().indexOf(tgt.getElement()) + 1;
                                int nbl = nbc;
                                while (nbl < base.getElement().size() && base.getElement().get(nbl).getPath().startsWith(tgt.getElement().getPath() + ".")) nbl++;
                                processPaths(indent + "  ", result, base, differential, nbc, start - 1, nbl - 1, diffCursor - 1, url, webUrl, profileName, tgt.getElement().getPath(), diffMatches.get(0).getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirectorStack(redirector, outcome, cpath), tgt.getSource());
                            } else {
                                int nbc = base.getElement().indexOf(tgt.getElement()) + 1;
                                int nbl = nbc;
                                while (nbl < base.getElement().size() && base.getElement().get(nbl).getPath().startsWith(tgt.getElement().getPath() + ".")) nbl++;
                                processPaths(indent + "  ", result, base, differential, nbc, start - 1, nbl - 1, diffCursor - 1, url, webUrl, profileName, tgt.getElement().getPath(), diffMatches.get(0).getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirectorStack(redirector, outcome, cpath), srcSD);
                            }
                        } else {
                            StructureDefinition dt = outcome.getType().size() == 1 ? getProfileForDataType(outcome.getType().get(0), webUrl) : getProfileForDataType("Element");
                            if (dt == null)
                                throw new DefinitionException(context.formatMessage(I18nConstants._HAS_CHILDREN__FOR_TYPE__IN_PROFILE__BUT_CANT_FIND_TYPE, diffMatches.get(0).getPath(), differential.getElement().get(diffCursor).getPath(), typeCode(outcome.getType()), profileName));
                            contextName = dt.getUrl();
                            processPaths(indent + "  ", result, dt.getSnapshot(), differential, 1, /* starting again on the data type, but skip the root */
                            start, dt.getSnapshot().getElement().size() - 1, diffCursor - 1, url, getWebUrl(dt, webUrl, indent), profileName + pathTail(diffMatches, 0), diffMatches.get(0).getPath(), outcome.getPath(), trimDifferential, contextName, resultPathBase, false, null, null, new ArrayList<ElementRedirection>(), srcSD);
                        }
                    }
                }
            } else if (diffsConstrainTypes(diffMatches, cpath, typeList)) {
                int start = 0;
                int nbl = findEndOfElement(base, baseCursor);
                int ndc = differential.getElement().indexOf(diffMatches.get(0));
                ElementDefinition elementToRemove = null;
                boolean shortCut = !typeList.isEmpty() && typeList.get(0).type != null;
                // we come here whether they are sliced in the diff, or whether the short cut is used.
                if (shortCut) {
                    // in R3 (and unpatched R4, as a workaround right now...
                    if (!FHIRVersion.isR4Plus(context.getVersion()) || !newSlicingProcessing) {
                        // newSlicingProcessing is a work around for editorial loop dependency
                        // we insert a cloned element with the right types at the start of the diffMatches
                        ElementDefinition ed = new ElementDefinition();
                        ed.setPath(determineTypeSlicePath(diffMatches.get(0).getPath(), cpath));
                        for (TypeSlice ts : typeList) ed.addType().setCode(ts.type);
                        ed.setSlicing(new ElementDefinitionSlicingComponent());
                        ed.getSlicing().addDiscriminator().setType(DiscriminatorType.TYPE).setPath("$this");
                        ed.getSlicing().setRules(SlicingRules.CLOSED);
                        ed.getSlicing().setOrdered(false);
                        diffMatches.add(0, ed);
                        differential.getElement().add(ndc, ed);
                        elementToRemove = ed;
                    } else {
                        // as of R4, this changed; if there's no slice, there's no constraint on the slice types, only one the type.
                        // so the element we insert specifies no types (= all types) allowed in the base, not just the listed type.
                        // see also discussion here: https://chat.fhir.org/#narrow/stream/179177-conformance/topic/Slicing.20a.20non-repeating.20element
                        ElementDefinition ed = new ElementDefinition();
                        ed.setPath(determineTypeSlicePath(diffMatches.get(0).getPath(), cpath));
                        ed.setSlicing(new ElementDefinitionSlicingComponent());
                        ed.getSlicing().addDiscriminator().setType(DiscriminatorType.TYPE).setPath("$this");
                        ed.getSlicing().setRules(SlicingRules.CLOSED);
                        ed.getSlicing().setOrdered(false);
                        diffMatches.add(0, ed);
                        differential.getElement().add(ndc, ed);
                        elementToRemove = ed;
                    }
                }
                int ndl = findEndOfElement(differential, ndc);
                if (diffMatches.get(0).getSlicing().hasOrdered()) {
                    if (diffMatches.get(0).getSlicing().getOrdered()) {
                        throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__IN__TYPE_SLICING_WITH_SLICINGORDERED__TRUE, cpath, url));
                    }
                }
                if (diffMatches.get(0).getSlicing().hasDiscriminator()) {
                    if (diffMatches.get(0).getSlicing().getDiscriminator().size() != 1) {
                        throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__IN__TYPE_SLICING_WITH_SLICINGDISCRIMINATORCOUNT__1, cpath, url));
                    }
                    if (diffMatches.get(0).getSlicing().getDiscriminatorFirstRep().getType() != DiscriminatorType.TYPE) {
                        throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__IN__TYPE_SLICING_WITH_SLICINGDISCRIMINATORTYPE__TYPE, cpath, url));
                    }
                    if (!"$this".equals(diffMatches.get(0).getSlicing().getDiscriminatorFirstRep().getPath())) {
                        throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__IN__TYPE_SLICING_WITH_SLICINGDISCRIMINATORPATH__THIS, cpath, url));
                    }
                }
                // check the slice names too while we're at it...
                for (TypeSlice ts : typeList) {
                    if (ts.type != null) {
                        String tn = rootName(cpath) + Utilities.capitalize(ts.type);
                        if (!ts.defn.hasSliceName()) {
                            ts.defn.setSliceName(tn);
                        } else if (!ts.defn.getSliceName().equals(tn)) {
                            if (autoFixSliceNames) {
                                ts.defn.setSliceName(tn);
                            } else {
                                throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__SLICE_NAME_MUST_BE__BUT_IS_, (!Utilities.noString(contextPathSrc) ? contextPathSrc : cpath), tn, ts.defn.getSliceName()));
                            }
                        }
                        if (!ts.defn.hasType()) {
                            ts.defn.addType().setCode(ts.type);
                        } else if (ts.defn.getType().size() > 1) {
                            throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__SLICE_FOR_TYPE__HAS_MORE_THAN_ONE_TYPE_, (!Utilities.noString(contextPathSrc) ? contextPathSrc : cpath), tn, ts.defn.typeSummary()));
                        } else if (!ts.defn.getType().get(0).getCode().equals(ts.type)) {
                            throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__SLICE_FOR_TYPE__HAS_WRONG_TYPE_, (!Utilities.noString(contextPathSrc) ? contextPathSrc : cpath), tn, ts.defn.typeSummary()));
                        }
                    }
                }
                // ok passed the checks.
                // copy the root diff, and then process any children it has
                ElementDefinition e = processPaths(indent + "  ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName + pathTail(diffMatches, 0), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, true, null, null, redirector, srcSD);
                if (e == null)
                    throw new FHIRException(context.formatMessage(I18nConstants.DID_NOT_FIND_TYPE_ROOT_, diffMatches.get(0).getPath()));
                // now set up slicing on the e (cause it was wiped by what we called.
                e.setSlicing(new ElementDefinitionSlicingComponent());
                e.getSlicing().addDiscriminator().setType(DiscriminatorType.TYPE).setPath("$this");
                // type slicing is always closed; the differential might call it open, but that just means it's not constraining the slices it doesn't mention
                e.getSlicing().setRules(SlicingRules.CLOSED);
                e.getSlicing().setOrdered(false);
                start++;
                String fixedType = null;
                // now we process the base scope repeatedly for each instance of the item in the differential list
                for (int i = start; i < diffMatches.size(); i++) {
                    // our processing scope for the differential is the item in the list, and all the items before the next one in the list
                    if (diffMatches.get(i).getMin() > 0) {
                        if (diffMatches.size() > i + 1) {
                            throw new FHIRException(context.formatMessage(I18nConstants.INVALID_SLICING__THERE_IS_MORE_THAN_ONE_TYPE_SLICE_AT__BUT_ONE_OF_THEM__HAS_MIN__1_SO_THE_OTHER_SLICES_CANNOT_EXIST, diffMatches.get(i).getPath(), diffMatches.get(i).getSliceName()));
                        } else {
                            e.setMin(1);
                        }
                        fixedType = determineFixedType(diffMatches, fixedType, i);
                    }
                    ndc = differential.getElement().indexOf(diffMatches.get(i));
                    ndl = findEndOfElement(differential, ndc);
                    processPaths(indent + "  ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName + pathTail(diffMatches, i), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, true, e, null, redirector, srcSD);
                }
                if (elementToRemove != null) {
                    differential.getElement().remove(elementToRemove);
                    ndl--;
                }
                if (fixedType != null) {
                    for (Iterator<TypeRefComponent> iter = e.getType().iterator(); iter.hasNext(); ) {
                        TypeRefComponent tr = iter.next();
                        if (!tr.getCode().equals(fixedType)) {
                            iter.remove();
                        }
                    }
                }
                if (!"0".equals(e.getMax())) {
                    // check that there's a slice for each allowed types
                    Set<String> allowedTypes = getListOfTypes(e);
                    for (TypeSlice t : typeList) {
                        if (t.type != null) {
                            allowedTypes.remove(t.type);
                        } else if (t.getDefn().hasSliceName() && t.getDefn().getType().size() == 1) {
                            allowedTypes.remove(t.getDefn().getType().get(0).getCode());
                        }
                    }
                    if (!allowedTypes.isEmpty()) {
                        if (cpath.contains("xtension.value")) {
                            for (Iterator<TypeRefComponent> iter = e.getType().iterator(); iter.hasNext(); ) {
                                TypeRefComponent tr = iter.next();
                                if (allowedTypes.contains(tr.getCode())) {
                                    iter.remove();
                                }
                            }
                        // System.out.println("!!: Extension Error at "+cpath+": Allowed Types not sliced = "+allowedTypes+". !Extension!!");
                        // throw new Error("Extension Error at "+cpath+": Allowed Types not sliced = "+allowedTypes+". !Extension!!");
                        } else {
                            e.getSlicing().setRules(SlicingRules.OPEN);
                        }
                    }
                }
                // ok, done with that - next in the base list
                baseCursor = nbl + 1;
                diffCursor = ndl + 1;
            } else {
                // ok, the differential slices the item. Let's check our pre-conditions to ensure that this is correct
                if (!unbounded(currentBase) && !isSlicedToOneOnly(diffMatches.get(0)))
                    // (but you might do that in order to split up constraints by type)
                    throw new DefinitionException(context.formatMessage(I18nConstants.ATTEMPT_TO_A_SLICE_AN_ELEMENT_THAT_DOES_NOT_REPEAT__FROM__IN_, currentBase.getPath(), currentBase.getPath(), contextName, url, diffMatches.get(0).getId(), sliceNames(diffMatches)));
                if (// well, the diff has set up a slice, but hasn't defined it. this is an error
                !diffMatches.get(0).hasSlicing() && !isExtension(currentBase))
                    throw new DefinitionException(context.formatMessage(I18nConstants.DIFFERENTIAL_DOES_NOT_HAVE_A_SLICE__B_OF_____IN_PROFILE_, currentBase.getPath(), baseCursor, baseLimit, diffCursor, diffLimit, url, cpath));
                // well, if it passed those preconditions then we slice the dest.
                int start = 0;
                int nbl = findEndOfElement(base, baseCursor);
                // if (diffMatches.size() > 1 && diffMatches.get(0).hasSlicing() && differential.getElement().indexOf(diffMatches.get(1)) > differential.getElement().indexOf(diffMatches.get(0))+1) {
                ElementDefinition slicerElement;
                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
                    int ndc = differential.getElement().indexOf(diffMatches.get(0));
                    int ndl = findEndOfElement(differential, ndc);
                    ElementDefinition e = processPaths(indent + "  ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName + pathTail(diffMatches, 0), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, true, null, null, redirector, srcSD);
                    if (e == null)
                        throw new FHIRException(context.formatMessage(I18nConstants.DID_NOT_FIND_SINGLE_SLICE_, diffMatches.get(0).getPath()));
                    e.setSlicing(diffMatches.get(0).getSlicing());
                    slicerElement = e;
                    start++;
                } else {
                    // we're just going to accept the differential slicing at face value
                    ElementDefinition outcome = updateURLs(url, webUrl, currentBase.copy());
                    outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
                    updateFromBase(outcome, currentBase);
                    if (!diffMatches.get(0).hasSlicing())
                        outcome.setSlicing(makeExtensionSlicing());
                    else
                        outcome.setSlicing(diffMatches.get(0).getSlicing().copy());
                    if (!outcome.getPath().startsWith(resultPathBase))
                        throw new DefinitionException(context.formatMessage(I18nConstants.ADDING_WRONG_PATH));
                    result.getElement().add(outcome);
                    slicerElement = outcome;
                    // 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.
                    if (!diffMatches.get(0).hasSliceName()) {
                        updateFromDefinition(outcome, diffMatches.get(0), profileName, trimDifferential, url, srcSD);
                        removeStatusExtensions(outcome);
                        if (!outcome.hasContentReference() && !outcome.hasType()) {
                            throw new DefinitionException(context.formatMessage(I18nConstants.NOT_DONE_YET));
                        }
                        if (hasInnerDiffMatches(differential, currentBase.getPath(), diffCursor, diffLimit, base.getElement(), false)) {
                            if (baseHasChildren(base, currentBase)) {
                                // not a new type here
                                throw new Error("This situation is not yet handled (constrain slicing to 1..1 and fix base slice for inline structure - please report issue to grahame@fhir.org along with a test case that reproduces this error (@ " + cpath + " | " + currentBase.getPath() + ")");
                            } else {
                                StructureDefinition dt = getTypeForElement(differential, diffCursor, profileName, diffMatches, outcome, webUrl);
                                contextName = dt.getUrl();
                                diffCursor++;
                                start = diffCursor;
                                while (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), cpath + ".")) diffCursor++;
                                diffCursor--;
                                processPaths(indent + "  ", result, dt.getSnapshot(), differential, 1, /* starting again on the data type, but skip the root */
                                start, dt.getSnapshot().getElement().size() - 1, diffCursor, url, getWebUrl(dt, webUrl, indent), profileName, cpath, outcome.getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirector, srcSD);
                            }
                        }
                        start++;
                    // result.getElement().remove(result.getElement().size()-1);
                    } else
                        checkExtensionDoco(outcome);
                }
                // now, for each entry in the diff matches, we're going to process the base item
                // our processing scope for base is all the children of the current path
                int ndc = diffCursor;
                int ndl = diffCursor;
                for (int i = start; i < diffMatches.size(); i++) {
                    // our processing scope for the differential is the item in the list, and all the items before the next one in the list
                    ndc = differential.getElement().indexOf(diffMatches.get(i));
                    ndl = findEndOfElement(differential, ndc);
                    /*            if (skipSlicingElement && i == 0) {
              ndc = ndc + 1;
              if (ndc > ndl)
                continue;
            }*/
                    // now we process the base scope repeatedly for each instance of the item in the differential list
                    processPaths(indent + "  ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName + pathTail(diffMatches, i), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, true, slicerElement, null, redirector, srcSD);
                }
                // ok, done with that - next in the base list
                baseCursor = nbl + 1;
                diffCursor = ndl + 1;
            }
        } else {
            // the item is already sliced in the base profile.
            // here's the rules
            // 1. irrespective of whether the slicing is ordered or not, the definition order must be maintained
            // 2. slice element names have to match.
            // 3. new slices must be introduced at the end
            // corallory: you can't re-slice existing slices. is that ok?
            // we're going to need this:
            String path = currentBase.getPath();
            ElementDefinition original = currentBase;
            if (diffMatches.isEmpty()) {
                if (hasInnerDiffMatches(differential, path, diffCursor, diffLimit, base.getElement(), true)) {
                    // so we just copy it in
                    ElementDefinition outcome = updateURLs(url, webUrl, currentBase.copy());
                    outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
                    updateFromBase(outcome, currentBase);
                    markDerived(outcome);
                    if (resultPathBase == null)
                        resultPathBase = outcome.getPath();
                    else if (!outcome.getPath().startsWith(resultPathBase))
                        throw new DefinitionException(context.formatMessage(I18nConstants.ADDING_WRONG_PATH));
                    result.getElement().add(outcome);
                    // did we implicitly step into a new type?
                    if (baseHasChildren(base, currentBase)) {
                        // not a new type here
                        processPaths(indent + "  ", result, base, differential, baseCursor + 1, diffCursor, baseLimit, diffLimit, url, webUrl, profileName, contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, false, null, null, redirector, srcSD);
                        baseCursor = indexOfFirstNonChild(base, currentBase, baseCursor, baseLimit);
                    } else {
                        StructureDefinition dt = getTypeForElement(differential, diffCursor, profileName, diffMatches, outcome, webUrl);
                        contextName = dt.getUrl();
                        int start = diffCursor;
                        if (differential.getElement().get(diffCursor).getPath().equals(cpath)) {
                            diffCursor++;
                        }
                        while (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), cpath + ".")) {
                            diffCursor++;
                        }
                        if (diffCursor > start) {
                            processPaths(indent + "  ", result, dt.getSnapshot(), differential, 1, /* starting again on the data type, but skip the root */
                            start, dt.getSnapshot().getElement().size() - 1, diffCursor - 1, url, getWebUrl(dt, webUrl, indent), profileName, cpath, outcome.getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirector, srcSD);
                        }
                    }
                    baseCursor++;
                } else {
                    // copy across the currentbase, and all of its children and siblings
                    while (baseCursor < base.getElement().size() && base.getElement().get(baseCursor).getPath().startsWith(path)) {
                        ElementDefinition outcome = updateURLs(url, webUrl, base.getElement().get(baseCursor).copy());
                        outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
                        if (!outcome.getPath().startsWith(resultPathBase))
                            throw new DefinitionException(context.formatMessage(I18nConstants.ADDING_WRONG_PATH_IN_PROFILE___VS_, profileName, outcome.getPath(), resultPathBase));
                        // so we just copy it in
                        result.getElement().add(outcome);
                        baseCursor++;
                    }
                }
            } else if (diffsConstrainTypes(diffMatches, cpath, typeList)) {
                int start = 0;
                int nbl = findEndOfElement(base, baseCursor);
                int ndc = differential.getElement().indexOf(diffMatches.get(0));
                ElementDefinition elementToRemove = null;
                boolean shortCut = (!typeList.isEmpty() && typeList.get(0).type != null) || (diffMatches.get(0).hasSliceName() && !diffMatches.get(0).hasSlicing());
                // we come here whether they are sliced in the diff, or whether the short cut is used.
                if (shortCut) {
                    // in R3 (and unpatched R4, as a workaround right now...
                    if (!FHIRVersion.isR4Plus(context.getVersion()) || !newSlicingProcessing) {
                        // newSlicingProcessing is a work around for editorial loop dependency
                        // we insert a cloned element with the right types at the start of the diffMatches
                        ElementDefinition ed = new ElementDefinition();
                        ed.setPath(determineTypeSlicePath(diffMatches.get(0).getPath(), cpath));
                        for (TypeSlice ts : typeList) ed.addType().setCode(ts.type);
                        ed.setSlicing(new ElementDefinitionSlicingComponent());
                        ed.getSlicing().addDiscriminator().setType(DiscriminatorType.TYPE).setPath("$this");
                        ed.getSlicing().setRules(SlicingRules.CLOSED);
                        ed.getSlicing().setOrdered(false);
                        diffMatches.add(0, ed);
                        differential.getElement().add(ndc, ed);
                        elementToRemove = ed;
                    } else {
                        // as of R4, this changed; if there's no slice, there's no constraint on the slice types, only one the type.
                        // so the element we insert specifies no types (= all types) allowed in the base, not just the listed type.
                        // see also discussion here: https://chat.fhir.org/#narrow/stream/179177-conformance/topic/Slicing.20a.20non-repeating.20element
                        ElementDefinition ed = new ElementDefinition();
                        ed.setPath(determineTypeSlicePath(diffMatches.get(0).getPath(), cpath));
                        ed.setSlicing(new ElementDefinitionSlicingComponent());
                        ed.getSlicing().addDiscriminator().setType(DiscriminatorType.TYPE).setPath("$this");
                        ed.getSlicing().setRules(SlicingRules.CLOSED);
                        ed.getSlicing().setOrdered(false);
                        diffMatches.add(0, ed);
                        differential.getElement().add(ndc, ed);
                        elementToRemove = ed;
                    }
                }
                int ndl = findEndOfElement(differential, ndc);
                if (diffMatches.get(0).getSlicing().hasOrdered()) {
                    if (diffMatches.get(0).getSlicing().getOrdered()) {
                        throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__IN__TYPE_SLICING_WITH_SLICINGORDERED__TRUE, cpath, url));
                    }
                }
                if (diffMatches.get(0).getSlicing().hasDiscriminator()) {
                    if (diffMatches.get(0).getSlicing().getDiscriminator().size() != 1) {
                        throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__IN__TYPE_SLICING_WITH_SLICINGDISCRIMINATORCOUNT__1, cpath, url));
                    }
                    if (diffMatches.get(0).getSlicing().getDiscriminatorFirstRep().getType() != DiscriminatorType.TYPE) {
                        throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__IN__TYPE_SLICING_WITH_SLICINGDISCRIMINATORTYPE__TYPE, cpath, url));
                    }
                    if (!"$this".equals(diffMatches.get(0).getSlicing().getDiscriminatorFirstRep().getPath())) {
                        throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__IN__TYPE_SLICING_WITH_SLICINGDISCRIMINATORPATH__THIS, cpath, url));
                    }
                }
                // check the slice names too while we're at it...
                for (TypeSlice ts : typeList) {
                    if (ts.type != null) {
                        String tn = rootName(cpath) + Utilities.capitalize(ts.type);
                        if (!ts.defn.hasSliceName()) {
                            ts.defn.setSliceName(tn);
                        } else if (!ts.defn.getSliceName().equals(tn)) {
                            throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__SLICE_NAME_MUST_BE__BUT_IS_, (!Utilities.noString(contextPathSrc) ? contextPathSrc : cpath), tn, ts.defn.getSliceName()));
                        }
                        if (!ts.defn.hasType()) {
                            ts.defn.addType().setCode(ts.type);
                        } else if (ts.defn.getType().size() > 1) {
                            throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__SLICE_FOR_TYPE__HAS_MORE_THAN_ONE_TYPE_, (!Utilities.noString(contextPathSrc) ? contextPathSrc : cpath), tn, ts.defn.typeSummary()));
                        } else if (!ts.defn.getType().get(0).getCode().equals(ts.type)) {
                            throw new FHIRException(context.formatMessage(I18nConstants.ERROR_AT_PATH__SLICE_FOR_TYPE__HAS_WRONG_TYPE_, (!Utilities.noString(contextPathSrc) ? contextPathSrc : cpath), tn, ts.defn.typeSummary()));
                        }
                    }
                }
                // ok passed the checks.
                // copy the root diff, and then process any children it has
                ElementDefinition e = processPaths(indent + "  ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName + pathTail(diffMatches, 0), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, true, null, cpath, redirector, srcSD);
                if (e == null)
                    throw new FHIRException(context.formatMessage(I18nConstants.DID_NOT_FIND_TYPE_ROOT_, diffMatches.get(0).getPath()));
                // now set up slicing on the e (cause it was wiped by what we called.
                e.setSlicing(new ElementDefinitionSlicingComponent());
                e.getSlicing().addDiscriminator().setType(DiscriminatorType.TYPE).setPath("$this");
                // type slicing is always closed; the differential might call it open, but that just means it's not constraining the slices it doesn't mention
                e.getSlicing().setRules(SlicingRules.CLOSED);
                e.getSlicing().setOrdered(false);
                start++;
                String fixedType = null;
                List<BaseTypeSlice> baseSlices = findBaseSlices(base, nbl);
                // now we process the base scope repeatedly for each instance of the item in the differential list
                for (int i = start; i < diffMatches.size(); i++) {
                    String type = determineFixedType(diffMatches, fixedType, i);
                    // our processing scope for the differential is the item in the list, and all the items before the next one in the list
                    if (diffMatches.get(i).getMin() > 0) {
                        if (diffMatches.size() > i + 1) {
                            throw new FHIRException(context.formatMessage(I18nConstants.INVALID_SLICING__THERE_IS_MORE_THAN_ONE_TYPE_SLICE_AT__BUT_ONE_OF_THEM__HAS_MIN__1_SO_THE_OTHER_SLICES_CANNOT_EXIST, diffMatches.get(i).getPath(), diffMatches.get(i).getSliceName()));
                        }
                        fixedType = type;
                    }
                    ndc = differential.getElement().indexOf(diffMatches.get(i));
                    ndl = findEndOfElement(differential, ndc);
                    int sStart = baseCursor;
                    int sEnd = nbl;
                    BaseTypeSlice bs = chooseMatchingBaseSlice(baseSlices, type);
                    if (bs != null) {
                        sStart = bs.start;
                        sEnd = bs.end;
                        bs.handled = true;
                    }
                    processPaths(indent + "  ", result, base, differential, sStart, ndc, sEnd, ndl, url, webUrl, profileName + pathTail(diffMatches, i), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, true, e, cpath, redirector, srcSD);
                }
                if (elementToRemove != null) {
                    differential.getElement().remove(elementToRemove);
                    ndl--;
                }
                if (fixedType != null) {
                    for (Iterator<TypeRefComponent> iter = e.getType().iterator(); iter.hasNext(); ) {
                        TypeRefComponent tr = iter.next();
                        if (!tr.getCode().equals(fixedType)) {
                            iter.remove();
                        }
                    }
                }
                for (BaseTypeSlice bs : baseSlices) {
                    if (!bs.handled) {
                        // ok we gimme up a fake differential that says nothing, and run that against the slice.
                        StructureDefinitionDifferentialComponent fakeDiff = new StructureDefinitionDifferentialComponent();
                        fakeDiff.getElementFirstRep().setPath(bs.defn.getPath());
                        processPaths(indent + "  ", result, base, fakeDiff, bs.start, 0, bs.end, 0, url, webUrl, profileName + tail(bs.defn.getPath()), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, true, e, cpath, redirector, srcSD);
                    }
                }
                // ok, done with that - next in the base list
                baseCursor = baseSlices.get(baseSlices.size() - 1).end + 1;
                diffCursor = ndl + 1;
            // throw new Error("not done yet - slicing / types @ "+cpath);
            } else {
                // first - check that the slicing is ok
                boolean closed = currentBase.getSlicing().getRules() == SlicingRules.CLOSED;
                int diffpos = 0;
                boolean isExtension = cpath.endsWith(".extension") || cpath.endsWith(".modifierExtension");
                if (diffMatches.get(0).hasSlicing()) {
                    // it might be null if the differential doesn't want to say anything about slicing
                    // if (!isExtension)
                    // diffpos++; // if there's a slice on the first, we'll ignore any content it has
                    ElementDefinitionSlicingComponent dSlice = diffMatches.get(0).getSlicing();
                    ElementDefinitionSlicingComponent bSlice = currentBase.getSlicing();
                    if (dSlice.hasOrderedElement() && bSlice.hasOrderedElement() && !orderMatches(dSlice.getOrderedElement(), bSlice.getOrderedElement()))
                        throw new DefinitionException(context.formatMessage(I18nConstants.SLICING_RULES_ON_DIFFERENTIAL__DO_NOT_MATCH_THOSE_ON_BASE___ORDER___, summarizeSlicing(dSlice), summarizeSlicing(bSlice), path, contextName));
                    if (!discriminatorMatches(dSlice.getDiscriminator(), bSlice.getDiscriminator()))
                        throw new DefinitionException(context.formatMessage(I18nConstants.SLICING_RULES_ON_DIFFERENTIAL__DO_NOT_MATCH_THOSE_ON_BASE___DISCIMINATOR___, summarizeSlicing(dSlice), summarizeSlicing(bSlice), path, contextName));
                    if (!currentBase.isChoice() && !ruleMatches(dSlice.getRules(), bSlice.getRules()))
                        throw new DefinitionException(context.formatMessage(I18nConstants.SLICING_RULES_ON_DIFFERENTIAL__DO_NOT_MATCH_THOSE_ON_BASE___RULE___, summarizeSlicing(dSlice), summarizeSlicing(bSlice), path, contextName));
                }
                ElementDefinition outcome = updateURLs(url, webUrl, currentBase.copy());
                outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
                updateFromBase(outcome, currentBase);
                if (diffMatches.get(0).hasSlicing() || !diffMatches.get(0).hasSliceName()) {
                    updateFromSlicing(outcome.getSlicing(), diffMatches.get(0).getSlicing());
                    // if there's no slice, we don't want to update the unsliced description
                    updateFromDefinition(outcome, diffMatches.get(0), profileName, closed, url, srcSD);
                    removeStatusExtensions(outcome);
                } else if (!diffMatches.get(0).hasSliceName()) {
                    // because of updateFromDefinition isn't called
                    diffMatches.get(0).setUserData(GENERATED_IN_SNAPSHOT, outcome);
                }
                result.getElement().add(outcome);
                if (!diffMatches.get(0).hasSliceName()) {
                    // it's not real content, just the slice
                    diffpos++;
                }
                if (hasInnerDiffMatches(differential, cpath, diffCursor, diffLimit, base.getElement(), false)) {
                    int nbl = findEndOfElement(base, baseCursor);
                    int ndx = differential.getElement().indexOf(diffMatches.get(0));
                    int ndc = ndx + (diffMatches.get(0).hasSlicing() ? 1 : 0);
                    int ndl = findEndOfElement(differential, ndx);
                    if (nbl == baseCursor) {
                        if (base.getElement().get(baseCursor).getType().size() != 1) {
                            throw new Error(context.formatMessage(I18nConstants.DIFFERENTIAL_WALKS_INTO____BUT_THE_BASE_DOES_NOT_AND_THERE_IS_NOT_A_SINGLE_FIXED_TYPE_THE_TYPE_IS__THIS_IS_NOT_HANDLED_YET, cpath, diffMatches.get(0).toString(), base.getElement().get(baseCursor).typeSummary()));
                        }
                        StructureDefinition dt = getProfileForDataType(base.getElement().get(baseCursor).getType().get(0), webUrl);
                        if (dt == null) {
                            throw new DefinitionException(context.formatMessage(I18nConstants.UNKNOWN_TYPE__AT_, outcome.getType().get(0), diffMatches.get(0).getPath()));
                        }
                        contextName = dt.getUrl();
                        while (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), cpath + ".")) diffCursor++;
                        processPaths(indent + "  ", result, dt.getSnapshot(), differential, 1, ndc, dt.getSnapshot().getElement().size() - 1, ndl, url, getWebUrl(dt, webUrl, indent), profileName, cpath, outcome.getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirector, srcSD);
                    } else {
                        processPaths(indent + "  ", result, base, differential, baseCursor + 1, ndc, nbl, ndl, url, webUrl, profileName + pathTail(diffMatches, 0), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, false, null, null, null, srcSD);
                    }
                // throw new Error("Not done yet");
                // } else if (currentBase.getType().get(0).getCode().equals("BackboneElement") && diffMatches.size() > 0 && diffMatches.get(0).hasSliceName()) {
                } else if (currentBase.getType().get(0).getCode().equals("BackboneElement")) {
                    // We need to copy children of the backbone element before we start messing around with slices
                    int nbl = findEndOfElement(base, baseCursor);
                    for (int i = baseCursor + 1; i <= nbl; i++) {
                        outcome = updateURLs(url, webUrl, base.getElement().get(i).copy());
                        result.getElement().add(outcome);
                    }
                }
                // now, we have two lists, base and diff. we're going to work through base, looking for matches in diff.
                List<ElementDefinition> baseMatches = getSiblings(base.getElement(), currentBase);
                for (ElementDefinition baseItem : baseMatches) {
                    baseCursor = base.getElement().indexOf(baseItem);
                    outcome = updateURLs(url, webUrl, baseItem.copy());
                    updateFromBase(outcome, currentBase);
                    outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
                    outcome.setSlicing(null);
                    if (!outcome.getPath().startsWith(resultPathBase))
                        throw new DefinitionException(context.formatMessage(I18nConstants.ADDING_WRONG_PATH));
                    if (diffpos < diffMatches.size() && diffMatches.get(diffpos).hasSliceName() && diffMatches.get(diffpos).getSliceName().equals(outcome.getSliceName())) {
                        // if there's a diff, we update the outcome with diff
                        // no? updateFromDefinition(outcome, diffMatches.get(diffpos), profileName, closed, url);
                        // then process any children
                        int nbl = findEndOfElement(base, baseCursor);
                        int ndc = differential.getElement().indexOf(diffMatches.get(diffpos));
                        int ndl = findEndOfElement(differential, ndc);
                        // now we process the base scope repeatedly for each instance of the item in the differential list
                        processPaths(indent + "  ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName + pathTail(diffMatches, diffpos), contextPathSrc, contextPathDst, closed, contextName, resultPathBase, true, null, null, redirector, srcSD);
                        // ok, done with that - now set the cursors for if this is the end
                        baseCursor = nbl;
                        diffCursor = ndl + 1;
                        diffpos++;
                    } else {
                        result.getElement().add(outcome);
                        baseCursor++;
                        // just copy any children on the base
                        while (baseCursor < base.getElement().size() && base.getElement().get(baseCursor).getPath().startsWith(path) && !base.getElement().get(baseCursor).getPath().equals(path)) {
                            outcome = updateURLs(url, webUrl, base.getElement().get(baseCursor).copy());
                            outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
                            if (!outcome.getPath().startsWith(resultPathBase))
                                throw new DefinitionException(context.formatMessage(I18nConstants.ADDING_WRONG_PATH));
                            result.getElement().add(outcome);
                            baseCursor++;
                        }
                        // Lloyd - add this for test T15
                        baseCursor--;
                    }
                }
                // finally, we process any remaining entries in diff, which are new (and which are only allowed if the base wasn't closed
                boolean checkImplicitTypes = false;
                if (closed && diffpos < diffMatches.size()) {
                    // this is a problem, unless we're on a polymorhpic type and we're going to constrain a slice that actually implicitly exists
                    if (currentBase.getPath().endsWith("[x]")) {
                        checkImplicitTypes = true;
                    } else {
                        throw new DefinitionException(context.formatMessage(I18nConstants.THE_BASE_SNAPSHOT_MARKS_A_SLICING_AS_CLOSED_BUT_THE_DIFFERENTIAL_TRIES_TO_EXTEND_IT_IN__AT__, profileName, path, cpath));
                    }
                }
                if (diffpos == diffMatches.size()) {
                // Lloyd This was causing problems w/ Telus
                // diffCursor++;
                } else {
                    while (diffpos < diffMatches.size()) {
                        ElementDefinition diffItem = diffMatches.get(diffpos);
                        for (ElementDefinition baseItem : baseMatches) if (baseItem.getSliceName().equals(diffItem.getSliceName()))
                            throw new DefinitionException(context.formatMessage(I18nConstants.NAMED_ITEMS_ARE_OUT_OF_ORDER_IN_THE_SLICE));
                        outcome = updateURLs(url, webUrl, currentBase.copy());
                        // outcome = updateURLs(url, diffItem.copy());
                        outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
                        updateFromBase(outcome, currentBase);
                        outcome.setSlicing(null);
                        // we're in a slice, so it's only a mandatory if it's explicitly marked so
                        outcome.setMin(0);
                        if (!outcome.getPath().startsWith(resultPathBase))
                            throw new DefinitionException(context.formatMessage(I18nConstants.ADDING_WRONG_PATH));
                        result.getElement().add(outcome);
                        updateFromDefinition(outcome, diffItem, profileName, trimDifferential, url, srcSD);
                        removeStatusExtensions(outcome);
                        // --- LM Added this
                        diffCursor = differential.getElement().indexOf(diffItem) + 1;
                        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
                            if (!baseWalksInto(base.getElement(), baseCursor)) {
                                if (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), diffMatches.get(0).getPath() + ".")) {
                                    if (outcome.getType().size() > 1)
                                        for (TypeRefComponent t : outcome.getType()) {
                                            if (!t.getCode().equals("Reference"))
                                                throw new DefinitionException(context.formatMessage(I18nConstants._HAS_CHILDREN__AND_MULTIPLE_TYPES__IN_PROFILE_, diffMatches.get(0).getPath(), differential.getElement().get(diffCursor).getPath(), typeCode(outcome.getType()), profileName));
                                        }
                                    TypeRefComponent t = outcome.getType().get(0);
                                    if (t.getCode().equals("BackboneElement")) {
                                        int baseStart = base.getElement().indexOf(currentBase) + 1;
                                        int baseMax = baseStart + 1;
                                        while (baseMax < base.getElement().size() && base.getElement().get(baseMax).getPath().startsWith(currentBase.getPath() + ".")) baseMax++;
                                        int start = diffCursor;
                                        while (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), diffMatches.get(0).getPath() + ".")) diffCursor++;
                                        processPaths(indent + "  ", result, base, differential, baseStart, start - 1, baseMax - 1, diffCursor - 1, url, webUrl, profileName + pathTail(diffMatches, 0), base.getElement().get(0).getPath(), base.getElement().get(0).getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirector, srcSD);
                                    } else {
                                        StructureDefinition dt = getProfileForDataType(outcome.getType().get(0), webUrl);
                                        // }
                                        if (dt == null)
                                            throw new DefinitionException(context.formatMessage(I18nConstants._HAS_CHILDREN__FOR_TYPE__IN_PROFILE__BUT_CANT_FIND_TYPE, diffMatches.get(0).getPath(), differential.getElement().get(diffCursor).getPath(), typeCode(outcome.getType()), profileName));
                                        contextName = dt.getUrl();
                                        int start = diffCursor;
                                        while (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), diffMatches.get(0).getPath() + ".")) diffCursor++;
                                        processPaths(indent + "  ", result, dt.getSnapshot(), differential, 1, /* starting again on the data type, but skip the root */
                                        start - 1, dt.getSnapshot().getElement().size() - 1, diffCursor - 1, url, getWebUrl(dt, webUrl, indent), profileName + pathTail(diffMatches, 0), diffMatches.get(0).getPath(), outcome.getPath(), trimDifferential, contextName, resultPathBase, false, null, null, redirector, srcSD);
                                    }
                                }
                            }
                        }
                        // ---
                        diffpos++;
                    }
                }
                baseCursor++;
            }
        }
    }
    int i = 0;
    for (ElementDefinition e : result.getElement()) {
        i++;
        if (e.hasMinElement() && e.getMinElement().getValue() == null)
            throw new Error(context.formatMessage(I18nConstants.NULL_MIN));
    }
    return res;
}
Also used : ArrayList(java.util.ArrayList) FHIRFormatError(org.hl7.fhir.exceptions.FHIRFormatError) CanonicalType(org.hl7.fhir.r5.model.CanonicalType) FHIRException(org.hl7.fhir.exceptions.FHIRException) StructureDefinition(org.hl7.fhir.r5.model.StructureDefinition) TypeRefComponent(org.hl7.fhir.r5.model.ElementDefinition.TypeRefComponent) Iterator(java.util.Iterator) StructureDefinitionDifferentialComponent(org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionDifferentialComponent) ElementDefinitionSlicingComponent(org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionSlicingComponent) ArrayList(java.util.ArrayList) List(java.util.List) ElementDefinition(org.hl7.fhir.r5.model.ElementDefinition) DefinitionException(org.hl7.fhir.exceptions.DefinitionException)

Example 35 with TS

use of org.hl7.v3.TS in project org.hl7.fhir.core by hapifhir.

the class ProfileUtilities method updateFromDefinition.

private void updateFromDefinition(ElementDefinition dest, ElementDefinition source, String pn, boolean trimDifferential, String purl, StructureDefinition srcSD) throws DefinitionException, FHIRException {
    source.setUserData(GENERATED_IN_SNAPSHOT, dest);
    // we start with a clone of the base profile ('dest') and we copy from the profile ('source')
    // over the top for anything the source has
    ElementDefinition base = dest;
    ElementDefinition derived = source;
    derived.setUserData(DERIVATION_POINTER, base);
    boolean isExtension = checkExtensionDoco(base);
    // Before applying changes, apply them to what's in the profile
    StructureDefinition profile = null;
    if (base.hasSliceName())
        profile = base.getType().size() == 1 && base.getTypeFirstRep().hasProfile() ? context.fetchResource(StructureDefinition.class, base.getTypeFirstRep().getProfile().get(0).getValue()) : null;
    if (profile == null)
        profile = source.getType().size() == 1 && source.getTypeFirstRep().hasProfile() ? context.fetchResource(StructureDefinition.class, source.getTypeFirstRep().getProfile().get(0).getValue()) : null;
    if (profile != null) {
        ElementDefinition e = profile.getSnapshot().getElement().get(0);
        String webroot = profile.getUserString("webroot");
        if (e.hasDefinition()) {
            base.setDefinition(processRelativeUrls(e.getDefinition(), webroot, baseSpecUrl(), context.getResourceNames(), masterSourceFileNames, null, true));
        }
        base.setShort(e.getShort());
        if (e.hasCommentElement())
            base.setCommentElement(e.getCommentElement());
        if (e.hasRequirementsElement())
            base.setRequirementsElement(e.getRequirementsElement());
        base.getAlias().clear();
        base.getAlias().addAll(e.getAlias());
        base.getMapping().clear();
        base.getMapping().addAll(e.getMapping());
    }
    if (derived != null) {
        if (derived.hasSliceName()) {
            base.setSliceName(derived.getSliceName());
        }
        if (derived.hasShortElement()) {
            if (!Base.compareDeep(derived.getShortElement(), base.getShortElement(), false))
                base.setShortElement(derived.getShortElement().copy());
            else if (trimDifferential)
                derived.setShortElement(null);
            else if (derived.hasShortElement())
                derived.getShortElement().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasDefinitionElement()) {
            if (derived.getDefinition().startsWith("..."))
                base.setDefinition(base.getDefinition() + "\r\n" + derived.getDefinition().substring(3));
            else if (!Base.compareDeep(derived.getDefinitionElement(), base.getDefinitionElement(), false))
                base.setDefinitionElement(derived.getDefinitionElement().copy());
            else if (trimDifferential)
                derived.setDefinitionElement(null);
            else if (derived.hasDefinitionElement())
                derived.getDefinitionElement().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasCommentElement()) {
            if (derived.getComment().startsWith("..."))
                base.setComment(base.getComment() + "\r\n" + derived.getComment().substring(3));
            else if (derived.hasCommentElement() != base.hasCommentElement() || !Base.compareDeep(derived.getCommentElement(), base.getCommentElement(), false))
                base.setCommentElement(derived.getCommentElement().copy());
            else if (trimDifferential)
                base.setCommentElement(derived.getCommentElement().copy());
            else if (derived.hasCommentElement())
                derived.getCommentElement().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasLabelElement()) {
            if (derived.getLabel().startsWith("..."))
                base.setLabel(base.getLabel() + "\r\n" + derived.getLabel().substring(3));
            else if (!base.hasLabelElement() || !Base.compareDeep(derived.getLabelElement(), base.getLabelElement(), false))
                base.setLabelElement(derived.getLabelElement().copy());
            else if (trimDifferential)
                base.setLabelElement(derived.getLabelElement().copy());
            else if (derived.hasLabelElement())
                derived.getLabelElement().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasRequirementsElement()) {
            if (derived.getRequirements().startsWith("..."))
                base.setRequirements(base.getRequirements() + "\r\n" + derived.getRequirements().substring(3));
            else if (!base.hasRequirementsElement() || !Base.compareDeep(derived.getRequirementsElement(), base.getRequirementsElement(), false))
                base.setRequirementsElement(derived.getRequirementsElement().copy());
            else if (trimDifferential)
                base.setRequirementsElement(derived.getRequirementsElement().copy());
            else if (derived.hasRequirementsElement())
                derived.getRequirementsElement().setUserData(DERIVATION_EQUALS, true);
        }
        // sdf-9
        if (derived.hasRequirements() && !base.getPath().contains("."))
            derived.setRequirements(null);
        if (base.hasRequirements() && !base.getPath().contains("."))
            base.setRequirements(null);
        if (derived.hasAlias()) {
            if (!Base.compareDeep(derived.getAlias(), base.getAlias(), false))
                for (StringType s : derived.getAlias()) {
                    if (!base.hasAlias(s.getValue()))
                        base.getAlias().add(s.copy());
                }
            else if (trimDifferential)
                derived.getAlias().clear();
            else
                for (StringType t : derived.getAlias()) t.setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasMinElement()) {
            if (!Base.compareDeep(derived.getMinElement(), base.getMinElement(), false)) {
                if (// in a slice, minimum cardinality rules do not apply
                derived.getMin() < base.getMin() && !derived.hasSliceName())
                    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));
                base.setMinElement(derived.getMinElement().copy());
            } else if (trimDifferential)
                derived.setMinElement(null);
            else
                derived.getMinElement().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasMaxElement()) {
            if (!Base.compareDeep(derived.getMaxElement(), base.getMaxElement(), false)) {
                if (isLargerMax(derived.getMax(), base.getMax()))
                    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));
                base.setMaxElement(derived.getMaxElement().copy());
            } else if (trimDifferential)
                derived.setMaxElement(null);
            else
                derived.getMaxElement().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasFixed()) {
            if (!Base.compareDeep(derived.getFixed(), base.getFixed(), true)) {
                base.setFixed(derived.getFixed().copy());
            } else if (trimDifferential)
                derived.setFixed(null);
            else
                derived.getFixed().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasPattern()) {
            if (!Base.compareDeep(derived.getPattern(), base.getPattern(), false)) {
                base.setPattern(derived.getPattern().copy());
            } else if (trimDifferential)
                derived.setPattern(null);
            else
                derived.getPattern().setUserData(DERIVATION_EQUALS, true);
        }
        for (ElementDefinitionExampleComponent ex : derived.getExample()) {
            boolean found = false;
            for (ElementDefinitionExampleComponent exS : base.getExample()) if (Base.compareDeep(ex, exS, false))
                found = true;
            if (!found)
                base.addExample(ex.copy());
            else if (trimDifferential)
                derived.getExample().remove(ex);
            else
                ex.setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasMaxLengthElement()) {
            if (!Base.compareDeep(derived.getMaxLengthElement(), base.getMaxLengthElement(), false))
                base.setMaxLengthElement(derived.getMaxLengthElement().copy());
            else if (trimDifferential)
                derived.setMaxLengthElement(null);
            else
                derived.getMaxLengthElement().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasMaxValue()) {
            if (!Base.compareDeep(derived.getMaxValue(), base.getMaxValue(), false))
                base.setMaxValue(derived.getMaxValue().copy());
            else if (trimDifferential)
                derived.setMaxValue(null);
            else
                derived.getMaxValue().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasMinValue()) {
            if (!Base.compareDeep(derived.getMinValue(), base.getMinValue(), false))
                base.setMinValue(derived.getMinValue().copy());
            else if (trimDifferential)
                derived.setMinValue(null);
            else
                derived.getMinValue().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasMustSupportElement()) {
            if (!(base.hasMustSupportElement() && Base.compareDeep(derived.getMustSupportElement(), base.getMustSupportElement(), false))) {
                if (base.hasMustSupport() && base.getMustSupport() && !derived.getMustSupport()) {
                    messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn + "." + derived.getPath(), "Illegal constraint [must-support = false] when [must-support = true] in the base profile", ValidationMessage.IssueSeverity.ERROR));
                }
                base.setMustSupportElement(derived.getMustSupportElement().copy());
            } else if (trimDifferential)
                derived.setMustSupportElement(null);
            else
                derived.getMustSupportElement().setUserData(DERIVATION_EQUALS, true);
        }
        // but extensions can change isModifier
        if (isExtension) {
            if (derived.hasIsModifierElement() && !(base.hasIsModifierElement() && Base.compareDeep(derived.getIsModifierElement(), base.getIsModifierElement(), false)))
                base.setIsModifierElement(derived.getIsModifierElement().copy());
            else if (trimDifferential)
                derived.setIsModifierElement(null);
            else if (derived.hasIsModifierElement())
                derived.getIsModifierElement().setUserData(DERIVATION_EQUALS, true);
            if (derived.hasIsModifierReasonElement() && !(base.hasIsModifierReasonElement() && Base.compareDeep(derived.getIsModifierReasonElement(), base.getIsModifierReasonElement(), false)))
                base.setIsModifierReasonElement(derived.getIsModifierReasonElement().copy());
            else if (trimDifferential)
                derived.setIsModifierReasonElement(null);
            else if (derived.hasIsModifierReasonElement())
                derived.getIsModifierReasonElement().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasBinding()) {
            if (!base.hasBinding() || !Base.compareDeep(derived.getBinding(), base.getBinding(), false)) {
                if (base.hasBinding() && base.getBinding().getStrength() == BindingStrength.REQUIRED && derived.getBinding().getStrength() != BindingStrength.REQUIRED)
                    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));
                else // throw new DefinitionException("StructureDefinition "+pn+" at "+derived.getPath()+": illegal attempt to change a binding from "+base.getBinding().getStrength().toCode()+" to "+derived.getBinding().getStrength().toCode());
                if (base.hasBinding() && derived.hasBinding() && base.getBinding().getStrength() == BindingStrength.REQUIRED && base.getBinding().hasValueSet() && derived.getBinding().hasValueSet()) {
                    ValueSet baseVs = context.fetchResource(ValueSet.class, base.getBinding().getValueSet());
                    ValueSet contextVs = context.fetchResource(ValueSet.class, derived.getBinding().getValueSet());
                    if (baseVs == null) {
                        messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn + "." + base.getPath(), "Binding " + base.getBinding().getValueSet() + " could not be located", ValidationMessage.IssueSeverity.WARNING));
                    } else if (contextVs == null) {
                        messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn + "." + derived.getPath(), "Binding " + derived.getBinding().getValueSet() + " could not be located", ValidationMessage.IssueSeverity.WARNING));
                    } else {
                        ValueSetExpansionOutcome expBase = context.expandVS(baseVs, true, false);
                        ValueSetExpansionOutcome expDerived = context.expandVS(contextVs, true, false);
                        if (expBase.getValueset() == null)
                            messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn + "." + base.getPath(), "Binding " + base.getBinding().getValueSet() + " could not be expanded", ValidationMessage.IssueSeverity.WARNING));
                        else if (expDerived.getValueset() == null)
                            messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn + "." + derived.getPath(), "Binding " + derived.getBinding().getValueSet() + " could not be expanded", ValidationMessage.IssueSeverity.WARNING));
                        else if (ToolingExtensions.hasExtension(expBase.getValueset().getExpansion(), ToolingExtensions.EXT_EXP_TOOCOSTLY))
                            messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn + "." + derived.getPath(), "Unable to check if " + derived.getBinding().getValueSet() + " is a proper subset of " + base.getBinding().getValueSet() + " - base value set is too large to check", ValidationMessage.IssueSeverity.WARNING));
                        else if (!isSubset(expBase.getValueset(), expDerived.getValueset()))
                            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));
                    }
                }
                ElementDefinitionBindingComponent d = derived.getBinding();
                ElementDefinitionBindingComponent nb = base.getBinding().copy();
                if (!COPY_BINDING_EXTENSIONS) {
                    nb.getExtension().clear();
                }
                nb.setDescription(null);
                nb.getExtension().addAll(d.getExtension());
                if (d.hasStrength()) {
                    nb.setStrength(d.getStrength());
                }
                if (d.hasDescription()) {
                    nb.setDescription(d.getDescription());
                }
                if (d.hasValueSet()) {
                    nb.setValueSet(d.getValueSet());
                }
                base.setBinding(nb);
            } else if (trimDifferential)
                derived.setBinding(null);
            else
                derived.getBinding().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasIsSummaryElement()) {
            if (!Base.compareDeep(derived.getIsSummaryElement(), base.getIsSummaryElement(), false)) {
                if (// work around a known issue with some 1.4.0 cosntraints
                base.hasIsSummary() && !context.getVersion().equals("1.4.0"))
                    throw new Error(context.formatMessage(I18nConstants.ERROR_IN_PROFILE__AT__BASE_ISSUMMARY___DERIVED_ISSUMMARY__, purl, derived.getPath(), base.getIsSummaryElement().asStringValue(), derived.getIsSummaryElement().asStringValue()));
                base.setIsSummaryElement(derived.getIsSummaryElement().copy());
            } else if (trimDifferential)
                derived.setIsSummaryElement(null);
            else
                derived.getIsSummaryElement().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasType()) {
            if (!Base.compareDeep(derived.getType(), base.getType(), false)) {
                if (base.hasType()) {
                    for (TypeRefComponent ts : derived.getType()) {
                        checkTypeDerivation(purl, srcSD, base, derived, ts);
                    }
                }
                base.getType().clear();
                for (TypeRefComponent t : derived.getType()) {
                    TypeRefComponent tt = t.copy();
                    // tt.setUserData(DERIVATION_EQUALS, true);
                    base.getType().add(tt);
                }
            } else if (trimDifferential)
                derived.getType().clear();
            else
                for (TypeRefComponent t : derived.getType()) t.setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasMapping()) {
            // todo: mappings are not cumulative - one replaces another
            if (!Base.compareDeep(derived.getMapping(), base.getMapping(), false)) {
                for (ElementDefinitionMappingComponent s : derived.getMapping()) {
                    boolean found = false;
                    for (ElementDefinitionMappingComponent d : base.getMapping()) {
                        found = found || (d.getIdentity().equals(s.getIdentity()) && d.getMap().equals(s.getMap()));
                    }
                    if (!found) {
                        base.getMapping().add(s);
                    }
                }
            } else if (trimDifferential) {
                derived.getMapping().clear();
            } else {
                for (ElementDefinitionMappingComponent t : derived.getMapping()) {
                    t.setUserData(DERIVATION_EQUALS, true);
                }
            }
        }
        for (ElementDefinitionMappingComponent m : base.getMapping()) {
            if (m.hasMap()) {
                m.setMap(m.getMap().trim());
            }
        }
        // todo: constraints are cumulative. there is no replacing
        for (ElementDefinitionConstraintComponent s : base.getConstraint()) {
            s.setUserData(IS_DERIVED, true);
            if (!s.hasSource()) {
                s.setSource(srcSD.getUrl());
            }
        }
        if (derived.hasConstraint()) {
            for (ElementDefinitionConstraintComponent s : derived.getConstraint()) {
                if (!base.hasConstraint(s.getKey())) {
                    ElementDefinitionConstraintComponent inv = s.copy();
                    base.getConstraint().add(inv);
                }
            }
        }
        for (IdType id : derived.getCondition()) {
            if (!base.hasCondition(id)) {
                base.getCondition().add(id);
            }
        }
        // now, check that we still have a bindable type; if not, delete the binding - see task 8477
        if (dest.hasBinding() && !hasBindableType(dest)) {
            dest.setBinding(null);
        }
        // finally, we copy any extensions from source to dest
        for (Extension ex : derived.getExtension()) {
            StructureDefinition sd = context.fetchResource(StructureDefinition.class, ex.getUrl());
            if (sd == null || sd.getSnapshot() == null || sd.getSnapshot().getElementFirstRep().getMax().equals("1")) {
                ToolingExtensions.removeExtension(dest, ex.getUrl());
            }
            dest.addExtension(ex.copy());
        }
    }
    if (dest.hasFixed()) {
        checkTypeOk(dest, dest.getFixed().fhirType(), srcSD);
    }
    if (dest.hasPattern()) {
        checkTypeOk(dest, dest.getPattern().fhirType(), srcSD);
    }
}
Also used : ElementDefinitionExampleComponent(org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionExampleComponent) ValidationMessage(org.hl7.fhir.utilities.validation.ValidationMessage) StringType(org.hl7.fhir.r5.model.StringType) FHIRFormatError(org.hl7.fhir.exceptions.FHIRFormatError) ElementDefinitionConstraintComponent(org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionConstraintComponent) IdType(org.hl7.fhir.r5.model.IdType) Extension(org.hl7.fhir.r5.model.Extension) StructureDefinition(org.hl7.fhir.r5.model.StructureDefinition) TypeRefComponent(org.hl7.fhir.r5.model.ElementDefinition.TypeRefComponent) ValueSetExpansionOutcome(org.hl7.fhir.r5.terminologies.ValueSetExpander.ValueSetExpansionOutcome) ElementDefinition(org.hl7.fhir.r5.model.ElementDefinition) ValueSet(org.hl7.fhir.r5.model.ValueSet) ElementDefinitionBindingComponent(org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionBindingComponent) ElementDefinitionMappingComponent(org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionMappingComponent)

Aggregations

ArrayList (java.util.ArrayList)15 DefinitionException (org.hl7.fhir.exceptions.DefinitionException)9 CS (net.ihe.gazelle.hl7v3.datatypes.CS)8 II (net.ihe.gazelle.hl7v3.datatypes.II)8 TS (net.ihe.gazelle.hl7v3.datatypes.TS)8 FHIRFormatError (org.hl7.fhir.exceptions.FHIRFormatError)8 BundleEntryComponent (org.hl7.fhir.r4.model.Bundle.BundleEntryComponent)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 BL (net.ihe.gazelle.hl7v3.datatypes.BL)7 CD (net.ihe.gazelle.hl7v3.datatypes.CD)7 CE (net.ihe.gazelle.hl7v3.datatypes.CE)7 INT (net.ihe.gazelle.hl7v3.datatypes.INT)7 MCCIMT000100UV01Device (net.ihe.gazelle.hl7v3.mccimt000100UV01.MCCIMT000100UV01Device)7 MCCIMT000100UV01Receiver (net.ihe.gazelle.hl7v3.mccimt000100UV01.MCCIMT000100UV01Receiver)7 MCCIMT000100UV01Sender (net.ihe.gazelle.hl7v3.mccimt000100UV01.MCCIMT000100UV01Sender)7 FHIRException (org.hl7.fhir.exceptions.FHIRException)7 Identifier (org.hl7.fhir.r4.model.Identifier)7 Test (org.junit.jupiter.api.Test)7 COCTMT090003UV01AssignedEntity (net.ihe.gazelle.hl7v3.coctmt090003UV01.COCTMT090003UV01AssignedEntity)6 COCTMT090003UV01Organization (net.ihe.gazelle.hl7v3.coctmt090003UV01.COCTMT090003UV01Organization)6