001package org.hl7.fhir.dstu3.utils;
002
003import ca.uhn.fhir.model.api.TemporalPrecisionEnum;
004import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
005import ca.uhn.fhir.util.ElementUtil;
006import org.hl7.fhir.dstu3.context.IWorkerContext;
007import org.hl7.fhir.dstu3.model.*;
008import org.hl7.fhir.dstu3.model.ElementDefinition.TypeRefComponent;
009import org.hl7.fhir.dstu3.model.ExpressionNode.*;
010import org.hl7.fhir.dstu3.model.StructureDefinition.StructureDefinitionKind;
011import org.hl7.fhir.dstu3.model.StructureDefinition.TypeDerivationRule;
012import org.hl7.fhir.dstu3.model.TypeDetails.ProfiledType;
013import org.hl7.fhir.dstu3.utils.FHIRLexer.FHIRLexerException;
014import org.hl7.fhir.dstu3.utils.FHIRPathEngine.IEvaluationContext.FunctionDetails;
015import org.hl7.fhir.exceptions.DefinitionException;
016import org.hl7.fhir.exceptions.FHIRException;
017import org.hl7.fhir.exceptions.PathEngineException;
018import org.hl7.fhir.exceptions.UcumException;
019import org.hl7.fhir.utilities.Utilities;
020import org.hl7.fhir.utilities.ucum.Decimal;
021
022import java.math.BigDecimal;
023import java.util.*;
024
025import static org.apache.commons.lang3.StringUtils.length;
026
027/**
028 * @author Grahame Grieve
029 */
030public class FHIRPathEngine {
031  private IWorkerContext worker;
032  private IEvaluationContext hostServices;
033  private StringBuilder log = new StringBuilder();
034  private Set<String> primitiveTypes = new HashSet<String>();
035  private Map<String, StructureDefinition> allTypes = new HashMap<String, StructureDefinition>();
036
037  /**
038   * @param worker - used when validating paths (@check), and used doing value set membership when executing tests (once that's defined)
039   */
040  public FHIRPathEngine(IWorkerContext worker) {
041    super();
042    this.worker = worker;
043    for (StructureDefinition sd : worker.allStructures()) {
044      if (sd.getDerivation() == TypeDerivationRule.SPECIALIZATION)
045        allTypes.put(sd.getName(), sd);
046      if (sd.getDerivation() == TypeDerivationRule.SPECIALIZATION && sd.getKind() == StructureDefinitionKind.PRIMITIVETYPE) {
047        primitiveTypes.add(sd.getName());
048      }
049    }
050  }
051
052  private TypeDetails anything(CollectionStatus status) {
053    return new TypeDetails(status, allTypes.keySet());
054  }
055
056
057  // --- 3 methods to override in children -------------------------------------------------------
058  // if you don't override, it falls through to the using the base reference implementation 
059  // HAPI overrides to these to support extending the base model
060
061  private ExecutionContext changeThis(ExecutionContext context, Base newThis) {
062    return new ExecutionContext(context.appInfo, context.resource, context.context, context.aliases, newThis);
063  }
064
065  private ExecutionTypeContext changeThis(ExecutionTypeContext context, TypeDetails newThis) {
066    return new ExecutionTypeContext(context.appInfo, context.resource, context.context, newThis);
067  }
068
069  /**
070   * check that paths referred to in the ExpressionNode are valid
071   * <p>
072   * xPathStartsWithValueRef is a hack work around for the fact that FHIR Path sometimes needs a different starting point than the xpath
073   * <p>
074   * returns a list of the possible types that might be returned by executing the ExpressionNode against a particular context
075   *
076   * @param context - the logical type against which this path is applied
077   * @param path    - the FHIR Path statement to check
078   * @throws DefinitionException
079   * @throws PathEngineException
080   * @if the path is not valid
081   */
082  public TypeDetails check(Object appContext, String resourceType, String context, ExpressionNode expr) throws FHIRLexerException, PathEngineException, DefinitionException {
083    // if context is a path that refers to a type, do that conversion now
084    TypeDetails types;
085    if (context == null) {
086      types = null; // this is a special case; the first path reference will have to resolve to something in the context
087    } else if (!context.contains(".")) {
088      StructureDefinition sd = worker.fetchResource(StructureDefinition.class, context);
089      types = new TypeDetails(CollectionStatus.SINGLETON, sd.getUrl());
090    } else {
091      String ctxt = context.substring(0, context.indexOf('.'));
092      if (Utilities.isAbsoluteUrl(resourceType)) {
093        ctxt = resourceType.substring(0, resourceType.lastIndexOf("/") + 1) + ctxt;
094      }
095      StructureDefinition sd = worker.fetchResource(StructureDefinition.class, ctxt);
096      if (sd == null)
097        throw new PathEngineException("Unknown context " + context);
098      ElementDefinitionMatch ed = getElementDefinition(sd, context, true);
099      if (ed == null)
100        throw new PathEngineException("Unknown context element " + context);
101      if (ed.fixedType != null)
102        types = new TypeDetails(CollectionStatus.SINGLETON, ed.fixedType);
103      else if (ed.getDefinition().getType().isEmpty() || isAbstractType(ed.getDefinition().getType()))
104        types = new TypeDetails(CollectionStatus.SINGLETON, ctxt + "#" + context);
105      else {
106        types = new TypeDetails(CollectionStatus.SINGLETON);
107        for (TypeRefComponent t : ed.getDefinition().getType())
108          types.addType(t.getCode());
109      }
110    }
111
112    return executeType(new ExecutionTypeContext(appContext, resourceType, context, types), types, expr, true);
113  }
114
115  // --- public API -------------------------------------------------------
116
117  public TypeDetails check(Object appContext, StructureDefinition sd, String context, ExpressionNode expr) throws FHIRLexerException, PathEngineException, DefinitionException {
118    // if context is a path that refers to a type, do that conversion now
119    TypeDetails types;
120    if (!context.contains(".")) {
121      types = new TypeDetails(CollectionStatus.SINGLETON, sd.getUrl());
122    } else {
123      ElementDefinitionMatch ed = getElementDefinition(sd, context, true);
124      if (ed == null)
125        throw new PathEngineException("Unknown context element " + context);
126      if (ed.fixedType != null)
127        types = new TypeDetails(CollectionStatus.SINGLETON, ed.fixedType);
128      else if (ed.getDefinition().getType().isEmpty() || isAbstractType(ed.getDefinition().getType()))
129        types = new TypeDetails(CollectionStatus.SINGLETON, sd.getUrl() + "#" + context);
130      else {
131        types = new TypeDetails(CollectionStatus.SINGLETON);
132        for (TypeRefComponent t : ed.getDefinition().getType())
133          types.addType(t.getCode());
134      }
135    }
136
137    return executeType(new ExecutionTypeContext(appContext, sd.getUrl(), context, types), types, expr, true);
138  }
139
140  public TypeDetails check(Object appContext, StructureDefinition sd, ExpressionNode expr) throws FHIRLexerException, PathEngineException, DefinitionException {
141    // if context is a path that refers to a type, do that conversion now
142    TypeDetails types = null; // this is a special case; the first path reference will have to resolve to something in the context
143    return executeType(new ExecutionTypeContext(appContext, sd == null ? null : sd.getUrl(), null, types), types, expr, true);
144  }
145
146  public TypeDetails check(Object appContext, String resourceType, String context, String expr) throws FHIRLexerException, PathEngineException, DefinitionException {
147    return check(appContext, resourceType, context, parse(expr));
148  }
149
150  private void checkConstant(String s, FHIRLexer lexer) throws FHIRLexerException {
151    if (s.startsWith("\'") && s.endsWith("\'")) {
152      int i = 1;
153      while (i < s.length() - 1) {
154        char ch = s.charAt(i);
155        if (ch == '\\') {
156          switch (ch) {
157            case 't':
158            case 'r':
159            case 'n':
160            case 'f':
161            case '\'':
162            case '\\':
163            case '/':
164              i++;
165              break;
166            case 'u':
167              if (!Utilities.isHex("0x" + s.substring(i, i + 4)))
168                throw lexer.error("Improper unicode escape \\u" + s.substring(i, i + 4));
169              break;
170            default:
171              throw lexer.error("Unknown character escape \\" + ch);
172          }
173        } else
174          i++;
175      }
176    }
177  }
178
179  private void checkContextCoded(TypeDetails focus, String name) throws PathEngineException {
180    if (!focus.hasType(worker, "string") && !focus.hasType(worker, "code") && !focus.hasType(worker, "uri") && !focus.hasType(worker, "Coding") && !focus.hasType(worker, "CodeableConcept"))
181      throw new PathEngineException("The function '" + name + "'() can only be used on string, code, uri, Coding, CodeableConcept");
182  }
183
184  private void checkContextPrimitive(TypeDetails focus, String name) throws PathEngineException {
185    if (!focus.hasType(primitiveTypes))
186      throw new PathEngineException("The function '" + name + "'() can only be used on " + primitiveTypes.toString());
187  }
188
189  private void checkContextReference(TypeDetails focus, String name) throws PathEngineException {
190    if (!focus.hasType(worker, "string") && !focus.hasType(worker, "uri") && !focus.hasType(worker, "Reference"))
191      throw new PathEngineException("The function '" + name + "'() can only be used on string, uri, Reference");
192  }
193
194  private void checkContextString(TypeDetails focus, String name) throws PathEngineException {
195    if (!focus.hasType(worker, "string") && !focus.hasType(worker, "code") && !focus.hasType(worker, "uri") && !focus.hasType(worker, "id"))
196      throw new PathEngineException("The function '" + name + "'() can only be used on string, uri, code, id, but found " + focus.describe());
197  }
198
199  private void checkOrdered(TypeDetails focus, String name) throws PathEngineException {
200    if (focus.getCollectionStatus() == CollectionStatus.UNORDERED)
201      throw new PathEngineException("The function '" + name + "'() can only be used on ordered collections");
202  }
203
204  private boolean checkParamCount(FHIRLexer lexer, SourceLocation location, ExpressionNode exp, int count) throws FHIRLexerException {
205    if (exp.getParameters().size() != count)
206      throw lexer.error("The function \"" + exp.getName() + "\" requires " + Integer.toString(count) + " parameters", location.toString());
207    return true;
208  }
209
210  private boolean checkParamCount(FHIRLexer lexer, SourceLocation location, ExpressionNode exp, int countMin, int countMax) throws FHIRLexerException {
211    if (exp.getParameters().size() < countMin || exp.getParameters().size() > countMax)
212      throw lexer.error("The function \"" + exp.getName() + "\" requires between " + Integer.toString(countMin) + " and " + Integer.toString(countMax) + " parameters", location.toString());
213    return true;
214  }
215
216  private void checkParamTypes(String funcName, List<TypeDetails> paramTypes, TypeDetails... typeSet) throws PathEngineException {
217    int i = 0;
218    for (TypeDetails pt : typeSet) {
219      if (i == paramTypes.size())
220        return;
221      TypeDetails actual = paramTypes.get(i);
222      i++;
223      for (String a : actual.getTypes()) {
224        if (!pt.hasType(worker, a))
225          throw new PathEngineException("The parameter type '" + a + "' is not legal for " + funcName + " parameter " + Integer.toString(i) + ". expecting " + pt.toString());
226      }
227    }
228  }
229
230  private boolean checkParameters(FHIRLexer lexer, SourceLocation location, ExpressionNode exp, FunctionDetails details) throws FHIRLexerException {
231    switch (exp.getFunction()) {
232      case Empty:
233        return checkParamCount(lexer, location, exp, 0);
234      case Not:
235        return checkParamCount(lexer, location, exp, 0);
236      case Exists:
237        return checkParamCount(lexer, location, exp, 0);
238      case SubsetOf:
239        return checkParamCount(lexer, location, exp, 1);
240      case SupersetOf:
241        return checkParamCount(lexer, location, exp, 1);
242      case IsDistinct:
243        return checkParamCount(lexer, location, exp, 0);
244      case Distinct:
245        return checkParamCount(lexer, location, exp, 0);
246      case Count:
247        return checkParamCount(lexer, location, exp, 0);
248      case Where:
249        return checkParamCount(lexer, location, exp, 1);
250      case Select:
251        return checkParamCount(lexer, location, exp, 1);
252      case All:
253        return checkParamCount(lexer, location, exp, 0, 1);
254      case Repeat:
255        return checkParamCount(lexer, location, exp, 1);
256      case Item:
257        return checkParamCount(lexer, location, exp, 1);
258      case As:
259        return checkParamCount(lexer, location, exp, 1);
260      case Is:
261        return checkParamCount(lexer, location, exp, 1);
262      case Single:
263        return checkParamCount(lexer, location, exp, 0);
264      case First:
265        return checkParamCount(lexer, location, exp, 0);
266      case Last:
267        return checkParamCount(lexer, location, exp, 0);
268      case Tail:
269        return checkParamCount(lexer, location, exp, 0);
270      case Skip:
271        return checkParamCount(lexer, location, exp, 1);
272      case Take:
273        return checkParamCount(lexer, location, exp, 1);
274      case Iif:
275        return checkParamCount(lexer, location, exp, 2, 3);
276      case ToInteger:
277        return checkParamCount(lexer, location, exp, 0);
278      case ToDecimal:
279        return checkParamCount(lexer, location, exp, 0);
280      case ToString:
281        return checkParamCount(lexer, location, exp, 0);
282      case Substring:
283        return checkParamCount(lexer, location, exp, 1, 2);
284      case StartsWith:
285        return checkParamCount(lexer, location, exp, 1);
286      case EndsWith:
287        return checkParamCount(lexer, location, exp, 1);
288      case Matches:
289        return checkParamCount(lexer, location, exp, 1);
290      case ReplaceMatches:
291        return checkParamCount(lexer, location, exp, 2);
292      case Contains:
293        return checkParamCount(lexer, location, exp, 1);
294      case Replace:
295        return checkParamCount(lexer, location, exp, 2);
296      case Length:
297        return checkParamCount(lexer, location, exp, 0);
298      case Children:
299        return checkParamCount(lexer, location, exp, 0);
300      case Descendants:
301        return checkParamCount(lexer, location, exp, 0);
302      case MemberOf:
303        return checkParamCount(lexer, location, exp, 1);
304      case Trace:
305        return checkParamCount(lexer, location, exp, 1);
306      case Today:
307        return checkParamCount(lexer, location, exp, 0);
308      case Now:
309        return checkParamCount(lexer, location, exp, 0);
310      case Resolve:
311        return checkParamCount(lexer, location, exp, 0);
312      case Extension:
313        return checkParamCount(lexer, location, exp, 1);
314      case HasValue:
315        return checkParamCount(lexer, location, exp, 0);
316      case Alias:
317        return checkParamCount(lexer, location, exp, 1);
318      case AliasAs:
319        return checkParamCount(lexer, location, exp, 1);
320      case Custom:
321        return checkParamCount(lexer, location, exp, details.getMinParameters(), details.getMaxParameters());
322    }
323    return false;
324  }
325
326  private TypeDetails childTypes(TypeDetails focus, String mask) throws PathEngineException, DefinitionException {
327    TypeDetails result = new TypeDetails(CollectionStatus.UNORDERED);
328    for (String f : focus.getTypes())
329      getChildTypesByName(f, mask, result);
330    return result;
331  }
332
333  private int compareDateTimeElements(Base theL, Base theR) {
334    String dateLeftString = theL.primitiveValue();
335    if (length(dateLeftString) > 10) {
336      DateTimeType dateLeft = new DateTimeType(dateLeftString);
337      dateLeft.setTimeZoneZulu(true);
338      dateLeftString = dateLeft.getValueAsString();
339    }
340    String dateRightString = theR.primitiveValue();
341    if (length(dateRightString) > 10) {
342      DateTimeType dateRight = new DateTimeType(dateRightString);
343      dateRight.setTimeZoneZulu(true);
344      dateRightString = dateRight.getValueAsString();
345    }
346    return dateLeftString.compareTo(dateRightString);
347  }
348
349  /**
350   * worker routine for converting a set of objects to a boolean representation (for invariants)
351   *
352   * @param items - result from @evaluate
353   * @return
354   */
355  public boolean convertToBoolean(List<Base> items) {
356    if (items == null)
357      return false;
358    else if (items.size() == 1 && items.get(0) instanceof BooleanType)
359      return ((BooleanType) items.get(0)).getValue();
360    else
361      return items.size() > 0;
362  }
363
364  /**
365   * worker routine for converting a set of objects to a string representation
366   *
367   * @param items - result from @evaluate
368   * @return
369   */
370  public String convertToString(List<Base> items) {
371    StringBuilder b = new StringBuilder();
372    boolean first = true;
373    for (Base item : items) {
374      if (first)
375        first = false;
376      else
377        b.append(',');
378
379      b.append(convertToString(item));
380    }
381    return b.toString();
382  }
383
384  private String convertToString(Base item) {
385    if (item.isPrimitive())
386      return item.primitiveValue();
387    else
388      return item.toString();
389  }
390
391  private boolean doContains(List<Base> list, Base item) {
392    for (Base test : list)
393      if (doEquals(test, item))
394        return true;
395    return false;
396  }
397
398  private boolean doEquals(Base left, Base right) {
399    if (left.isPrimitive() && right.isPrimitive())
400      return Base.equals(left.primitiveValue(), right.primitiveValue());
401    else
402      return Base.compareDeep(left, right, false);
403  }
404
405  private boolean doEquivalent(Base left, Base right) throws PathEngineException {
406    if (left.hasType("integer") && right.hasType("integer"))
407      return doEquals(left, right);
408    if (left.hasType("boolean") && right.hasType("boolean"))
409      return doEquals(left, right);
410    if (left.hasType("integer", "decimal", "unsignedInt", "positiveInt") && right.hasType("integer", "decimal", "unsignedInt", "positiveInt"))
411      return Utilities.equivalentNumber(left.primitiveValue(), right.primitiveValue());
412    if (left.hasType("date", "dateTime", "time", "instant") && right.hasType("date", "dateTime", "time", "instant"))
413      return compareDateTimeElements(left, right) == 0;
414    if (left.hasType("string", "id", "code", "uri") && right.hasType("string", "id", "code", "uri"))
415      return Utilities.equivalent(convertToString(left), convertToString(right));
416
417    throw new PathEngineException(String.format("Unable to determine equivalence between %s and %s", left.fhirType(), right.fhirType()));
418  }
419
420  /**
421   * evaluate a path and return the matching elements
422   *
423   * @param base           - the object against which the path is being evaluated
424   * @param ExpressionNode - the parsed ExpressionNode statement to use
425   * @return
426   * @throws FHIRException
427   * @
428   */
429  public List<Base> evaluate(Base base, ExpressionNode ExpressionNode) throws FHIRException {
430    List<Base> list = new ArrayList<Base>();
431    if (base != null)
432      list.add(base);
433    log = new StringBuilder();
434    return execute(new ExecutionContext(null, base != null && base.isResource() ? base : null, base, null, base), list, ExpressionNode, true);
435  }
436
437  /**
438   * evaluate a path and return the matching elements
439   *
440   * @param base - the object against which the path is being evaluated
441   * @param path - the FHIR Path statement to use
442   * @return
443   * @throws FHIRException
444   * @
445   */
446  public List<Base> evaluate(Base base, String path) throws FHIRException {
447    ExpressionNode exp = parse(path);
448    List<Base> list = new ArrayList<Base>();
449    if (base != null)
450      list.add(base);
451    log = new StringBuilder();
452    return execute(new ExecutionContext(null, base.isResource() ? base : null, base, null, base), list, exp, true);
453  }
454
455  /**
456   * evaluate a path and return the matching elements
457   *
458   * @param base           - the object against which the path is being evaluated
459   * @param ExpressionNode - the parsed ExpressionNode statement to use
460   * @return
461   * @throws FHIRException
462   * @
463   */
464  public List<Base> evaluate(Object appContext, Resource resource, Base base, ExpressionNode ExpressionNode) throws FHIRException {
465    List<Base> list = new ArrayList<Base>();
466    if (base != null)
467      list.add(base);
468    log = new StringBuilder();
469    return execute(new ExecutionContext(appContext, resource, base, null, base), list, ExpressionNode, true);
470  }
471
472  /**
473   * evaluate a path and return the matching elements
474   *
475   * @param base           - the object against which the path is being evaluated
476   * @param ExpressionNode - the parsed ExpressionNode statement to use
477   * @return
478   * @throws FHIRException
479   * @
480   */
481  public List<Base> evaluate(Object appContext, Base resource, Base base, ExpressionNode ExpressionNode) throws FHIRException {
482    List<Base> list = new ArrayList<Base>();
483    if (base != null)
484      list.add(base);
485    log = new StringBuilder();
486    return execute(new ExecutionContext(appContext, resource, base, null, base), list, ExpressionNode, true);
487  }
488
489  /**
490   * evaluate a path and return the matching elements
491   *
492   * @param base - the object against which the path is being evaluated
493   * @param path - the FHIR Path statement to use
494   * @return
495   * @throws FHIRException
496   * @
497   */
498  public List<Base> evaluate(Object appContext, Resource resource, Base base, String path) throws FHIRException {
499    ExpressionNode exp = parse(path);
500    List<Base> list = new ArrayList<Base>();
501    if (base != null)
502      list.add(base);
503    log = new StringBuilder();
504    return execute(new ExecutionContext(appContext, resource, base, null, base), list, exp, true);
505  }
506
507  private List<Base> evaluateFunction(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
508    switch (exp.getFunction()) {
509      case Empty:
510        return funcEmpty(context, focus, exp);
511      case Not:
512        return funcNot(context, focus, exp);
513      case Exists:
514        return funcExists(context, focus, exp);
515      case SubsetOf:
516        return funcSubsetOf(context, focus, exp);
517      case SupersetOf:
518        return funcSupersetOf(context, focus, exp);
519      case IsDistinct:
520        return funcIsDistinct(context, focus, exp);
521      case Distinct:
522        return funcDistinct(context, focus, exp);
523      case Count:
524        return funcCount(context, focus, exp);
525      case Where:
526        return funcWhere(context, focus, exp);
527      case Select:
528        return funcSelect(context, focus, exp);
529      case All:
530        return funcAll(context, focus, exp);
531      case Repeat:
532        return funcRepeat(context, focus, exp);
533      case Item:
534        return funcItem(context, focus, exp);
535      case As:
536        return funcAs(context, focus, exp);
537      case Is:
538        return funcIs(context, focus, exp);
539      case Single:
540        return funcSingle(context, focus, exp);
541      case First:
542        return funcFirst(context, focus, exp);
543      case Last:
544        return funcLast(context, focus, exp);
545      case Tail:
546        return funcTail(context, focus, exp);
547      case Skip:
548        return funcSkip(context, focus, exp);
549      case Take:
550        return funcTake(context, focus, exp);
551      case Iif:
552        return funcIif(context, focus, exp);
553      case ToInteger:
554        return funcToInteger(context, focus, exp);
555      case ToDecimal:
556        return funcToDecimal(context, focus, exp);
557      case ToString:
558        return funcToString(context, focus, exp);
559      case Substring:
560        return funcSubstring(context, focus, exp);
561      case StartsWith:
562        return funcStartsWith(context, focus, exp);
563      case EndsWith:
564        return funcEndsWith(context, focus, exp);
565      case Matches:
566        return funcMatches(context, focus, exp);
567      case ReplaceMatches:
568        return funcReplaceMatches(context, focus, exp);
569      case Contains:
570        return funcContains(context, focus, exp);
571      case Replace:
572        return funcReplace(context, focus, exp);
573      case Length:
574        return funcLength(context, focus, exp);
575      case Children:
576        return funcChildren(context, focus, exp);
577      case Descendants:
578        return funcDescendants(context, focus, exp);
579      case MemberOf:
580        return funcMemberOf(context, focus, exp);
581      case Trace:
582        return funcTrace(context, focus, exp);
583      case Today:
584        return funcToday(context, focus, exp);
585      case Now:
586        return funcNow(context, focus, exp);
587      case Resolve:
588        return funcResolve(context, focus, exp);
589      case Extension:
590        return funcExtension(context, focus, exp);
591      case HasValue:
592        return funcHasValue(context, focus, exp);
593      case AliasAs:
594        return funcAliasAs(context, focus, exp);
595      case Alias:
596        return funcAlias(context, focus, exp);
597      case Custom: {
598        List<List<Base>> params = new ArrayList<List<Base>>();
599        for (ExpressionNode p : exp.getParameters())
600          params.add(execute(context, focus, p, true));
601        return hostServices.executeFunction(context.appInfo, exp.getName(), params);
602      }
603      default:
604        throw new Error("not Implemented yet");
605    }
606  }
607
608  @SuppressWarnings("unchecked")
609  private TypeDetails evaluateFunctionType(ExecutionTypeContext context, TypeDetails focus, ExpressionNode exp) throws PathEngineException, DefinitionException {
610    List<TypeDetails> paramTypes = new ArrayList<TypeDetails>();
611    if (exp.getFunction() == Function.Is || exp.getFunction() == Function.As)
612      paramTypes.add(new TypeDetails(CollectionStatus.SINGLETON, "string"));
613    else
614      for (ExpressionNode expr : exp.getParameters()) {
615        if (exp.getFunction() == Function.Where || exp.getFunction() == Function.Select || exp.getFunction() == Function.Repeat)
616          paramTypes.add(executeType(changeThis(context, focus), focus, expr, true));
617        else
618          paramTypes.add(executeType(context, focus, expr, true));
619      }
620    switch (exp.getFunction()) {
621      case Empty:
622        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
623      case Not:
624        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
625      case Exists:
626        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
627      case SubsetOf: {
628        checkParamTypes(exp.getFunction().toCode(), paramTypes, focus);
629        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
630      }
631      case SupersetOf: {
632        checkParamTypes(exp.getFunction().toCode(), paramTypes, focus);
633        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
634      }
635      case IsDistinct:
636        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
637      case Distinct:
638        return focus;
639      case Count:
640        return new TypeDetails(CollectionStatus.SINGLETON, "integer");
641      case Where:
642        return focus;
643      case Select:
644        return anything(focus.getCollectionStatus());
645      case All:
646        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
647      case Repeat:
648        return anything(focus.getCollectionStatus());
649      case Item: {
650        checkOrdered(focus, "item");
651        checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, "integer"));
652        return focus;
653      }
654      case As: {
655        checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, "string"));
656        return new TypeDetails(CollectionStatus.SINGLETON, exp.getParameters().get(0).getName());
657      }
658      case Is: {
659        checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, "string"));
660        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
661      }
662      case Single:
663        return focus.toSingleton();
664      case First: {
665        checkOrdered(focus, "first");
666        return focus.toSingleton();
667      }
668      case Last: {
669        checkOrdered(focus, "last");
670        return focus.toSingleton();
671      }
672      case Tail: {
673        checkOrdered(focus, "tail");
674        return focus;
675      }
676      case Skip: {
677        checkOrdered(focus, "skip");
678        checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, "integer"));
679        return focus;
680      }
681      case Take: {
682        checkOrdered(focus, "take");
683        checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, "integer"));
684        return focus;
685      }
686      case Iif: {
687        TypeDetails types = new TypeDetails(null);
688        types.update(paramTypes.get(0));
689        if (paramTypes.size() > 1)
690          types.update(paramTypes.get(1));
691        return types;
692      }
693      case ToInteger: {
694        checkContextPrimitive(focus, "toInteger");
695        return new TypeDetails(CollectionStatus.SINGLETON, "integer");
696      }
697      case ToDecimal: {
698        checkContextPrimitive(focus, "toDecimal");
699        return new TypeDetails(CollectionStatus.SINGLETON, "decimal");
700      }
701      case ToString: {
702        checkContextPrimitive(focus, "toString");
703        return new TypeDetails(CollectionStatus.SINGLETON, "string");
704      }
705      case Substring: {
706        checkContextString(focus, "subString");
707        checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, "integer"), new TypeDetails(CollectionStatus.SINGLETON, "integer"));
708        return new TypeDetails(CollectionStatus.SINGLETON, "string");
709      }
710      case StartsWith: {
711        checkContextString(focus, "startsWith");
712        checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, "string"));
713        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
714      }
715      case EndsWith: {
716        checkContextString(focus, "endsWith");
717        checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, "string"));
718        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
719      }
720      case Matches: {
721        checkContextString(focus, "matches");
722        checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, "string"));
723        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
724      }
725      case ReplaceMatches: {
726        checkContextString(focus, "replaceMatches");
727        checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, "string"), new TypeDetails(CollectionStatus.SINGLETON, "string"));
728        return new TypeDetails(CollectionStatus.SINGLETON, "string");
729      }
730      case Contains: {
731        checkContextString(focus, "contains");
732        checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, "string"));
733        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
734      }
735      case Replace: {
736        checkContextString(focus, "replace");
737        checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, "string"), new TypeDetails(CollectionStatus.SINGLETON, "string"));
738        return new TypeDetails(CollectionStatus.SINGLETON, "string");
739      }
740      case Length: {
741        checkContextPrimitive(focus, "length");
742        return new TypeDetails(CollectionStatus.SINGLETON, "integer");
743      }
744      case Children:
745        return childTypes(focus, "*");
746      case Descendants:
747        return childTypes(focus, "**");
748      case MemberOf: {
749        checkContextCoded(focus, "memberOf");
750        checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, "string"));
751        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
752      }
753      case Trace: {
754        checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, "string"));
755        return focus;
756      }
757      case Today:
758        return new TypeDetails(CollectionStatus.SINGLETON, "date");
759      case Now:
760        return new TypeDetails(CollectionStatus.SINGLETON, "dateTime");
761      case Resolve: {
762        checkContextReference(focus, "resolve");
763        return new TypeDetails(CollectionStatus.SINGLETON, "DomainResource");
764      }
765      case Extension: {
766        checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, "string"));
767        return new TypeDetails(CollectionStatus.SINGLETON, "Extension");
768      }
769      case HasValue:
770        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
771      case Alias:
772        checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, "string"));
773        return anything(CollectionStatus.SINGLETON);
774      case AliasAs:
775        checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, "string"));
776        return focus;
777      case Custom: {
778        return hostServices.checkFunction(context.appInfo, exp.getName(), paramTypes);
779      }
780      default:
781        break;
782    }
783    throw new Error("not Implemented yet");
784  }
785
786  /**
787   * evaluate a path and return true or false (e.g. for an invariant)
788   *
789   * @param base - the object against which the path is being evaluated
790   * @param path - the FHIR Path statement to use
791   * @return
792   * @throws FHIRException
793   * @
794   */
795  public boolean evaluateToBoolean(Resource resource, Base base, String path) throws FHIRException {
796    return convertToBoolean(evaluate(null, resource, base, path));
797  }
798
799  //  procedure CheckParamCount(c : integer);
800  //  begin
801  //    if exp.Parameters.Count <> c then
802  //      raise lexer.error('The function "'+exp.name+'" requires '+inttostr(c)+' parameters', offset);
803  //  end;
804
805  /**
806   * evaluate a path and return true or false (e.g. for an invariant)
807   *
808   * @param base - the object against which the path is being evaluated
809   * @return
810   * @throws FHIRException
811   * @
812   */
813  public boolean evaluateToBoolean(Resource resource, Base base, ExpressionNode node) throws FHIRException {
814    return convertToBoolean(evaluate(null, resource, base, node));
815  }
816
817  /**
818   * evaluate a path and return true or false (e.g. for an invariant)
819   *
820   * @param base - the object against which the path is being evaluated
821   * @return
822   * @throws FHIRException
823   * @
824   */
825  public boolean evaluateToBoolean(Object appInfo, Resource resource, Base base, ExpressionNode node) throws FHIRException {
826    return convertToBoolean(evaluate(appInfo, resource, base, node));
827  }
828
829  /**
830   * evaluate a path and return true or false (e.g. for an invariant)
831   *
832   * @param base - the object against which the path is being evaluated
833   * @return
834   * @throws FHIRException
835   * @
836   */
837  public boolean evaluateToBoolean(Base resource, Base base, ExpressionNode node) throws FHIRException {
838    return convertToBoolean(evaluate(null, resource, base, node));
839  }
840
841  /**
842   * evaluate a path and a string containing the outcome (for display)
843   *
844   * @param base - the object against which the path is being evaluated
845   * @param path - the FHIR Path statement to use
846   * @return
847   * @throws FHIRException
848   * @
849   */
850  public String evaluateToString(Base base, String path) throws FHIRException {
851    return convertToString(evaluate(base, path));
852  }
853
854  public String evaluateToString(Object appInfo, Base resource, Base base, ExpressionNode node) throws FHIRException {
855    return convertToString(evaluate(appInfo, resource, base, node));
856  }
857
858  private List<Base> execute(ExecutionContext context, List<Base> focus, ExpressionNode exp, boolean atEntry) throws FHIRException {
859//    System.out.println("Evaluate {'"+exp.toString()+"'} on "+focus.toString());
860    List<Base> work = new ArrayList<Base>();
861    switch (exp.getKind()) {
862      case Name:
863        if (atEntry && exp.getName().equals("$this"))
864          work.add(context.getThisItem());
865        else
866          for (Base item : focus) {
867            List<Base> outcome = execute(context, item, exp, atEntry);
868            for (Base base : outcome)
869              if (base != null)
870                work.add(base);
871          }
872        break;
873      case Function:
874        List<Base> work2 = evaluateFunction(context, focus, exp);
875        work.addAll(work2);
876        break;
877      case Constant:
878        Base b = processConstant(context, exp.getConstant());
879        if (b != null)
880          work.add(b);
881        break;
882      case Group:
883        work2 = execute(context, focus, exp.getGroup(), atEntry);
884        work.addAll(work2);
885    }
886
887    if (exp.getInner() != null)
888      work = execute(context, work, exp.getInner(), false);
889
890    if (exp.isProximal() && exp.getOperation() != null) {
891      ExpressionNode next = exp.getOpNext();
892      ExpressionNode last = exp;
893      while (next != null) {
894        List<Base> work2 = preOperate(work, last.getOperation());
895        if (work2 != null)
896          work = work2;
897        else if (last.getOperation() == Operation.Is || last.getOperation() == Operation.As) {
898          work2 = executeTypeName(context, focus, next, false);
899          work = operate(work, last.getOperation(), work2);
900        } else {
901          work2 = execute(context, focus, next, true);
902          work = operate(work, last.getOperation(), work2);
903//          System.out.println("Result of {'"+last.toString()+" "+last.getOperation().toCode()+" "+next.toString()+"'}: "+focus.toString());
904        }
905        last = next;
906        next = next.getOpNext();
907      }
908    }
909//    System.out.println("Result of {'"+exp.toString()+"'}: "+work.toString());
910    return work;
911  }
912
913  private List<Base> execute(ExecutionContext context, Base item, ExpressionNode exp, boolean atEntry) throws FHIRException {
914    List<Base> result = new ArrayList<Base>();
915    if (atEntry && Character.isUpperCase(exp.getName().charAt(0))) {// special case for start up
916      if (item.isResource() && item.fhirType().equals(exp.getName()))
917        result.add(item);
918    } else
919      getChildrenByName(item, exp.getName(), result);
920    if (result.size() == 0 && atEntry && context.appInfo != null) {
921      Base temp = hostServices.resolveConstant(context.appInfo, exp.getName());
922      if (temp != null) {
923        result.add(temp);
924      }
925    }
926    return result;
927  }
928
929  private TypeDetails executeContextType(ExecutionTypeContext context, String name) throws PathEngineException, DefinitionException {
930    if (hostServices == null)
931      throw new PathEngineException("Unable to resolve context reference since no host services are provided");
932    return hostServices.resolveConstantType(context.appInfo, name);
933  }
934
935  private TypeDetails executeType(ExecutionTypeContext context, TypeDetails focus, ExpressionNode exp, boolean atEntry) throws PathEngineException, DefinitionException {
936    TypeDetails result = new TypeDetails(null);
937    switch (exp.getKind()) {
938      case Name:
939        if (atEntry && exp.getName().equals("$this"))
940          result.update(context.getThisItem());
941        else if (atEntry && focus == null)
942          result.update(executeContextType(context, exp.getName()));
943        else {
944          for (String s : focus.getTypes()) {
945            result.update(executeType(s, exp, atEntry));
946          }
947          if (result.hasNoTypes())
948            throw new PathEngineException("The name " + exp.getName() + " is not valid for any of the possible types: " + focus.describe());
949        }
950        break;
951      case Function:
952        result.update(evaluateFunctionType(context, focus, exp));
953        break;
954      case Constant:
955        result.update(readConstantType(context, exp.getConstant()));
956        break;
957      case Group:
958        result.update(executeType(context, focus, exp.getGroup(), atEntry));
959    }
960    exp.setTypes(result);
961
962    if (exp.getInner() != null) {
963      result = executeType(context, result, exp.getInner(), false);
964    }
965
966    if (exp.isProximal() && exp.getOperation() != null) {
967      ExpressionNode next = exp.getOpNext();
968      ExpressionNode last = exp;
969      while (next != null) {
970        TypeDetails work;
971        if (last.getOperation() == Operation.Is || last.getOperation() == Operation.As)
972          work = executeTypeName(context, focus, next, atEntry);
973        else
974          work = executeType(context, focus, next, atEntry);
975        result = operateTypes(result, last.getOperation(), work);
976        last = next;
977        next = next.getOpNext();
978      }
979      exp.setOpTypes(result);
980    }
981    return result;
982  }
983
984  private TypeDetails executeType(String type, ExpressionNode exp, boolean atEntry) throws PathEngineException, DefinitionException {
985    if (atEntry && Character.isUpperCase(exp.getName().charAt(0)) && tail(type).equals(exp.getName())) // special case for start up
986      return new TypeDetails(CollectionStatus.SINGLETON, type);
987    TypeDetails result = new TypeDetails(null);
988    getChildTypesByName(type, exp.getName(), result);
989    return result;
990  }
991
992  private List<Base> executeTypeName(ExecutionContext context, List<Base> focus, ExpressionNode next, boolean atEntry) {
993    List<Base> result = new ArrayList<Base>();
994    result.add(new StringType(next.getName()));
995    return result;
996  }
997
998  private TypeDetails executeTypeName(ExecutionTypeContext context, TypeDetails focus, ExpressionNode exp, boolean atEntry) throws PathEngineException, DefinitionException {
999    return new TypeDetails(CollectionStatus.SINGLETON, exp.getName());
1000  }
1001
1002  public String forLog() {
1003    if (log.length() > 0)
1004      return " (" + log.toString() + ")";
1005    else
1006      return "";
1007  }
1008
1009  private List<Base> funcAlias(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1010    List<Base> nl = execute(context, focus, exp.getParameters().get(0), true);
1011    String name = nl.get(0).primitiveValue();
1012    List<Base> res = new ArrayList<Base>();
1013    Base b = context.getAlias(name);
1014    if (b != null)
1015      res.add(b);
1016    return res;
1017
1018  }
1019
1020  private List<Base> funcAliasAs(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1021    List<Base> nl = execute(context, focus, exp.getParameters().get(0), true);
1022    String name = nl.get(0).primitiveValue();
1023    context.addAlias(name, focus);
1024    return focus;
1025  }
1026
1027  private List<Base> funcAll(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1028    if (exp.getParameters().size() == 1) {
1029      List<Base> result = new ArrayList<Base>();
1030      List<Base> pc = new ArrayList<Base>();
1031      boolean all = true;
1032      for (Base item : focus) {
1033        pc.clear();
1034        pc.add(item);
1035        if (!convertToBoolean(execute(changeThis(context, item), pc, exp.getParameters().get(0), true))) {
1036          all = false;
1037          break;
1038        }
1039      }
1040      result.add(new BooleanType(all));
1041      return result;
1042    } else {// (exp.getParameters().size() == 0) {
1043      List<Base> result = new ArrayList<Base>();
1044      boolean all = true;
1045      for (Base item : focus) {
1046        boolean v = false;
1047        if (item instanceof BooleanType) {
1048          v = ((BooleanType) item).booleanValue();
1049        } else
1050          v = item != null;
1051        if (!v) {
1052          all = false;
1053          break;
1054        }
1055      }
1056      result.add(new BooleanType(all));
1057      return result;
1058    }
1059  }
1060
1061  private List<Base> funcAs(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
1062    List<Base> result = new ArrayList<Base>();
1063    String tn = exp.getParameters().get(0).getName();
1064    for (Base b : focus)
1065      if (b.hasType(tn))
1066        result.add(b);
1067    return result;
1068  }
1069
1070  private List<Base> funcChildren(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1071    List<Base> result = new ArrayList<Base>();
1072    for (Base b : focus)
1073      getChildrenByName(b, "*", result);
1074    return result;
1075  }
1076
1077  private List<Base> funcContains(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1078    List<Base> result = new ArrayList<Base>();
1079    String sw = convertToString(execute(context, focus, exp.getParameters().get(0), true));
1080
1081    if (focus.size() == 1 && !Utilities.noString(sw)) {
1082      String st = convertToString(focus.get(0));
1083      if (Utilities.noString(st))
1084        result.add(new BooleanType(false));
1085      else
1086        result.add(new BooleanType(st.contains(sw)));
1087    } else
1088      result.add(new BooleanType(false));
1089    return result;
1090  }
1091
1092  private List<Base> funcCount(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
1093    List<Base> result = new ArrayList<Base>();
1094    result.add(new IntegerType(focus.size()));
1095    return result;
1096  }
1097
1098  private List<Base> funcDescendants(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1099    List<Base> result = new ArrayList<Base>();
1100    List<Base> current = new ArrayList<Base>();
1101    current.addAll(focus);
1102    List<Base> added = new ArrayList<Base>();
1103    boolean more = true;
1104    while (more) {
1105      added.clear();
1106      for (Base item : current) {
1107        getChildrenByName(item, "*", added);
1108      }
1109      more = !added.isEmpty();
1110      result.addAll(added);
1111      current.clear();
1112      current.addAll(added);
1113    }
1114    return result;
1115  }
1116
1117  private List<Base> funcDistinct(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
1118    if (focus.size() <= 1)
1119      return focus;
1120
1121    List<Base> result = new ArrayList<Base>();
1122    for (int i = 0; i < focus.size(); i++) {
1123      boolean found = false;
1124      for (int j = i + 1; j < focus.size(); j++) {
1125        if (doEquals(focus.get(j), focus.get(i))) {
1126          found = true;
1127          break;
1128        }
1129      }
1130      if (!found)
1131        result.add(focus.get(i));
1132    }
1133    return result;
1134  }
1135
1136  private List<Base> funcEmpty(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
1137    List<Base> result = new ArrayList<Base>();
1138    result.add(new BooleanType(ElementUtil.isEmpty(focus)));
1139    return result;
1140  }
1141
1142  private List<Base> funcEndsWith(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1143    List<Base> result = new ArrayList<Base>();
1144    String sw = convertToString(execute(context, focus, exp.getParameters().get(0), true));
1145
1146    if (focus.size() == 1 && !Utilities.noString(sw))
1147      result.add(new BooleanType(convertToString(focus.get(0)).endsWith(sw)));
1148    else
1149      result.add(new BooleanType(false));
1150    return result;
1151  }
1152
1153  private List<Base> funcExists(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
1154    List<Base> result = new ArrayList<Base>();
1155    result.add(new BooleanType(!ElementUtil.isEmpty(focus)));
1156    return result;
1157  }
1158
1159  private List<Base> funcExtension(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1160    List<Base> result = new ArrayList<Base>();
1161    List<Base> nl = execute(context, focus, exp.getParameters().get(0), true);
1162    String url = nl.get(0).primitiveValue();
1163
1164    for (Base item : focus) {
1165      List<Base> ext = new ArrayList<Base>();
1166      getChildrenByName(item, "extension", ext);
1167      getChildrenByName(item, "modifierExtension", ext);
1168      for (Base ex : ext) {
1169        List<Base> vl = new ArrayList<Base>();
1170        getChildrenByName(ex, "url", vl);
1171        if (convertToString(vl).equals(url))
1172          result.add(ex);
1173      }
1174    }
1175    return result;
1176  }
1177
1178  private List<Base> funcFirst(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
1179    List<Base> result = new ArrayList<Base>();
1180    if (focus.size() > 0)
1181      result.add(focus.get(0));
1182    return result;
1183  }
1184
1185  private List<Base> funcHasValue(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
1186    List<Base> result = new ArrayList<Base>();
1187    if (focus.size() == 1) {
1188      String s = convertToString(focus.get(0));
1189      result.add(new BooleanType(!Utilities.noString(s)));
1190    }
1191    return result;
1192  }
1193
1194  private List<Base> funcIif(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1195    List<Base> n1 = execute(context, focus, exp.getParameters().get(0), true);
1196    Boolean v = convertToBoolean(n1);
1197
1198    if (v)
1199      return execute(context, focus, exp.getParameters().get(1), true);
1200    else if (exp.getParameters().size() < 3)
1201      return new ArrayList<Base>();
1202    else
1203      return execute(context, focus, exp.getParameters().get(2), true);
1204  }
1205
1206  private List<Base> funcIs(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws PathEngineException {
1207    List<Base> result = new ArrayList<Base>();
1208    if (focus.size() == 0 || focus.size() > 1)
1209      result.add(new BooleanType(false));
1210    else {
1211      String tn = exp.getParameters().get(0).getName();
1212      result.add(new BooleanType(focus.get(0).hasType(tn)));
1213    }
1214    return result;
1215  }
1216
1217  private List<Base> funcIsDistinct(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
1218    if (focus.size() <= 1)
1219      return makeBoolean(true);
1220
1221    boolean distinct = true;
1222    for (int i = 0; i < focus.size(); i++) {
1223      for (int j = i + 1; j < focus.size(); j++) {
1224        if (doEquals(focus.get(j), focus.get(i))) {
1225          distinct = false;
1226          break;
1227        }
1228      }
1229    }
1230    return makeBoolean(distinct);
1231  }
1232
1233  private List<Base> funcItem(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1234    List<Base> result = new ArrayList<Base>();
1235    String s = convertToString(execute(context, focus, exp.getParameters().get(0), true));
1236    if (Utilities.isInteger(s) && Integer.parseInt(s) < focus.size())
1237      result.add(focus.get(Integer.parseInt(s)));
1238    return result;
1239  }
1240
1241  private List<Base> funcLast(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
1242    List<Base> result = new ArrayList<Base>();
1243    if (focus.size() > 0)
1244      result.add(focus.get(focus.size() - 1));
1245    return result;
1246  }
1247
1248  private List<Base> funcLength(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
1249    List<Base> result = new ArrayList<Base>();
1250    if (focus.size() == 1) {
1251      String s = convertToString(focus.get(0));
1252      result.add(new IntegerType(s.length()));
1253    }
1254    return result;
1255  }
1256
1257  private List<Base> funcMatches(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1258    List<Base> result = new ArrayList<Base>();
1259    String sw = convertToString(execute(context, focus, exp.getParameters().get(0), true));
1260
1261    if (focus.size() == 1 && !Utilities.noString(sw)) {
1262      String st = convertToString(focus.get(0));
1263      if (Utilities.noString(st))
1264        result.add(new BooleanType(false));
1265      else
1266        result.add(new BooleanType(st.matches(sw)));
1267    } else
1268      result.add(new BooleanType(false));
1269    return result;
1270  }
1271
1272  private List<Base> funcMemberOf(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
1273    throw new Error("not Implemented yet");
1274  }
1275
1276  private List<Base> funcNot(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
1277    return makeBoolean(!convertToBoolean(focus));
1278  }
1279
1280  private List<Base> funcNow(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
1281    List<Base> result = new ArrayList<Base>();
1282    result.add(DateTimeType.now());
1283    return result;
1284  }
1285
1286  private List<Base> funcRepeat(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1287    List<Base> result = new ArrayList<Base>();
1288    List<Base> current = new ArrayList<Base>();
1289    current.addAll(focus);
1290    List<Base> added = new ArrayList<Base>();
1291    boolean more = true;
1292    while (more) {
1293      added.clear();
1294      List<Base> pc = new ArrayList<Base>();
1295      for (Base item : current) {
1296        pc.clear();
1297        pc.add(item);
1298        added.addAll(execute(changeThis(context, item), pc, exp.getParameters().get(0), false));
1299      }
1300      more = !added.isEmpty();
1301      result.addAll(added);
1302      current.clear();
1303      current.addAll(added);
1304    }
1305    return result;
1306  }
1307
1308  private List<Base> funcReplace(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
1309    throw new Error("not Implemented yet");
1310  }
1311
1312  private List<Base> funcReplaceMatches(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1313    List<Base> result = new ArrayList<Base>();
1314    String sw = convertToString(execute(context, focus, exp.getParameters().get(0), true));
1315
1316    if (focus.size() == 1 && !Utilities.noString(sw))
1317      result.add(new BooleanType(convertToString(focus.get(0)).contains(sw)));
1318    else
1319      result.add(new BooleanType(false));
1320    return result;
1321  }
1322
1323  private List<Base> funcResolve(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
1324    List<Base> result = new ArrayList<Base>();
1325    for (Base item : focus) {
1326      String s = convertToString(item);
1327      if (item.fhirType().equals("Reference")) {
1328        Property p = item.getChildByName("reference");
1329        if (p.hasValues())
1330          s = convertToString(p.getValues().get(0));
1331      }
1332      Base res = null;
1333      if (s.startsWith("#")) {
1334        Property p = context.resource.getChildByName("contained");
1335        for (Base c : p.getValues()) {
1336          if (s.equals(c.getIdBase()))
1337            res = c;
1338        }
1339      } else if (hostServices != null) {
1340        res = hostServices.resolveReference(context.appInfo, s);
1341      }
1342      if (res != null)
1343        result.add(res);
1344    }
1345    return result;
1346  }
1347
1348  private List<Base> funcSelect(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1349    List<Base> result = new ArrayList<Base>();
1350    List<Base> pc = new ArrayList<Base>();
1351    for (Base item : focus) {
1352      pc.clear();
1353      pc.add(item);
1354      result.addAll(execute(changeThis(context, item), pc, exp.getParameters().get(0), true));
1355    }
1356    return result;
1357  }
1358
1359  private List<Base> funcSingle(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws PathEngineException {
1360    if (focus.size() == 1)
1361      return focus;
1362    throw new PathEngineException(String.format("Single() : checking for 1 item but found %d items", focus.size()));
1363  }
1364
1365  private List<Base> funcSkip(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1366    List<Base> n1 = execute(context, focus, exp.getParameters().get(0), true);
1367    int i1 = Integer.parseInt(n1.get(0).primitiveValue());
1368
1369    List<Base> result = new ArrayList<Base>();
1370    for (int i = i1; i < focus.size(); i++)
1371      result.add(focus.get(i));
1372    return result;
1373  }
1374
1375  private List<Base> funcStartsWith(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1376    List<Base> result = new ArrayList<Base>();
1377    String sw = convertToString(execute(context, focus, exp.getParameters().get(0), true));
1378
1379    if (focus.size() == 1 && !Utilities.noString(sw))
1380      result.add(new BooleanType(convertToString(focus.get(0)).startsWith(sw)));
1381    else
1382      result.add(new BooleanType(false));
1383    return result;
1384  }
1385
1386  private List<Base> funcSubsetOf(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1387    List<Base> target = execute(context, focus, exp.getParameters().get(0), true);
1388
1389    boolean valid = true;
1390    for (Base item : focus) {
1391      boolean found = false;
1392      for (Base t : target) {
1393        if (Base.compareDeep(item, t, false)) {
1394          found = true;
1395          break;
1396        }
1397      }
1398      if (!found) {
1399        valid = false;
1400        break;
1401      }
1402    }
1403    List<Base> result = new ArrayList<Base>();
1404    result.add(new BooleanType(valid));
1405    return result;
1406  }
1407
1408  private List<Base> funcSubstring(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1409    List<Base> result = new ArrayList<Base>();
1410    List<Base> n1 = execute(context, focus, exp.getParameters().get(0), true);
1411    int i1 = Integer.parseInt(n1.get(0).primitiveValue());
1412    int i2 = -1;
1413    if (exp.parameterCount() == 2) {
1414      List<Base> n2 = execute(context, focus, exp.getParameters().get(1), true);
1415      i2 = Integer.parseInt(n2.get(0).primitiveValue());
1416    }
1417
1418    if (focus.size() == 1) {
1419      String sw = convertToString(focus.get(0));
1420      String s;
1421      if (i1 < 0 || i1 >= sw.length())
1422        return new ArrayList<Base>();
1423      if (exp.parameterCount() == 2)
1424        s = sw.substring(i1, Math.min(sw.length(), i1 + i2));
1425      else
1426        s = sw.substring(i1);
1427      if (!Utilities.noString(s))
1428        result.add(new StringType(s));
1429    }
1430    return result;
1431  }
1432
1433  private List<Base> funcSupersetOf(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1434    List<Base> target = execute(context, focus, exp.getParameters().get(0), true);
1435
1436    boolean valid = true;
1437    for (Base item : target) {
1438      boolean found = false;
1439      for (Base t : focus) {
1440        if (Base.compareDeep(item, t, false)) {
1441          found = true;
1442          break;
1443        }
1444      }
1445      if (!found) {
1446        valid = false;
1447        break;
1448      }
1449    }
1450    List<Base> result = new ArrayList<Base>();
1451    result.add(new BooleanType(valid));
1452    return result;
1453  }
1454
1455  private List<Base> funcTail(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
1456    List<Base> result = new ArrayList<Base>();
1457    for (int i = 1; i < focus.size(); i++)
1458      result.add(focus.get(i));
1459    return result;
1460  }
1461
1462  private List<Base> funcTake(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1463    List<Base> n1 = execute(context, focus, exp.getParameters().get(0), true);
1464    int i1 = Integer.parseInt(n1.get(0).primitiveValue());
1465
1466    List<Base> result = new ArrayList<Base>();
1467    for (int i = 0; i < Math.min(focus.size(), i1); i++)
1468      result.add(focus.get(i));
1469    return result;
1470  }
1471
1472  private List<Base> funcToDecimal(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
1473    String s = convertToString(focus);
1474    List<Base> result = new ArrayList<Base>();
1475    if (Utilities.isDecimal(s))
1476      result.add(new DecimalType(s));
1477    return result;
1478  }
1479
1480  private List<Base> funcToInteger(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
1481    String s = convertToString(focus);
1482    List<Base> result = new ArrayList<Base>();
1483    if (Utilities.isInteger(s))
1484      result.add(new IntegerType(s));
1485    return result;
1486  }
1487
1488  private List<Base> funcToString(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
1489    List<Base> result = new ArrayList<Base>();
1490    result.add(new StringType(convertToString(focus)));
1491    return result;
1492  }
1493
1494  private List<Base> funcToday(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
1495    List<Base> result = new ArrayList<Base>();
1496    result.add(new DateType(new Date(), TemporalPrecisionEnum.DAY));
1497    return result;
1498  }
1499
1500  private List<Base> funcTrace(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1501    List<Base> nl = execute(context, focus, exp.getParameters().get(0), true);
1502    String name = nl.get(0).primitiveValue();
1503
1504    log(name, focus);
1505    return focus;
1506  }
1507
1508  private List<Base> funcWhere(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
1509    List<Base> result = new ArrayList<Base>();
1510    List<Base> pc = new ArrayList<Base>();
1511    for (Base item : focus) {
1512      pc.clear();
1513      pc.add(item);
1514      if (convertToBoolean(execute(changeThis(context, item), pc, exp.getParameters().get(0), true)))
1515        result.add(item);
1516    }
1517    return result;
1518  }
1519
1520  private ExpressionNode gatherPrecedence(FHIRLexer lexer, ExpressionNode start, EnumSet<Operation> ops) {
1521    //    work : boolean;
1522    //    focus, node, group : ExpressionNode;
1523
1524    assert (start.isProximal());
1525
1526    // is there anything to do?
1527    boolean work = false;
1528    ExpressionNode focus = start.getOpNext();
1529    if (ops.contains(start.getOperation())) {
1530      while (focus != null && focus.getOperation() != null) {
1531        work = work || !ops.contains(focus.getOperation());
1532        focus = focus.getOpNext();
1533      }
1534    } else {
1535      while (focus != null && focus.getOperation() != null) {
1536        work = work || ops.contains(focus.getOperation());
1537        focus = focus.getOpNext();
1538      }
1539    }
1540    if (!work)
1541      return start;
1542
1543    // entry point: tricky
1544    ExpressionNode group;
1545    if (ops.contains(start.getOperation())) {
1546      group = newGroup(lexer, start);
1547      group.setProximal(true);
1548      focus = start;
1549      start = group;
1550    } else {
1551      ExpressionNode node = start;
1552
1553      focus = node.getOpNext();
1554      while (!ops.contains(focus.getOperation())) {
1555        node = focus;
1556        focus = focus.getOpNext();
1557      }
1558      group = newGroup(lexer, focus);
1559      node.setOpNext(group);
1560    }
1561
1562    // now, at this point:
1563    //   group is the group we are adding to, it already has a .group property filled out.
1564    //   focus points at the group.group
1565    do {
1566      // run until we find the end of the sequence
1567      while (ops.contains(focus.getOperation()))
1568        focus = focus.getOpNext();
1569      if (focus.getOperation() != null) {
1570        group.setOperation(focus.getOperation());
1571        group.setOpNext(focus.getOpNext());
1572        focus.setOperation(null);
1573        focus.setOpNext(null);
1574        // now look for another sequence, and start it
1575        ExpressionNode node = group;
1576        focus = group.getOpNext();
1577        if (focus != null) {
1578          while (focus != null && !ops.contains(focus.getOperation())) {
1579            node = focus;
1580            focus = focus.getOpNext();
1581          }
1582          if (focus != null) { // && (focus.Operation in Ops) - must be true
1583            group = newGroup(lexer, focus);
1584            node.setOpNext(group);
1585          }
1586        }
1587      }
1588    }
1589    while (focus != null && focus.getOperation() != null);
1590    return start;
1591  }
1592
1593  private void getChildTypesByName(String type, String name, TypeDetails result) throws PathEngineException, DefinitionException {
1594    if (Utilities.noString(type))
1595      throw new PathEngineException("No type provided in BuildToolPathEvaluator.getChildTypesByName");
1596    if (type.equals("http://hl7.org/fhir/StructureDefinition/xhtml"))
1597      return;
1598    String url = null;
1599    if (type.contains("#")) {
1600      url = type.substring(0, type.indexOf("#"));
1601    } else {
1602      url = type;
1603    }
1604    String tail = "";
1605    StructureDefinition sd = worker.fetchResource(StructureDefinition.class, url);
1606    if (sd == null)
1607      throw new DefinitionException("Unknown type " + type); // this really is an error, because we can only get to here if the internal infrastrucgture is wrong
1608    List<StructureDefinition> sdl = new ArrayList<StructureDefinition>();
1609    ElementDefinitionMatch m = null;
1610    if (type.contains("#"))
1611      m = getElementDefinition(sd, type.substring(type.indexOf("#") + 1), false);
1612    if (m != null && hasDataType(m.definition)) {
1613      if (m.fixedType != null) {
1614        StructureDefinition dt = worker.fetchResource(StructureDefinition.class, "http://hl7.org/fhir/StructureDefinition/" + m.fixedType);
1615        if (dt == null)
1616          throw new DefinitionException("unknown data type " + m.fixedType);
1617        sdl.add(dt);
1618      } else
1619        for (TypeRefComponent t : m.definition.getType()) {
1620          StructureDefinition dt = worker.fetchResource(StructureDefinition.class, "http://hl7.org/fhir/StructureDefinition/" + t.getCode());
1621          if (dt == null)
1622            throw new DefinitionException("unknown data type " + t.getCode());
1623          sdl.add(dt);
1624        }
1625    } else {
1626      sdl.add(sd);
1627      if (type.contains("#")) {
1628        tail = type.substring(type.indexOf("#") + 1);
1629        tail = tail.substring(tail.indexOf("."));
1630      }
1631    }
1632
1633    for (StructureDefinition sdi : sdl) {
1634      String path = sdi.getSnapshot().getElement().get(0).getPath() + tail + ".";
1635      if (name.equals("**")) {
1636        assert (result.getCollectionStatus() == CollectionStatus.UNORDERED);
1637        for (ElementDefinition ed : sdi.getSnapshot().getElement()) {
1638          if (ed.getPath().startsWith(path))
1639            for (TypeRefComponent t : ed.getType()) {
1640              if (t.hasCode() && t.getCodeElement().hasValue()) {
1641                String tn = null;
1642                if (t.getCode().equals("Element") || t.getCode().equals("BackboneElement"))
1643                  tn = sdi.getType() + "#" + ed.getPath();
1644                else
1645                  tn = t.getCode();
1646                if (t.getCode().equals("Resource")) {
1647                  for (String rn : worker.getResourceNames()) {
1648                    if (!result.hasType(worker, rn)) {
1649                      getChildTypesByName(result.addType(rn), "**", result);
1650                    }
1651                  }
1652                } else if (!result.hasType(worker, tn)) {
1653                  getChildTypesByName(result.addType(tn), "**", result);
1654                }
1655              }
1656            }
1657        }
1658      } else if (name.equals("*")) {
1659        assert (result.getCollectionStatus() == CollectionStatus.UNORDERED);
1660        for (ElementDefinition ed : sdi.getSnapshot().getElement()) {
1661          if (ed.getPath().startsWith(path) && !ed.getPath().substring(path.length()).contains("."))
1662            for (TypeRefComponent t : ed.getType()) {
1663              if (t.getCode().equals("Element") || t.getCode().equals("BackboneElement"))
1664                result.addType(sdi.getType() + "#" + ed.getPath());
1665              else if (t.getCode().equals("Resource"))
1666                result.addTypes(worker.getResourceNames());
1667              else
1668                result.addType(t.getCode());
1669            }
1670        }
1671      } else {
1672        path = sdi.getSnapshot().getElement().get(0).getPath() + tail + "." + name;
1673
1674        ElementDefinitionMatch ed = getElementDefinition(sdi, path, false);
1675        if (ed != null) {
1676          if (!Utilities.noString(ed.getFixedType()))
1677            result.addType(ed.getFixedType());
1678          else
1679            for (TypeRefComponent t : ed.getDefinition().getType()) {
1680              if (Utilities.noString(t.getCode()))
1681                break; // throw new PathEngineException("Illegal reference to primitive value attribute @ "+path);
1682
1683              ProfiledType pt = null;
1684              if (t.getCode().equals("Element") || t.getCode().equals("BackboneElement"))
1685                pt = new ProfiledType(sdi.getUrl() + "#" + path);
1686              else if (t.getCode().equals("Resource"))
1687                result.addTypes(worker.getResourceNames());
1688              else
1689                pt = new ProfiledType(t.getCode());
1690              if (pt != null) {
1691                if (t.hasProfile())
1692                  pt.addProfile(t.getProfile());
1693                if (ed.getDefinition().hasBinding())
1694                  pt.addBinding(ed.getDefinition().getBinding());
1695                result.addType(pt);
1696              }
1697            }
1698        }
1699      }
1700    }
1701  }
1702
1703  //    private boolean isPrimitiveType(String s) {
1704  //            return s.equals("boolean") || s.equals("integer") || s.equals("decimal") || s.equals("base64Binary") || s.equals("instant") || s.equals("string") || s.equals("uri") || s.equals("date") || s.equals("dateTime") || s.equals("time") || s.equals("code") || s.equals("oid") || s.equals("id") || s.equals("unsignedInt") || s.equals("positiveInt") || s.equals("markdown");
1705  //    }
1706
1707  /**
1708   * Given an item, return all the children that conform to the pattern described in name
1709   * <p>
1710   * Possible patterns:
1711   * - a simple name (which may be the base of a name with [] e.g. value[x])
1712   * - a name with a type replacement e.g. valueCodeableConcept
1713   * - * which means all children
1714   * - ** which means all descendants
1715   *
1716   * @param item
1717   * @param name
1718   * @param result
1719   * @throws FHIRException
1720   */
1721  protected void getChildrenByName(Base item, String name, List<Base> result) throws FHIRException {
1722    Base[] list = item.listChildrenByName(name, false);
1723    if (list != null)
1724      for (Base v : list)
1725        if (v != null)
1726          result.add(v);
1727  }
1728
1729  private ElementDefinitionMatch getElementDefinition(StructureDefinition sd, String path, boolean allowTypedName) throws PathEngineException {
1730    for (ElementDefinition ed : sd.getSnapshot().getElement()) {
1731      if (ed.getPath().equals(path)) {
1732        if (ed.hasContentReference()) {
1733          return getElementDefinitionById(sd, ed.getContentReference());
1734        } else
1735          return new ElementDefinitionMatch(ed, null);
1736      }
1737      if (ed.getPath().endsWith("[x]") && path.startsWith(ed.getPath().substring(0, ed.getPath().length() - 3)) && path.length() == ed.getPath().length() - 3)
1738        return new ElementDefinitionMatch(ed, null);
1739      if (allowTypedName && ed.getPath().endsWith("[x]") && path.startsWith(ed.getPath().substring(0, ed.getPath().length() - 3)) && path.length() > ed.getPath().length() - 3) {
1740        String s = Utilities.uncapitalize(path.substring(ed.getPath().length() - 3));
1741        if (primitiveTypes.contains(s))
1742          return new ElementDefinitionMatch(ed, s);
1743        else
1744          return new ElementDefinitionMatch(ed, path.substring(ed.getPath().length() - 3));
1745      }
1746      if (ed.getPath().contains(".") && path.startsWith(ed.getPath() + ".") && (ed.getType().size() > 0) && !isAbstractType(ed.getType())) {
1747        // now we walk into the type.
1748        if (ed.getType().size() > 1)  // if there's more than one type, the test above would fail this
1749          throw new PathEngineException("Internal typing issue....");
1750        StructureDefinition nsd = worker.fetchResource(StructureDefinition.class, "http://hl7.org/fhir/StructureDefinition/" + ed.getType().get(0).getCode());
1751        if (nsd == null)
1752          throw new PathEngineException("Unknown type " + ed.getType().get(0).getCode());
1753        return getElementDefinition(nsd, nsd.getId() + path.substring(ed.getPath().length()), allowTypedName);
1754      }
1755      if (ed.hasContentReference() && path.startsWith(ed.getPath() + ".")) {
1756        ElementDefinitionMatch m = getElementDefinitionById(sd, ed.getContentReference());
1757        return getElementDefinition(sd, m.definition.getPath() + path.substring(ed.getPath().length()), allowTypedName);
1758      }
1759    }
1760    return null;
1761  }
1762
1763  private ElementDefinitionMatch getElementDefinitionById(StructureDefinition sd, String ref) {
1764    for (ElementDefinition ed : sd.getSnapshot().getElement()) {
1765      if (ref.equals("#" + ed.getId()))
1766        return new ElementDefinitionMatch(ed, null);
1767    }
1768    return null;
1769  }
1770
1771  public IEvaluationContext getHostServices() {
1772    return hostServices;
1773  }
1774
1775  public void setHostServices(IEvaluationContext constantResolver) {
1776    this.hostServices = constantResolver;
1777  }
1778
1779  private boolean hasDataType(ElementDefinition ed) {
1780    return ed.hasType() && !(ed.getType().get(0).getCode().equals("Element") || ed.getType().get(0).getCode().equals("BackboneElement"));
1781  }
1782
1783  public boolean hasLog() {
1784    return log != null && log.length() > 0;
1785  }
1786
1787  private boolean hasType(ElementDefinition ed, String s) {
1788    for (TypeRefComponent t : ed.getType())
1789      if (s.equalsIgnoreCase(t.getCode()))
1790        return true;
1791    return false;
1792  }
1793
1794  private boolean isAbstractType(List<TypeRefComponent> list) {
1795    return list.size() != 1 ? true : Utilities.existsInList(list.get(0).getCode(), "Element", "BackboneElement", "Resource", "DomainResource");
1796  }
1797
1798  private boolean isBoolean(List<Base> list, boolean b) {
1799    return list.size() == 1 && list.get(0) instanceof BooleanType && ((BooleanType) list.get(0)).booleanValue() == b;
1800  }
1801
1802  private void log(String name, List<Base> contents) {
1803    if (hostServices == null || !hostServices.log(name, contents)) {
1804      if (log.length() > 0)
1805        log.append("; ");
1806      log.append(name);
1807      log.append(": ");
1808      boolean first = true;
1809      for (Base b : contents) {
1810        if (first)
1811          first = false;
1812        else
1813          log.append(",");
1814        log.append(convertToString(b));
1815      }
1816    }
1817  }
1818
1819  private List<Base> makeBoolean(boolean b) {
1820    List<Base> res = new ArrayList<Base>();
1821    res.add(new BooleanType(b));
1822    return res;
1823  }
1824
1825  private ExpressionNode newGroup(FHIRLexer lexer, ExpressionNode next) {
1826    ExpressionNode result = new ExpressionNode(lexer.nextId());
1827    result.setKind(Kind.Group);
1828    result.setGroup(next);
1829    result.getGroup().setProximal(true);
1830    return result;
1831  }
1832
1833  private List<Base> opAnd(List<Base> left, List<Base> right) {
1834    if (left.isEmpty() && right.isEmpty())
1835      return new ArrayList<Base>();
1836    else if (isBoolean(left, false) || isBoolean(right, false))
1837      return makeBoolean(false);
1838    else if (left.isEmpty() || right.isEmpty())
1839      return new ArrayList<Base>();
1840    else if (convertToBoolean(left) && convertToBoolean(right))
1841      return makeBoolean(true);
1842    else
1843      return makeBoolean(false);
1844  }
1845
1846  private List<Base> opAs(List<Base> left, List<Base> right) {
1847    List<Base> result = new ArrayList<Base>();
1848    if (left.size() != 1 || right.size() != 1)
1849      return result;
1850    else {
1851      String tn = convertToString(right);
1852      if (tn.equals(left.get(0).fhirType()))
1853        result.add(left.get(0));
1854    }
1855    return result;
1856  }
1857
1858  private List<Base> opConcatenate(List<Base> left, List<Base> right) {
1859    List<Base> result = new ArrayList<Base>();
1860    result.add(new StringType(convertToString(left) + convertToString((right))));
1861    return result;
1862  }
1863
1864  private List<Base> opContains(List<Base> left, List<Base> right) {
1865    boolean ans = true;
1866    for (Base r : right) {
1867      boolean f = false;
1868      for (Base l : left)
1869        if (doEquals(l, r)) {
1870          f = true;
1871          break;
1872        }
1873      if (!f) {
1874        ans = false;
1875        break;
1876      }
1877    }
1878    return makeBoolean(ans);
1879  }
1880
1881  private List<Base> opDiv(List<Base> left, List<Base> right) throws PathEngineException {
1882    if (left.size() == 0)
1883      throw new PathEngineException("Error performing div: left operand has no value");
1884    if (left.size() > 1)
1885      throw new PathEngineException("Error performing div: left operand has more than one value");
1886    if (!left.get(0).isPrimitive())
1887      throw new PathEngineException(String.format("Error performing div: left operand has the wrong type (%s)", left.get(0).fhirType()));
1888    if (right.size() == 0)
1889      throw new PathEngineException("Error performing div: right operand has no value");
1890    if (right.size() > 1)
1891      throw new PathEngineException("Error performing div: right operand has more than one value");
1892    if (!right.get(0).isPrimitive())
1893      throw new PathEngineException(String.format("Error performing div: right operand has the wrong type (%s)", right.get(0).fhirType()));
1894
1895    List<Base> result = new ArrayList<Base>();
1896    Base l = left.get(0);
1897    Base r = right.get(0);
1898
1899    if (l.hasType("integer") && r.hasType("integer"))
1900      result.add(new IntegerType(Integer.parseInt(l.primitiveValue()) / Integer.parseInt(r.primitiveValue())));
1901    else if (l.hasType("decimal", "integer") && r.hasType("decimal", "integer")) {
1902      Decimal d1;
1903      try {
1904        d1 = new Decimal(l.primitiveValue());
1905        Decimal d2 = new Decimal(r.primitiveValue());
1906        result.add(new IntegerType(d1.divInt(d2).asDecimal()));
1907      } catch (UcumException e) {
1908        throw new PathEngineException(e);
1909      }
1910    } else
1911      throw new PathEngineException(String.format("Error performing div: left and right operand have incompatible or illegal types (%s, %s)", left.get(0).fhirType(), right.get(0).fhirType()));
1912    return result;
1913  }
1914
1915  private List<Base> opDivideBy(List<Base> left, List<Base> right) throws PathEngineException {
1916    if (left.size() == 0)
1917      throw new PathEngineException("Error performing /: left operand has no value");
1918    if (left.size() > 1)
1919      throw new PathEngineException("Error performing /: left operand has more than one value");
1920    if (!left.get(0).isPrimitive())
1921      throw new PathEngineException(String.format("Error performing -: left operand has the wrong type (%s)", left.get(0).fhirType()));
1922    if (right.size() == 0)
1923      throw new PathEngineException("Error performing /: right operand has no value");
1924    if (right.size() > 1)
1925      throw new PathEngineException("Error performing /: right operand has more than one value");
1926    if (!right.get(0).isPrimitive())
1927      throw new PathEngineException(String.format("Error performing /: right operand has the wrong type (%s)", right.get(0).fhirType()));
1928
1929    List<Base> result = new ArrayList<Base>();
1930    Base l = left.get(0);
1931    Base r = right.get(0);
1932
1933    if (l.hasType("integer", "decimal", "unsignedInt", "positiveInt") && r.hasType("integer", "decimal", "unsignedInt", "positiveInt")) {
1934      Decimal d1;
1935      try {
1936        d1 = new Decimal(l.primitiveValue());
1937        Decimal d2 = new Decimal(r.primitiveValue());
1938        result.add(new DecimalType(d1.divide(d2).asDecimal()));
1939      } catch (UcumException e) {
1940        throw new PathEngineException(e);
1941      }
1942    } else
1943      throw new PathEngineException(String.format("Error performing /: left and right operand have incompatible or illegal types (%s, %s)", left.get(0).fhirType(), right.get(0).fhirType()));
1944    return result;
1945  }
1946
1947  private List<Base> opEquals(List<Base> left, List<Base> right) {
1948    if (left.size() != right.size())
1949      return makeBoolean(false);
1950
1951    boolean res = true;
1952    for (int i = 0; i < left.size(); i++) {
1953      if (!doEquals(left.get(i), right.get(i))) {
1954        res = false;
1955        break;
1956      }
1957    }
1958    return makeBoolean(res);
1959  }
1960
1961  private List<Base> opEquivalent(List<Base> left, List<Base> right) throws PathEngineException {
1962    if (left.size() != right.size())
1963      return makeBoolean(false);
1964
1965    boolean res = true;
1966    for (int i = 0; i < left.size(); i++) {
1967      boolean found = false;
1968      for (int j = 0; j < right.size(); j++) {
1969        if (doEquivalent(left.get(i), right.get(j))) {
1970          found = true;
1971          break;
1972        }
1973      }
1974      if (!found) {
1975        res = false;
1976        break;
1977      }
1978    }
1979    return makeBoolean(res);
1980  }
1981
1982  private List<Base> opGreater(List<Base> left, List<Base> right) throws FHIRException {
1983    if (left.size() == 1 && right.size() == 1 && left.get(0).isPrimitive() && right.get(0).isPrimitive()) {
1984      Base l = left.get(0);
1985      Base r = right.get(0);
1986      if (l.hasType("string") && r.hasType("string"))
1987        return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) > 0);
1988      else if ((l.hasType("integer", "decimal", "unsignedInt", "positiveInt")) && (r.hasType("integer", "decimal", "unsignedInt", "positiveInt")))
1989        return makeBoolean(new Double(l.primitiveValue()) > new Double(r.primitiveValue()));
1990      else if ((l.hasType("date", "dateTime", "instant")) && (r.hasType("date", "dateTime", "instant")))
1991        return makeBoolean(compareDateTimeElements(l, r) > 0);
1992      else if ((l.hasType("time")) && (r.hasType("time")))
1993        return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) > 0);
1994    } else if (left.size() == 1 && right.size() == 1 && left.get(0).fhirType().equals("Quantity") && right.get(0).fhirType().equals("Quantity")) {
1995      List<Base> lUnit = left.get(0).listChildrenByName("unit");
1996      List<Base> rUnit = right.get(0).listChildrenByName("unit");
1997      if (Base.compareDeep(lUnit, rUnit, true)) {
1998        return opGreater(left.get(0).listChildrenByName("value"), right.get(0).listChildrenByName("value"));
1999      } else {
2000        throw new InternalErrorException("Canonical Comparison isn't done yet");
2001      }
2002    }
2003    return new ArrayList<Base>();
2004  }
2005
2006  private List<Base> opGreaterOrEqual(List<Base> left, List<Base> right) throws FHIRException {
2007    if (left.size() == 1 && right.size() == 1 && left.get(0).isPrimitive() && right.get(0).isPrimitive()) {
2008      Base l = left.get(0);
2009      Base r = right.get(0);
2010      if (l.hasType("string") && r.hasType("string"))
2011        return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) >= 0);
2012      else if ((l.hasType("integer", "decimal", "unsignedInt", "positiveInt")) && (r.hasType("integer", "decimal", "unsignedInt", "positiveInt")))
2013        return makeBoolean(new Double(l.primitiveValue()) >= new Double(r.primitiveValue()));
2014      else if ((l.hasType("date", "dateTime", "instant")) && (r.hasType("date", "dateTime", "instant")))
2015        return makeBoolean(compareDateTimeElements(l, r) >= 0);
2016      else if ((l.hasType("time")) && (r.hasType("time")))
2017        return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) >= 0);
2018    } else if (left.size() == 1 && right.size() == 1 && left.get(0).fhirType().equals("Quantity") && right.get(0).fhirType().equals("Quantity")) {
2019      List<Base> lUnit = left.get(0).listChildrenByName("unit");
2020      List<Base> rUnit = right.get(0).listChildrenByName("unit");
2021      if (Base.compareDeep(lUnit, rUnit, true)) {
2022        return opGreaterOrEqual(left.get(0).listChildrenByName("value"), right.get(0).listChildrenByName("value"));
2023      } else {
2024        throw new InternalErrorException("Canonical Comparison isn't done yet");
2025      }
2026    }
2027    return new ArrayList<Base>();
2028  }
2029
2030  private List<Base> opImplies(List<Base> left, List<Base> right) {
2031    if (!convertToBoolean(left))
2032      return makeBoolean(true);
2033    else if (right.size() == 0)
2034      return new ArrayList<Base>();
2035    else
2036      return makeBoolean(convertToBoolean(right));
2037  }
2038
2039  private List<Base> opIn(List<Base> left, List<Base> right) {
2040    boolean ans = true;
2041    for (Base l : left) {
2042      boolean f = false;
2043      for (Base r : right)
2044        if (doEquals(l, r)) {
2045          f = true;
2046          break;
2047        }
2048      if (!f) {
2049        ans = false;
2050        break;
2051      }
2052    }
2053    return makeBoolean(ans);
2054  }
2055
2056  private List<Base> opIs(List<Base> left, List<Base> right) {
2057    List<Base> result = new ArrayList<Base>();
2058    if (left.size() != 1 || right.size() != 1)
2059      result.add(new BooleanType(false));
2060    else {
2061      String tn = convertToString(right);
2062      result.add(new BooleanType(left.get(0).hasType(tn)));
2063    }
2064    return result;
2065  }
2066
2067  private List<Base> opLessOrEqual(List<Base> left, List<Base> right) throws FHIRException {
2068    if (left.size() == 1 && right.size() == 1 && left.get(0).isPrimitive() && right.get(0).isPrimitive()) {
2069      Base l = left.get(0);
2070      Base r = right.get(0);
2071      if (l.hasType("string") && r.hasType("string"))
2072        return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) <= 0);
2073      else if ((l.hasType("integer", "decimal", "unsignedInt", "positiveInt")) && (r.hasType("integer", "decimal", "unsignedInt", "positiveInt")))
2074        return makeBoolean(new Double(l.primitiveValue()) <= new Double(r.primitiveValue()));
2075      else if ((l.hasType("date", "dateTime", "instant")) && (r.hasType("date", "dateTime", "instant")))
2076        return makeBoolean(compareDateTimeElements(l, r) <= 0);
2077      else if ((l.hasType("time")) && (r.hasType("time")))
2078        return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) <= 0);
2079    } else if (left.size() == 1 && right.size() == 1 && left.get(0).fhirType().equals("Quantity") && right.get(0).fhirType().equals("Quantity")) {
2080      List<Base> lUnits = left.get(0).listChildrenByName("unit");
2081      String lunit = lUnits.size() == 1 ? lUnits.get(0).primitiveValue() : null;
2082      List<Base> rUnits = right.get(0).listChildrenByName("unit");
2083      String runit = rUnits.size() == 1 ? rUnits.get(0).primitiveValue() : null;
2084      if ((lunit == null && runit == null) || lunit.equals(runit)) {
2085        return opLessOrEqual(left.get(0).listChildrenByName("value"), right.get(0).listChildrenByName("value"));
2086      } else {
2087        throw new InternalErrorException("Canonical Comparison isn't done yet");
2088      }
2089    }
2090    return new ArrayList<Base>();
2091  }
2092
2093  private List<Base> opLessThen(List<Base> left, List<Base> right) throws FHIRException {
2094    if (left.size() == 1 && right.size() == 1 && left.get(0).isPrimitive() && right.get(0).isPrimitive()) {
2095      Base l = left.get(0);
2096      Base r = right.get(0);
2097      if (l.hasType("string") && r.hasType("string"))
2098        return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) < 0);
2099      else if ((l.hasType("integer") || l.hasType("decimal")) && (r.hasType("integer") || r.hasType("decimal")))
2100        return makeBoolean(new Double(l.primitiveValue()) < new Double(r.primitiveValue()));
2101      else if ((l.hasType("date", "dateTime", "instant")) && (r.hasType("date", "dateTime", "instant")))
2102        return makeBoolean(compareDateTimeElements(l, r) < 0);
2103      else if ((l.hasType("time")) && (r.hasType("time")))
2104        return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) < 0);
2105    } else if (left.size() == 1 && right.size() == 1 && left.get(0).fhirType().equals("Quantity") && right.get(0).fhirType().equals("Quantity")) {
2106      List<Base> lUnit = left.get(0).listChildrenByName("unit");
2107      List<Base> rUnit = right.get(0).listChildrenByName("unit");
2108      if (Base.compareDeep(lUnit, rUnit, true)) {
2109        return opLessThen(left.get(0).listChildrenByName("value"), right.get(0).listChildrenByName("value"));
2110      } else {
2111        throw new InternalErrorException("Canonical Comparison isn't done yet");
2112      }
2113    }
2114    return new ArrayList<Base>();
2115  }
2116
2117  private List<Base> opMinus(List<Base> left, List<Base> right) throws PathEngineException {
2118    if (left.size() == 0)
2119      throw new PathEngineException("Error performing -: left operand has no value");
2120    if (left.size() > 1)
2121      throw new PathEngineException("Error performing -: left operand has more than one value");
2122    if (!left.get(0).isPrimitive())
2123      throw new PathEngineException(String.format("Error performing -: left operand has the wrong type (%s)", left.get(0).fhirType()));
2124    if (right.size() == 0)
2125      throw new PathEngineException("Error performing -: right operand has no value");
2126    if (right.size() > 1)
2127      throw new PathEngineException("Error performing -: right operand has more than one value");
2128    if (!right.get(0).isPrimitive())
2129      throw new PathEngineException(String.format("Error performing -: right operand has the wrong type (%s)", right.get(0).fhirType()));
2130
2131    List<Base> result = new ArrayList<Base>();
2132    Base l = left.get(0);
2133    Base r = right.get(0);
2134
2135    if (l.hasType("integer") && r.hasType("integer"))
2136      result.add(new IntegerType(Integer.parseInt(l.primitiveValue()) - Integer.parseInt(r.primitiveValue())));
2137    else if (l.hasType("decimal", "integer") && r.hasType("decimal", "integer"))
2138      result.add(new DecimalType(new BigDecimal(l.primitiveValue()).subtract(new BigDecimal(r.primitiveValue()))));
2139    else
2140      throw new PathEngineException(String.format("Error performing -: left and right operand have incompatible or illegal types (%s, %s)", left.get(0).fhirType(), right.get(0).fhirType()));
2141    return result;
2142  }
2143
2144  private List<Base> opMod(List<Base> left, List<Base> right) throws PathEngineException {
2145    if (left.size() == 0)
2146      throw new PathEngineException("Error performing mod: left operand has no value");
2147    if (left.size() > 1)
2148      throw new PathEngineException("Error performing mod: left operand has more than one value");
2149    if (!left.get(0).isPrimitive())
2150      throw new PathEngineException(String.format("Error performing mod: left operand has the wrong type (%s)", left.get(0).fhirType()));
2151    if (right.size() == 0)
2152      throw new PathEngineException("Error performing mod: right operand has no value");
2153    if (right.size() > 1)
2154      throw new PathEngineException("Error performing mod: right operand has more than one value");
2155    if (!right.get(0).isPrimitive())
2156      throw new PathEngineException(String.format("Error performing mod: right operand has the wrong type (%s)", right.get(0).fhirType()));
2157
2158    List<Base> result = new ArrayList<Base>();
2159    Base l = left.get(0);
2160    Base r = right.get(0);
2161
2162    if (l.hasType("integer") && r.hasType("integer"))
2163      result.add(new IntegerType(Integer.parseInt(l.primitiveValue()) % Integer.parseInt(r.primitiveValue())));
2164    else if (l.hasType("decimal", "integer") && r.hasType("decimal", "integer")) {
2165      Decimal d1;
2166      try {
2167        d1 = new Decimal(l.primitiveValue());
2168        Decimal d2 = new Decimal(r.primitiveValue());
2169        result.add(new DecimalType(d1.modulo(d2).asDecimal()));
2170      } catch (UcumException e) {
2171        throw new PathEngineException(e);
2172      }
2173    } else
2174      throw new PathEngineException(String.format("Error performing mod: left and right operand have incompatible or illegal types (%s, %s)", left.get(0).fhirType(), right.get(0).fhirType()));
2175    return result;
2176  }
2177
2178  private List<Base> opNotEquals(List<Base> left, List<Base> right) {
2179    if (left.size() != right.size())
2180      return makeBoolean(true);
2181
2182    boolean res = true;
2183    for (int i = 0; i < left.size(); i++) {
2184      if (!doEquals(left.get(i), right.get(i))) {
2185        res = false;
2186        break;
2187      }
2188    }
2189    return makeBoolean(!res);
2190  }
2191
2192  private List<Base> opNotEquivalent(List<Base> left, List<Base> right) throws PathEngineException {
2193    if (left.size() != right.size())
2194      return makeBoolean(true);
2195
2196    boolean res = true;
2197    for (int i = 0; i < left.size(); i++) {
2198      boolean found = false;
2199      for (int j = 0; j < right.size(); j++) {
2200        if (doEquivalent(left.get(i), right.get(j))) {
2201          found = true;
2202          break;
2203        }
2204      }
2205      if (!found) {
2206        res = false;
2207        break;
2208      }
2209    }
2210    return makeBoolean(!res);
2211  }
2212
2213  private List<Base> opOr(List<Base> left, List<Base> right) {
2214    if (left.isEmpty() && right.isEmpty())
2215      return new ArrayList<Base>();
2216    else if (convertToBoolean(left) || convertToBoolean(right))
2217      return makeBoolean(true);
2218    else if (left.isEmpty() || right.isEmpty())
2219      return new ArrayList<Base>();
2220    else
2221      return makeBoolean(false);
2222  }
2223
2224  private List<Base> opPlus(List<Base> left, List<Base> right) throws PathEngineException {
2225    if (left.size() == 0)
2226      throw new PathEngineException("Error performing +: left operand has no value");
2227    if (left.size() > 1)
2228      throw new PathEngineException("Error performing +: left operand has more than one value");
2229    if (!left.get(0).isPrimitive())
2230      throw new PathEngineException(String.format("Error performing +: left operand has the wrong type (%s)", left.get(0).fhirType()));
2231    if (right.size() == 0)
2232      throw new PathEngineException("Error performing +: right operand has no value");
2233    if (right.size() > 1)
2234      throw new PathEngineException("Error performing +: right operand has more than one value");
2235    if (!right.get(0).isPrimitive())
2236      throw new PathEngineException(String.format("Error performing +: right operand has the wrong type (%s)", right.get(0).fhirType()));
2237
2238    List<Base> result = new ArrayList<Base>();
2239    Base l = left.get(0);
2240    Base r = right.get(0);
2241    if (l.hasType("string", "id", "code", "uri") && r.hasType("string", "id", "code", "uri"))
2242      result.add(new StringType(l.primitiveValue() + r.primitiveValue()));
2243    else if (l.hasType("integer") && r.hasType("integer"))
2244      result.add(new IntegerType(Integer.parseInt(l.primitiveValue()) + Integer.parseInt(r.primitiveValue())));
2245    else if (l.hasType("decimal", "integer") && r.hasType("decimal", "integer"))
2246      result.add(new DecimalType(new BigDecimal(l.primitiveValue()).add(new BigDecimal(r.primitiveValue()))));
2247    else
2248      throw new PathEngineException(String.format("Error performing +: left and right operand have incompatible or illegal types (%s, %s)", left.get(0).fhirType(), right.get(0).fhirType()));
2249    return result;
2250  }
2251
2252  private List<Base> opTimes(List<Base> left, List<Base> right) throws PathEngineException {
2253    if (left.size() == 0)
2254      throw new PathEngineException("Error performing *: left operand has no value");
2255    if (left.size() > 1)
2256      throw new PathEngineException("Error performing *: left operand has more than one value");
2257    if (!left.get(0).isPrimitive())
2258      throw new PathEngineException(String.format("Error performing +: left operand has the wrong type (%s)", left.get(0).fhirType()));
2259    if (right.size() == 0)
2260      throw new PathEngineException("Error performing *: right operand has no value");
2261    if (right.size() > 1)
2262      throw new PathEngineException("Error performing *: right operand has more than one value");
2263    if (!right.get(0).isPrimitive())
2264      throw new PathEngineException(String.format("Error performing *: right operand has the wrong type (%s)", right.get(0).fhirType()));
2265
2266    List<Base> result = new ArrayList<Base>();
2267    Base l = left.get(0);
2268    Base r = right.get(0);
2269
2270    if (l.hasType("integer") && r.hasType("integer"))
2271      result.add(new IntegerType(Integer.parseInt(l.primitiveValue()) * Integer.parseInt(r.primitiveValue())));
2272    else if (l.hasType("decimal", "integer") && r.hasType("decimal", "integer"))
2273      result.add(new DecimalType(new BigDecimal(l.primitiveValue()).multiply(new BigDecimal(r.primitiveValue()))));
2274    else
2275      throw new PathEngineException(String.format("Error performing *: left and right operand have incompatible or illegal types (%s, %s)", left.get(0).fhirType(), right.get(0).fhirType()));
2276    return result;
2277  }
2278
2279  private List<Base> opUnion(List<Base> left, List<Base> right) {
2280    List<Base> result = new ArrayList<Base>();
2281    for (Base item : left) {
2282      if (!doContains(result, item))
2283        result.add(item);
2284    }
2285    for (Base item : right) {
2286      if (!doContains(result, item))
2287        result.add(item);
2288    }
2289    return result;
2290  }
2291
2292  private List<Base> opXor(List<Base> left, List<Base> right) {
2293    if (left.isEmpty() || right.isEmpty())
2294      return new ArrayList<Base>();
2295    else
2296      return makeBoolean(convertToBoolean(left) ^ convertToBoolean(right));
2297  }
2298
2299  private List<Base> operate(List<Base> left, Operation operation, List<Base> right) throws FHIRException {
2300    switch (operation) {
2301      case Equals:
2302        return opEquals(left, right);
2303      case Equivalent:
2304        return opEquivalent(left, right);
2305      case NotEquals:
2306        return opNotEquals(left, right);
2307      case NotEquivalent:
2308        return opNotEquivalent(left, right);
2309      case LessThen:
2310        return opLessThen(left, right);
2311      case Greater:
2312        return opGreater(left, right);
2313      case LessOrEqual:
2314        return opLessOrEqual(left, right);
2315      case GreaterOrEqual:
2316        return opGreaterOrEqual(left, right);
2317      case Union:
2318        return opUnion(left, right);
2319      case In:
2320        return opIn(left, right);
2321      case Contains:
2322        return opContains(left, right);
2323      case Or:
2324        return opOr(left, right);
2325      case And:
2326        return opAnd(left, right);
2327      case Xor:
2328        return opXor(left, right);
2329      case Implies:
2330        return opImplies(left, right);
2331      case Plus:
2332        return opPlus(left, right);
2333      case Times:
2334        return opTimes(left, right);
2335      case Minus:
2336        return opMinus(left, right);
2337      case Concatenate:
2338        return opConcatenate(left, right);
2339      case DivideBy:
2340        return opDivideBy(left, right);
2341      case Div:
2342        return opDiv(left, right);
2343      case Mod:
2344        return opMod(left, right);
2345      case Is:
2346        return opIs(left, right);
2347      case As:
2348        return opAs(left, right);
2349      default:
2350        throw new Error("Not Done Yet: " + operation.toCode());
2351    }
2352  }
2353
2354  private TypeDetails operateTypes(TypeDetails left, Operation operation, TypeDetails right) {
2355    switch (operation) {
2356      case Equals:
2357        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
2358      case Equivalent:
2359        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
2360      case NotEquals:
2361        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
2362      case NotEquivalent:
2363        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
2364      case LessThen:
2365        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
2366      case Greater:
2367        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
2368      case LessOrEqual:
2369        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
2370      case GreaterOrEqual:
2371        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
2372      case Is:
2373        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
2374      case As:
2375        return new TypeDetails(CollectionStatus.SINGLETON, right.getTypes());
2376      case Union:
2377        return left.union(right);
2378      case Or:
2379        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
2380      case And:
2381        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
2382      case Xor:
2383        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
2384      case Implies:
2385        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
2386      case Times:
2387        TypeDetails result = new TypeDetails(CollectionStatus.SINGLETON);
2388        if (left.hasType(worker, "integer") && right.hasType(worker, "integer"))
2389          result.addType("integer");
2390        else if (left.hasType(worker, "integer", "decimal") && right.hasType(worker, "integer", "decimal"))
2391          result.addType("decimal");
2392        return result;
2393      case DivideBy:
2394        result = new TypeDetails(CollectionStatus.SINGLETON);
2395        if (left.hasType(worker, "integer") && right.hasType(worker, "integer"))
2396          result.addType("decimal");
2397        else if (left.hasType(worker, "integer", "decimal") && right.hasType(worker, "integer", "decimal"))
2398          result.addType("decimal");
2399        return result;
2400      case Concatenate:
2401        result = new TypeDetails(CollectionStatus.SINGLETON, "");
2402        return result;
2403      case Plus:
2404        result = new TypeDetails(CollectionStatus.SINGLETON);
2405        if (left.hasType(worker, "integer") && right.hasType(worker, "integer"))
2406          result.addType("integer");
2407        else if (left.hasType(worker, "integer", "decimal") && right.hasType(worker, "integer", "decimal"))
2408          result.addType("decimal");
2409        else if (left.hasType(worker, "string", "id", "code", "uri") && right.hasType(worker, "string", "id", "code", "uri"))
2410          result.addType("string");
2411        return result;
2412      case Minus:
2413        result = new TypeDetails(CollectionStatus.SINGLETON);
2414        if (left.hasType(worker, "integer") && right.hasType(worker, "integer"))
2415          result.addType("integer");
2416        else if (left.hasType(worker, "integer", "decimal") && right.hasType(worker, "integer", "decimal"))
2417          result.addType("decimal");
2418        return result;
2419      case Div:
2420      case Mod:
2421        result = new TypeDetails(CollectionStatus.SINGLETON);
2422        if (left.hasType(worker, "integer") && right.hasType(worker, "integer"))
2423          result.addType("integer");
2424        else if (left.hasType(worker, "integer", "decimal") && right.hasType(worker, "integer", "decimal"))
2425          result.addType("decimal");
2426        return result;
2427      case In:
2428        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
2429      case Contains:
2430        return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
2431      default:
2432        return null;
2433    }
2434  }
2435
2436  private ExpressionNode organisePrecedence(FHIRLexer lexer, ExpressionNode node) {
2437    node = gatherPrecedence(lexer, node, EnumSet.of(Operation.Times, Operation.DivideBy, Operation.Div, Operation.Mod));
2438    node = gatherPrecedence(lexer, node, EnumSet.of(Operation.Plus, Operation.Minus, Operation.Concatenate));
2439    node = gatherPrecedence(lexer, node, EnumSet.of(Operation.Union));
2440    node = gatherPrecedence(lexer, node, EnumSet.of(Operation.LessThen, Operation.Greater, Operation.LessOrEqual, Operation.GreaterOrEqual));
2441    node = gatherPrecedence(lexer, node, EnumSet.of(Operation.Is));
2442    node = gatherPrecedence(lexer, node, EnumSet.of(Operation.Equals, Operation.Equivalent, Operation.NotEquals, Operation.NotEquivalent));
2443    node = gatherPrecedence(lexer, node, EnumSet.of(Operation.And));
2444    node = gatherPrecedence(lexer, node, EnumSet.of(Operation.Xor, Operation.Or));
2445    // last: implies
2446    return node;
2447  }
2448
2449  /**
2450   * Parse a path for later use using execute
2451   *
2452   * @param path
2453   * @return
2454   * @throws PathEngineException
2455   * @throws Exception
2456   */
2457  public ExpressionNode parse(String path) throws FHIRLexerException {
2458    FHIRLexer lexer = new FHIRLexer(path);
2459    if (lexer.done())
2460      throw lexer.error("Path cannot be empty");
2461    ExpressionNode result = parseExpression(lexer, true);
2462    if (!lexer.done())
2463      throw lexer.error("Premature ExpressionNode termination at unexpected token \"" + lexer.getCurrent() + "\"");
2464    result.check();
2465    return result;
2466  }
2467
2468  /**
2469   * Parse a path that is part of some other syntax
2470   *
2471   * @param path
2472   * @return
2473   * @throws PathEngineException
2474   * @throws Exception
2475   */
2476  public ExpressionNode parse(FHIRLexer lexer) throws FHIRLexerException {
2477    ExpressionNode result = parseExpression(lexer, true);
2478    result.check();
2479    return result;
2480  }
2481
2482  private ExpressionNode parseExpression(FHIRLexer lexer, boolean proximal) throws FHIRLexerException {
2483    ExpressionNode result = new ExpressionNode(lexer.nextId());
2484    SourceLocation c = lexer.getCurrentStartLocation();
2485    result.setStart(lexer.getCurrentLocation());
2486    // special:
2487    if (lexer.getCurrent().equals("-")) {
2488      lexer.take();
2489      lexer.setCurrent("-" + lexer.getCurrent());
2490    }
2491    if (lexer.getCurrent().equals("+")) {
2492      lexer.take();
2493      lexer.setCurrent("+" + lexer.getCurrent());
2494    }
2495    if (lexer.isConstant(false)) {
2496      checkConstant(lexer.getCurrent(), lexer);
2497      result.setConstant(lexer.take());
2498      result.setKind(Kind.Constant);
2499      result.setEnd(lexer.getCurrentLocation());
2500    } else if ("(".equals(lexer.getCurrent())) {
2501      lexer.next();
2502      result.setKind(Kind.Group);
2503      result.setGroup(parseExpression(lexer, true));
2504      if (!")".equals(lexer.getCurrent()))
2505        throw lexer.error("Found " + lexer.getCurrent() + " expecting a \")\"");
2506      result.setEnd(lexer.getCurrentLocation());
2507      lexer.next();
2508    } else {
2509      if (!lexer.isToken() && !lexer.getCurrent().startsWith("\""))
2510        throw lexer.error("Found " + lexer.getCurrent() + " expecting a token name");
2511      if (lexer.getCurrent().startsWith("\""))
2512        result.setName(lexer.readConstant("Path Name"));
2513      else
2514        result.setName(lexer.take());
2515      result.setEnd(lexer.getCurrentLocation());
2516      if (!result.checkName())
2517        throw lexer.error("Found " + result.getName() + " expecting a valid token name");
2518      if ("(".equals(lexer.getCurrent())) {
2519        Function f = Function.fromCode(result.getName());
2520        FunctionDetails details = null;
2521        if (f == null) {
2522          if (hostServices != null)
2523            details = hostServices.resolveFunction(result.getName());
2524          if (details == null)
2525            throw lexer.error("The name " + result.getName() + " is not a valid function name");
2526          f = Function.Custom;
2527        }
2528        result.setKind(Kind.Function);
2529        result.setFunction(f);
2530        lexer.next();
2531        while (!")".equals(lexer.getCurrent())) {
2532          result.getParameters().add(parseExpression(lexer, true));
2533          if (",".equals(lexer.getCurrent()))
2534            lexer.next();
2535          else if (!")".equals(lexer.getCurrent()))
2536            throw lexer.error("The token " + lexer.getCurrent() + " is not expected here - either a \",\" or a \")\" expected");
2537        }
2538        result.setEnd(lexer.getCurrentLocation());
2539        lexer.next();
2540        checkParameters(lexer, c, result, details);
2541      } else
2542        result.setKind(Kind.Name);
2543    }
2544    ExpressionNode focus = result;
2545    if ("[".equals(lexer.getCurrent())) {
2546      lexer.next();
2547      ExpressionNode item = new ExpressionNode(lexer.nextId());
2548      item.setKind(Kind.Function);
2549      item.setFunction(ExpressionNode.Function.Item);
2550      item.getParameters().add(parseExpression(lexer, true));
2551      if (!lexer.getCurrent().equals("]"))
2552        throw lexer.error("The token " + lexer.getCurrent() + " is not expected here - a \"]\" expected");
2553      lexer.next();
2554      result.setInner(item);
2555      focus = item;
2556    }
2557    if (".".equals(lexer.getCurrent())) {
2558      lexer.next();
2559      focus.setInner(parseExpression(lexer, false));
2560    }
2561    result.setProximal(proximal);
2562    if (proximal) {
2563      while (lexer.isOp()) {
2564        focus.setOperation(ExpressionNode.Operation.fromCode(lexer.getCurrent()));
2565        focus.setOpStart(lexer.getCurrentStartLocation());
2566        focus.setOpEnd(lexer.getCurrentLocation());
2567        lexer.next();
2568        focus.setOpNext(parseExpression(lexer, false));
2569        focus = focus.getOpNext();
2570      }
2571      result = organisePrecedence(lexer, result);
2572    }
2573    return result;
2574  }
2575
2576  private List<Base> preOperate(List<Base> left, Operation operation) {
2577    switch (operation) {
2578      case And:
2579        return isBoolean(left, false) ? makeBoolean(false) : null;
2580      case Or:
2581        return isBoolean(left, true) ? makeBoolean(true) : null;
2582      case Implies:
2583        return convertToBoolean(left) ? null : makeBoolean(true);
2584      default:
2585        return null;
2586    }
2587  }
2588
2589  private Base processConstant(ExecutionContext context, String constant) throws PathEngineException {
2590    if (constant.equals("true")) {
2591      return new BooleanType(true);
2592    } else if (constant.equals("false")) {
2593      return new BooleanType(false);
2594    } else if (constant.equals("{}")) {
2595      return null;
2596    } else if (Utilities.isInteger(constant)) {
2597      return new IntegerType(constant);
2598    } else if (Utilities.isDecimal(constant)) {
2599      return new DecimalType(constant);
2600    } else if (constant.startsWith("\'")) {
2601      return new StringType(processConstantString(constant));
2602    } else if (constant.startsWith("%")) {
2603      return resolveConstant(context, constant);
2604    } else if (constant.startsWith("@")) {
2605      return processDateConstant(context.appInfo, constant.substring(1));
2606    } else {
2607      return new StringType(constant);
2608    }
2609  }
2610
2611  private String processConstantString(String s) throws PathEngineException {
2612    StringBuilder b = new StringBuilder();
2613    int i = 1;
2614    while (i < s.length() - 1) {
2615      char ch = s.charAt(i);
2616      if (ch == '\\') {
2617        i++;
2618        switch (s.charAt(i)) {
2619          case 't':
2620            b.append('\t');
2621            break;
2622          case 'r':
2623            b.append('\r');
2624            break;
2625          case 'n':
2626            b.append('\n');
2627            break;
2628          case 'f':
2629            b.append('\f');
2630            break;
2631          case '\'':
2632            b.append('\'');
2633            break;
2634          case '\\':
2635            b.append('\\');
2636            break;
2637          case '/':
2638            b.append('/');
2639            break;
2640          case 'u':
2641            i++;
2642            int uc = Integer.parseInt(s.substring(i, i + 4), 16);
2643            b.append((char) uc);
2644            i = i + 3;
2645            break;
2646          default:
2647            throw new PathEngineException("Unknown character escape \\" + s.charAt(i));
2648        }
2649        i++;
2650      } else {
2651        b.append(ch);
2652        i++;
2653      }
2654    }
2655    return b.toString();
2656  }
2657
2658  private Base processDateConstant(Object appInfo, String value) throws PathEngineException {
2659    if (value.startsWith("T"))
2660      return new TimeType(value.substring(1));
2661    String v = value;
2662    if (v.length() > 10) {
2663      int i = v.substring(10).indexOf("-");
2664      if (i == -1)
2665        i = v.substring(10).indexOf("+");
2666      if (i == -1)
2667        i = v.substring(10).indexOf("Z");
2668      v = i == -1 ? value : v.substring(0, 10 + i);
2669    }
2670    if (v.length() > 10)
2671      return new DateTimeType(value);
2672    else
2673      return new DateType(value);
2674  }
2675
2676  private TypeDetails readConstantType(ExecutionTypeContext context, String constant) throws PathEngineException {
2677    if (constant.equals("true"))
2678      return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
2679    else if (constant.equals("false"))
2680      return new TypeDetails(CollectionStatus.SINGLETON, "boolean");
2681    else if (Utilities.isInteger(constant))
2682      return new TypeDetails(CollectionStatus.SINGLETON, "integer");
2683    else if (Utilities.isDecimal(constant))
2684      return new TypeDetails(CollectionStatus.SINGLETON, "decimal");
2685    else if (constant.startsWith("%"))
2686      return resolveConstantType(context, constant);
2687    else
2688      return new TypeDetails(CollectionStatus.SINGLETON, "string");
2689  }
2690
2691  private Base resolveConstant(ExecutionContext context, String s) throws PathEngineException {
2692    if (s.equals("%sct"))
2693      return new StringType("http://snomed.info/sct");
2694    else if (s.equals("%loinc"))
2695      return new StringType("http://loinc.org");
2696    else if (s.equals("%ucum"))
2697      return new StringType("http://unitsofmeasure.org");
2698    else if (s.equals("%resource")) {
2699      if (context.resource == null)
2700        throw new PathEngineException("Cannot use %resource in this context");
2701      return context.resource;
2702    } else if (s.equals("%context")) {
2703      return context.context;
2704    } else if (s.equals("%us-zip"))
2705      return new StringType("[0-9]{5}(-[0-9]{4}){0,1}");
2706    else if (s.startsWith("%\"vs-"))
2707      return new StringType("http://hl7.org/fhir/ValueSet/" + s.substring(5, s.length() - 1) + "");
2708    else if (s.startsWith("%\"cs-"))
2709      return new StringType("http://hl7.org/fhir/" + s.substring(5, s.length() - 1) + "");
2710    else if (s.startsWith("%\"ext-"))
2711      return new StringType("http://hl7.org/fhir/StructureDefinition/" + s.substring(6, s.length() - 1));
2712    else if (hostServices == null)
2713      throw new PathEngineException("Unknown fixed constant '" + s + "'");
2714    else
2715      return hostServices.resolveConstant(context.appInfo, s.substring(1));
2716  }
2717
2718  private TypeDetails resolveConstantType(ExecutionTypeContext context, String s) throws PathEngineException {
2719    if (s.equals("%sct"))
2720      return new TypeDetails(CollectionStatus.SINGLETON, "string");
2721    else if (s.equals("%loinc"))
2722      return new TypeDetails(CollectionStatus.SINGLETON, "string");
2723    else if (s.equals("%ucum"))
2724      return new TypeDetails(CollectionStatus.SINGLETON, "string");
2725    else if (s.equals("%resource")) {
2726      if (context.resource == null)
2727        throw new PathEngineException("%resource cannot be used in this context");
2728      return new TypeDetails(CollectionStatus.SINGLETON, context.resource);
2729    } else if (s.equals("%context")) {
2730      return new TypeDetails(CollectionStatus.SINGLETON, context.context);
2731    } else if (s.equals("%map-codes"))
2732      return new TypeDetails(CollectionStatus.SINGLETON, "string");
2733    else if (s.equals("%us-zip"))
2734      return new TypeDetails(CollectionStatus.SINGLETON, "string");
2735    else if (s.startsWith("%\"vs-"))
2736      return new TypeDetails(CollectionStatus.SINGLETON, "string");
2737    else if (s.startsWith("%\"cs-"))
2738      return new TypeDetails(CollectionStatus.SINGLETON, "string");
2739    else if (s.startsWith("%\"ext-"))
2740      return new TypeDetails(CollectionStatus.SINGLETON, "string");
2741    else if (hostServices == null)
2742      throw new PathEngineException("Unknown fixed constant type for '" + s + "'");
2743    else
2744      return hostServices.resolveConstantType(context.appInfo, s);
2745  }
2746
2747  private String tail(String type) {
2748    return type.contains("#") ? "" : type.substring(type.lastIndexOf("/") + 1);
2749  }
2750
2751  public String takeLog() {
2752    if (!hasLog())
2753      return "";
2754    String s = log.toString();
2755    log = new StringBuilder();
2756    return s;
2757  }
2758
2759  // if the fhir path expressions are allowed to use constants beyond those defined in the specification
2760  // the application can implement them by providing a constant resolver
2761  public interface IEvaluationContext {
2762    /**
2763     * Check the function parameters, and throw an error if they are incorrect, or return the type for the function
2764     *
2765     * @param functionName
2766     * @param parameters
2767     * @return
2768     */
2769    public TypeDetails checkFunction(Object appContext, String functionName, List<TypeDetails> parameters) throws PathEngineException;
2770
2771    /**
2772     * @param appContext
2773     * @param functionName
2774     * @param parameters
2775     * @return
2776     */
2777    public List<Base> executeFunction(Object appContext, String functionName, List<List<Base>> parameters);
2778
2779    /**
2780     * when the .log() function is called
2781     *
2782     * @param argument
2783     * @param focus
2784     * @return
2785     */
2786    public boolean log(String argument, List<Base> focus);
2787
2788    /**
2789     * A constant reference - e.g. a reference to a name that must be resolved in context.
2790     * The % will be removed from the constant name before this is invoked.
2791     * <p>
2792     * This will also be called if the host invokes the FluentPath engine with a context of null
2793     *
2794     * @param appContext - content passed into the fluent path engine
2795     * @param name       - name reference to resolve
2796     * @return the value of the reference (or null, if it's not valid, though can throw an exception if desired)
2797     */
2798    public Base resolveConstant(Object appContext, String name) throws PathEngineException;
2799
2800    // extensibility for functions
2801
2802    public TypeDetails resolveConstantType(Object appContext, String name) throws PathEngineException;
2803
2804    /**
2805     * @param functionName
2806     * @return null if the function is not known
2807     */
2808    public FunctionDetails resolveFunction(String functionName);
2809
2810    /**
2811     * Implementation of resolve() function. Passed a string, return matching resource, if one is known - else null
2812     *
2813     * @param appInfo
2814     * @param url
2815     * @return
2816     */
2817    public Base resolveReference(Object appContext, String url);
2818
2819    public class FunctionDetails {
2820      private String description;
2821      private int minParameters;
2822      private int maxParameters;
2823
2824      public FunctionDetails(String description, int minParameters, int maxParameters) {
2825        super();
2826        this.description = description;
2827        this.minParameters = minParameters;
2828        this.maxParameters = maxParameters;
2829      }
2830
2831      public String getDescription() {
2832        return description;
2833      }
2834
2835      public int getMaxParameters() {
2836        return maxParameters;
2837      }
2838
2839      public int getMinParameters() {
2840        return minParameters;
2841      }
2842
2843    }
2844  }
2845
2846  private class ExecutionContext {
2847    private Object appInfo;
2848    private Base resource;
2849    private Base context;
2850    private Base thisItem;
2851    private Map<String, Base> aliases;
2852
2853    public ExecutionContext(Object appInfo, Base resource, Base context, Map<String, Base> aliases, Base thisItem) {
2854      this.appInfo = appInfo;
2855      this.context = context;
2856      this.resource = resource;
2857      this.aliases = aliases;
2858      this.thisItem = thisItem;
2859    }
2860
2861    public void addAlias(String name, List<Base> focus) throws FHIRException {
2862      if (aliases == null)
2863        aliases = new HashMap<String, Base>();
2864      else
2865        aliases = new HashMap<String, Base>(aliases); // clone it, since it's going to change
2866      if (focus.size() > 1)
2867        throw new FHIRException("Attempt to alias a collection, not a singleton");
2868      aliases.put(name, focus.size() == 0 ? null : focus.get(0));
2869    }
2870
2871    public Base getAlias(String name) {
2872      return aliases == null ? null : aliases.get(name);
2873    }
2874
2875    public Base getResource() {
2876      return resource;
2877    }
2878
2879    public Base getThisItem() {
2880      return thisItem;
2881    }
2882  }
2883
2884  private class ExecutionTypeContext {
2885    private Object appInfo;
2886    private String resource;
2887    private String context;
2888    private TypeDetails thisItem;
2889
2890
2891    public ExecutionTypeContext(Object appInfo, String resource, String context, TypeDetails thisItem) {
2892      super();
2893      this.appInfo = appInfo;
2894      this.resource = resource;
2895      this.context = context;
2896      this.thisItem = thisItem;
2897
2898    }
2899
2900    public String getResource() {
2901      return resource;
2902    }
2903
2904    public TypeDetails getThisItem() {
2905      return thisItem;
2906    }
2907  }
2908
2909  public class ElementDefinitionMatch {
2910    private ElementDefinition definition;
2911    private String fixedType;
2912
2913    public ElementDefinitionMatch(ElementDefinition definition, String fixedType) {
2914      super();
2915      this.definition = definition;
2916      this.fixedType = fixedType;
2917    }
2918
2919    public ElementDefinition getDefinition() {
2920      return definition;
2921    }
2922
2923    public String getFixedType() {
2924      return fixedType;
2925    }
2926
2927  }
2928
2929}