Search in sources :

Example 1 with NamedType

use of org.hl7.cql.model.NamedType in project clinical_quality_language by cqframework.

the class SemanticTests method testTypeOperators.

@Test
public void testTypeOperators() throws IOException {
    CqlTranslator translator = runSemanticTest("OperatorTests/TypeOperators.cql");
    org.hl7.elm.r1.Library library = translator.toELM();
    Map<String, ExpressionDef> defs = new HashMap<>();
    if (library.getStatements() != null) {
        for (ExpressionDef def : library.getStatements().getDef()) {
            defs.put(def.getName(), def);
        }
    }
    ExpressionDef def = defs.get("TestIf");
    assertThat(def.getResultType(), instanceOf(ChoiceType.class));
    ChoiceType choiceType = (ChoiceType) def.getResultType();
    DataType type = null;
    for (DataType dt : choiceType.getTypes()) {
        if (type == null) {
            type = dt;
            assertThat(dt, instanceOf(NamedType.class));
            assertThat(((NamedType) dt).getName(), equalTo("System.String"));
        } else {
            assertThat(dt, instanceOf(NamedType.class));
            assertThat(((NamedType) dt).getName(), equalTo("System.Boolean"));
        }
    }
    def = defs.get("TestCase");
    assertThat(def.getResultType(), instanceOf(ChoiceType.class));
    choiceType = (ChoiceType) def.getResultType();
    type = null;
    for (DataType dt : choiceType.getTypes()) {
        if (type == null) {
            type = dt;
            assertThat(dt, instanceOf(NamedType.class));
            assertThat(((NamedType) dt).getName(), equalTo("System.String"));
        } else {
            assertThat(dt, instanceOf(NamedType.class));
            assertThat(((NamedType) dt).getName(), equalTo("System.Boolean"));
        }
    }
}
Also used : HashMap(java.util.HashMap) ChoiceType(org.hl7.cql.model.ChoiceType) NamedType(org.hl7.cql.model.NamedType) DataType(org.hl7.cql.model.DataType) org.hl7.elm.r1(org.hl7.elm.r1) Test(org.testng.annotations.Test)

Example 2 with NamedType

use of org.hl7.cql.model.NamedType in project clinical_quality_language by cqframework.

the class Cql2ElmVisitor method visitRetrieve.

