use of org.hl7.cql.model.ClassType in project clinical_quality_language by cqframework.
the class Cql2ElmVisitor method visitContextDefinition.
@Override
public Object visitContextDefinition(cqlParser.ContextDefinitionContext ctx) {
String modelIdentifier = parseString(ctx.modelIdentifier());
String unqualifiedIdentifier = parseString(ctx.identifier());
currentContext = modelIdentifier != null ? modelIdentifier + "." + unqualifiedIdentifier : unqualifiedIdentifier;
if (!isUnfilteredContext(unqualifiedIdentifier)) {
ModelContext modelContext = libraryBuilder.resolveContextName(modelIdentifier, unqualifiedIdentifier);
// If this is the first time a context definition is encountered, construct a context definition:
// define <Context> = element of [<Context model type>]
Element modelContextDefinition = contextDefinitions.get(modelContext.getName());
if (modelContextDefinition == null) {
if (libraryBuilder.hasUsings()) {
ModelInfo modelInfo = modelIdentifier == null ? libraryBuilder.getModel(libraryInfo.getDefaultModelName()).getModelInfo() : libraryBuilder.getModel(modelIdentifier).getModelInfo();
// String contextTypeName = modelContext.getName();
// DataType contextType = libraryBuilder.resolveTypeName(modelInfo.getName(), contextTypeName);
DataType contextType = modelContext.getType();
modelContextDefinition = libraryBuilder.resolveParameterRef(modelContext.getName());
if (modelContextDefinition != null) {
contextDefinitions.put(modelContext.getName(), modelContextDefinition);
} else {
Retrieve contextRetrieve = of.createRetrieve().withDataType(libraryBuilder.dataTypeToQName(contextType));
track(contextRetrieve, ctx);
contextRetrieve.setResultType(new ListType(contextType));
String contextClassIdentifier = ((ClassType) contextType).getIdentifier();
if (contextClassIdentifier != null) {
contextRetrieve.setTemplateId(contextClassIdentifier);
}
modelContextDefinition = of.createExpressionDef().withName(unqualifiedIdentifier).withContext(currentContext).withExpression(of.createSingletonFrom().withOperand(contextRetrieve));
track(modelContextDefinition, ctx);
((ExpressionDef) modelContextDefinition).getExpression().setResultType(contextType);
modelContextDefinition.setResultType(contextType);
libraryBuilder.addExpression((ExpressionDef) modelContextDefinition);
contextDefinitions.put(modelContext.getName(), modelContextDefinition);
}
} else {
modelContextDefinition = of.createExpressionDef().withName(unqualifiedIdentifier).withContext(currentContext).withExpression(of.createNull());
track(modelContextDefinition, ctx);
((ExpressionDef) modelContextDefinition).getExpression().setResultType(libraryBuilder.resolveTypeName("System", "Any"));
modelContextDefinition.setResultType(((ExpressionDef) modelContextDefinition).getExpression().getResultType());
libraryBuilder.addExpression((ExpressionDef) modelContextDefinition);
contextDefinitions.put(modelContext.getName(), modelContextDefinition);
}
}
}
ContextDef contextDef = of.createContextDef().withName(currentContext);
track(contextDef, ctx);
if (libraryBuilder.isCompatibleWith("1.5")) {
libraryBuilder.addContext(contextDef);
}
return currentContext;
}
use of org.hl7.cql.model.ClassType in project clinical_quality_language by cqframework.
the class ElmDataRequirement method applyJoinRequirementTo.
private void applyJoinRequirementTo(ElmJoinRequirement joinRequirement, Retrieve retrieve, ElmRequirementsContext context, ElmQueryRequirement queryRequirements) {
ElmDataRequirement leftRequirement = queryRequirements.getDataRequirement(joinRequirement.getLeftProperty().getSource());
ElmDataRequirement rightRequirement = queryRequirements.getDataRequirement(joinRequirement.getRightProperty().getSource());
if (leftRequirement != null && rightRequirement != null) {
Retrieve leftRetrieve = leftRequirement.getRetrieve();
Retrieve rightRetrieve = rightRequirement.getRetrieve();
// Only report include possibility if the retrieves can both be tied to the data model
if (leftRetrieve.getDataType() != null && rightRetrieve.getDataType() != null) {
ClassType leftRetrieveType = getRetrieveType(context, leftRetrieve);
ClassType rightRetrieveType = getRetrieveType(context, rightRetrieve);
if (leftRetrieveType != null && rightRetrieveType != null) {
SearchType leftSearch;
SearchType rightSearch;
for (SearchType search : leftRetrieveType.getSearches()) {
if (joinRequirement.getLeftProperty().getProperty().getPath().startsWith(search.getPath())) {
if (search.getType().isCompatibleWith(rightRetrieveType)) {
leftSearch = search;
break;
}
}
}
for (SearchType search : rightRetrieveType.getSearches()) {
if (joinRequirement.getRightProperty().getProperty().getPath().startsWith(search.getPath())) {
if (search.getType().isCompatibleWith(leftRetrieveType)) {
rightSearch = search;
break;
}
}
}
// Search from the model info should be used to inform the selection, but will in general resolve to multiple choices
// May be a choice better left to the capabilityStatement-informed planning phase anyway
}
// In the absence of search information, either of these formulations is correct, favor primary query sources over withs
if (leftRetrieve.getLocalId() == null) {
leftRetrieve.setLocalId(context.generateLocalId());
}
if (rightRetrieve.getLocalId() == null) {
rightRetrieve.setLocalId(context.generateLocalId());
}
if (rightRequirement.getQuerySource() instanceof With) {
leftRetrieve.getInclude().add(new IncludeElement().withIncludeFrom(rightRetrieve.getLocalId()).withRelatedDataType(rightRetrieve.getDataType()).withRelatedProperty(joinRequirement.getLeftProperty().getProperty().getPath()).withIsReverse(false));
rightRetrieve.setIncludedIn(leftRetrieve.getLocalId());
} else {
rightRetrieve.getInclude().add(new IncludeElement().withIncludeFrom(leftRetrieve.getLocalId()).withRelatedDataType(leftRetrieve.getDataType()).withRelatedProperty(joinRequirement.getRightProperty().getProperty().getPath()).withIsReverse(false));
leftRetrieve.setIncludedIn(rightRetrieve.getLocalId());
}
}
}
}
use of org.hl7.cql.model.ClassType in project clinical_quality_language by cqframework.
the class BaseTest method assertResultType.
private void assertResultType(CompiledLibrary translatedLibrary, String expressionName, String namespace, String name) {
ExpressionDef ed = translatedLibrary.resolveExpressionRef(expressionName);
DataType resultType = ed.getExpression().getResultType();
assertThat(resultType, instanceOf(ClassType.class));
ClassType resultClassType = (ClassType) resultType;
assertThat(resultClassType.getNamespace(), equalTo(namespace));
assertThat(resultClassType.getSimpleName(), equalTo(name));
}
use of org.hl7.cql.model.ClassType 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;
}
Aggregations