@Override
@SuppressWarnings("unchecked")
public Retrieve visitRetrieve(cqlParser.RetrieveContext ctx) {
    libraryBuilder.checkLiteralContext();
    List<String> qualifiers = parseQualifiers(ctx.namedTypeSpecifier());
    String model = getModelIdentifier(qualifiers);
    String label = getTypeIdentifier(qualifiers, parseString(ctx.namedTypeSpecifier().referentialOrTypeNameIdentifier()));
    DataType dataType = libraryBuilder.resolveTypeName(model, label);
    if (dataType == null) {
        // ERROR:
        throw new IllegalArgumentException(String.format("Could not resolve type name %s.", label));
    }
    if (!(dataType instanceof ClassType) || !((ClassType) dataType).isRetrievable()) {
        // ERROR:
        throw new IllegalArgumentException(String.format("Specified data type %s does not support retrieval.", label));
    }
    ClassType classType = (ClassType) dataType;
    // BTR -> The original intent of this code was to have the retrieve return the base type, and use the "templateId"
    // element of the retrieve to communicate the "positive" or "negative" profile to the data access layer.
    // However, because this notion of carrying the "profile" through a type is not general, it causes inconsistencies
    // when using retrieve results with functions defined in terms of the same type (see GitHub Issue #131).
    // Based on the discussion there, the retrieve will now return the declared type, whether it is a profile or not.
    // ProfileType profileType = dataType instanceof ProfileType ? (ProfileType)dataType : null;
    // NamedType namedType = profileType == null ? classType : (NamedType)classType.getBaseType();
    NamedType namedType = classType;
    ModelInfo modelInfo = libraryBuilder.getModel(namedType.getNamespace()).getModelInfo();
    boolean useStrictRetrieveTyping = modelInfo.isStrictRetrieveTyping() != null && modelInfo.isStrictRetrieveTyping();
    Retrieve retrieve = of.createRetrieve().withDataType(libraryBuilder.dataTypeToQName((DataType) namedType)).withTemplateId(classType.getIdentifier());
    if (ctx.contextIdentifier() != null) {
        List<String> identifiers = (List<String>) visit(ctx.contextIdentifier());
        Expression contextExpression = resolveQualifiedIdentifier(identifiers);
        retrieve.setContext(contextExpression);
    }
    if (ctx.terminology() != null) {
        if (ctx.codePath() != null) {
            String identifiers = (String) visit(ctx.codePath());
            retrieve.setCodeProperty(identifiers);
        } else if (classType.getPrimaryCodePath() != null) {
            retrieve.setCodeProperty(classType.getPrimaryCodePath());
        }
        Property property = null;
        CqlCompilerException propertyException = null;
        if (retrieve.getCodeProperty() == null) {
            // ERROR:
            // WARNING:
            propertyException = new CqlSemanticException("Retrieve has a terminology target but does not specify a code path and the type of the retrieve does not have a primary code path defined.", useStrictRetrieveTyping ? CqlCompilerException.ErrorSeverity.Error : CqlCompilerException.ErrorSeverity.Warning, getTrackBack(ctx));
            libraryBuilder.recordParsingException(propertyException);
        } else {
            try {
                DataType codeType = libraryBuilder.resolvePath((DataType) namedType, retrieve.getCodeProperty());
                property = of.createProperty().withPath(retrieve.getCodeProperty());
                property.setResultType(codeType);
            } catch (Exception e) {
                // ERROR:
                // WARNING:
                propertyException = new CqlSemanticException(String.format("Could not resolve code path %s for the type of the retrieve %s.", retrieve.getCodeProperty(), namedType.getName()), useStrictRetrieveTyping ? CqlCompilerException.ErrorSeverity.Error : CqlCompilerException.ErrorSeverity.Warning, getTrackBack(ctx), e);
                libraryBuilder.recordParsingException(propertyException);
            }
        }
        Expression terminology = null;
        if (ctx.terminology().qualifiedIdentifierExpression() != null) {
            List<String> identifiers = (List<String>) visit(ctx.terminology());
            terminology = resolveQualifiedIdentifier(identifiers);
            track(terminology, ctx.terminology().qualifiedIdentifierExpression());
        } else {
            terminology = parseExpression(ctx.terminology().expression());
        }
        String codeComparator = ctx.codeComparator() != null ? (String) visit(ctx.codeComparator()) : null;
        // Resolve the terminology target using an in or ~ operator
        try {
            if (codeComparator == null) {
                codeComparator = (terminology.getResultType() instanceof ListType || (libraryBuilder.isCompatibleWith("1.5") && terminology.getResultType().isSubTypeOf(libraryBuilder.resolveTypeName("System", "Vocabulary")))) ? "in" : "~";
            }
            if (property == null) {
                throw propertyException;
            }
            switch(codeComparator) {
                case "in":
                    {
                        Expression in = libraryBuilder.resolveIn(property, terminology);
                        if (in instanceof In) {
                            retrieve.setCodes(((In) in).getOperand().get(1));
                        } else if (in instanceof InValueSet) {
                            retrieve.setCodes(((InValueSet) in).getValueset());
                        } else if (in instanceof InCodeSystem) {
                            retrieve.setCodes(((InCodeSystem) in).getCodesystem());
                        } else if (in instanceof AnyInValueSet) {
                            retrieve.setCodes(((AnyInValueSet) in).getValueset());
                        } else if (in instanceof AnyInCodeSystem) {
                            retrieve.setCodes(((AnyInCodeSystem) in).getCodesystem());
                        } else {
                            // ERROR:
                            // WARNING:
                            libraryBuilder.recordParsingException(new CqlSemanticException(String.format("Unexpected membership operator %s in retrieve", in.getClass().getSimpleName()), useStrictRetrieveTyping ? CqlCompilerException.ErrorSeverity.Error : CqlCompilerException.ErrorSeverity.Warning, getTrackBack(ctx)));
                        }
                    }
                    break;
                case "~":
                    {
                        // Resolve with equivalent to verify the type of the target
                        BinaryExpression equivalent = of.createEquivalent().withOperand(property, terminology);
                        libraryBuilder.resolveBinaryCall("System", "Equivalent", equivalent);
                        // Automatically promote to a list for use in the retrieve target
                        if (!(equivalent.getOperand().get(1).getResultType() instanceof ListType)) {
                            retrieve.setCodes(libraryBuilder.resolveToList(equivalent.getOperand().get(1)));
                        } else {
                            retrieve.setCodes(equivalent.getOperand().get(1));
                        }
                    }
                    break;
                case "=":
                    {
                        // Resolve with equality to verify the type of the source and target
                        BinaryExpression equal = of.createEqual().withOperand(property, terminology);
                        libraryBuilder.resolveBinaryCall("System", "Equal", equal);
                        // Automatically promote to a list for use in the retrieve target
                        if (!(equal.getOperand().get(1).getResultType() instanceof ListType)) {
                            retrieve.setCodes(libraryBuilder.resolveToList(equal.getOperand().get(1)));
                        } else {
                            retrieve.setCodes(equal.getOperand().get(1));
                        }
                    }
                    break;
                default:
                    // ERROR:
                    // WARNING:
                    libraryBuilder.recordParsingException(new CqlSemanticException(String.format("Unknown code comparator % in retrieve", codeComparator), useStrictRetrieveTyping ? CqlCompilerException.ErrorSeverity.Error : CqlCompilerException.ErrorSeverity.Warning, getTrackBack(ctx.codeComparator())));
            }
            retrieve.setCodeComparator(codeComparator);
            // In that case, convert to a list of code (Union the Code elements of the Concepts in the list)
            if (retrieve.getCodes() != null && retrieve.getCodes().getResultType() != null && retrieve.getCodes().getResultType() instanceof ListType && ((ListType) retrieve.getCodes().getResultType()).getElementType().equals(libraryBuilder.resolveTypeName("System", "Concept"))) {
                if (retrieve.getCodes() instanceof ToList) {
                    // ToList will always have a single argument
                    ToList toList = (ToList) retrieve.getCodes();
                    // If that argument is a ToConcept, replace the ToList argument with the code (skip the implicit conversion, the data access layer is responsible for it)
                    if (toList.getOperand() instanceof ToConcept) {
                        toList.setOperand(((ToConcept) toList.getOperand()).getOperand());
                    } else {
                        // Otherwise, access the codes property of the resulting Concept
                        Expression codesAccessor = libraryBuilder.buildProperty(toList.getOperand(), "codes", false, toList.getOperand().getResultType());
                        retrieve.setCodes(codesAccessor);
                    }
                } else {
                    // WARNING:
                    libraryBuilder.recordParsingException(new CqlSemanticException("Terminology target is a list of concepts, but expects a list of codes", CqlCompilerException.ErrorSeverity.Warning, getTrackBack(ctx)));
                }
            }
        } catch (Exception e) {
            // it shouldn't prevent translation unless the modelinfo indicates strict retrieve typing
            if ((libraryBuilder.isCompatibleWith("1.5") && !(terminology.getResultType().isSubTypeOf(libraryBuilder.resolveTypeName("System", "Vocabulary")))) || (!libraryBuilder.isCompatibleWith("1.5") && !(terminology.getResultType() instanceof ListType))) {
                retrieve.setCodes(libraryBuilder.resolveToList(terminology));
            } else {
                retrieve.setCodes(terminology);
            }
            retrieve.setCodeComparator(codeComparator);
            // ERROR:
            // WARNING:
            libraryBuilder.recordParsingException(new CqlSemanticException("Could not resolve membership operator for terminology target of the retrieve.", useStrictRetrieveTyping ? CqlCompilerException.ErrorSeverity.Error : CqlCompilerException.ErrorSeverity.Warning, getTrackBack(ctx), e));
        }
    }
    retrieves.add(retrieve);
    retrieve.setResultType(new ListType((DataType) namedType));
    return retrieve;
}
Also used : ModelInfo(org.hl7.elm_modelinfo.r1.ModelInfo) List(java.util.List)

Example 3 with NamedType

use of org.hl7.cql.model.NamedType in project clinical_quality_language by cqframework.

the class TypeBuilder method dataTypeToQName.

public QName dataTypeToQName(DataType type) {
    if (type instanceof NamedType) {
        NamedType namedType = (NamedType) type;
        ModelInfo modelInfo = mr.getModel(namedType.getNamespace()).getModelInfo();
        return new QName(modelInfo.getTargetUrl() != null ? modelInfo.getTargetUrl() : modelInfo.getUrl(), namedType.getTarget() != null ? namedType.getTarget() : namedType.getSimpleName());
    }
    // ERROR:
    throw new IllegalArgumentException("A named type is required in this context.");
}
Also used : ModelInfo(org.hl7.elm_modelinfo.r1.ModelInfo) QName(javax.xml.namespace.QName)

Example 4 with NamedType

use of org.hl7.cql.model.NamedType in project clinical_quality_language by cqframework.

the class SystemLibraryHelper method add.

private static void add(CompiledLibrary systemLibrary, TypeBuilder tb, Operator operator) {
    // In the case that an operator is added directly, manufacture a FunctionDef so it can be referred to in ELM Analysis
    FunctionDef fd = new FunctionDef();
    fd.setName(operator.getName());
    int n = 0;
    for (DataType dataType : operator.getSignature().getOperandTypes()) {
        n++;
        OperandDef od = new OperandDef().withName(String.format("param%d", n));
        if (dataType instanceof NamedType) {
            od.setOperandType(tb.dataTypeToQName(dataType));
        } else {
            od.setOperandTypeSpecifier(tb.dataTypeToTypeSpecifier(dataType));
        }
        od.setResultType(dataType);
        fd.getOperand().add(od);
    }
    operator.setFunctionDef(fd);
    systemLibrary.add(fd, operator);
}
Also used : OperandDef(org.hl7.elm.r1.OperandDef) FunctionDef(org.hl7.elm.r1.FunctionDef)

Aggregations

ModelInfo (org.hl7.elm_modelinfo.r1.ModelInfo)2 HashMap (java.util.HashMap)1 List (java.util.List)1 QName (javax.xml.namespace.QName)1 ChoiceType (org.hl7.cql.model.ChoiceType)1 DataType (org.hl7.cql.model.DataType)1 NamedType (org.hl7.cql.model.NamedType)1 org.hl7.elm.r1 (org.hl7.elm.r1)1 FunctionDef (org.hl7.elm.r1.FunctionDef)1 OperandDef (org.hl7.elm.r1.OperandDef)1 Test (org.testng.annotations.Test)1