001package org.hl7.fhir.r5.utils;
002
003import ca.uhn.fhir.model.api.TemporalPrecisionEnum;
004import ca.uhn.fhir.util.ElementUtil;
005import org.apache.commons.lang3.NotImplementedException;
006import org.fhir.ucum.Decimal;
007import org.fhir.ucum.Pair;
008import org.fhir.ucum.UcumException;
009import org.hl7.fhir.exceptions.DefinitionException;
010import org.hl7.fhir.exceptions.FHIRException;
011import org.hl7.fhir.exceptions.PathEngineException;
012import org.hl7.fhir.r5.model.Base;
013import org.hl7.fhir.r5.model.ExpressionNode;
014import org.hl7.fhir.r5.model.IntegerType;
015import org.hl7.fhir.r5.conformance.ProfileUtilities;
016import org.hl7.fhir.r5.context.IWorkerContext;
017import org.hl7.fhir.r5.model.*;
018import org.hl7.fhir.r5.model.ElementDefinition.TypeRefComponent;
019import org.hl7.fhir.r5.model.ExpressionNode.*;
020import org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionKind;
021import org.hl7.fhir.r5.model.StructureDefinition.TypeDerivationRule;
022import org.hl7.fhir.r5.model.TypeDetails.ProfiledType;
023import org.hl7.fhir.r5.utils.FHIRLexer.FHIRLexerException;
024import org.hl7.fhir.r5.utils.FHIRPathEngine.IEvaluationContext.FunctionDetails;
025import org.hl7.fhir.utilities.TerminologyServiceOptions;
026import org.hl7.fhir.utilities.Utilities;
027import org.hl7.fhir.utilities.validation.ValidationOptions;
028
029import java.math.BigDecimal;
030import java.util.*;
031
032/*-
033 * #%L
034 * org.hl7.fhir.r5
035 * %%
036 * Copyright (C) 2014 - 2019 Health Level 7
037 * %%
038 * Licensed under the Apache License, Version 2.0 (the "License");
039 * you may not use this file except in compliance with the License.
040 * You may obtain a copy of the License at
041 * 
042 *      http://www.apache.org/licenses/LICENSE-2.0
043 * 
044 * Unless required by applicable law or agreed to in writing, software
045 * distributed under the License is distributed on an "AS IS" BASIS,
046 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
047 * See the License for the specific language governing permissions and
048 * limitations under the License.
049 * #L%
050 */
051
052/**
053 * 
054 * @author Grahame Grieve
055 *
056 */
057public class FHIRPathEngine {
058  private enum Equality { Null, True, False }
059
060  private class FHIRConstant extends Base {
061
062    private static final long serialVersionUID = -8933773658248269439L;
063    private String value;
064
065    public FHIRConstant(String value) {
066      this.value = value;
067    }
068
069    @Override
070    public String fhirType() {
071      return "%constant";
072    }
073
074    @Override
075    protected void listChildren(List<Property> result) {
076    }
077
078    @Override
079    public String getIdBase() {
080      return null;
081    }
082
083    @Override
084    public void setIdBase(String value) {
085    }
086
087    public String getValue() {
088      return value;
089    }
090    
091    @Override
092    public String primitiveValue() {
093      return value;
094    }
095  }
096  
097  private class ClassTypeInfo extends Base {
098    private static final long serialVersionUID = 4909223114071029317L;
099    private Base instance;
100
101    public ClassTypeInfo(Base instance) {
102      super();
103      this.instance = instance;
104    }
105
106    @Override
107    public String fhirType() {
108      return "ClassInfo";
109    }
110
111    @Override
112    protected void listChildren(List<Property> result) {
113    }
114
115    @Override
116    public String getIdBase() {
117      return null;
118    }
119
120    @Override
121    public void setIdBase(String value) {
122    }
123    public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException {
124      if (name.equals("name")) 
125        return new Base[]{new StringType(getName())};
126      else if (name.equals("namespace")) 
127        return new Base[]{new StringType(getNamespace())};
128      else
129        return super.getProperty(hash, name, checkValid);
130    }
131
132    private String getNamespace() {
133      if ((instance instanceof Resource))
134        return "FHIR";
135      else if (!(instance instanceof Element) || ((Element)instance).isDisallowExtensions())
136        return "System";
137      else
138        return "FHIR";
139    }
140
141    private String getName() {
142      if ((instance instanceof Resource))
143        return instance.fhirType();
144      else if (!(instance instanceof Element) || ((Element)instance).isDisallowExtensions())
145        return Utilities.capitalize(instance.fhirType());
146      else
147        return instance.fhirType();
148    }
149  }
150
151  private IWorkerContext worker;
152  private IEvaluationContext hostServices;
153  private StringBuilder log = new StringBuilder();
154  private Set<String> primitiveTypes = new HashSet<String>();
155  private Map<String, StructureDefinition> allTypes = new HashMap<String, StructureDefinition>();
156  private boolean legacyMode; // some R2 and R3 constraints assume that != is valid for emptty sets, so when running for R2/R3, this is set ot true  
157  private ValidationOptions terminologyServiceOptions = new ValidationOptions();
158
159  // if the fhir path expressions are allowed to use constants beyond those defined in the specification
160  // the application can implement them by providing a constant resolver 
161  public interface IEvaluationContext {
162    public class FunctionDetails {
163      private String description;
164      private int minParameters;
165      private int maxParameters;
166      public FunctionDetails(String description, int minParameters, int maxParameters) {
167        super();
168        this.description = description;
169        this.minParameters = minParameters;
170        this.maxParameters = maxParameters;
171      }
172      public String getDescription() {
173        return description;
174      }
175      public int getMinParameters() {
176        return minParameters;
177      }
178      public int getMaxParameters() {
179        return maxParameters;
180      }
181
182    }
183
184    /**
185     * A constant reference - e.g. a reference to a name that must be resolved in context.
186     * The % will be removed from the constant name before this is invoked.
187     * 
188     * This will also be called if the host invokes the FluentPath engine with a context of null
189     *  
190     * @param appContext - content passed into the fluent path engine
191     * @param name - name reference to resolve
192     * @param beforeContext - whether this is being called before the name is resolved locally, or not
193     * @return the value of the reference (or null, if it's not valid, though can throw an exception if desired)
194     */
195    public Base resolveConstant(Object appContext, String name, boolean beforeContext)  throws PathEngineException;
196    public TypeDetails resolveConstantType(Object appContext, String name) throws PathEngineException;
197    
198    /**
199     * when the .log() function is called
200     * 
201     * @param argument
202     * @param focus
203     * @return
204     */
205    public boolean log(String argument, List<Base> focus);
206
207    // extensibility for functions
208    /**
209     * 
210     * @param functionName
211     * @return null if the function is not known
212     */
213    public FunctionDetails resolveFunction(String functionName);
214    
215    /**
216     * Check the function parameters, and throw an error if they are incorrect, or return the type for the function
217     * @param functionName
218     * @param parameters
219     * @return
220     */
221    public TypeDetails checkFunction(Object appContext, String functionName, List<TypeDetails> parameters) throws PathEngineException;
222    
223    /**
224     * @param appContext
225     * @param functionName
226     * @param parameters
227     * @return
228     */
229    public List<Base> executeFunction(Object appContext, String functionName, List<List<Base>> parameters);
230    
231    /**
232     * Implementation of resolve() function. Passed a string, return matching resource, if one is known - else null
233     * @appContext - passed in by the host to the FHIRPathEngine
234     * @param url the reference (Reference.reference or the value of the canonical
235     * @return
236     * @throws FHIRException 
237     */
238    public Base resolveReference(Object appContext, String url) throws FHIRException;
239    
240    public boolean conformsToProfile(Object appContext, Base item, String url) throws FHIRException;
241    
242    /* 
243     * return the value set referenced by the url, which has been used in memberOf()
244     */
245    public ValueSet resolveValueSet(Object appContext, String url);
246  }
247
248
249  /**
250   * @param worker - used when validating paths (@check), and used doing value set membership when executing tests (once that's defined)
251   */
252  public FHIRPathEngine(IWorkerContext worker) {
253    super();
254    this.worker = worker;
255    for (StructureDefinition sd : worker.getStructures()) {
256      if (sd.getDerivation() == TypeDerivationRule.SPECIALIZATION && sd.getKind() != StructureDefinitionKind.LOGICAL)
257        allTypes.put(sd.getName(), sd);
258      if (sd.getDerivation() == TypeDerivationRule.SPECIALIZATION && sd.getKind() == StructureDefinitionKind.PRIMITIVETYPE) {
259        primitiveTypes.add(sd.getName());
260      }
261    }
262  }
263
264
265  // --- 3 methods to override in children -------------------------------------------------------
266  // if you don't override, it falls through to the using the base reference implementation 
267  // HAPI overrides to these to support extending the base model
268
269  public IEvaluationContext getHostServices() {
270    return hostServices;
271  }
272
273
274  public void setHostServices(IEvaluationContext constantResolver) {
275    this.hostServices = constantResolver;
276  }
277
278
279  /**
280   * Given an item, return all the children that conform to the pattern described in name
281   * 
282   * Possible patterns:
283   *  - a simple name (which may be the base of a name with [] e.g. value[x])
284   *  - a name with a type replacement e.g. valueCodeableConcept
285   *  - * which means all children
286   *  - ** which means all descendants
287   *  
288   * @param item
289   * @param name
290   * @param result
291         * @throws FHIRException 
292   */
293  protected void getChildrenByName(Base item, String name, List<Base> result) throws FHIRException {
294        Base[] list = item.listChildrenByName(name, false);
295        if (list != null)
296                for (Base v : list)
297      if (v != null)
298        result.add(v);
299  }
300
301  
302  public boolean isLegacyMode() {
303    return legacyMode;
304  }
305
306
307  public void setLegacyMode(boolean legacyMode) {
308    this.legacyMode = legacyMode;
309  }
310
311
312  // --- public API -------------------------------------------------------
313  /**
314   * Parse a path for later use using execute
315   * 
316   * @param path
317   * @return
318   * @throws PathEngineException 
319   * @throws Exception
320   */
321  public ExpressionNode parse(String path) throws FHIRLexerException {
322    return parse(path, null);
323  }
324  
325  public ExpressionNode parse(String path, String name) throws FHIRLexerException {
326    FHIRLexer lexer = new FHIRLexer(path, name);
327    if (lexer.done())
328      throw lexer.error("Path cannot be empty");
329    ExpressionNode result = parseExpression(lexer, true);
330    if (!lexer.done())
331      throw lexer.error("Premature ExpressionNode termination at unexpected token \""+lexer.getCurrent()+"\"");
332    result.check();
333    return result;    
334  }
335
336  public static class ExpressionNodeWithOffset {
337    private int offset;
338    private ExpressionNode node;
339    public ExpressionNodeWithOffset(int offset, ExpressionNode node) {
340      super();
341      this.offset = offset;
342      this.node = node;
343    }
344    public int getOffset() {
345      return offset;
346    }
347    public ExpressionNode getNode() {
348      return node;
349    }
350    
351  }
352  /**
353   * Parse a path for later use using execute
354   * 
355   * @param path
356   * @return
357   * @throws PathEngineException 
358   * @throws Exception
359   */
360  public ExpressionNodeWithOffset parsePartial(String path, int i) throws FHIRLexerException {
361    FHIRLexer lexer = new FHIRLexer(path, i);
362    if (lexer.done())
363      throw lexer.error("Path cannot be empty");
364    ExpressionNode result = parseExpression(lexer, true);
365    result.check();
366    return new ExpressionNodeWithOffset(lexer.getCurrentStart(), result);    
367  }
368
369  /**
370   * Parse a path that is part of some other syntax
371   *  
372   * @return
373   * @throws PathEngineException 
374   * @throws Exception
375   */
376  public ExpressionNode parse(FHIRLexer lexer) throws FHIRLexerException {
377    ExpressionNode result = parseExpression(lexer, true);
378    result.check();
379    return result;    
380  }
381
382  /**
383   * check that paths referred to in the ExpressionNode are valid
384   * 
385   * xPathStartsWithValueRef is a hack work around for the fact that FHIR Path sometimes needs a different starting point than the xpath
386   * 
387   * returns a list of the possible types that might be returned by executing the ExpressionNode against a particular context
388   * 
389   * @param context - the logical type against which this path is applied
390   * @throws DefinitionException
391   * @throws PathEngineException 
392   * @if the path is not valid
393   */
394  public TypeDetails check(Object appContext, String resourceType, String context, ExpressionNode expr) throws FHIRLexerException, PathEngineException, DefinitionException {
395    // if context is a path that refers to a type, do that conversion now 
396        TypeDetails types; 
397        if (context == null) {
398          types = null; // this is a special case; the first path reference will have to resolve to something in the context
399        } else if (!context.contains(".")) {
400    StructureDefinition sd = worker.fetchTypeDefinition(context);
401          types = new TypeDetails(CollectionStatus.SINGLETON, sd.getUrl());
402        } else {
403          String ctxt = context.substring(0, context.indexOf('.'));
404      if (Utilities.isAbsoluteUrl(resourceType)) {
405        ctxt = resourceType.substring(0, resourceType.lastIndexOf("/")+1)+ctxt;
406      }
407          StructureDefinition sd = worker.fetchResource(StructureDefinition.class, ctxt);
408          if (sd == null) 
409            throw new PathEngineException("Unknown context "+context);
410          ElementDefinitionMatch ed = getElementDefinition(sd, context, true);
411          if (ed == null) 
412            throw new PathEngineException("Unknown context element "+context);
413          if (ed.fixedType != null) 
414            types = new TypeDetails(CollectionStatus.SINGLETON, ed.fixedType);
415          else if (ed.getDefinition().getType().isEmpty() || isAbstractType(ed.getDefinition().getType())) 
416            types = new TypeDetails(CollectionStatus.SINGLETON, ctxt+"#"+context);
417          else {
418            types = new TypeDetails(CollectionStatus.SINGLETON);
419                for (TypeRefComponent t : ed.getDefinition().getType()) 
420                  types.addType(t.getCode());
421          }
422        }
423
424    return executeType(new ExecutionTypeContext(appContext, resourceType, types, types), types, expr, true);
425  }
426
427  public TypeDetails check(Object appContext, StructureDefinition sd, String context, ExpressionNode expr) throws FHIRLexerException, PathEngineException, DefinitionException {
428    // if context is a path that refers to a type, do that conversion now 
429    TypeDetails types; 
430    if (!context.contains(".")) {
431      types = new TypeDetails(CollectionStatus.SINGLETON, sd.getUrl());
432    } else {
433      ElementDefinitionMatch ed = getElementDefinition(sd, context, true);
434      if (ed == null) 
435        throw new PathEngineException("Unknown context element "+context);
436      if (ed.fixedType != null) 
437        types = new TypeDetails(CollectionStatus.SINGLETON, ed.fixedType);
438      else if (ed.getDefinition().getType().isEmpty() || isAbstractType(ed.getDefinition().getType())) 
439        types = new TypeDetails(CollectionStatus.SINGLETON, sd.getUrl()+"#"+context);
440      else {
441        types = new TypeDetails(CollectionStatus.SINGLETON);
442        for (TypeRefComponent t : ed.getDefinition().getType()) 
443          types.addType(t.getCode());
444      }
445    }
446
447    return executeType(new ExecutionTypeContext(appContext, sd.getUrl(), types, types), types, expr, true);
448  }
449
450  public TypeDetails check(Object appContext, StructureDefinition sd, ExpressionNode expr) throws FHIRLexerException, PathEngineException, DefinitionException {
451    // if context is a path that refers to a type, do that conversion now 
452    TypeDetails types = null; // this is a special case; the first path reference will have to resolve to something in the context
453    return executeType(new ExecutionTypeContext(appContext, sd == null ? null : sd.getUrl(), null, types), types, expr, true);
454  }
455
456  public TypeDetails check(Object appContext, String resourceType, String context, String expr) throws FHIRLexerException, PathEngineException, DefinitionException {
457    return check(appContext, resourceType, context, parse(expr));
458  }
459
460  private int compareDateTimeElements(Base theL, Base theR, boolean theEquivalenceTest) {
461    String dateLeftString = theL.primitiveValue();
462    DateTimeType dateLeft = new DateTimeType(dateLeftString);
463
464    String dateRightString = theR.primitiveValue();
465    DateTimeType dateRight = new DateTimeType(dateRightString);
466
467    if (theEquivalenceTest) {
468      return dateLeft.equalsUsingFhirPathRules(dateRight) == Boolean.TRUE ? 0 : 1;
469    }
470
471    if (dateLeft.getPrecision().ordinal() > TemporalPrecisionEnum.DAY.ordinal()) {
472      dateLeft.setTimeZoneZulu(true);
473    }
474    if (dateRight.getPrecision().ordinal() > TemporalPrecisionEnum.DAY.ordinal()) {
475      dateRight.setTimeZoneZulu(true);
476    }
477
478    dateLeftString = dateLeft.getValueAsString();
479    dateRightString = dateRight.getValueAsString();
480
481    return dateLeftString.compareTo(dateRightString);
482  }
483
484  /**
485   * evaluate a path and return the matching elements
486   * 
487   * @param base - the object against which the path is being evaluated
488   * @param ExpressionNode - the parsed ExpressionNode statement to use
489   * @return
490   * @throws FHIRException 
491   * @
492   */
493        public List<Base> evaluate(Base base, ExpressionNode ExpressionNode) throws FHIRException {
494    List<Base> list = new ArrayList<Base>();
495    if (base != null)
496      list.add(base);
497    log = new StringBuilder();
498    return execute(new ExecutionContext(null, base != null && base.isResource() ? base : null, base != null && base.isResource() ? base : null, base, null, base), list, ExpressionNode, true);
499  }
500
501  /**
502   * evaluate a path and return the matching elements
503   * 
504   * @param base - the object against which the path is being evaluated
505   * @param path - the FHIR Path statement to use
506   * @return
507         * @throws FHIRException 
508   * @
509   */
510        public List<Base> evaluate(Base base, String path) throws FHIRException {
511    ExpressionNode exp = parse(path);
512    List<Base> list = new ArrayList<Base>();
513    if (base != null)
514      list.add(base);
515    log = new StringBuilder();
516    return execute(new ExecutionContext(null, base.isResource() ? base : null, base.isResource() ? base : null, base, null, base), list, exp, true);
517  }
518
519  /**
520   * evaluate a path and return the matching elements
521   * 
522   * @param base - the object against which the path is being evaluated
523   * @param ExpressionNode - the parsed ExpressionNode statement to use
524   * @return
525         * @throws FHIRException 
526   * @
527   */
528        public List<Base> evaluate(Object appContext, Resource focusResource, Resource rootResource, Base base, ExpressionNode ExpressionNode) throws FHIRException {
529    List<Base> list = new ArrayList<Base>();
530    if (base != null)
531      list.add(base);
532    log = new StringBuilder();
533    return execute(new ExecutionContext(appContext, focusResource, rootResource, base, null, base), list, ExpressionNode, true);
534  }
535
536  /**
537   * evaluate a path and return the matching elements
538   * 
539   * @param base - the object against which the path is being evaluated
540   * @param ExpressionNode - the parsed ExpressionNode statement to use
541   * @return
542   * @throws FHIRException 
543   * @
544   */
545  public List<Base> evaluate(Object appContext, Base focusResource, Base rootResource, Base base, ExpressionNode ExpressionNode) throws FHIRException {
546    List<Base> list = new ArrayList<Base>();
547    if (base != null)
548      list.add(base);
549    log = new StringBuilder();
550    return execute(new ExecutionContext(appContext, focusResource, rootResource, base, null, base), list, ExpressionNode, true);
551  }
552
553  /**
554   * evaluate a path and return the matching elements
555   * 
556   * @param base - the object against which the path is being evaluated
557   * @param path - the FHIR Path statement to use
558   * @return
559         * @throws FHIRException 
560   * @
561   */
562        public List<Base> evaluate(Object appContext, Resource focusResource, Resource rootResource, Base base, String path) throws FHIRException {
563    ExpressionNode exp = parse(path);
564    List<Base> list = new ArrayList<Base>();
565    if (base != null)
566      list.add(base);
567    log = new StringBuilder();
568    return execute(new ExecutionContext(appContext, focusResource, rootResource, base, null, base), list, exp, true);
569  }
570
571  /**
572   * evaluate a path and return true or false (e.g. for an invariant)
573   * 
574   * @param base - the object against which the path is being evaluated
575   * @param path - the FHIR Path statement to use
576   * @return
577         * @throws FHIRException 
578   * @
579   */
580        public boolean evaluateToBoolean(Resource focusResource, Resource rootResource, Base base, String path) throws FHIRException {
581    return convertToBoolean(evaluate(null, focusResource, rootResource, base, path));
582  }
583
584  /**
585   * evaluate a path and return true or false (e.g. for an invariant)
586   * 
587   * @param base - the object against which the path is being evaluated
588   * @return
589   * @throws FHIRException 
590   * @
591   */
592  public boolean evaluateToBoolean(Resource focusResource, Resource rootResource, Base base, ExpressionNode node) throws FHIRException {
593    return convertToBoolean(evaluate(null, focusResource, rootResource, base, node));
594  }
595
596  /**
597   * evaluate a path and return true or false (e.g. for an invariant)
598   * 
599   * @param appInfo - application context
600   * @param base - the object against which the path is being evaluated
601   * @return
602   * @throws FHIRException 
603   * @
604   */
605  public boolean evaluateToBoolean(Object appInfo, Resource focusResource, Resource rootResource, Base base, ExpressionNode node) throws FHIRException {
606    return convertToBoolean(evaluate(appInfo, focusResource, rootResource, base, node));
607  }
608
609  /**
610   * evaluate a path and return true or false (e.g. for an invariant)
611   * 
612   * @param base - the object against which the path is being evaluated
613   * @return
614   * @throws FHIRException 
615   * @
616   */
617  public boolean evaluateToBoolean(Object appInfo, Base focusResource, Base rootResource, Base base, ExpressionNode node) throws FHIRException {
618    return convertToBoolean(evaluate(appInfo, focusResource, rootResource, base, node));
619  }
620
621  /**
622   * evaluate a path and a string containing the outcome (for display)
623   * 
624   * @param base - the object against which the path is being evaluated
625   * @param path - the FHIR Path statement to use
626   * @return
627         * @throws FHIRException 
628   * @
629   */
630  public String evaluateToString(Base base, String path) throws FHIRException {
631    return convertToString(evaluate(base, path));
632  }
633
634  public String evaluateToString(Object appInfo, Base focusResource, Base rootResource, Base base, ExpressionNode node) throws FHIRException {
635    return convertToString(evaluate(appInfo, focusResource, rootResource, base, node));
636  }
637
638  /**
639   * worker routine for converting a set of objects to a string representation
640   * 
641   * @param items - result from @evaluate
642   * @return
643   */
644  public String convertToString(List<Base> items) {
645    StringBuilder b = new StringBuilder();
646    boolean first = true;
647    for (Base item : items) {
648      if (first) 
649        first = false;
650      else
651        b.append(',');
652
653      b.append(convertToString(item));
654    }
655    return b.toString();
656  }
657
658  public String convertToString(Base item) {
659    if (item.isPrimitive())
660      return item.primitiveValue();
661    else if (item instanceof Quantity) {
662      Quantity q = (Quantity) item;
663      if (q.getSystem().equals("http://unitsofmeasure.org")) {
664        String u = "'"+q.getCode()+"'";
665        return q.getValue().toPlainString()+" "+u;
666      }
667      else
668        return item.toString();
669    } else
670      return item.toString();
671  }
672
673  /**
674   * worker routine for converting a set of objects to a boolean representation (for invariants)
675   * 
676   * @param items - result from @evaluate
677   * @return
678   */
679  public boolean convertToBoolean(List<Base> items) {
680    if (items == null)
681      return false;
682    else if (items.size() == 1 && items.get(0) instanceof BooleanType)
683      return ((BooleanType) items.get(0)).getValue();
684    else if (items.size() == 1 && items.get(0).isBooleanPrimitive()) // element model
685      return Boolean.valueOf(items.get(0).primitiveValue());
686    else 
687      return items.size() > 0;
688  }
689
690
691  private void log(String name, List<Base> contents) {
692    if (hostServices == null || !hostServices.log(name, contents)) {
693      if (log.length() > 0)
694        log.append("; ");
695      log.append(name);
696      log.append(": ");
697      boolean first = true;
698      for (Base b : contents) {
699        if (first)
700          first = false;
701        else
702          log.append(",");
703        log.append(convertToString(b));
704      }
705    }
706  }
707
708  public String forLog() {
709    if (log.length() > 0)
710      return " ("+log.toString()+")";
711    else
712      return "";
713  }
714
715  private class ExecutionContext {
716    private Object appInfo;
717    private Base focusResource;
718    private Base rootResource;
719    private Base context;
720    private Base thisItem;
721    private List<Base> total;
722    private Map<String, Base> aliases;
723    
724    public ExecutionContext(Object appInfo, Base resource, Base rootResource, Base context, Map<String, Base> aliases, Base thisItem) {
725      this.appInfo = appInfo;
726      this.context = context;
727      this.focusResource = resource; 
728      this.rootResource = rootResource; 
729      this.aliases = aliases;
730      this.thisItem = thisItem;
731    }
732    public Base getFocusResource() {
733      return focusResource;
734    }
735    public Base getRootResource() {
736        return rootResource;
737    }
738    public Base getThisItem() {
739      return thisItem;
740    }
741    public List<Base> getTotal() {
742      return total;
743    }
744    public void addAlias(String name, List<Base> focus) throws FHIRException {
745      if (aliases == null)
746        aliases = new HashMap<String, Base>();
747      else
748        aliases = new HashMap<String, Base>(aliases); // clone it, since it's going to change 
749      if (focus.size() > 1)
750        throw new FHIRException("Attempt to alias a collection, not a singleton");
751      aliases.put(name, focus.size() == 0 ? null : focus.get(0));      
752    }
753    public Base getAlias(String name) {
754      return aliases == null ? null : aliases.get(name);
755    }
756  }
757
758  private class ExecutionTypeContext {
759    private Object appInfo; 
760    private String resource;
761    private TypeDetails context;
762    private TypeDetails thisItem;
763    private TypeDetails total;
764
765
766    public ExecutionTypeContext(Object appInfo, String resource, TypeDetails context, TypeDetails thisItem) {
767      super();
768      this.appInfo = appInfo;
769      this.resource = resource;
770      this.context = context;
771      this.thisItem = thisItem;
772      
773    }
774    public String getResource() {
775      return resource;
776    }
777    public TypeDetails getThisItem() {
778      return thisItem;
779    }
780
781    
782  }
783
784  private ExpressionNode parseExpression(FHIRLexer lexer, boolean proximal) throws FHIRLexerException {
785    ExpressionNode result = new ExpressionNode(lexer.nextId());
786    ExpressionNode wrapper = null;
787    SourceLocation c = lexer.getCurrentStartLocation();
788    result.setStart(lexer.getCurrentLocation());
789    // special: +/- represents a unary operation at this point, but cannot be a feature of the lexer, since that's not always true.
790    // so we back correct for both +/- and as part of a numeric constant below.
791    
792    // special: +/- represents a unary operation at this point, but cannot be a feature of the lexer, since that's not always true.
793    // so we back correct for both +/- and as part of a numeric constant below.
794    if (Utilities.existsInList(lexer.getCurrent(), "-", "+")) {
795      wrapper = new ExpressionNode(lexer.nextId());
796      wrapper.setKind(Kind.Unary);
797      wrapper.setOperation(ExpressionNode.Operation.fromCode(lexer.take()));
798      wrapper.setProximal(proximal);
799    }
800
801    if (lexer.isConstant()) {
802      boolean isString = lexer.isStringConstant();
803      if (!isString && (lexer.getCurrent().startsWith("-") || lexer.getCurrent().startsWith("+"))) {
804        // the grammar says that this is a unary operation; it affects the correct processing order of the inner operations
805        wrapper = new ExpressionNode(lexer.nextId());
806        wrapper.setKind(Kind.Unary);
807        wrapper.setOperation(ExpressionNode.Operation.fromCode(lexer.getCurrent().substring(0, 1)));
808        wrapper.setProximal(proximal);
809        lexer.setCurrent(lexer.getCurrent().substring(1));
810      }
811      result.setConstant(processConstant(lexer));
812      result.setKind(Kind.Constant);
813      if (!isString && !lexer.done() && (result.getConstant() instanceof IntegerType || result.getConstant() instanceof DecimalType) && (lexer.isStringConstant() || lexer.hasToken("year", "years", "month", "months", "week", "weeks", "day", "days", "hour", "hours", "minute", "minutes", "second", "seconds", "millisecond", "milliseconds"))) {
814        // it's a quantity
815        String ucum = null;
816        if (lexer.hasToken("year", "years", "month", "months", "week", "weeks", "day", "days", "hour", "hours", "minute", "minutes", "second", "seconds", "millisecond", "milliseconds")) {
817          String s = lexer.take();
818          if (s.equals("year") || s.equals("years"))
819            ucum = "a";
820          else if (s.equals("month") || s.equals("months"))
821            ucum = "mo";
822          else if (s.equals("week") || s.equals("weeks"))
823            ucum = "wk";
824          else if (s.equals("day") || s.equals("days"))
825            ucum = "d";
826          else if (s.equals("hour") || s.equals("hours"))
827            ucum = "h";
828          else if (s.equals("minute") || s.equals("minutes"))
829            ucum = "min";
830          else if (s.equals("second") || s.equals("seconds"))
831            ucum = "s";
832          else // (s.equals("millisecond") || s.equals("milliseconds"))
833            ucum = "ms";
834        } else 
835          ucum = lexer.readConstant("units");
836        result.setConstant(new Quantity().setValue(new BigDecimal(result.getConstant().primitiveValue())).setSystem("http://unitsofmeasure.org").setCode(ucum));
837      }
838      result.setEnd(lexer.getCurrentLocation());
839    } else if ("(".equals(lexer.getCurrent())) {
840      lexer.next();
841      result.setKind(Kind.Group);
842      result.setGroup(parseExpression(lexer, true));
843      if (!")".equals(lexer.getCurrent())) 
844        throw lexer.error("Found "+lexer.getCurrent()+" expecting a \")\"");
845      result.setEnd(lexer.getCurrentLocation());
846      lexer.next();
847    } else {
848      if (!lexer.isToken() && !lexer.getCurrent().startsWith("`")) 
849        throw lexer.error("Found "+lexer.getCurrent()+" expecting a token name");
850      if (lexer.isFixedName())
851        result.setName(lexer.readFixedName("Path Name"));
852      else
853        result.setName(lexer.take());
854      result.setEnd(lexer.getCurrentLocation());
855      if (!result.checkName())
856        throw lexer.error("Found "+result.getName()+" expecting a valid token name");
857      if ("(".equals(lexer.getCurrent())) {
858        Function f = Function.fromCode(result.getName());
859        FunctionDetails details = null;
860        if (f == null) {
861          if (hostServices != null)
862            details = hostServices.resolveFunction(result.getName());
863          if (details == null)
864            throw lexer.error("The name "+result.getName()+" is not a valid function name");
865          f = Function.Custom;
866        }
867        result.setKind(Kind.Function);
868        result.setFunction(f);
869        lexer.next();
870        while (!")".equals(lexer.getCurrent())) { 
871          result.getParameters().add(parseExpression(lexer, true));
872          if (",".equals(lexer.getCurrent()))
873            lexer.next();
874          else if (!")".equals(lexer.getCurrent()))
875            throw lexer.error("The token "+lexer.getCurrent()+" is not expected here - either a \",\" or a \")\" expected");
876        }
877        result.setEnd(lexer.getCurrentLocation());
878        lexer.next();
879        checkParameters(lexer, c, result, details);
880      } else
881        result.setKind(Kind.Name);
882    }
883    ExpressionNode focus = result;
884    if ("[".equals(lexer.getCurrent())) {
885      lexer.next();
886      ExpressionNode item = new ExpressionNode(lexer.nextId());
887      item.setKind(Kind.Function);
888      item.setFunction(ExpressionNode.Function.Item);
889      item.getParameters().add(parseExpression(lexer, true));
890      if (!lexer.getCurrent().equals("]"))
891        throw lexer.error("The token "+lexer.getCurrent()+" is not expected here - a \"]\" expected");
892      lexer.next();
893      result.setInner(item);
894      focus = item;
895    }
896    if (".".equals(lexer.getCurrent())) {
897      lexer.next();
898      focus.setInner(parseExpression(lexer, false));
899    }
900    result.setProximal(proximal);
901    if (proximal) {
902      while (lexer.isOp()) {
903        focus.setOperation(ExpressionNode.Operation.fromCode(lexer.getCurrent()));
904        focus.setOpStart(lexer.getCurrentStartLocation());
905        focus.setOpEnd(lexer.getCurrentLocation());
906        lexer.next();
907        focus.setOpNext(parseExpression(lexer, false));
908        focus = focus.getOpNext();
909      }
910      result = organisePrecedence(lexer, result);
911    }
912    if (wrapper != null) {
913      wrapper.setOpNext(result);
914      result.setProximal(false);
915      result = wrapper;
916    }
917    return result;
918  }
919
920  private ExpressionNode organisePrecedence(FHIRLexer lexer, ExpressionNode node) {
921    node = gatherPrecedence(lexer, node, EnumSet.of(Operation.Times, Operation.DivideBy, Operation.Div, Operation.Mod)); 
922    node = gatherPrecedence(lexer, node, EnumSet.of(Operation.Plus, Operation.Minus, Operation.Concatenate)); 
923    node = gatherPrecedence(lexer, node, EnumSet.of(Operation.Union)); 
924    node = gatherPrecedence(lexer, node, EnumSet.of(Operation.LessThan, Operation.Greater, Operation.LessOrEqual, Operation.GreaterOrEqual));
925    node = gatherPrecedence(lexer, node, EnumSet.of(Operation.Is));
926    node = gatherPrecedence(lexer, node, EnumSet.of(Operation.Equals, Operation.Equivalent, Operation.NotEquals, Operation.NotEquivalent));
927    node = gatherPrecedence(lexer, node, EnumSet.of(Operation.And));
928    node = gatherPrecedence(lexer, node, EnumSet.of(Operation.Xor, Operation.Or));
929    // last: implies
930    return node;
931  }
932
933  private ExpressionNode gatherPrecedence(FHIRLexer lexer, ExpressionNode start, EnumSet<Operation> ops) {
934    //    work : boolean;
935    //    focus, node, group : ExpressionNode;
936
937    assert(start.isProximal());
938
939    // is there anything to do?
940    boolean work = false;
941    ExpressionNode focus = start.getOpNext();
942    if (ops.contains(start.getOperation())) {
943      while (focus != null && focus.getOperation() != null) {
944        work = work || !ops.contains(focus.getOperation());
945        focus = focus.getOpNext();
946      }
947    } else {
948      while (focus != null && focus.getOperation() != null) {
949        work = work || ops.contains(focus.getOperation());
950        focus = focus.getOpNext();
951      }
952    }  
953    if (!work)
954      return start;
955
956    // entry point: tricky
957    ExpressionNode group;
958    if (ops.contains(start.getOperation())) {
959      group = newGroup(lexer, start);
960      group.setProximal(true);
961      focus = start;
962      start = group;
963    } else {
964      ExpressionNode node = start;
965
966      focus = node.getOpNext();
967      while (!ops.contains(focus.getOperation())) {
968        node = focus;
969        focus = focus.getOpNext();
970      }
971      group = newGroup(lexer, focus);
972      node.setOpNext(group);
973    }
974
975    // now, at this point:
976    //   group is the group we are adding to, it already has a .group property filled out.
977    //   focus points at the group.group
978    do {
979      // run until we find the end of the sequence
980      while (ops.contains(focus.getOperation()))
981        focus = focus.getOpNext();
982      if (focus.getOperation() != null) {
983        group.setOperation(focus.getOperation());
984        group.setOpNext(focus.getOpNext());
985        focus.setOperation(null);
986        focus.setOpNext(null);
987        // now look for another sequence, and start it
988        ExpressionNode node = group;
989        focus = group.getOpNext();
990        if (focus != null) { 
991          while (focus != null && !ops.contains(focus.getOperation())) {
992            node = focus;
993            focus = focus.getOpNext();
994          }
995          if (focus != null) { // && (focus.Operation in Ops) - must be true 
996            group = newGroup(lexer, focus);
997            node.setOpNext(group);
998          }
999        }
1000      }
1001    }
1002    while (focus != null && focus.getOperation() != null);
1003    return start;
1004  }
1005
1006
1007  private ExpressionNode newGroup(FHIRLexer lexer, ExpressionNode next) {
1008    ExpressionNode result = new ExpressionNode(lexer.nextId());
1009    result.setKind(Kind.Group);
1010    result.setGroup(next);
1011    result.getGroup().setProximal(true);
1012    return result;
1013  }
1014
1015  private Base processConstant(FHIRLexer lexer) throws FHIRLexerException {
1016    if (lexer.isStringConstant()) {
1017      return new StringType(processConstantString(lexer.take(), lexer)).noExtensions();
1018    } else if (Utilities.isInteger(lexer.getCurrent())) {
1019      return new IntegerType(lexer.take()).noExtensions();
1020    } else if (Utilities.isDecimal(lexer.getCurrent(), false)) {
1021      return new DecimalType(lexer.take()).noExtensions();
1022    } else if (Utilities.existsInList(lexer.getCurrent(), "true", "false")) {
1023      return new BooleanType(lexer.take()).noExtensions();
1024    } else if (lexer.getCurrent().equals("{}")) {
1025      lexer.take();
1026      return null;
1027    } else if (lexer.getCurrent().startsWith("%") || lexer.getCurrent().startsWith("@")) {
1028      return new FHIRConstant(lexer.take());
1029    } else
1030      throw lexer.error("Invalid Constant "+lexer.getCurrent());
1031  }
1032
1033  //  procedure CheckParamCount(c : integer);
1034  //  begin
1035  //    if exp.Parameters.Count <> c then
1036  //      raise lexer.error('The function "'+exp.name+'" requires '+inttostr(c)+' parameters', offset);
1037  //  end;
1038
1039  private boolean checkParamCount(FHIRLexer lexer, SourceLocation location, ExpressionNode exp, int count) throws FHIRLexerException {
1040    if (exp.getParameters().size() != count)
1041      throw lexer.error("The function \""+exp.getName()+"\" requires "+Integer.toString(count)+" parameters", location.toString());
1042    return true;
1043  }
1044
1045  private boolean checkParamCount(FHIRLexer lexer, SourceLocation location, ExpressionNode exp, int countMin, int countMax) throws FHIRLexerException {
1046    if (exp.getParameters().size() < countMin || exp.getParameters().size() > countMax)
1047      throw lexer.error("The function \""+exp.getName()+"\" requires between "+Integer.toString(countMin)+" and "+Integer.toString(countMax)+" parameters", location.toString());
1048    return true;
1049  }
1050
1051  private boolean checkParameters(FHIRLexer lexer, SourceLocation location, ExpressionNode exp, FunctionDetails details) throws FHIRLexerException {
1052    switch (exp.getFunction()) {
1053    case Empty: return checkParamCount(lexer, location, exp, 0);
1054    case Not: return checkParamCount(lexer, location, exp, 0);
1055    case Exists: return checkParamCount(lexer, location, exp, 0);
1056    case SubsetOf: return checkParamCount(lexer, location, exp, 1);
1057    case SupersetOf: return checkParamCount(lexer, location, exp, 1);
1058    case IsDistinct: return checkParamCount(lexer, location, exp, 0);
1059    case Distinct: return checkParamCount(lexer, location, exp, 0);
1060    case Count: return checkParamCount(lexer, location, exp, 0);
1061    case Where: return checkParamCount(lexer, location, exp, 1);
1062    case Select: return checkParamCount(lexer, location, exp, 1);
1063    case All: return checkParamCount(lexer, location, exp, 0, 1);
1064    case Repeat: return checkParamCount(lexer, location, exp, 1);
1065    case Aggregate: return checkParamCount(lexer, location, exp, 1, 2);
1066    case Item: return checkParamCount(lexer, location, exp, 1);
1067    case As: return checkParamCount(lexer, location, exp, 1);
1068    case OfType: return checkParamCount(lexer, location, exp, 1);
1069    case Type: return checkParamCount(lexer, location, exp, 0);
1070    case Is: return checkParamCount(lexer, location, exp, 1);
1071    case Single: return checkParamCount(lexer, location, exp, 0);
1072    case First: return checkParamCount(lexer, location, exp, 0);
1073    case Last: return checkParamCount(lexer, location, exp, 0);
1074    case Tail: return checkParamCount(lexer, location, exp, 0);
1075    case Skip: return checkParamCount(lexer, location, exp, 1);
1076    case Take: return checkParamCount(lexer, location, exp, 1);
1077    case Union: return checkParamCount(lexer, location, exp, 1);
1078    case Combine: return checkParamCount(lexer, location, exp, 1);
1079    case Intersect: return checkParamCount(lexer, location, exp, 1);
1080    case Exclude: return checkParamCount(lexer, location, exp, 1);
1081    case Iif: return checkParamCount(lexer, location, exp, 2,3);
1082    case Lower: return checkParamCount(lexer, location, exp, 0);
1083    case Upper: return checkParamCount(lexer, location, exp, 0);
1084    case ToChars: return checkParamCount(lexer, location, exp, 0);
1085    case IndexOf : return checkParamCount(lexer, location, exp, 1);
1086    case Substring: return checkParamCount(lexer, location, exp, 1, 2);
1087    case StartsWith: return checkParamCount(lexer, location, exp, 1);
1088    case EndsWith: return checkParamCount(lexer, location, exp, 1);
1089    case Matches: return checkParamCount(lexer, location, exp, 1);
1090    case ReplaceMatches: return checkParamCount(lexer, location, exp, 2);
1091    case Contains: return checkParamCount(lexer, location, exp, 1);
1092    case Replace: return checkParamCount(lexer, location, exp, 2);
1093    case Length: return checkParamCount(lexer, location, exp, 0);
1094    case Children: return checkParamCount(lexer, location, exp, 0);
1095    case Descendants: return checkParamCount(lexer, location, exp, 0);
1096    case MemberOf: return checkParamCount(lexer, location, exp, 1);
1097    case Trace: return checkParamCount(lexer, location, exp, 1, 2);
1098    case Check: return checkParamCount(lexer, location, exp, 2);
1099    case Today: return checkParamCount(lexer, location, exp, 0);
1100    case Now: return checkParamCount(lexer, location, exp, 0);
1101    case Resolve: return checkParamCount(lexer, location, exp, 0);
1102    case Extension: return checkParamCount(lexer, location, exp, 1);
1103    case AllFalse: return checkParamCount(lexer, location, exp, 0);
1104    case AnyFalse: return checkParamCount(lexer, location, exp, 0);
1105    case AllTrue: return checkParamCount(lexer, location, exp, 0);
1106    case AnyTrue: return checkParamCount(lexer, location, exp, 0);
1107    case HasValue: return checkParamCount(lexer, location, exp, 0);
1108    case Alias: return checkParamCount(lexer, location, exp, 1);
1109    case AliasAs: return checkParamCount(lexer, location, exp, 1);
1110    case HtmlChecks: return checkParamCount(lexer, location, exp, 0);
1111    case ToInteger: return checkParamCount(lexer, location, exp, 0);
1112    case ToDecimal: return checkParamCount(lexer, location, exp, 0);
1113    case ToString: return checkParamCount(lexer, location, exp, 0);
1114    case ToQuantity: return checkParamCount(lexer, location, exp, 0);
1115    case ToBoolean: return checkParamCount(lexer, location, exp, 0);
1116    case ToDateTime: return checkParamCount(lexer, location, exp, 0);
1117    case ToTime: return checkParamCount(lexer, location, exp, 0);
1118    case ConvertsToInteger: return checkParamCount(lexer, location, exp, 0);
1119    case ConvertsToDecimal: return checkParamCount(lexer, location, exp, 0);
1120    case ConvertsToString: return checkParamCount(lexer, location, exp, 0);
1121    case ConvertsToQuantity: return checkParamCount(lexer, location, exp, 0);
1122    case ConvertsToBoolean: return checkParamCount(lexer, location, exp, 0);
1123    case ConvertsToDateTime: return checkParamCount(lexer, location, exp, 0);
1124    case ConvertsToTime: return checkParamCount(lexer, location, exp, 0);
1125    case ConformsTo: return checkParamCount(lexer, location, exp, 1);
1126    case Custom: return checkParamCount(lexer, location, exp, details.getMinParameters(), details.getMaxParameters());
1127    }
1128    return false;
1129  }
1130
1131        private List<Base> execute(ExecutionContext context, List<Base> focus, ExpressionNode exp, boolean atEntry) throws FHIRException {
1132//    System.out.println("Evaluate {'"+exp.toString()+"'} on "+focus.toString());
1133    List<Base> work = new ArrayList<Base>();
1134    switch (exp.getKind()) {
1135    case Unary:
1136      work.add(new IntegerType(0));
1137      break;
1138    case Name:
1139      if (atEntry && exp.getName().equals("$this"))
1140        work.add(context.getThisItem());
1141      else if (atEntry && exp.getName().equals("$total"))
1142        work.addAll(context.getTotal());
1143      else
1144        for (Base item : focus) {
1145          List<Base> outcome = execute(context, item, exp, atEntry);
1146          for (Base base : outcome)
1147            if (base != null)
1148              work.add(base);
1149        }                       
1150      break;
1151    case Function:
1152      List<Base> work2 = evaluateFunction(context, focus, exp);
1153      work.addAll(work2);
1154      break;
1155    case Constant:
1156      Base b = resolveConstant(context, exp.getConstant(), false);
1157      if (b != null)
1158        work.add(b);
1159      break;
1160    case Group:
1161      work2 = execute(context, focus, exp.getGroup(), atEntry);
1162      work.addAll(work2);
1163    }
1164
1165    if (exp.getInner() != null)
1166      work = execute(context, work, exp.getInner(), false);
1167
1168    if (exp.isProximal() && exp.getOperation() != null) {
1169      ExpressionNode next = exp.getOpNext();
1170      ExpressionNode last = exp;
1171      while (next != null) {
1172        List<Base> work2 = preOperate(work, last.getOperation());
1173        if (work2 != null)
1174          work = work2;
1175        else if (last.getOperation() == Operation.Is || last.getOperation() == Operation.As) {
1176          work2 = executeTypeName(context, focus, next, false);
1177          work = operate(context, work, last.getOperation(), work2);
1178        } else {
1179          work2 = execute(context, focus, next, true);
1180          work = operate(context, work, last.getOperation(), work2);
1181//          System.out.println("Result of {'"+last.toString()+" "+last.getOperation().toCode()+" "+next.toString()+"'}: "+focus.toString());
1182        }
1183        last = next;
1184        next = next.getOpNext();
1185      }
1186    }
1187//    System.out.println("Result of {'"+exp.toString()+"'}: "+work.toString());
1188    return work;
1189  }
1190
1191  private List<Base> executeTypeName(ExecutionContext context, List<Base> focus, ExpressionNode next, boolean atEntry) {
1192    List<Base> result = new ArrayList<Base>();
1193    if (next.getInner() != null)
1194      result.add(new StringType(next.getName()+"."+next.getInner().getName()));
1195    else 
1196      result.add(new StringType(next.getName()));
1197    return result;
1198  }
1199
1200
1201  private List<Base> preOperate(List<Base> left, Operation operation) throws PathEngineException {
1202    if (left.size() == 0)
1203      return null;
1204    switch (operation) {
1205    case And:
1206      return isBoolean(left, false) ? makeBoolean(false) : null;
1207    case Or:
1208      return isBoolean(left, true) ? makeBoolean(true) : null;
1209    case Implies:
1210      Equality v = asBool(left); 
1211      return v == Equality.False ? makeBoolean(true) : null;
1212    default: 
1213      return null;
1214    }
1215  }
1216
1217  private List<Base> makeBoolean(boolean b) {
1218    List<Base> res = new ArrayList<Base>();
1219    res.add(new BooleanType(b).noExtensions());
1220    return res;
1221  }
1222
1223  private List<Base> makeNull() {
1224    List<Base> res = new ArrayList<Base>();
1225    return res;
1226  }
1227
1228  private TypeDetails executeTypeName(ExecutionTypeContext context, TypeDetails focus, ExpressionNode exp, boolean atEntry) throws PathEngineException, DefinitionException {
1229    return new TypeDetails(CollectionStatus.SINGLETON, exp.getName());
1230  }
1231
1232  private TypeDetails executeType(ExecutionTypeContext context, TypeDetails focus, ExpressionNode exp, boolean atEntry) throws PathEngineException, DefinitionException {
1233    TypeDetails result = new TypeDetails(null);
1234    switch (exp.getKind()) {
1235    case Name:
1236      if (atEntry && exp.getName().equals("$this"))
1237        result.update(context.getThisItem());
1238      else if (atEntry && exp.getName().equals("$total"))
1239        result.update(anything(CollectionStatus.UNORDERED));
1240      else if (atEntry && focus == null)
1241        result.update(executeContextType(context, exp.getName()));
1242      else {
1243        for (String s : focus.getTypes()) {
1244          result.update(executeType(s, exp, atEntry));
1245        }
1246        if (result.hasNoTypes()) 
1247          throw new PathEngineException("The name '"+exp.getName()+"' is not valid for any of the possible types: "+focus.describe());
1248      }
1249      break;
1250    case Function:
1251      result.update(evaluateFunctionType(context, focus, exp));
1252      break;
1253    case Unary:
1254      result.addType("integer");
1255      break;
1256    case Constant:
1257      result.update(resolveConstantType(context, exp.getConstant()));
1258      break;
1259    case Group:
1260      result.update(executeType(context, focus, exp.getGroup(), atEntry));
1261    }
1262    exp.setTypes(result);
1263
1264    if (exp.getInner() != null) {
1265      result = executeType(context, result, exp.getInner(), false);
1266    }
1267
1268    if (exp.isProximal() && exp.getOperation() != null) {
1269      ExpressionNode next = exp.getOpNext();
1270      ExpressionNode last = exp;
1271      while (next != null) {
1272        TypeDetails work;
1273        if (last.getOperation() == Operation.Is || last.getOperation() == Operation.As)
1274          work = executeTypeName(context, focus, next, atEntry);
1275        else
1276          work = executeType(context, focus, next, atEntry);
1277        result = operateTypes(result, last.getOperation(), work);
1278        last = next;
1279        next = next.getOpNext();
1280      }
1281      exp.setOpTypes(result);
1282    }
1283    return result;
1284  }
1285
1286  private Base resolveConstant(ExecutionContext context, Base constant, boolean beforeContext) throws PathEngineException {
1287    if (!(constant instanceof FHIRConstant))
1288      return constant;
1289    FHIRConstant c = (FHIRConstant) constant;
1290    if (c.getValue().startsWith("%")) {
1291      return resolveConstant(context, c.getValue(), beforeContext);
1292    } else if (c.getValue().startsWith("@")) {
1293      return processDateConstant(context.appInfo, c.getValue().substring(1));
1294    } else 
1295      throw new PathEngineException("Invaild FHIR Constant "+c.getValue());
1296  }
1297
1298  private Base processDateConstant(Object appInfo, String value) throws PathEngineException {
1299    if (value.startsWith("T"))
1300      return new TimeType(value.substring(1)).noExtensions();
1301    String v = value;
1302    if (v.length() > 10) {
1303      int i = v.substring(10).indexOf("-");
1304      if (i == -1)
1305        i = v.substring(10).indexOf("+");
1306      if (i == -1)
1307        i = v.substring(10).indexOf("Z");
1308      v = i == -1 ? value : v.substring(0,  10+i);
1309    }
1310    if (v.length() > 10)
1311      return new DateTimeType(value).noExtensions();
1312    else 
1313      return new DateType(value).noExtensions();
1314  }
1315
1316
1317  private Base resolveConstant(ExecutionContext context, String s, boolean beforeContext) throws PathEngineException {
1318    if (s.equals("%sct"))
1319      return new StringType("http://snomed.info/sct").noExtensions();
1320    else if (s.equals("%loinc"))
1321      return new StringType("http://loinc.org").noExtensions();
1322    else if (s.equals("%ucum"))
1323      return new StringType("http://unitsofmeasure.org").noExtensions();
1324    else if (s.equals("%resource")) {
1325      if (context.focusResource == null)
1326        throw new PathEngineException("Cannot use %resource in this context");
1327      return context.focusResource;
1328    } else if (s.equals("%rootResource")) {
1329      if (context.rootResource == null)
1330        throw new PathEngineException("Cannot use %rootResource in this context");
1331      return context.rootResource;
1332    } else if (s.equals("%context")) {
1333      return context.context;
1334    } else if (s.equals("%us-zip"))
1335      return new StringType("[0-9]{5}(-[0-9]{4}){0,1}").noExtensions();
1336    else if (s.startsWith("%`vs-"))
1337      return new StringType("http://hl7.org/fhir/ValueSet/"+s.substring(5, s.length()-1)+"").noExtensions();
1338    else if (s.startsWith("%`cs-"))
1339      return new StringType("http://hl7.org/fhir/"+s.substring(5, s.length()-1)+"").noExtensions();
1340    else if (s.startsWith("%`ext-"))
1341      return new StringType("http://hl7.org/fhir/StructureDefinition/"+s.substring(6, s.length()-1)).noExtensions();
1342    else if (hostServices == null)
1343      throw new PathEngineException("Unknown fixed constant '"+s+"'");
1344    else
1345      return hostServices.resolveConstant(context.appInfo, s.substring(1), beforeContext);
1346  }
1347
1348
1349  private String processConstantString(String s, FHIRLexer lexer) throws FHIRLexerException {
1350    StringBuilder b = new StringBuilder();
1351    int i = 1;
1352    while (i < s.length()-1) {
1353      char ch = s.charAt(i);
1354      if (ch == '\\') {
1355        i++;
1356        switch (s.charAt(i)) {
1357        case 't': 
1358          b.append('\t');
1359          break;
1360        case 'r':
1361          b.append('\r');
1362          break;
1363        case 'n': 
1364          b.append('\n');
1365          break;
1366        case 'f': 
1367          b.append('\f');
1368          break;
1369        case '\'':
1370          b.append('\'');
1371          break;
1372        case '"':
1373          b.append('"');
1374          break;
1375        case '`':
1376          b.append('`');
1377          break;
1378        case '\\': 
1379          b.append('\\');
1380          break;
1381        case '/': 
1382          b.append('/');
1383          break;
1384        case 'u':
1385          i++;
1386          int uc = Integer.parseInt(s.substring(i, i+4), 16);
1387          b.append((char) uc);
1388          i = i + 3;
1389          break;
1390        default:
1391          throw lexer.error("Unknown character escape \\"+s.charAt(i));
1392        }
1393        i++;
1394      } else {
1395        b.append(ch);
1396        i++;
1397      }
1398    }
1399    return b.toString();
1400  }
1401
1402
1403  private List<Base> operate(ExecutionContext context, List<Base> left, Operation operation, List<Base> right) throws FHIRException {
1404    switch (operation) {
1405    case Equals: return opEquals(left, right);
1406    case Equivalent: return opEquivalent(left, right);
1407    case NotEquals: return opNotEquals(left, right);
1408    case NotEquivalent: return opNotEquivalent(left, right);
1409    case LessThan: return opLessThan(left, right);
1410    case Greater: return opGreater(left, right);
1411    case LessOrEqual: return opLessOrEqual(left, right);
1412    case GreaterOrEqual: return opGreaterOrEqual(left, right);
1413    case Union: return opUnion(left, right);
1414    case In: return opIn(left, right);
1415    case MemberOf: return opMemberOf(context, left, right);
1416    case Contains: return opContains(left, right);
1417    case Or:  return opOr(left, right);
1418    case And:  return opAnd(left, right);
1419    case Xor: return opXor(left, right);
1420    case Implies: return opImplies(left, right);
1421    case Plus: return opPlus(left, right);
1422    case Times: return opTimes(left, right);
1423    case Minus: return opMinus(left, right);
1424    case Concatenate: return opConcatenate(left, right);
1425    case DivideBy: return opDivideBy(left, right);
1426    case Div: return opDiv(left, right);
1427    case Mod: return opMod(left, right);
1428    case Is: return opIs(left, right);
1429    case As: return opAs(left, right);
1430    default: 
1431      throw new Error("Not Done Yet: "+operation.toCode());
1432    }
1433  }
1434
1435  private List<Base> opAs(List<Base> left, List<Base> right) {
1436    List<Base> result = new ArrayList<>();
1437    if (right.size() != 1)
1438      return result;
1439    else {
1440      String tn = convertToString(right);
1441      for (Base nextLeft : left) {
1442        if (tn.equals(nextLeft.fhirType()))
1443          result.add(nextLeft);
1444      }
1445    }
1446    return result;
1447  }
1448
1449
1450  private List<Base> opIs(List<Base> left, List<Base> right) {
1451    List<Base> result = new ArrayList<Base>();
1452    if (left.size() == 0 || right.size() == 0) {
1453    } else if (left.size() != 1 || right.size() != 1) 
1454      result.add(new BooleanType(false).noExtensions());
1455    else {
1456      String tn = convertToString(right);
1457      if (left.get(0) instanceof org.hl7.fhir.r5.elementmodel.Element)
1458        result.add(new BooleanType(left.get(0).hasType(tn)).noExtensions());
1459      else if ((left.get(0) instanceof Element) && ((Element) left.get(0)).isDisallowExtensions())
1460        result.add(new BooleanType(Utilities.capitalize(left.get(0).fhirType()).equals(tn) || ("System."+Utilities.capitalize(left.get(0).fhirType())).equals(tn)).noExtensions());
1461      else
1462        result.add(new BooleanType(left.get(0).hasType(tn)).noExtensions());
1463    }
1464    return result;
1465  }
1466
1467
1468  private TypeDetails operateTypes(TypeDetails left, Operation operation, TypeDetails right) {
1469    switch (operation) {
1470    case Equals: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
1471    case Equivalent: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
1472    case NotEquals: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
1473    case NotEquivalent: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
1474    case LessThan: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
1475    case Greater: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
1476    case LessOrEqual: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
1477    case GreaterOrEqual: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
1478    case Is: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
1479    case As: return new TypeDetails(CollectionStatus.SINGLETON, right.getTypes());
1480    case Union: return left.union(right);
1481    case Or: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
1482    case And: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
1483    case Xor: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
1484    case Implies : return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
1485    case Times: 
1486      TypeDetails result = new TypeDetails(CollectionStatus.SINGLETON);
1487      if (left.hasType(worker, "integer") && right.hasType(worker, "integer"))
1488        result.addType(TypeDetails.FP_Integer);
1489      else if (left.hasType(worker, "integer", "decimal") && right.hasType(worker, "integer", "decimal"))
1490        result.addType(TypeDetails.FP_Decimal);
1491      return result;
1492    case DivideBy: 
1493      result = new TypeDetails(CollectionStatus.SINGLETON);
1494      if (left.hasType(worker, "integer") && right.hasType(worker, "integer"))
1495        result.addType(TypeDetails.FP_Decimal);
1496      else if (left.hasType(worker, "integer", "decimal") && right.hasType(worker, "integer", "decimal"))
1497        result.addType(TypeDetails.FP_Decimal);
1498      return result;
1499    case Concatenate:
1500      result = new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String);
1501      return result;
1502    case Plus:
1503      result = new TypeDetails(CollectionStatus.SINGLETON);
1504      if (left.hasType(worker, "integer") && right.hasType(worker, "integer"))
1505        result.addType(TypeDetails.FP_Integer);
1506      else if (left.hasType(worker, "integer", "decimal") && right.hasType(worker, "integer", "decimal"))
1507        result.addType(TypeDetails.FP_Decimal);
1508      else if (left.hasType(worker, "string", "id", "code", "uri") && right.hasType(worker, "string", "id", "code", "uri"))
1509        result.addType(TypeDetails.FP_String);
1510      return result;
1511    case Minus:
1512      result = new TypeDetails(CollectionStatus.SINGLETON);
1513      if (left.hasType(worker, "integer") && right.hasType(worker, "integer"))
1514        result.addType(TypeDetails.FP_Integer);
1515      else if (left.hasType(worker, "integer", "decimal") && right.hasType(worker, "integer", "decimal"))
1516        result.addType(TypeDetails.FP_Decimal);
1517      return result;
1518    case Div: 
1519    case Mod: 
1520      result = new TypeDetails(CollectionStatus.SINGLETON);
1521      if (left.hasType(worker, "integer") && right.hasType(worker, "integer"))
1522        result.addType(TypeDetails.FP_Integer);
1523      else if (left.hasType(worker, "integer", "decimal") && right.hasType(worker, "integer", "decimal"))
1524        result.addType(TypeDetails.FP_Decimal);
1525      return result;
1526    case In: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
1527    case MemberOf: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
1528    case Contains: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
1529    default: 
1530      return null;
1531    }
1532  }
1533
1534
1535  private List<Base> opEquals(List<Base> left, List<Base> right) {
1536    if (left.size() == 0 || right.size() == 0) 
1537      return new ArrayList<Base>();
1538
1539    if (left.size() != right.size())
1540      return makeBoolean(false);
1541
1542    boolean res = true;
1543    boolean nil = false;
1544    for (int i = 0; i < left.size(); i++) {
1545      Boolean eq = doEquals(left.get(i), right.get(i));
1546      if (eq == null)
1547        nil = true;
1548      else if (eq == false) { 
1549        res = false;
1550        break;
1551      }
1552    }
1553    if (!res)
1554      return makeBoolean(res);
1555    else if (nil)
1556      return new ArrayList<Base>();
1557    else
1558      return makeBoolean(res);
1559  }
1560
1561  private List<Base> opNotEquals(List<Base> left, List<Base> right) {
1562    if (!legacyMode && (left.size() == 0 || right.size() == 0))
1563      return new ArrayList<Base>();
1564
1565    if (left.size() != right.size())
1566      return makeBoolean(true);
1567
1568    boolean res = true;
1569    boolean nil = false;
1570    for (int i = 0; i < left.size(); i++) {
1571      Boolean eq = doEquals(left.get(i), right.get(i));
1572      if (eq == null)
1573        nil = true;
1574      else if (eq == true) { 
1575        res = false;
1576        break;
1577      }
1578    }
1579    if (!res)
1580      return makeBoolean(res);
1581    else if (nil)
1582      return new ArrayList<Base>();
1583    else
1584      return makeBoolean(res);
1585  }
1586
1587  private String removeTrailingZeros(String s) {
1588    if (Utilities.noString(s))
1589      return "";
1590    int i = s.length()-1;
1591    boolean done = false;
1592    boolean dot = false;
1593    while (i > 0 && !done) {
1594      if (s.charAt(i) == '.') {
1595        i--;
1596        dot = true;
1597      }
1598      else if (!dot && s.charAt(i) == '0')
1599        i--;
1600      else
1601        done = true;
1602    }
1603    return s.substring(0, i+1);
1604  }
1605
1606  private boolean decEqual(String left, String right) {
1607    left = removeTrailingZeros(left);
1608    right = removeTrailingZeros(right);
1609    return left.equals(right);
1610  }
1611  
1612  private Boolean compareDates(BaseDateTimeType left, BaseDateTimeType right) {
1613    return left.equalsUsingFhirPathRules(right);
1614  }
1615  
1616  private Boolean doEquals(Base left, Base right) {
1617    if (left instanceof Quantity && right instanceof Quantity)
1618      return qtyEqual((Quantity) left, (Quantity) right);
1619    else if (left.isDateTime() && right.isDateTime()) {
1620      return compareDates(left.dateTimeValue(), right.dateTimeValue());
1621    } else if (left instanceof DecimalType || right instanceof DecimalType) 
1622      return decEqual(left.primitiveValue(), right.primitiveValue());
1623    else if (left.isPrimitive() && right.isPrimitive())
1624                        return Base.equals(left.primitiveValue(), right.primitiveValue());
1625    else
1626      return Base.compareDeep(left, right, false);
1627  }
1628
1629
1630  private boolean doEquivalent(Base left, Base right) throws PathEngineException {
1631    if (left instanceof Quantity && right instanceof Quantity)
1632      return qtyEquivalent((Quantity) left, (Quantity) right);
1633    if (left.hasType("integer") && right.hasType("integer"))
1634      return doEquals(left, right);
1635    if (left.hasType("boolean") && right.hasType("boolean"))
1636      return doEquals(left, right);
1637    if (left.hasType("integer", "decimal", "unsignedInt", "positiveInt") && right.hasType("integer", "decimal", "unsignedInt", "positiveInt"))
1638      return Utilities.equivalentNumber(left.primitiveValue(), right.primitiveValue());
1639    if (left.hasType("date", "dateTime", "time", "instant") && right.hasType("date", "dateTime", "time", "instant"))
1640      return compareDateTimeElements(left, right, true) == 0;
1641    if (left.hasType(FHIR_TYPES_STRING) && right.hasType(FHIR_TYPES_STRING))
1642      return Utilities.equivalent(convertToString(left), convertToString(right));
1643
1644    throw new PathEngineException(String.format("Unable to determine equivalence between %s and %s", left.fhirType(), right.fhirType()));
1645  }
1646
1647  private boolean qtyEqual(Quantity left, Quantity right) {
1648    if (worker.getUcumService() != null) {
1649      DecimalType dl = qtyToCanonical(left);
1650      DecimalType dr = qtyToCanonical(right);
1651      if (dl != null && dr != null) 
1652        return doEquals(dl,  dr);
1653    }
1654    return left.equals(right);
1655  }
1656
1657  private DecimalType qtyToCanonical(Quantity q) {
1658    if (!"http://unitsofmeasure.org".equals(q.getSystem()))
1659      return null;
1660    try {
1661      Pair p = new Pair(new Decimal(q.getValue().toPlainString()), q.getCode());
1662      Pair c = worker.getUcumService().getCanonicalForm(p);
1663      return new DecimalType(c.getValue().asDecimal());
1664    } catch (UcumException e) {
1665      return null;
1666    }
1667  }
1668
1669  private Base pairToQty(Pair p) {
1670    return new Quantity().setValue(new BigDecimal(p.getValue().toString())).setSystem("http://unitsofmeasure.org").setCode(p.getCode()).noExtensions();
1671  }
1672
1673
1674  private Pair qtyToPair(Quantity q) {
1675    if (!"http://unitsofmeasure.org".equals(q.getSystem()))
1676      return null;
1677    try {
1678      return new Pair(new Decimal(q.getValue().toPlainString()), q.getCode());
1679    } catch (UcumException e) {
1680      return null;
1681    }
1682  }
1683
1684
1685  private boolean qtyEquivalent(Quantity left, Quantity right) throws PathEngineException {
1686    if (worker.getUcumService() != null) {
1687      DecimalType dl = qtyToCanonical(left);
1688      DecimalType dr = qtyToCanonical(right);
1689      if (dl != null && dr != null) 
1690        return doEquivalent(dl,  dr);
1691    }
1692    return left.equals(right);
1693  }
1694
1695
1696
1697  private List<Base> opEquivalent(List<Base> left, List<Base> right) throws PathEngineException {
1698    if (left.size() != right.size())
1699      return makeBoolean(false);
1700
1701    boolean res = true;
1702    for (int i = 0; i < left.size(); i++) {
1703      boolean found = false;
1704      for (int j = 0; j < right.size(); j++) {
1705        if (doEquivalent(left.get(i), right.get(j))) {
1706          found = true;
1707          break;
1708        }
1709      }
1710      if (!found) {
1711        res = false;
1712        break;
1713      }
1714    }
1715    return makeBoolean(res);
1716  }
1717
1718  private List<Base> opNotEquivalent(List<Base> left, List<Base> right) throws PathEngineException {
1719    if (left.size() != right.size())
1720      return makeBoolean(true);
1721
1722    boolean res = true;
1723    for (int i = 0; i < left.size(); i++) {
1724      boolean found = false;
1725      for (int j = 0; j < right.size(); j++) {
1726        if (doEquivalent(left.get(i), right.get(j))) {
1727          found = true;
1728          break;
1729        }
1730      }
1731      if (!found) {
1732        res = false;
1733        break;
1734      }
1735    }
1736    return makeBoolean(!res);
1737  }
1738
1739  private final static String[] FHIR_TYPES_STRING = new String[] {"string", "uri", "code", "oid", "id", "uuid", "sid", "markdown", "base64Binary", "canonical", "url"};
1740
1741        private List<Base> opLessThan(List<Base> left, List<Base> right) throws FHIRException {
1742    if (left.size() == 0 || right.size() == 0) 
1743      return new ArrayList<Base>();
1744    
1745    if (left.size() == 1 && right.size() == 1 && left.get(0).isPrimitive() && right.get(0).isPrimitive()) {
1746      Base l = left.get(0);
1747      Base r = right.get(0);
1748      if (l.hasType(FHIR_TYPES_STRING) && r.hasType(FHIR_TYPES_STRING)) 
1749        return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) < 0);
1750      else if ((l.hasType("integer") || l.hasType("decimal")) && (r.hasType("integer") || r.hasType("decimal"))) 
1751        return makeBoolean(new Double(l.primitiveValue()) < new Double(r.primitiveValue()));
1752      else if ((l.hasType("date", "dateTime", "instant")) && (r.hasType("date", "dateTime", "instant")))
1753        return makeBoolean(compareDateTimeElements(l, r, false) < 0);
1754      else if ((l.hasType("time")) && (r.hasType("time"))) 
1755        return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) < 0);
1756      else
1757        throw new PathEngineException("Unable to compare values of type "+l.fhirType()+" and "+r.fhirType());
1758    } else if (left.size() == 1 && right.size() == 1 && left.get(0).fhirType().equals("Quantity") && right.get(0).fhirType().equals("Quantity") ) {
1759      List<Base> lUnit = left.get(0).listChildrenByName("code");
1760      List<Base> rUnit = right.get(0).listChildrenByName("code");
1761      if (Base.compareDeep(lUnit, rUnit, true)) {
1762        return opLessThan(left.get(0).listChildrenByName("value"), right.get(0).listChildrenByName("value"));
1763      } else {
1764        if (worker.getUcumService() == null)
1765          return makeBoolean(false);
1766        else {
1767          List<Base> dl = new ArrayList<Base>();
1768          dl.add(qtyToCanonical((Quantity) left.get(0)));
1769          List<Base> dr = new ArrayList<Base>();
1770          dr.add(qtyToCanonical((Quantity) right.get(0)));
1771          return opLessThan(dl, dr);
1772        }
1773      }
1774    }
1775    return new ArrayList<Base>();
1776  }
1777
1778        private List<Base> opGreater(List<Base> left, List<Base> right) throws FHIRException {
1779    if (left.size() == 0 || right.size() == 0) 
1780      return new ArrayList<Base>();
1781    if (left.size() == 1 && right.size() == 1 && left.get(0).isPrimitive() && right.get(0).isPrimitive()) {
1782      Base l = left.get(0);
1783      Base r = right.get(0);
1784      if (l.hasType(FHIR_TYPES_STRING) && r.hasType(FHIR_TYPES_STRING)) 
1785        return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) > 0);
1786      else if ((l.hasType("integer", "decimal", "unsignedInt", "positiveInt")) && (r.hasType("integer", "decimal", "unsignedInt", "positiveInt"))) 
1787        return makeBoolean(new Double(l.primitiveValue()) > new Double(r.primitiveValue()));
1788      else if ((l.hasType("date", "dateTime", "instant")) && (r.hasType("date", "dateTime", "instant")))
1789        return makeBoolean(compareDateTimeElements(l, r, false) > 0);
1790      else if ((l.hasType("time")) && (r.hasType("time"))) 
1791        return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) > 0);
1792      else
1793        throw new PathEngineException("Unable to compare values of type "+l.fhirType()+" and "+r.fhirType());
1794    } else if (left.size() == 1 && right.size() == 1 && left.get(0).fhirType().equals("Quantity") && right.get(0).fhirType().equals("Quantity") ) {
1795      List<Base> lUnit = left.get(0).listChildrenByName("unit");
1796      List<Base> rUnit = right.get(0).listChildrenByName("unit");
1797      if (Base.compareDeep(lUnit, rUnit, true)) {
1798        return opGreater(left.get(0).listChildrenByName("value"), right.get(0).listChildrenByName("value"));
1799      } else {
1800        if (worker.getUcumService() == null)
1801          return makeBoolean(false);
1802        else {
1803          List<Base> dl = new ArrayList<Base>();
1804          dl.add(qtyToCanonical((Quantity) left.get(0)));
1805          List<Base> dr = new ArrayList<Base>();
1806          dr.add(qtyToCanonical((Quantity) right.get(0)));
1807          return opGreater(dl, dr);
1808        }
1809      }
1810    }
1811    return new ArrayList<Base>();
1812  }
1813
1814        private List<Base> opLessOrEqual(List<Base> left, List<Base> right) throws FHIRException {
1815    if (left.size() == 0 || right.size() == 0) 
1816      return new ArrayList<Base>();
1817    if (left.size() == 1 && right.size() == 1 && left.get(0).isPrimitive() && right.get(0).isPrimitive()) {
1818      Base l = left.get(0);
1819      Base r = right.get(0);
1820      if (l.hasType(FHIR_TYPES_STRING) && r.hasType(FHIR_TYPES_STRING)) 
1821        return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) <= 0);
1822      else if ((l.hasType("integer", "decimal", "unsignedInt", "positiveInt")) && (r.hasType("integer", "decimal", "unsignedInt", "positiveInt"))) 
1823        return makeBoolean(new Double(l.primitiveValue()) <= new Double(r.primitiveValue()));
1824      else if ((l.hasType("date", "dateTime", "instant")) && (r.hasType("date", "dateTime", "instant")))
1825        return makeBoolean(compareDateTimeElements(l, r, false) <= 0);
1826      else if ((l.hasType("time")) && (r.hasType("time"))) 
1827        return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) <= 0);
1828      else
1829        throw new PathEngineException("Unable to compare values of type "+l.fhirType()+" and "+r.fhirType());
1830    } else if (left.size() == 1 && right.size() == 1 && left.get(0).fhirType().equals("Quantity") && right.get(0).fhirType().equals("Quantity") ) {
1831      List<Base> lUnits = left.get(0).listChildrenByName("unit");
1832      String lunit = lUnits.size() == 1 ? lUnits.get(0).primitiveValue() : null;
1833      List<Base> rUnits = right.get(0).listChildrenByName("unit");
1834      String runit = rUnits.size() == 1 ? rUnits.get(0).primitiveValue() : null;
1835      if ((lunit == null && runit == null) || lunit.equals(runit)) {
1836        return opLessOrEqual(left.get(0).listChildrenByName("value"), right.get(0).listChildrenByName("value"));
1837      } else {
1838        if (worker.getUcumService() == null)
1839          return makeBoolean(false);
1840        else {
1841          List<Base> dl = new ArrayList<Base>();
1842          dl.add(qtyToCanonical((Quantity) left.get(0)));
1843          List<Base> dr = new ArrayList<Base>();
1844          dr.add(qtyToCanonical((Quantity) right.get(0)));
1845          return opLessOrEqual(dl, dr);
1846        }
1847      }
1848    }
1849    return new ArrayList<Base>();
1850  }
1851
1852        private List<Base> opGreaterOrEqual(List<Base> left, List<Base> right) throws FHIRException {
1853    if (left.size() == 0 || right.size() == 0) 
1854      return new ArrayList<Base>();
1855    if (left.size() == 1 && right.size() == 1 && left.get(0).isPrimitive() && right.get(0).isPrimitive()) {
1856      Base l = left.get(0);
1857      Base r = right.get(0);
1858      if (l.hasType(FHIR_TYPES_STRING) && r.hasType(FHIR_TYPES_STRING)) 
1859        return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) >= 0);
1860      else if ((l.hasType("integer", "decimal", "unsignedInt", "positiveInt")) && (r.hasType("integer", "decimal", "unsignedInt", "positiveInt"))) 
1861        return makeBoolean(new Double(l.primitiveValue()) >= new Double(r.primitiveValue()));
1862      else if ((l.hasType("date", "dateTime", "instant")) && (r.hasType("date", "dateTime", "instant")))
1863        return makeBoolean(compareDateTimeElements(l, r, false) >= 0);
1864      else if ((l.hasType("time")) && (r.hasType("time"))) 
1865        return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) >= 0);
1866      else
1867        throw new PathEngineException("Unable to compare values of type "+l.fhirType()+" and "+r.fhirType());
1868    } else if (left.size() == 1 && right.size() == 1 && left.get(0).fhirType().equals("Quantity") && right.get(0).fhirType().equals("Quantity") ) {
1869      List<Base> lUnit = left.get(0).listChildrenByName("unit");
1870      List<Base> rUnit = right.get(0).listChildrenByName("unit");
1871      if (Base.compareDeep(lUnit, rUnit, true)) {
1872        return opGreaterOrEqual(left.get(0).listChildrenByName("value"), right.get(0).listChildrenByName("value"));
1873      } else {
1874        if (worker.getUcumService() == null)
1875          return makeBoolean(false);
1876        else {
1877          List<Base> dl = new ArrayList<Base>();
1878          dl.add(qtyToCanonical((Quantity) left.get(0)));
1879          List<Base> dr = new ArrayList<Base>();
1880          dr.add(qtyToCanonical((Quantity) right.get(0)));
1881          return opGreaterOrEqual(dl, dr);
1882        }
1883      }
1884    }
1885    return new ArrayList<Base>();
1886  }
1887
1888        private List<Base> opMemberOf(ExecutionContext context, List<Base> left, List<Base> right) throws FHIRException {
1889          boolean ans = false;
1890          ValueSet vs = hostServices != null ? hostServices.resolveValueSet(context.appInfo, right.get(0).primitiveValue()) : worker.fetchResource(ValueSet.class, right.get(0).primitiveValue());
1891          if (vs != null) {
1892            for (Base l : left) {
1893              if (l.fhirType().equals("code")) {
1894          if (worker.validateCode(terminologyServiceOptions , TypeConvertor.castToCoding(l), vs).isOk())
1895            ans = true;
1896              } else if (l.fhirType().equals("Coding")) {
1897                if (worker.validateCode(terminologyServiceOptions, TypeConvertor.castToCoding(l), vs).isOk())
1898                  ans = true;
1899              } else if (l.fhirType().equals("CodeableConcept")) {
1900                if (worker.validateCode(terminologyServiceOptions, TypeConvertor.castToCodeableConcept(l), vs).isOk())
1901                  ans = true;
1902              }
1903            }
1904          }
1905          return makeBoolean(ans);
1906        }
1907
1908  private List<Base> opIn(List<Base> left, List<Base> right) throws FHIRException {
1909    if (left.size() == 0) 
1910      return new ArrayList<Base>();
1911    if (right.size() == 0) 
1912      return makeBoolean(false);
1913    boolean ans = true;
1914    for (Base l : left) {
1915      boolean f = false;
1916      for (Base r : right) {
1917        Boolean eq = doEquals(l, r);
1918        if (eq != null && eq == true) {
1919          f = true;
1920          break;
1921        }
1922      }
1923      if (!f) {
1924        ans = false;
1925        break;
1926      }
1927    }
1928    return makeBoolean(ans);
1929  }
1930
1931  private List<Base> opContains(List<Base> left, List<Base> right) {
1932    if (left.size() == 0 || right.size() == 0) 
1933     return new ArrayList<Base>();
1934    boolean ans = true;
1935    for (Base r : right) {
1936      boolean f = false;
1937      for (Base l : left) {
1938        Boolean eq = doEquals(l, r);
1939        if (eq != null && eq == true) {
1940          f = true;
1941          break;
1942        }
1943      }
1944      if (!f) {
1945        ans = false;
1946        break;
1947      }
1948    }
1949    return makeBoolean(ans);
1950  }
1951
1952  private List<Base> opPlus(List<Base> left, List<Base> right) throws PathEngineException {
1953    if (left.size() == 0 || right.size() == 0) 
1954      return new ArrayList<Base>();
1955    if (left.size() > 1)
1956      throw new PathEngineException("Error performing +: left operand has more than one value");
1957    if (!left.get(0).isPrimitive())
1958      throw new PathEngineException(String.format("Error performing +: left operand has the wrong type (%s)", left.get(0).fhirType()));
1959    if (right.size() > 1)
1960      throw new PathEngineException("Error performing +: right operand has more than one value");
1961    if (!right.get(0).isPrimitive())
1962      throw new PathEngineException(String.format("Error performing +: right operand has the wrong type (%s)", right.get(0).fhirType()));
1963
1964    List<Base> result = new ArrayList<Base>();
1965    Base l = left.get(0);
1966    Base r = right.get(0);
1967    if (l.hasType(FHIR_TYPES_STRING) && r.hasType(FHIR_TYPES_STRING)) 
1968      result.add(new StringType(l.primitiveValue() + r.primitiveValue()));
1969    else if (l.hasType("integer") && r.hasType("integer")) 
1970      result.add(new IntegerType(Integer.parseInt(l.primitiveValue()) + Integer.parseInt(r.primitiveValue())));
1971    else if (l.hasType("decimal", "integer") && r.hasType("decimal", "integer")) 
1972      result.add(new DecimalType(new BigDecimal(l.primitiveValue()).add(new BigDecimal(r.primitiveValue()))));
1973    else
1974      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()));
1975    return result;
1976  }
1977
1978  private List<Base> opTimes(List<Base> left, List<Base> right) throws PathEngineException {
1979    if (left.size() == 0 || right.size() == 0) 
1980      return new ArrayList<Base>();
1981    if (left.size() > 1)
1982      throw new PathEngineException("Error performing *: left operand has more than one value");
1983    if (!left.get(0).isPrimitive() && !(left.get(0) instanceof Quantity))
1984      throw new PathEngineException(String.format("Error performing +: left operand has the wrong type (%s)", left.get(0).fhirType()));
1985    if (right.size() > 1)
1986      throw new PathEngineException("Error performing *: right operand has more than one value");
1987    if (!right.get(0).isPrimitive() && !(right.get(0) instanceof Quantity))
1988      throw new PathEngineException(String.format("Error performing *: right operand has the wrong type (%s)", right.get(0).fhirType()));
1989
1990    List<Base> result = new ArrayList<Base>();
1991    Base l = left.get(0);
1992    Base r = right.get(0);
1993
1994    if (l.hasType("integer") && r.hasType("integer")) 
1995      result.add(new IntegerType(Integer.parseInt(l.primitiveValue()) * Integer.parseInt(r.primitiveValue())));
1996    else if (l.hasType("decimal", "integer") && r.hasType("decimal", "integer")) 
1997      result.add(new DecimalType(new BigDecimal(l.primitiveValue()).multiply(new BigDecimal(r.primitiveValue()))));
1998    else if (l instanceof Quantity && r instanceof Quantity && worker.getUcumService() != null) {
1999      Pair pl = qtyToPair((Quantity) l);
2000      Pair pr = qtyToPair((Quantity) r);
2001      Pair p;
2002      try {
2003        p = worker.getUcumService().multiply(pl, pr);
2004        result.add(pairToQty(p));
2005      } catch (UcumException e) {
2006        throw new PathEngineException(e.getMessage(), e);
2007      }
2008    } else
2009      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()));
2010    return result;
2011  }
2012
2013
2014  private List<Base> opConcatenate(List<Base> left, List<Base> right) throws PathEngineException {
2015    if (left.size() > 1)
2016      throw new PathEngineException("Error performing &: left operand has more than one value");
2017    if (left.size() > 0 && !left.get(0).hasType(FHIR_TYPES_STRING))
2018      throw new PathEngineException(String.format("Error performing &: left operand has the wrong type (%s)", left.get(0).fhirType()));
2019    if (right.size() > 1)
2020      throw new PathEngineException("Error performing &: right operand has more than one value");
2021    if (right.size() > 0 && !right.get(0).hasType(FHIR_TYPES_STRING))
2022      throw new PathEngineException(String.format("Error performing &: right operand has the wrong type (%s)", right.get(0).fhirType()));
2023
2024    List<Base> result = new ArrayList<Base>();
2025    String l = left.size() == 0 ? "" : left.get(0).primitiveValue();
2026    String r = right.size() == 0 ? "" : right.get(0).primitiveValue();
2027    result.add(new StringType(l + r));
2028    return result;
2029  }
2030
2031  private List<Base> opUnion(List<Base> left, List<Base> right) {
2032    List<Base> result = new ArrayList<Base>();
2033    for (Base item : left) {
2034      if (!doContains(result, item))
2035        result.add(item);
2036    }
2037    for (Base item : right) {
2038      if (!doContains(result, item))
2039        result.add(item);
2040    }
2041    return result;
2042  }
2043
2044  private boolean doContains(List<Base> list, Base item) {
2045    for (Base test : list) {
2046      Boolean eq = doEquals(test, item);
2047      if (eq != null && eq == true)
2048        return true;
2049    }
2050    return false;
2051  }
2052
2053
2054  private List<Base> opAnd(List<Base> left, List<Base> right) throws PathEngineException {
2055    Equality l = asBool(left);
2056    Equality r = asBool(right);
2057    switch (l) {
2058    case False: return makeBoolean(false);
2059    case Null:
2060      if (r == Equality.False)
2061        return makeBoolean(false);
2062      else
2063        return makeNull();
2064    case True:
2065      switch (r) {
2066      case False: return makeBoolean(false);
2067      case Null: return makeNull();
2068      case True: return makeBoolean(true);
2069      }
2070    }
2071    return makeNull();
2072  }
2073
2074  private boolean isBoolean(List<Base> list, boolean b) {
2075    return list.size() == 1 && list.get(0) instanceof BooleanType && ((BooleanType) list.get(0)).booleanValue() == b;
2076  }
2077
2078  private List<Base> opOr(List<Base> left, List<Base> right) throws PathEngineException {
2079    Equality l = asBool(left);
2080    Equality r = asBool(right);
2081    switch (l) {
2082    case True: return makeBoolean(true);
2083    case Null:
2084      if (r == Equality.True)
2085        return makeBoolean(true);
2086      else
2087        return makeNull();
2088    case False:
2089      switch (r) {
2090      case False: return makeBoolean(false);
2091      case Null: return makeNull();
2092      case True: return makeBoolean(true);
2093      }
2094    }
2095    return makeNull();
2096  }
2097
2098  private List<Base> opXor(List<Base> left, List<Base> right) throws PathEngineException {
2099    Equality l = asBool(left);
2100    Equality r = asBool(right);
2101    switch (l) {
2102    case True: 
2103      switch (r) {
2104      case False: return makeBoolean(true);
2105      case True: return makeBoolean(false);
2106      case Null: return makeNull();
2107      }
2108    case Null:
2109      return makeNull();
2110    case False:
2111      switch (r) {
2112      case False: return makeBoolean(false);
2113      case True: return makeBoolean(true);
2114      case Null: return makeNull();
2115      }
2116    }
2117    return makeNull();
2118  }
2119
2120  private List<Base> opImplies(List<Base> left, List<Base> right) throws PathEngineException {
2121    Equality eq = asBool(left);
2122    if (eq == Equality.False) 
2123      return makeBoolean(true);
2124    else if (right.size() == 0)
2125      return makeNull();
2126    else switch (asBool(right)) {
2127    case False: return eq == Equality.Null ? makeNull() : makeBoolean(false);
2128    case Null: return makeNull();
2129    case True: return makeBoolean(true);
2130    }
2131    return makeNull();
2132  }
2133
2134
2135  private List<Base> opMinus(List<Base> left, List<Base> right) throws PathEngineException {
2136    if (left.size() == 0 || right.size() == 0) 
2137      return new ArrayList<Base>();
2138    if (left.size() > 1)
2139      throw new PathEngineException("Error performing -: left operand has more than one value");
2140    if (!left.get(0).isPrimitive())
2141      throw new PathEngineException(String.format("Error performing -: left operand has the wrong type (%s)", left.get(0).fhirType()));
2142    if (right.size() > 1)
2143      throw new PathEngineException("Error performing -: right operand has more than one value");
2144    if (!right.get(0).isPrimitive())
2145      throw new PathEngineException(String.format("Error performing -: right operand has the wrong type (%s)", right.get(0).fhirType()));
2146
2147    List<Base> result = new ArrayList<Base>();
2148    Base l = left.get(0);
2149    Base r = right.get(0);
2150
2151    if (l.hasType("integer") && r.hasType("integer")) 
2152      result.add(new IntegerType(Integer.parseInt(l.primitiveValue()) - Integer.parseInt(r.primitiveValue())));
2153    else if (l.hasType("decimal", "integer") && r.hasType("decimal", "integer")) 
2154      result.add(new DecimalType(new BigDecimal(l.primitiveValue()).subtract(new BigDecimal(r.primitiveValue()))));
2155    else
2156      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()));
2157    return result;
2158  }
2159
2160  private List<Base> opDivideBy(List<Base> left, List<Base> right) throws PathEngineException {
2161    if (left.size() == 0 || right.size() == 0) 
2162      return new ArrayList<Base>();
2163    if (left.size() > 1)
2164      throw new PathEngineException("Error performing /: left operand has more than one value");
2165    if (!left.get(0).isPrimitive() && !(left.get(0) instanceof Quantity))
2166      throw new PathEngineException(String.format("Error performing -: left operand has the wrong type (%s)", left.get(0).fhirType()));
2167    if (right.size() > 1)
2168      throw new PathEngineException("Error performing /: right operand has more than one value");
2169    if (!right.get(0).isPrimitive() && !(right.get(0) instanceof Quantity))
2170      throw new PathEngineException(String.format("Error performing /: right operand has the wrong type (%s)", right.get(0).fhirType()));
2171
2172    List<Base> result = new ArrayList<Base>();
2173    Base l = left.get(0);
2174    Base r = right.get(0);
2175
2176    if (l.hasType("integer", "decimal", "unsignedInt", "positiveInt") && r.hasType("integer", "decimal", "unsignedInt", "positiveInt")) {
2177      Decimal d1;
2178      try {
2179        d1 = new Decimal(l.primitiveValue());
2180        Decimal d2 = new Decimal(r.primitiveValue());
2181        result.add(new DecimalType(d1.divide(d2).asDecimal()));
2182      } catch (UcumException e) {
2183        throw new PathEngineException(e);
2184      }
2185    } else if (l instanceof Quantity && r instanceof Quantity && worker.getUcumService() != null) {
2186      Pair pl = qtyToPair((Quantity) l);
2187      Pair pr = qtyToPair((Quantity) r);
2188      Pair p;
2189      try {
2190        p = worker.getUcumService().multiply(pl, pr);
2191        result.add(pairToQty(p));
2192      } catch (UcumException e) {
2193        throw new PathEngineException(e.getMessage(), e);
2194      }
2195    } else
2196      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()));
2197    return result;
2198  }
2199
2200  private List<Base> opDiv(List<Base> left, List<Base> right) throws PathEngineException {
2201    if (left.size() == 0 || right.size() == 0) 
2202      return new ArrayList<Base>();
2203    if (left.size() > 1)
2204      throw new PathEngineException("Error performing div: left operand has more than one value");
2205    if (!left.get(0).isPrimitive() && !(left.get(0) instanceof Quantity))
2206      throw new PathEngineException(String.format("Error performing div: left operand has the wrong type (%s)", left.get(0).fhirType()));
2207    if (right.size() > 1)
2208      throw new PathEngineException("Error performing div: right operand has more than one value");
2209    if (!right.get(0).isPrimitive() && !(right.get(0) instanceof Quantity))
2210      throw new PathEngineException(String.format("Error performing div: right operand has the wrong type (%s)", right.get(0).fhirType()));
2211
2212    List<Base> result = new ArrayList<Base>();
2213    Base l = left.get(0);
2214    Base r = right.get(0);
2215
2216    if (l.hasType("integer") && r.hasType("integer")) 
2217      result.add(new IntegerType(Integer.parseInt(l.primitiveValue()) / Integer.parseInt(r.primitiveValue())));
2218    else if (l.hasType("decimal", "integer") && r.hasType("decimal", "integer")) { 
2219      Decimal d1;
2220      try {
2221        d1 = new Decimal(l.primitiveValue());
2222        Decimal d2 = new Decimal(r.primitiveValue());
2223        result.add(new IntegerType(d1.divInt(d2).asDecimal()));
2224      } catch (UcumException e) {
2225        throw new PathEngineException(e);
2226      }
2227    }
2228    else
2229      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()));
2230    return result;
2231  }
2232
2233  private List<Base> opMod(List<Base> left, List<Base> right) throws PathEngineException {
2234    if (left.size() == 0 || right.size() == 0) 
2235      return new ArrayList<Base>();
2236    if (left.size() > 1)
2237      throw new PathEngineException("Error performing mod: left operand has more than one value");
2238    if (!left.get(0).isPrimitive())
2239      throw new PathEngineException(String.format("Error performing mod: left operand has the wrong type (%s)", left.get(0).fhirType()));
2240    if (right.size() > 1)
2241      throw new PathEngineException("Error performing mod: right operand has more than one value");
2242    if (!right.get(0).isPrimitive())
2243      throw new PathEngineException(String.format("Error performing mod: right operand has the wrong type (%s)", right.get(0).fhirType()));
2244
2245    List<Base> result = new ArrayList<Base>();
2246    Base l = left.get(0);
2247    Base r = right.get(0);
2248
2249    if (l.hasType("integer") && r.hasType("integer")) 
2250      result.add(new IntegerType(Integer.parseInt(l.primitiveValue()) % Integer.parseInt(r.primitiveValue())));
2251    else if (l.hasType("decimal", "integer") && r.hasType("decimal", "integer")) {
2252      Decimal d1;
2253      try {
2254        d1 = new Decimal(l.primitiveValue());
2255        Decimal d2 = new Decimal(r.primitiveValue());
2256        result.add(new DecimalType(d1.modulo(d2).asDecimal()));
2257      } catch (UcumException e) {
2258        throw new PathEngineException(e);
2259      }
2260    }
2261    else
2262      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()));
2263    return result;
2264  }
2265
2266
2267  private TypeDetails resolveConstantType(ExecutionTypeContext context, Base constant) throws PathEngineException {
2268    if (constant instanceof BooleanType) 
2269      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
2270    else if (constant instanceof IntegerType)
2271      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Integer);
2272    else if (constant instanceof DecimalType)
2273      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Decimal);
2274    else if (constant instanceof Quantity)
2275      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Quantity);
2276    else if (constant instanceof FHIRConstant)
2277      return resolveConstantType(context, ((FHIRConstant) constant).getValue());
2278    else
2279      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String);
2280  }
2281
2282  private TypeDetails resolveConstantType(ExecutionTypeContext context, String s) throws PathEngineException {
2283    if (s.startsWith("@")) {
2284      if (s.startsWith("@T"))
2285        return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Time);
2286      else
2287        return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_DateTime);
2288    } else if (s.equals("%sct"))
2289      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String);
2290    else if (s.equals("%loinc"))
2291      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String);
2292    else if (s.equals("%ucum"))
2293      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String);
2294    else if (s.equals("%resource")) {
2295      if (context.resource == null)
2296        throw new PathEngineException("%resource cannot be used in this context");
2297      return new TypeDetails(CollectionStatus.SINGLETON, context.resource);
2298    } else if (s.equals("%rootResource")) {
2299      if (context.resource == null)
2300        throw new PathEngineException("%rootResource cannot be used in this context");
2301      return new TypeDetails(CollectionStatus.SINGLETON, context.resource);
2302    } else if (s.equals("%context")) {
2303      return context.context;
2304    } else if (s.equals("%map-codes"))
2305      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String);
2306    else if (s.equals("%us-zip"))
2307      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String);
2308    else if (s.startsWith("%`vs-"))
2309      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String);
2310    else if (s.startsWith("%`cs-"))
2311      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String);
2312    else if (s.startsWith("%`ext-"))
2313      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String);
2314    else if (hostServices == null)
2315      throw new PathEngineException("Unknown fixed constant type for '"+s+"'");
2316    else
2317      return hostServices.resolveConstantType(context.appInfo, s);
2318  }
2319
2320        private List<Base> execute(ExecutionContext context, Base item, ExpressionNode exp, boolean atEntry) throws FHIRException {
2321    List<Base> result = new ArrayList<Base>(); 
2322    if (atEntry && context.appInfo != null && hostServices != null) {
2323      // we'll see if the name matches a constant known by the context.
2324      Base temp = hostServices.resolveConstant(context.appInfo, exp.getName(), true);
2325      if (temp != null) {
2326        result.add(temp);
2327        return result;
2328      }
2329    }
2330    if (atEntry && Character.isUpperCase(exp.getName().charAt(0))) {// special case for start up
2331      if (item.isResource() && item.fhirType().equals(exp.getName()))  
2332        result.add(item);
2333    } else 
2334      getChildrenByName(item, exp.getName(), result);
2335    if (atEntry && context.appInfo != null && hostServices != null && result.isEmpty()) {
2336      // well, we didn't get a match on the name - we'll see if the name matches a constant known by the context.
2337      // (if the name does match, and the user wants to get the constant value, they'll have to try harder...
2338      Base temp = hostServices.resolveConstant(context.appInfo, exp.getName(), false);
2339      if (temp != null) {
2340        result.add(temp);
2341      }
2342    }
2343    return result;
2344  }     
2345
2346  private TypeDetails executeContextType(ExecutionTypeContext context, String name) throws PathEngineException, DefinitionException {
2347    if (hostServices == null)
2348      throw new PathEngineException("Unable to resolve context reference since no host services are provided");
2349    return hostServices.resolveConstantType(context.appInfo, name);
2350  }
2351  
2352  private TypeDetails executeType(String type, ExpressionNode exp, boolean atEntry) throws PathEngineException, DefinitionException {
2353    if (atEntry && Character.isUpperCase(exp.getName().charAt(0)) && hashTail(type).equals(exp.getName())) // special case for start up
2354      return new TypeDetails(CollectionStatus.SINGLETON, type);
2355    TypeDetails result = new TypeDetails(null);
2356    getChildTypesByName(type, exp.getName(), result);
2357    return result;
2358  }
2359
2360
2361  private String hashTail(String type) {
2362    return type.contains("#") ? "" : type.substring(type.lastIndexOf("/")+1);
2363  }
2364
2365
2366  @SuppressWarnings("unchecked")
2367  private TypeDetails evaluateFunctionType(ExecutionTypeContext context, TypeDetails focus, ExpressionNode exp) throws PathEngineException, DefinitionException {
2368    List<TypeDetails> paramTypes = new ArrayList<TypeDetails>();
2369    if (exp.getFunction() == Function.Is || exp.getFunction() == Function.As || exp.getFunction() == Function.OfType)
2370      paramTypes.add(new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String));
2371    else
2372      for (ExpressionNode expr : exp.getParameters()) {
2373        if (exp.getFunction() == Function.Where || exp.getFunction() == Function.All || exp.getFunction() == Function.Select || exp.getFunction() == Function.Repeat || exp.getFunction() == Function.Aggregate)
2374          paramTypes.add(executeType(changeThis(context, focus), focus, expr, true));
2375        else
2376          paramTypes.add(executeType(context, focus, expr, true));
2377      }
2378    switch (exp.getFunction()) {
2379    case Empty : 
2380      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
2381    case Not : 
2382      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
2383    case Exists : 
2384      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
2385    case SubsetOf : {
2386      checkParamTypes(exp.getFunction().toCode(), paramTypes, focus); 
2387      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 
2388    }
2389    case SupersetOf : {
2390      checkParamTypes(exp.getFunction().toCode(), paramTypes, focus); 
2391      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 
2392    }
2393    case IsDistinct : 
2394      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
2395    case Distinct : 
2396      return focus;
2397    case Count : 
2398      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Integer);
2399    case Where : 
2400      return focus;
2401    case Select : 
2402      return anything(focus.getCollectionStatus());
2403    case All : 
2404      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
2405    case Repeat : 
2406      return anything(focus.getCollectionStatus());
2407    case Aggregate : 
2408      return anything(focus.getCollectionStatus());
2409    case Item : {
2410      checkOrdered(focus, "item");
2411      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Integer)); 
2412      return focus; 
2413    }
2414    case As : {
2415      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 
2416      return new TypeDetails(CollectionStatus.SINGLETON, exp.getParameters().get(0).getName());
2417    }
2418    case OfType : { 
2419      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 
2420      return new TypeDetails(CollectionStatus.SINGLETON, exp.getParameters().get(0).getName());
2421    }
2422    case Type : { 
2423      boolean s = false;
2424      boolean c = false;
2425      for (ProfiledType pt : focus.getProfiledTypes()) {
2426        s = s || pt.isSystemType();
2427        c = c || !pt.isSystemType();
2428      }
2429      if (s && c)
2430        return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_SimpleTypeInfo, TypeDetails.FP_ClassInfo);
2431      else if (s)
2432        return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_SimpleTypeInfo);
2433      else
2434        return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_ClassInfo);
2435    }
2436    case Is : {
2437      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 
2438      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 
2439    }
2440    case Single :
2441      return focus.toSingleton();
2442    case First : {
2443      checkOrdered(focus, "first");
2444      return focus.toSingleton();
2445    }
2446    case Last : {
2447      checkOrdered(focus, "last");
2448      return focus.toSingleton();
2449    }
2450    case Tail : {
2451      checkOrdered(focus, "tail");
2452      return focus;
2453    }
2454    case Skip : {
2455      checkOrdered(focus, "skip");
2456      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Integer)); 
2457      return focus;
2458    }
2459    case Take : {
2460      checkOrdered(focus, "take");
2461      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Integer)); 
2462      return focus;
2463    }
2464    case Union : {
2465      return focus.union(paramTypes.get(0));
2466    }
2467    case Combine : {
2468      return focus.union(paramTypes.get(0));
2469    }
2470    case Intersect : {
2471      return focus.intersect(paramTypes.get(0));
2472    }
2473    case Exclude : {
2474      return focus;
2475    }
2476    case Iif : {
2477      TypeDetails types = new TypeDetails(null);
2478      types.update(paramTypes.get(0));
2479      if (paramTypes.size() > 1)
2480        types.update(paramTypes.get(1));
2481      return types;
2482    }
2483    case Lower : {
2484      checkContextString(focus, "lower");
2485      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String); 
2486    }
2487    case Upper : {
2488      checkContextString(focus, "upper");
2489      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String); 
2490    }
2491    case ToChars : {
2492      checkContextString(focus, "toChars");
2493      return new TypeDetails(CollectionStatus.ORDERED, TypeDetails.FP_String); 
2494    }
2495    case IndexOf : {
2496      checkContextString(focus, "indexOf");
2497      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 
2498      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Integer); 
2499    }
2500    case Substring : {
2501      checkContextString(focus, "subString");
2502      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Integer), new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Integer)); 
2503      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String); 
2504    }
2505    case StartsWith : {
2506      checkContextString(focus, "startsWith");
2507      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 
2508      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 
2509    }
2510    case EndsWith : {
2511      checkContextString(focus, "endsWith");
2512      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 
2513      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 
2514    }
2515    case Matches : {
2516      checkContextString(focus, "matches");
2517      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 
2518      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 
2519    }
2520    case ReplaceMatches : {
2521      checkContextString(focus, "replaceMatches");
2522      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String), new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 
2523      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String); 
2524    }
2525    case Contains : {
2526      checkContextString(focus, "contains");
2527      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 
2528      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
2529    }
2530    case Replace : {
2531      checkContextString(focus, "replace");
2532      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, "string"), new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 
2533      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String);
2534    }
2535    case Length : { 
2536      checkContextPrimitive(focus, "length", false);
2537      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Integer);
2538    }
2539    case Children : 
2540      return childTypes(focus, "*");
2541    case Descendants : 
2542      return childTypes(focus, "**");
2543    case MemberOf : {
2544      checkContextCoded(focus, "memberOf");
2545      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 
2546      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
2547    }
2548    case Trace : {
2549      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 
2550      return focus; 
2551    }
2552    case Check : {
2553      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 
2554      return focus; 
2555    }
2556    case Today : 
2557      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_DateTime);
2558    case Now : 
2559      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_DateTime);
2560    case Resolve : {
2561      checkContextReference(focus, "resolve");
2562      return new TypeDetails(CollectionStatus.SINGLETON, "DomainResource"); 
2563    }
2564    case Extension : {
2565      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 
2566      return new TypeDetails(CollectionStatus.SINGLETON, "Extension"); 
2567    }
2568    case AnyTrue: 
2569      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
2570    case AllTrue: 
2571      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
2572    case AnyFalse: 
2573      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
2574    case AllFalse: 
2575      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
2576    case HasValue : 
2577      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
2578    case HtmlChecks : 
2579      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
2580    case Alias : 
2581      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 
2582      return anything(CollectionStatus.SINGLETON); 
2583    case AliasAs : 
2584      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 
2585      return focus; 
2586    case ToInteger : {
2587      checkContextPrimitive(focus, "toInteger", true);
2588      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Integer);
2589    }
2590    case ToDecimal : {
2591      checkContextPrimitive(focus, "toDecimal", true);
2592      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Decimal);
2593    }
2594    case ToString : {
2595      checkContextPrimitive(focus, "toString", true);
2596      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String);
2597    }
2598    case ToQuantity : {
2599      checkContextPrimitive(focus, "toQuantity", true);
2600      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Quantity);
2601    }
2602    case ToBoolean : {
2603      checkContextPrimitive(focus, "toBoolean", false);
2604      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
2605    }
2606    case ToDateTime : {
2607      checkContextPrimitive(focus, "toBoolean", false);
2608      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_DateTime);
2609    }
2610    case ToTime : {
2611      checkContextPrimitive(focus, "toBoolean", false);
2612      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Time);
2613    }
2614    case ConvertsToString : 
2615    case ConvertsToQuantity :{
2616      checkContextPrimitive(focus, exp.getFunction().toCode(), true);
2617      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
2618    } 
2619    case ConvertsToInteger : 
2620    case ConvertsToDecimal : 
2621    case ConvertsToDateTime : 
2622    case ConvertsToTime : 
2623    case ConvertsToBoolean : {
2624      checkContextPrimitive(focus, exp.getFunction().toCode(), false);
2625      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);
2626    }
2627    case ConformsTo: {
2628      checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 
2629      return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean);       
2630    }
2631    case Custom : {
2632      return hostServices.checkFunction(context.appInfo, exp.getName(), paramTypes);
2633    }
2634    default:
2635      break;
2636    }
2637    throw new Error("not Implemented yet");
2638  }
2639
2640
2641  private void checkParamTypes(String funcName, List<TypeDetails> paramTypes, TypeDetails... typeSet) throws PathEngineException {
2642    int i = 0;
2643    for (TypeDetails pt : typeSet) {
2644      if (i == paramTypes.size())
2645        return;
2646      TypeDetails actual = paramTypes.get(i);
2647      i++;
2648      for (String a : actual.getTypes()) {
2649        if (!pt.hasType(worker, a))
2650          throw new PathEngineException("The parameter type '"+a+"' is not legal for "+funcName+" parameter "+Integer.toString(i)+". expecting "+pt.toString()); 
2651      }
2652    }
2653  }
2654
2655  private void checkOrdered(TypeDetails focus, String name) throws PathEngineException {
2656    if (focus.getCollectionStatus() == CollectionStatus.UNORDERED)
2657      throw new PathEngineException("The function '"+name+"'() can only be used on ordered collections"); 
2658  }
2659
2660  private void checkContextReference(TypeDetails focus, String name) throws PathEngineException {
2661    if (!focus.hasType(worker, "string") && !focus.hasType(worker, "uri") && !focus.hasType(worker, "Reference") && !focus.hasType(worker, "canonical"))
2662      throw new PathEngineException("The function '"+name+"'() can only be used on string, uri, canonical, Reference"); 
2663  }
2664
2665
2666  private void checkContextCoded(TypeDetails focus, String name) throws PathEngineException {
2667    if (!focus.hasType(worker, "string") && !focus.hasType(worker, "code") && !focus.hasType(worker, "uri") && !focus.hasType(worker, "Coding") && !focus.hasType(worker, "CodeableConcept"))
2668      throw new PathEngineException("The function '"+name+"'() can only be used on string, code, uri, Coding, CodeableConcept");     
2669  }
2670
2671
2672  private void checkContextString(TypeDetails focus, String name) throws PathEngineException {
2673    if (!focus.hasType(worker, "string") && !focus.hasType(worker, "code") && !focus.hasType(worker, "uri") && !focus.hasType(worker, "canonical") && !focus.hasType(worker, "id"))
2674      throw new PathEngineException("The function '"+name+"'() can only be used on string, uri, code, id, but found "+focus.describe()); 
2675  }
2676
2677
2678  private void checkContextPrimitive(TypeDetails focus, String name, boolean canQty) throws PathEngineException {
2679    if (canQty) {
2680       if (!focus.hasType(primitiveTypes) && !focus.hasType("Quantity"))
2681        throw new PathEngineException("The function '"+name+"'() can only be used on a Quantity or on "+primitiveTypes.toString()); 
2682    } else if (!focus.hasType(primitiveTypes))
2683      throw new PathEngineException("The function '"+name+"'() can only be used on "+primitiveTypes.toString()); 
2684  }
2685
2686
2687  private TypeDetails childTypes(TypeDetails focus, String mask) throws PathEngineException, DefinitionException {
2688    TypeDetails result = new TypeDetails(CollectionStatus.UNORDERED);
2689    for (String f : focus.getTypes()) 
2690      getChildTypesByName(f, mask, result);
2691    return result;
2692  }
2693
2694  private TypeDetails anything(CollectionStatus status) {
2695    return new TypeDetails(status, allTypes.keySet());
2696  }
2697
2698  //    private boolean isPrimitiveType(String s) {
2699  //            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");
2700  //    }
2701
2702        private List<Base> evaluateFunction(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
2703    switch (exp.getFunction()) {
2704    case Empty : return funcEmpty(context, focus, exp);
2705    case Not : return funcNot(context, focus, exp);
2706    case Exists : return funcExists(context, focus, exp);
2707    case SubsetOf : return funcSubsetOf(context, focus, exp);
2708    case SupersetOf : return funcSupersetOf(context, focus, exp);
2709    case IsDistinct : return funcIsDistinct(context, focus, exp);
2710    case Distinct : return funcDistinct(context, focus, exp);
2711    case Count : return funcCount(context, focus, exp);
2712    case Where : return funcWhere(context, focus, exp);
2713    case Select : return funcSelect(context, focus, exp);
2714    case All : return funcAll(context, focus, exp);
2715    case Repeat : return funcRepeat(context, focus, exp);
2716    case Aggregate : return funcAggregate(context, focus, exp);
2717    case Item : return funcItem(context, focus, exp);
2718    case As : return funcAs(context, focus, exp);
2719    case OfType : return funcAs(context, focus, exp);
2720    case Type : return funcType(context, focus, exp);
2721    case Is : return funcIs(context, focus, exp);
2722    case Single : return funcSingle(context, focus, exp);
2723    case First : return funcFirst(context, focus, exp);
2724    case Last : return funcLast(context, focus, exp);
2725    case Tail : return funcTail(context, focus, exp);
2726    case Skip : return funcSkip(context, focus, exp);
2727    case Take : return funcTake(context, focus, exp);
2728    case Union : return funcUnion(context, focus, exp);
2729    case Combine : return funcCombine(context, focus, exp);
2730    case Intersect : return funcIntersect(context, focus, exp);
2731    case Exclude : return funcExclude(context, focus, exp);
2732    case Iif : return funcIif(context, focus, exp);
2733    case Lower : return funcLower(context, focus, exp);
2734    case Upper : return funcUpper(context, focus, exp);
2735    case ToChars : return funcToChars(context, focus, exp);
2736    case IndexOf : return funcIndexOf(context, focus, exp);
2737    case Substring : return funcSubstring(context, focus, exp);
2738    case StartsWith : return funcStartsWith(context, focus, exp);
2739    case EndsWith : return funcEndsWith(context, focus, exp);
2740    case Matches : return funcMatches(context, focus, exp);
2741    case ReplaceMatches : return funcReplaceMatches(context, focus, exp);
2742    case Contains : return funcContains(context, focus, exp);
2743    case Replace : return funcReplace(context, focus, exp);
2744    case Length : return funcLength(context, focus, exp);
2745    case Children : return funcChildren(context, focus, exp);
2746    case Descendants : return funcDescendants(context, focus, exp);
2747    case MemberOf : return funcMemberOf(context, focus, exp);
2748    case Trace : return funcTrace(context, focus, exp);
2749    case Check : return funcCheck(context, focus, exp);
2750    case Today : return funcToday(context, focus, exp);
2751    case Now : return funcNow(context, focus, exp);
2752    case Resolve : return funcResolve(context, focus, exp);
2753    case Extension : return funcExtension(context, focus, exp);
2754    case AnyFalse: return funcAnyFalse(context, focus, exp);
2755    case AllFalse: return funcAllFalse(context, focus, exp);
2756    case AnyTrue: return funcAnyTrue(context, focus, exp);
2757    case AllTrue: return funcAllTrue(context, focus, exp);
2758    case HasValue : return funcHasValue(context, focus, exp);
2759    case AliasAs : return funcAliasAs(context, focus, exp);
2760    case Alias : return funcAlias(context, focus, exp);
2761    case HtmlChecks : return funcHtmlChecks(context, focus, exp);
2762    case ToInteger : return funcToInteger(context, focus, exp);
2763    case ToDecimal : return funcToDecimal(context, focus, exp);
2764    case ToString : return funcToString(context, focus, exp);
2765    case ToBoolean : return funcToBoolean(context, focus, exp);
2766    case ToQuantity : return funcToQuantity(context, focus, exp);
2767    case ToDateTime : return funcToDateTime(context, focus, exp);
2768    case ToTime : return funcToTime(context, focus, exp);
2769    case ConvertsToInteger : return funcIsInteger(context, focus, exp);
2770    case ConvertsToDecimal : return funcIsDecimal(context, focus, exp);
2771    case ConvertsToString : return funcIsString(context, focus, exp);
2772    case ConvertsToBoolean : return funcIsBoolean(context, focus, exp);
2773    case ConvertsToQuantity : return funcIsQuantity(context, focus, exp);
2774    case ConvertsToDateTime : return funcIsDateTime(context, focus, exp);
2775    case ConvertsToTime : return funcIsTime(context, focus, exp);
2776    case ConformsTo : return funcConformsTo(context, focus, exp); 
2777    case Custom: { 
2778      List<List<Base>> params = new ArrayList<List<Base>>();
2779      for (ExpressionNode p : exp.getParameters()) 
2780        params.add(execute(context, focus, p, true));
2781      return hostServices.executeFunction(context.appInfo, exp.getName(), params);
2782    }
2783    default:
2784      throw new Error("not Implemented yet");
2785    }
2786  }
2787
2788        private List<Base> funcAliasAs(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
2789    List<Base> nl = execute(context, focus, exp.getParameters().get(0), true);
2790    String name = nl.get(0).primitiveValue();
2791    context.addAlias(name, focus);
2792    return focus;
2793  }
2794
2795  private List<Base> funcAlias(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
2796    List<Base> nl = execute(context, focus, exp.getParameters().get(0), true);
2797    String name = nl.get(0).primitiveValue();
2798    List<Base> res = new ArrayList<Base>();
2799    Base b = context.getAlias(name);
2800    if (b != null)
2801      res.add(b);
2802    return res;    
2803  }
2804
2805  private List<Base> funcHtmlChecks(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
2806    // todo: actually check the HTML
2807    return makeBoolean(true);    
2808  }
2809
2810  
2811  private List<Base> funcAll(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
2812    List<Base> result = new ArrayList<Base>();
2813    if (exp.getParameters().size() == 1) {
2814      List<Base> pc = new ArrayList<Base>();
2815      boolean all = true;
2816      for (Base item : focus) {
2817        pc.clear();
2818        pc.add(item);
2819        Equality eq = asBool(execute(changeThis(context, item), pc, exp.getParameters().get(0), true));
2820        if (eq != Equality.True) {
2821          all = false;
2822          break;
2823        }
2824      }
2825      result.add(new BooleanType(all).noExtensions());
2826    } else {// (exp.getParameters().size() == 0) {
2827      boolean all = true;
2828      for (Base item : focus) {
2829        Equality eq = asBool(item);
2830        if (eq != Equality.True) {
2831          all = false;
2832          break;
2833        }
2834      }
2835      result.add(new BooleanType(all).noExtensions());
2836    }
2837    return result;
2838  }
2839
2840
2841  private ExecutionContext changeThis(ExecutionContext context, Base newThis) {
2842    return new ExecutionContext(context.appInfo, context.focusResource, context.rootResource, context.context, context.aliases, newThis);
2843  }
2844
2845  private ExecutionTypeContext changeThis(ExecutionTypeContext context, TypeDetails newThis) {
2846    return new ExecutionTypeContext(context.appInfo, context.resource, context.context, newThis);
2847  }
2848
2849
2850  private List<Base> funcNow(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
2851    List<Base> result = new ArrayList<Base>();
2852    result.add(DateTimeType.now());
2853    return result;
2854  }
2855
2856
2857  private List<Base> funcToday(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
2858    List<Base> result = new ArrayList<Base>();
2859    result.add(new DateType(new Date(), TemporalPrecisionEnum.DAY));
2860    return result;
2861  }
2862
2863
2864  private List<Base> funcMemberOf(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
2865    throw new Error("not Implemented yet");
2866  }
2867
2868
2869  private List<Base> funcDescendants(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
2870    List<Base> result = new ArrayList<Base>();
2871    List<Base> current = new ArrayList<Base>();
2872    current.addAll(focus);
2873    List<Base> added = new ArrayList<Base>();
2874    boolean more = true;
2875    while (more) {
2876      added.clear();
2877      for (Base item : current) {
2878        getChildrenByName(item, "*", added);
2879      }
2880      more = !added.isEmpty();
2881      result.addAll(added);
2882      current.clear();
2883      current.addAll(added);
2884    }
2885    return result;
2886  }
2887
2888
2889  private List<Base> funcChildren(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
2890    List<Base> result = new ArrayList<Base>();
2891    for (Base b : focus)
2892      getChildrenByName(b, "*", result);
2893    return result;
2894  }
2895
2896
2897  private List<Base> funcReplace(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException, PathEngineException {
2898    List<Base> result = new ArrayList<Base>();
2899
2900    if (focus.size() == 1) {
2901      String f = convertToString(focus.get(0));
2902
2903      if (!Utilities.noString(f)) {
2904
2905        if (exp.getParameters().size() == 2) {
2906
2907          String t = convertToString(execute(context, focus, exp.getParameters().get(0), true));
2908          String r = convertToString(execute(context, focus, exp.getParameters().get(1), true));
2909
2910          String n = f.replace(t, r);
2911          result.add(new StringType(n));
2912        }
2913        else {
2914          throw new PathEngineException(String.format("funcReplace() : checking for 2 arguments (pattern, substitution) but found %d items", exp.getParameters().size()));
2915        }
2916      }
2917      else {
2918        throw new PathEngineException(String.format("funcReplace() : checking for 1 string item but found empty item"));
2919      }
2920    }
2921    else {
2922      throw new PathEngineException(String.format("funcReplace() : checking for 1 string item but found %d items", focus.size()));
2923    }
2924    return result;
2925  }
2926
2927
2928  private List<Base> funcReplaceMatches(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
2929    List<Base> result = new ArrayList<Base>();
2930    String regex = convertToString(execute(context, focus, exp.getParameters().get(0), true));
2931    String repl = convertToString(execute(context, focus, exp.getParameters().get(1), true));
2932
2933    if (focus.size() == 1 && !Utilities.noString(regex))
2934      result.add(new StringType(convertToString(focus.get(0)).replaceAll(regex, repl)).noExtensions());
2935    else
2936      result.add(new StringType(convertToString(focus.get(0))).noExtensions());
2937    return result;
2938  }
2939
2940
2941  private List<Base> funcEndsWith(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
2942    List<Base> result = new ArrayList<Base>();
2943    String sw = convertToString(execute(context, focus, exp.getParameters().get(0), true));
2944
2945    if (focus.size() == 0)
2946      result.add(new BooleanType(false).noExtensions());
2947    else if (Utilities.noString(sw))
2948      result.add(new BooleanType(true).noExtensions());
2949    else {
2950      if (focus.size() == 1 && !Utilities.noString(sw))
2951        result.add(new BooleanType(convertToString(focus.get(0)).endsWith(sw)).noExtensions());
2952      else
2953        result.add(new BooleanType(false).noExtensions());
2954    }
2955    return result;
2956  }
2957
2958
2959  private List<Base> funcToString(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
2960    List<Base> result = new ArrayList<Base>();
2961    result.add(new StringType(convertToString(focus)).noExtensions());
2962    return result;
2963  }
2964
2965  private List<Base> funcToBoolean(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
2966    List<Base> result = new ArrayList<Base>();
2967    if (focus.size() == 1) {
2968      if (focus.get(0) instanceof BooleanType)
2969        result.add(focus.get(0));
2970      else if (focus.get(0) instanceof IntegerType) {
2971        int i = Integer.parseInt(focus.get(0).primitiveValue());
2972        if (i == 0)
2973          result.add(new BooleanType(false).noExtensions());
2974        else if (i == 1)
2975          result.add(new BooleanType(true).noExtensions());
2976      } else if (focus.get(0) instanceof DecimalType) {
2977        if (((DecimalType) focus.get(0)).getValue().compareTo(BigDecimal.ZERO) == 0)
2978          result.add(new BooleanType(false).noExtensions());
2979        else if (((DecimalType) focus.get(0)).getValue().compareTo(BigDecimal.ONE) == 0)
2980          result.add(new BooleanType(true).noExtensions());
2981      } else if (focus.get(0) instanceof StringType) {
2982        if ("true".equalsIgnoreCase(focus.get(0).primitiveValue()))
2983          result.add(new BooleanType(true).noExtensions());
2984        else if ("false".equalsIgnoreCase(focus.get(0).primitiveValue()))
2985          result.add(new BooleanType(false).noExtensions()); 
2986      }
2987    }
2988    return result;
2989  }
2990
2991  private List<Base> funcToQuantity(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
2992    List<Base> result = new ArrayList<Base>();
2993    if (focus.size() == 1) {
2994      if (focus.get(0) instanceof Quantity) 
2995        result.add(focus.get(0));
2996      else if (focus.get(0) instanceof StringType) {
2997        Quantity q = parseQuantityString(focus.get(0).primitiveValue());
2998        if (q != null)
2999          result.add(q.noExtensions());
3000      } else if (focus.get(0) instanceof IntegerType) {
3001        result.add(new Quantity().setValue(new BigDecimal(focus.get(0).primitiveValue())).setSystem("http://unitsofmeasure.org").setCode("1").noExtensions());
3002      } else if (focus.get(0) instanceof DecimalType) {
3003        result.add(new Quantity().setValue(new BigDecimal(focus.get(0).primitiveValue())).setSystem("http://unitsofmeasure.org").setCode("1").noExtensions());
3004      }
3005    }
3006    return result;
3007  }
3008
3009  private List<Base> funcToDateTime(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3010//  List<Base> result = new ArrayList<Base>();
3011//  result.add(new BooleanType(convertToBoolean(focus)));
3012//  return result;
3013  throw new NotImplementedException("funcToDateTime is not implemented");
3014}
3015
3016  private List<Base> funcToTime(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3017//  List<Base> result = new ArrayList<Base>();
3018//  result.add(new BooleanType(convertToBoolean(focus)));
3019//  return result;
3020  throw new NotImplementedException("funcToTime is not implemented");
3021}
3022
3023
3024  private List<Base> funcToDecimal(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3025    String s = convertToString(focus);
3026    List<Base> result = new ArrayList<Base>();
3027    if (Utilities.isDecimal(s, true))
3028      result.add(new DecimalType(s).noExtensions());
3029    if ("true".equals(s))
3030      result.add(new DecimalType(1).noExtensions());
3031    if ("false".equals(s))
3032      result.add(new DecimalType(0).noExtensions());
3033    return result;
3034  }
3035
3036
3037  private List<Base> funcIif(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3038    List<Base> n1 = execute(context, focus, exp.getParameters().get(0), true);
3039    Equality v = asBool(n1);
3040
3041    if (v == Equality.True)
3042      return execute(context, focus, exp.getParameters().get(1), true);
3043    else if (exp.getParameters().size() < 3)
3044      return new ArrayList<Base>();
3045    else
3046      return execute(context, focus, exp.getParameters().get(2), true);
3047  }
3048
3049
3050  private List<Base> funcTake(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3051    List<Base> n1 = execute(context, focus, exp.getParameters().get(0), true);
3052    int i1 = Integer.parseInt(n1.get(0).primitiveValue());
3053
3054    List<Base> result = new ArrayList<Base>();
3055    for (int i = 0; i < Math.min(focus.size(), i1); i++)
3056      result.add(focus.get(i));
3057    return result;
3058  }
3059
3060
3061  private List<Base> funcUnion(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3062    List<Base> result = new ArrayList<Base>();
3063    for (Base item : focus) {
3064      if (!doContains(result, item))
3065        result.add(item);
3066    }
3067    for (Base item : execute(context, focus, exp.getParameters().get(0), true)) {
3068      if (!doContains(result, item))
3069        result.add(item);
3070    }
3071    return result;
3072  }
3073
3074  private List<Base> funcCombine(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3075    List<Base> result = new ArrayList<Base>();
3076    for (Base item : focus) {
3077      result.add(item);
3078    }
3079    for (Base item : execute(context, focus, exp.getParameters().get(0), true)) {
3080      result.add(item);
3081    }
3082    return result;
3083  }
3084
3085  private List<Base> funcIntersect(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3086    List<Base> result = new ArrayList<Base>();
3087    List<Base> other = execute(context, focus, exp.getParameters().get(0), true);
3088    
3089    for (Base item : focus) {
3090      if (!doContains(result, item) && doContains(other, item))
3091        result.add(item);
3092    }
3093    return result;    
3094  }
3095
3096  private List<Base> funcExclude(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3097    List<Base> result = new ArrayList<Base>();
3098    List<Base> other = execute(context, focus, exp.getParameters().get(0), true);
3099    
3100    for (Base item : focus) {
3101      if (!doContains(other, item))
3102        result.add(item);
3103    }
3104    return result;
3105  }
3106
3107
3108  private List<Base> funcSingle(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws PathEngineException {
3109    if (focus.size() == 1)
3110      return focus;
3111    throw new PathEngineException(String.format("Single() : checking for 1 item but found %d items", focus.size()));
3112  }
3113
3114
3115  private List<Base> funcIs(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws PathEngineException {
3116    if (focus.size() == 0 || focus.size() > 1) 
3117      return makeBoolean(false);
3118    String ns = null;
3119    String n = null;
3120    
3121    ExpressionNode texp = exp.getParameters().get(0);
3122    if (texp.getKind() != Kind.Name)
3123      throw new PathEngineException("Unsupported Expression type for Parameter on Is");
3124    if (texp.getInner() != null) {
3125      if (texp.getInner().getKind() != Kind.Name)
3126        throw new PathEngineException("Unsupported Expression type for Parameter on Is");
3127      ns = texp.getName();
3128      n = texp.getInner().getName();
3129    } else if (Utilities.existsInList(texp.getName(), "Boolean", "Integer", "Decimal", "String", "DateTime", "Time", "SimpleTypeInfo", "ClassInfo")) {
3130      ns = "System";
3131      n = texp.getName();
3132    } else {
3133      ns = "FHIR";
3134      n = texp.getName();        
3135    }
3136    if (ns.equals("System")) {
3137      if (focus.get(0) instanceof Resource)
3138        return makeBoolean(false);
3139      if (!(focus.get(0) instanceof Element) || ((Element) focus.get(0)).isDisallowExtensions())
3140        return makeBoolean(n.equals(Utilities.capitalize(focus.get(0).fhirType())));
3141      else
3142        return makeBoolean(false);
3143    } else if (ns.equals("FHIR")) {
3144      return makeBoolean(n.equals(focus.get(0).fhirType()));
3145    } else { 
3146      return makeBoolean(false);
3147    }
3148  }
3149
3150
3151  private List<Base> funcAs(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3152    List<Base> result = new ArrayList<Base>();
3153    String tn;
3154    if (exp.getParameters().get(0).getInner() != null)
3155      tn = exp.getParameters().get(0).getName()+"."+exp.getParameters().get(0).getInner().getName();
3156    else
3157      tn = "FHIR."+exp.getParameters().get(0).getName();
3158    for (Base b : focus) {
3159      if (tn.startsWith("System.")) {
3160          if (b instanceof Element &&((Element) b).isDisallowExtensions()) 
3161            if (b.hasType(tn.substring(7))) 
3162              result.add(b);
3163      } else if (tn.startsWith("FHIR.")) {
3164          if (b.hasType(tn.substring(5))) 
3165            result.add(b);
3166      }
3167    }
3168    return result;
3169  }
3170
3171  private List<Base> funcType(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3172    List<Base> result = new ArrayList<Base>();
3173    for (Base item : focus)
3174      result.add(new ClassTypeInfo(item));
3175    return result;
3176  }
3177
3178
3179  private List<Base> funcRepeat(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3180    List<Base> result = new ArrayList<Base>();
3181    List<Base> current = new ArrayList<Base>();
3182    current.addAll(focus);
3183    List<Base> added = new ArrayList<Base>();
3184    boolean more = true;
3185    while (more) {
3186      added.clear();
3187      List<Base> pc = new ArrayList<Base>();
3188      for (Base item : current) {
3189        pc.clear();
3190        pc.add(item);
3191        added.addAll(execute(changeThis(context, item), pc, exp.getParameters().get(0), false));
3192      }
3193      more = !added.isEmpty();
3194      result.addAll(added);
3195      current.clear();
3196      current.addAll(added);
3197    }
3198    return result;
3199  }
3200
3201
3202  private List<Base> funcAggregate(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3203    List<Base> total = new ArrayList<Base>();
3204    if (exp.parameterCount() > 1)
3205      total = execute(context, focus, exp.getParameters().get(1), false);
3206
3207    List<Base> pc = new ArrayList<Base>();
3208    for (Base item : focus) {
3209      ExecutionContext c = changeThis(context, item);
3210      c.total = total;
3211      total = execute(c, pc, exp.getParameters().get(0), true);
3212    }
3213    return total;
3214  }
3215
3216
3217
3218  private List<Base> funcIsDistinct(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3219    if (focus.size() < 1)
3220      return makeBoolean(true);
3221    if (focus.size() == 1)
3222      return makeBoolean(true);
3223
3224    boolean distinct = true;
3225    for (int i = 0; i < focus.size(); i++) {
3226      for (int j = i+1; j < focus.size(); j++) {
3227        Boolean eq = doEquals(focus.get(j), focus.get(i));
3228        if (eq == null) {
3229          return new ArrayList<Base>();
3230        } else if (eq == true) {
3231          distinct = false;
3232          break;
3233        }
3234      }
3235    }
3236    return makeBoolean(distinct);
3237  }
3238
3239
3240  private List<Base> funcSupersetOf(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3241    List<Base> target = execute(context, focus, exp.getParameters().get(0), true);
3242
3243    boolean valid = true;
3244    for (Base item : target) {
3245      boolean found = false;
3246      for (Base t : focus) {
3247        if (Base.compareDeep(item, t, false)) {
3248          found = true;
3249          break;
3250        }
3251      }
3252      if (!found) {
3253        valid = false;
3254        break;
3255      }
3256    }
3257    List<Base> result = new ArrayList<Base>();
3258    result.add(new BooleanType(valid).noExtensions());
3259    return result;
3260  }
3261
3262
3263  private List<Base> funcSubsetOf(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3264    List<Base> target = execute(context, focus, exp.getParameters().get(0), true);
3265
3266    boolean valid = true;
3267    for (Base item : focus) {
3268      boolean found = false;
3269      for (Base t : target) {
3270        if (Base.compareDeep(item, t, false)) {
3271          found = true;
3272          break;
3273        }
3274      }
3275      if (!found) {
3276        valid = false;
3277        break;
3278      }
3279    }
3280    List<Base> result = new ArrayList<Base>();
3281    result.add(new BooleanType(valid).noExtensions());
3282    return result;
3283  }
3284
3285
3286  private List<Base> funcExists(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3287    List<Base> result = new ArrayList<Base>();
3288    boolean empty = true;
3289    for (Base f : focus)
3290      if (!f.isEmpty())
3291        empty = false;
3292    result.add(new BooleanType(!empty).noExtensions());
3293    return result;
3294  }
3295
3296
3297  private List<Base> funcResolve(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3298    List<Base> result = new ArrayList<Base>();
3299    for (Base item : focus) {
3300      String s = convertToString(item);
3301      if (item.fhirType().equals("Reference")) {
3302        Property p = item.getChildByName("reference");
3303        if (p != null && p.hasValues())
3304          s = convertToString(p.getValues().get(0));
3305        else
3306          s = null; // a reference without any valid actual reference (just identifier or display, but we can't resolve it)
3307      }
3308      if (item.fhirType().equals("canonical")) {
3309        s = item.primitiveValue();
3310      }
3311      if (s != null) {
3312        Base res = null;
3313        if (s.startsWith("#")) {
3314          Property p = context.rootResource.getChildByName("contained");
3315          for (Base c : p.getValues()) {
3316            if (chompHash(s).equals(chompHash(c.getIdBase()))) {
3317              res = c;
3318              break;
3319            }
3320          }
3321        } else if (hostServices != null) {
3322          res = hostServices.resolveReference(context.appInfo, s);
3323        }
3324        if (res != null)
3325          result.add(res);
3326      }
3327    }
3328
3329    return result;
3330  }
3331
3332  /**
3333   * Strips a leading hashmark (#) if present at the start of a string
3334   */
3335  private String chompHash(String theId) {
3336    String retVal = theId;
3337    while (retVal.startsWith("#")) {
3338      retVal = retVal.substring(1);
3339    }
3340    return retVal;
3341  }
3342
3343  private List<Base> funcExtension(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3344    List<Base> result = new ArrayList<Base>();
3345    List<Base> nl = execute(context, focus, exp.getParameters().get(0), true);
3346    String url = nl.get(0).primitiveValue();
3347
3348    for (Base item : focus) {
3349      List<Base> ext = new ArrayList<Base>();
3350      getChildrenByName(item, "extension", ext);
3351      getChildrenByName(item, "modifierExtension", ext);
3352      for (Base ex : ext) {
3353        List<Base> vl = new ArrayList<Base>();
3354        getChildrenByName(ex, "url", vl);
3355        if (convertToString(vl).equals(url))
3356          result.add(ex);
3357      }
3358    }
3359    return result;
3360  }
3361
3362        private List<Base> funcAllFalse(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3363          List<Base> result = new ArrayList<Base>();
3364          if (exp.getParameters().size() == 1) {
3365            boolean all = true;
3366            List<Base> pc = new ArrayList<Base>();
3367            for (Base item : focus) {
3368              pc.clear();
3369              pc.add(item);
3370              List<Base> res = execute(context, pc, exp.getParameters().get(0), true);
3371              Equality v = asBool(res);
3372              if (v != Equality.False) {
3373                all = false;
3374                break;
3375              }
3376            }
3377            result.add(new BooleanType(all).noExtensions());
3378          } else { 
3379            boolean all = true;
3380            for (Base item : focus) {
3381              Equality v = asBool(item);
3382        if (v != Equality.False) {
3383                all = false;
3384                break;
3385              }
3386            }
3387            result.add(new BooleanType(all).noExtensions());
3388          }
3389          return result;
3390        }
3391  
3392        private List<Base> funcAnyFalse(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3393          List<Base> result = new ArrayList<Base>();
3394          if (exp.getParameters().size() == 1) {
3395            boolean any = false;
3396            List<Base> pc = new ArrayList<Base>();
3397            for (Base item : focus) {
3398              pc.clear();
3399              pc.add(item);
3400              List<Base> res = execute(context, pc, exp.getParameters().get(0), true);
3401              Equality v = asBool(res);
3402        if (v == Equality.False) {
3403                any = true;
3404                break;
3405              }
3406            }
3407            result.add(new BooleanType(any).noExtensions());
3408          } else {
3409            boolean any = false;
3410            for (Base item : focus) {
3411              Equality v = asBool(item);
3412        if (v == Equality.False) {
3413                any = true;
3414                break;
3415              }
3416            }
3417            result.add(new BooleanType(any).noExtensions());
3418          }
3419          return result;
3420        }
3421  
3422        private List<Base> funcAllTrue(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3423          List<Base> result = new ArrayList<Base>();
3424          if (exp.getParameters().size() == 1) {
3425            boolean all = true;
3426            List<Base> pc = new ArrayList<Base>();
3427            for (Base item : focus) {
3428              pc.clear();
3429              pc.add(item);
3430              List<Base> res = execute(context, pc, exp.getParameters().get(0), true);
3431              Equality v = asBool(res);
3432        if (v != Equality.True) {
3433                all = false;
3434                break;
3435              }
3436            }
3437            result.add(new BooleanType(all).noExtensions());
3438          } else { 
3439            boolean all = true;
3440            for (Base item : focus) {
3441              Equality v = asBool(item);
3442        if (v != Equality.True) {
3443                all = false;
3444                break;
3445              }
3446            }
3447            result.add(new BooleanType(all).noExtensions());
3448          }
3449          return result;
3450        }
3451
3452        private List<Base> funcAnyTrue(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3453          List<Base> result = new ArrayList<Base>();
3454          if (exp.getParameters().size() == 1) {
3455            boolean any = false;
3456            List<Base> pc = new ArrayList<Base>();
3457            for (Base item : focus) {
3458              pc.clear();
3459              pc.add(item);
3460              List<Base> res = execute(context, pc, exp.getParameters().get(0), true);
3461              Equality v = asBool(res);
3462        if (v == Equality.True) {
3463                any = true;
3464                break;
3465              }
3466            }
3467            result.add(new BooleanType(any).noExtensions());
3468          } else {
3469            boolean any = false;
3470      for (Base item : focus) {
3471        Equality v = asBool(item);
3472        if (v == Equality.True) {
3473                  any = true;
3474                  break;
3475                }
3476      }
3477      result.add(new BooleanType(any).noExtensions());
3478          }
3479          return result;
3480        }
3481
3482        private List<Base> funcTrace(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3483    List<Base> nl = execute(context, focus, exp.getParameters().get(0), true);
3484    String name = nl.get(0).primitiveValue();
3485    if (exp.getParameters().size() == 2) {
3486      List<Base> n2 = execute(context, focus, exp.getParameters().get(1), true);
3487      log(name, n2);
3488    } else 
3489      log(name, focus);
3490    return focus;
3491  }
3492
3493  private List<Base> funcCheck(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3494    List<Base> n1 = execute(context, focus, exp.getParameters().get(0), true);
3495    if (!convertToBoolean(n1)) {
3496      List<Base> n2 = execute(context, focus, exp.getParameters().get(1), true);
3497      String name = n2.get(0).primitiveValue();
3498      throw new FHIRException("check failed: "+name);
3499    }
3500    return focus;
3501  }
3502
3503  private List<Base> funcDistinct(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3504    if (focus.size() <= 1)
3505      return focus;
3506
3507    List<Base> result = new ArrayList<Base>();
3508    for (int i = 0; i < focus.size(); i++) {
3509      boolean found = false;
3510      for (int j = i+1; j < focus.size(); j++) {
3511        Boolean eq = doEquals(focus.get(j), focus.get(i));
3512        if (eq == null)
3513          return new ArrayList<Base>();
3514        else if (eq == true) {
3515          found = true;
3516          break;
3517        }
3518      }
3519      if (!found)
3520        result.add(focus.get(i));
3521    }
3522    return result;
3523  }
3524
3525        private List<Base> funcMatches(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3526    List<Base> result = new ArrayList<Base>();
3527    String sw = convertToString(execute(context, focus, exp.getParameters().get(0), true));
3528
3529    if (focus.size() == 1 && !Utilities.noString(sw)) {
3530      String st = convertToString(focus.get(0));
3531      if (Utilities.noString(st))
3532        result.add(new BooleanType(false).noExtensions());
3533      else {
3534        boolean ok = st.matches(sw);
3535        result.add(new BooleanType(ok).noExtensions());
3536      }
3537    } else
3538      result.add(new BooleanType(false).noExtensions());
3539    return result;
3540  }
3541
3542        private List<Base> funcContains(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3543    List<Base> result = new ArrayList<Base>();
3544    String sw = convertToString(execute(context, focus, exp.getParameters().get(0), true));
3545
3546    if (focus.size() != 1) {
3547      result.add(new BooleanType(false).noExtensions());
3548    } else if (Utilities.noString(sw)) {
3549      result.add(new BooleanType(true).noExtensions());
3550    } else {
3551      String st = convertToString(focus.get(0));
3552      if (Utilities.noString(st))
3553        result.add(new BooleanType(false).noExtensions());
3554      else
3555        result.add(new BooleanType(st.contains(sw)).noExtensions());
3556    } 
3557    return result;
3558  }
3559
3560  private List<Base> funcLength(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3561    List<Base> result = new ArrayList<Base>();
3562    if (focus.size() == 1) {
3563      String s = convertToString(focus.get(0));
3564      result.add(new IntegerType(s.length()).noExtensions());
3565    }
3566    return result;
3567  }
3568
3569  private List<Base> funcHasValue(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3570    List<Base> result = new ArrayList<Base>();
3571    if (focus.size() == 1) {
3572      String s = convertToString(focus.get(0));
3573      result.add(new BooleanType(!Utilities.noString(s)).noExtensions());
3574    } else
3575      result.add(new BooleanType(false).noExtensions());
3576    return result;
3577  }
3578
3579        private List<Base> funcStartsWith(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3580    List<Base> result = new ArrayList<Base>();
3581    String sw = convertToString(execute(context, focus, exp.getParameters().get(0), true));
3582
3583    if (focus.size() == 0) {
3584      result.add(new BooleanType(false).noExtensions());
3585    } else if (Utilities.noString(sw)) {
3586      result.add(new BooleanType(true).noExtensions());
3587    } else {
3588      String s = convertToString(focus.get(0));
3589      if (s == null)
3590        result.add(new BooleanType(false).noExtensions());
3591      else
3592        result.add(new BooleanType(s.startsWith(sw)).noExtensions());
3593    }
3594    return result;
3595  }
3596
3597  private List<Base> funcLower(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3598    List<Base> result = new ArrayList<Base>();
3599    if (focus.size() == 1) {
3600      String s = convertToString(focus.get(0));
3601      if (!Utilities.noString(s)) 
3602        result.add(new StringType(s.toLowerCase()).noExtensions());
3603    }
3604    return result;
3605  }
3606
3607  private List<Base> funcUpper(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3608    List<Base> result = new ArrayList<Base>();
3609    if (focus.size() == 1) {
3610      String s = convertToString(focus.get(0));
3611      if (!Utilities.noString(s)) 
3612        result.add(new StringType(s.toUpperCase()).noExtensions());
3613    }
3614    return result;
3615  }
3616
3617  private List<Base> funcToChars(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3618    List<Base> result = new ArrayList<Base>();
3619    if (focus.size() == 1) {
3620      String s = convertToString(focus.get(0));
3621      for (char c : s.toCharArray())  
3622        result.add(new StringType(String.valueOf(c)).noExtensions());
3623    }
3624    return result;
3625  }
3626  
3627  private List<Base> funcIndexOf(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3628    List<Base> result = new ArrayList<Base>();
3629    
3630    String sw = convertToString(execute(context, focus, exp.getParameters().get(0), true));
3631    if (focus.size() == 0) {
3632      result.add(new IntegerType(0).noExtensions());
3633    } else if (Utilities.noString(sw)) {
3634      result.add(new IntegerType(0).noExtensions());
3635    } else {
3636      String s = convertToString(focus.get(0));
3637      if (s == null)
3638        result.add(new IntegerType(0).noExtensions());
3639      else
3640        result.add(new IntegerType(s.indexOf(sw)).noExtensions());
3641    }
3642    return result;
3643  }
3644
3645        private List<Base> funcSubstring(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3646    List<Base> result = new ArrayList<Base>();
3647    List<Base> n1 = execute(context, focus, exp.getParameters().get(0), true);
3648    int i1 = Integer.parseInt(n1.get(0).primitiveValue());
3649    int i2 = -1;
3650    if (exp.parameterCount() == 2) {
3651      List<Base> n2 = execute(context, focus, exp.getParameters().get(1), true);
3652      i2 = Integer.parseInt(n2.get(0).primitiveValue());
3653    }
3654
3655    if (focus.size() == 1) {
3656      String sw = convertToString(focus.get(0));
3657      String s;
3658      if (i1 < 0 || i1 >= sw.length())
3659        return new ArrayList<Base>();
3660      if (exp.parameterCount() == 2)
3661        s = sw.substring(i1, Math.min(sw.length(), i1+i2));
3662      else
3663        s = sw.substring(i1);
3664      if (!Utilities.noString(s)) 
3665        result.add(new StringType(s).noExtensions());
3666    }
3667    return result;
3668  }
3669
3670  private List<Base> funcToInteger(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3671    String s = convertToString(focus);
3672    List<Base> result = new ArrayList<Base>();
3673    if (Utilities.isInteger(s))
3674      result.add(new IntegerType(s).noExtensions());
3675    else if ("true".equals(s))
3676      result.add(new IntegerType(1).noExtensions());
3677    else if ("false".equals(s))
3678      result.add(new IntegerType(0).noExtensions());
3679    return result;
3680  }
3681
3682  private List<Base> funcIsInteger(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3683    List<Base> result = new ArrayList<Base>();
3684    if (focus.size() != 1)
3685      result.add(new BooleanType(false).noExtensions());
3686    else if (focus.get(0) instanceof IntegerType)
3687      result.add(new BooleanType(true).noExtensions());
3688    else if (focus.get(0) instanceof BooleanType)
3689      result.add(new BooleanType(true).noExtensions());
3690    else if (focus.get(0) instanceof StringType)
3691      result.add(new BooleanType(Utilities.isInteger(convertToString(focus.get(0)))).noExtensions());
3692    else 
3693      result.add(new BooleanType(false).noExtensions());
3694    return result;
3695  }
3696
3697  private List<Base> funcIsBoolean(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3698    List<Base> result = new ArrayList<Base>();
3699    if (focus.size() != 1)
3700      result.add(new BooleanType(false).noExtensions());
3701    else if (focus.get(0) instanceof IntegerType)
3702      result.add(new BooleanType(((IntegerType) focus.get(0)).getValue() >= 0 && ((IntegerType) focus.get(0)).getValue() <= 1).noExtensions());
3703    else if (focus.get(0) instanceof DecimalType)
3704      result.add(new BooleanType(((DecimalType) focus.get(0)).getValue().compareTo(BigDecimal.ZERO) == 0 || ((DecimalType) focus.get(0)).getValue().compareTo(BigDecimal.ONE) == 0).noExtensions());
3705    else if (focus.get(0) instanceof BooleanType)
3706      result.add(new BooleanType(true).noExtensions());
3707    else if (focus.get(0) instanceof StringType)
3708      result.add(new BooleanType(Utilities.existsInList(convertToString(focus.get(0)).toLowerCase(), "true", "false")).noExtensions());
3709    else 
3710      result.add(new BooleanType(false).noExtensions());
3711    return result;
3712  }
3713
3714  private List<Base> funcIsDateTime(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3715    List<Base> result = new ArrayList<Base>();
3716    if (focus.size() != 1)
3717      result.add(new BooleanType(false).noExtensions());
3718    else if (focus.get(0) instanceof DateTimeType || focus.get(0) instanceof DateType)
3719      result.add(new BooleanType(true).noExtensions());
3720    else if (focus.get(0) instanceof StringType)
3721      result.add(new BooleanType((convertToString(focus.get(0)).matches
3722          ("([0-9]([0-9]([0-9][1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2][0-9]|3[0-1])(T([01][0-9]|2[0-3]):[0-5][0-9]:([0-5][0-9]|60)(\\.[0-9]+)?(Z|(\\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)?)?)?"))).noExtensions());
3723    else 
3724      result.add(new BooleanType(false).noExtensions());
3725    return result;
3726  }
3727
3728  private List<Base> funcConformsTo(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3729    if (hostServices == null)
3730      throw new FHIRException("Unable to check conformsTo - no hostservices provided");
3731    List<Base> result = new ArrayList<Base>();
3732    if (focus.size() != 1)
3733      result.add(new BooleanType(false).noExtensions());
3734    else {
3735      String url = convertToString(execute(context, focus, exp.getParameters().get(0), true));
3736      result.add(new BooleanType(hostServices.conformsToProfile(context.appInfo,  focus.get(0), url)).noExtensions());
3737    }
3738    return result;
3739  }
3740
3741  private List<Base> funcIsTime(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3742    List<Base> result = new ArrayList<Base>();
3743    if (focus.size() != 1)
3744      result.add(new BooleanType(false).noExtensions());
3745    else if (focus.get(0) instanceof TimeType)
3746      result.add(new BooleanType(true).noExtensions());
3747    else if (focus.get(0) instanceof StringType)
3748      result.add(new BooleanType((convertToString(focus.get(0)).matches
3749          ("T([01][0-9]|2[0-3]):[0-5][0-9]:([0-5][0-9]|60)(\\.[0-9]+)?(Z|(\\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?"))).noExtensions());
3750    else 
3751      result.add(new BooleanType(false).noExtensions());
3752    return result;
3753  }
3754
3755  private List<Base> funcIsString(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3756    List<Base> result = new ArrayList<Base>();
3757    if (focus.size() != 1)
3758      result.add(new BooleanType(false).noExtensions());
3759    else if (!(focus.get(0) instanceof DateTimeType) && !(focus.get(0) instanceof TimeType))
3760      result.add(new BooleanType(true).noExtensions());
3761    else 
3762      result.add(new BooleanType(false).noExtensions());
3763    return result;
3764  }
3765
3766  private List<Base> funcIsQuantity(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3767    List<Base> result = new ArrayList<Base>();
3768    if (focus.size() != 1)
3769      result.add(new BooleanType(false).noExtensions());
3770    else if (focus.get(0) instanceof IntegerType)
3771      result.add(new BooleanType(true).noExtensions());
3772    else if (focus.get(0) instanceof DecimalType)
3773      result.add(new BooleanType(true).noExtensions());
3774    else if (focus.get(0) instanceof Quantity)
3775      result.add(new BooleanType(true).noExtensions());
3776    else if (focus.get(0) instanceof BooleanType)
3777      result.add(new BooleanType(true).noExtensions());
3778    else  if (focus.get(0) instanceof StringType) {
3779      Quantity q = parseQuantityString(focus.get(0).primitiveValue());
3780      result.add(new BooleanType(q != null).noExtensions());
3781    } else
3782      result.add(new BooleanType(false).noExtensions());
3783    return result;
3784  }
3785
3786  public Quantity parseQuantityString(String s) {
3787    if (s == null)
3788      return null;
3789    s = s.trim();
3790    if (s.contains(" ")) {
3791      String v = s.substring(0, s.indexOf(" ")).trim();
3792      s = s.substring(s.indexOf(" ")).trim();
3793      if (!Utilities.isDecimal(v, false))
3794        return null;
3795      if (s.startsWith("'") && s.endsWith("'"))
3796        return Quantity.fromUcum(v, s.substring(1, s.length()-1));
3797      if (s.equals("year") || s.equals("years"))
3798        return Quantity.fromUcum(v, "a");
3799      else if (s.equals("month") || s.equals("months"))
3800        return Quantity.fromUcum(v, "mo");
3801      else if (s.equals("week") || s.equals("weeks"))
3802        return Quantity.fromUcum(v, "wk");
3803      else if (s.equals("day") || s.equals("days"))
3804        return Quantity.fromUcum(v, "d");
3805      else if (s.equals("hour") || s.equals("hours"))
3806        return Quantity.fromUcum(v, "h");
3807      else if (s.equals("minute") || s.equals("minutes"))
3808        return Quantity.fromUcum(v, "min");
3809      else if (s.equals("second") || s.equals("seconds"))
3810        return Quantity.fromUcum(v, "s");
3811      else if (s.equals("millisecond") || s.equals("milliseconds"))
3812        return Quantity.fromUcum(v, "ms");
3813      else
3814        return null;      
3815    } else {
3816      if (Utilities.isDecimal(s, true))
3817        return new Quantity().setValue(new BigDecimal(s)).setSystem("http://unitsofmeasure.org").setCode("1");
3818      else
3819        return null;
3820    }
3821  }
3822
3823
3824  private List<Base> funcIsDecimal(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3825    List<Base> result = new ArrayList<Base>();
3826    if (focus.size() != 1)
3827      result.add(new BooleanType(false).noExtensions());
3828    else if (focus.get(0) instanceof IntegerType)
3829      result.add(new BooleanType(true).noExtensions());
3830    else if (focus.get(0) instanceof BooleanType)
3831      result.add(new BooleanType(true).noExtensions());
3832    else if (focus.get(0) instanceof DecimalType)
3833      result.add(new BooleanType(true).noExtensions());
3834    else if (focus.get(0) instanceof StringType)
3835      result.add(new BooleanType(Utilities.isDecimal(convertToString(focus.get(0)), true)).noExtensions());
3836    else 
3837      result.add(new BooleanType(false).noExtensions());
3838    return result;
3839  }
3840
3841  private List<Base> funcCount(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3842    List<Base> result = new ArrayList<Base>();
3843    result.add(new IntegerType(focus.size()).noExtensions());
3844    return result;
3845  }
3846
3847  private List<Base> funcSkip(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3848    List<Base> n1 = execute(context, focus, exp.getParameters().get(0), true);
3849    int i1 = Integer.parseInt(n1.get(0).primitiveValue());
3850
3851    List<Base> result = new ArrayList<Base>();
3852    for (int i = i1; i < focus.size(); i++)
3853      result.add(focus.get(i));
3854    return result;
3855  }
3856
3857  private List<Base> funcTail(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3858    List<Base> result = new ArrayList<Base>();
3859    for (int i = 1; i < focus.size(); i++)
3860      result.add(focus.get(i));
3861    return result;
3862  }
3863
3864  private List<Base> funcLast(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3865    List<Base> result = new ArrayList<Base>();
3866    if (focus.size() > 0)
3867      result.add(focus.get(focus.size()-1));
3868    return result;
3869  }
3870
3871  private List<Base> funcFirst(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3872    List<Base> result = new ArrayList<Base>();
3873    if (focus.size() > 0)
3874      result.add(focus.get(0));
3875    return result;
3876  }
3877
3878
3879        private List<Base> funcWhere(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3880    List<Base> result = new ArrayList<Base>();
3881    List<Base> pc = new ArrayList<Base>();
3882    for (Base item : focus) {
3883      pc.clear();
3884      pc.add(item);
3885      Equality v = asBool(execute(changeThis(context, item), pc, exp.getParameters().get(0), true));
3886      if (v == Equality.True)
3887        result.add(item);
3888    }
3889    return result;
3890  }
3891
3892  private List<Base> funcSelect(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3893    List<Base> result = new ArrayList<Base>();
3894    List<Base> pc = new ArrayList<Base>();
3895    for (Base item : focus) {
3896      pc.clear();
3897      pc.add(item);
3898      result.addAll(execute(changeThis(context, item), pc, exp.getParameters().get(0), true));
3899    }
3900    return result;
3901  }
3902
3903
3904        private List<Base> funcItem(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException {
3905    List<Base> result = new ArrayList<Base>();
3906    String s = convertToString(execute(context, focus, exp.getParameters().get(0), true));
3907    if (Utilities.isInteger(s) && Integer.parseInt(s) < focus.size())
3908      result.add(focus.get(Integer.parseInt(s)));
3909    return result;
3910  }
3911
3912  private List<Base> funcEmpty(ExecutionContext context, List<Base> focus, ExpressionNode exp) {
3913    List<Base> result = new ArrayList<Base>();
3914                result.add(new BooleanType(ElementUtil.isEmpty(focus)).noExtensions());
3915    return result;
3916  }
3917
3918  private List<Base> funcNot(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws PathEngineException {
3919    List<Base> result = new ArrayList<Base>();  
3920    Equality v = asBool(focus);
3921    if (v != Equality.Null)
3922      result.add(new BooleanType(v != Equality.True));
3923    return result;
3924  }
3925
3926  public class ElementDefinitionMatch {
3927    private ElementDefinition definition;
3928    private String fixedType;
3929    public ElementDefinitionMatch(ElementDefinition definition, String fixedType) {
3930      super();
3931      this.definition = definition;
3932      this.fixedType = fixedType;
3933    }
3934    public ElementDefinition getDefinition() {
3935      return definition;
3936    }
3937    public String getFixedType() {
3938      return fixedType;
3939    }
3940
3941  }
3942
3943  private void getChildTypesByName(String type, String name, TypeDetails result) throws PathEngineException, DefinitionException {
3944    if (Utilities.noString(type))
3945      throw new PathEngineException("No type provided in BuildToolPathEvaluator.getChildTypesByName");
3946    if (type.equals("http://hl7.org/fhir/StructureDefinition/xhtml"))
3947      return;
3948    if (type.startsWith(Constants.NS_SYSTEM_TYPE))
3949      return;
3950    
3951    if (type.equals(TypeDetails.FP_SimpleTypeInfo)) { 
3952      getSimpleTypeChildTypesByName(name, result);
3953    } else if (type.equals(TypeDetails.FP_ClassInfo)) { 
3954      getClassInfoChildTypesByName(name, result);
3955    } else {
3956    String url = null;
3957    if (type.contains("#")) {
3958      url = type.substring(0, type.indexOf("#"));
3959    } else {
3960      url = type;
3961    }
3962    String tail = "";
3963    StructureDefinition sd = worker.fetchResource(StructureDefinition.class, url);
3964    if (sd == null)
3965      throw new DefinitionException("Unknown type "+type); // this really is an error, because we can only get to here if the internal infrastrucgture is wrong
3966    List<StructureDefinition> sdl = new ArrayList<StructureDefinition>();
3967    ElementDefinitionMatch m = null;
3968    if (type.contains("#"))
3969      m = getElementDefinition(sd, type.substring(type.indexOf("#")+1), false);
3970    if (m != null && hasDataType(m.definition)) {
3971      if (m.fixedType != null)
3972      {
3973        StructureDefinition dt = worker.fetchResource(StructureDefinition.class, ProfileUtilities.sdNs(m.fixedType, worker.getOverrideVersionNs()));
3974        if (dt == null)
3975          throw new DefinitionException("unknown data type "+m.fixedType);
3976        sdl.add(dt);
3977      } else
3978        for (TypeRefComponent t : m.definition.getType()) {
3979          StructureDefinition dt = worker.fetchResource(StructureDefinition.class, ProfileUtilities.sdNs(t.getCode(), worker.getOverrideVersionNs()));
3980          if (dt == null)
3981            throw new DefinitionException("unknown data type "+t.getCode());
3982          sdl.add(dt);
3983        }
3984    } else {
3985      sdl.add(sd);
3986      if (type.contains("#")) {
3987        tail = type.substring(type.indexOf("#")+1);
3988        tail = tail.substring(tail.indexOf("."));
3989      }
3990    }
3991
3992    for (StructureDefinition sdi : sdl) {
3993      String path = sdi.getSnapshot().getElement().get(0).getPath()+tail+".";
3994      if (name.equals("**")) {
3995        assert(result.getCollectionStatus() == CollectionStatus.UNORDERED);
3996        for (ElementDefinition ed : sdi.getSnapshot().getElement()) {
3997          if (ed.getPath().startsWith(path))
3998            for (TypeRefComponent t : ed.getType()) {
3999              if (t.hasCode() && t.getCodeElement().hasValue()) {
4000                String tn = null;
4001                if (t.getCode().equals("Element") || t.getCode().equals("BackboneElement"))
4002                  tn = sdi.getType()+"#"+ed.getPath();
4003                else
4004                  tn = t.getCode();
4005                if (t.getCode().equals("Resource")) {
4006                  for (String rn : worker.getResourceNames()) {
4007                    if (!result.hasType(worker, rn)) {
4008                      getChildTypesByName(result.addType(rn), "**", result);
4009                    }                  
4010                  }
4011                } else if (!result.hasType(worker, tn)) {
4012                  getChildTypesByName(result.addType(tn), "**", result);
4013                }
4014              }
4015            }
4016        }      
4017      } else if (name.equals("*")) {
4018        assert(result.getCollectionStatus() == CollectionStatus.UNORDERED);
4019        for (ElementDefinition ed : sdi.getSnapshot().getElement()) {
4020          if (ed.getPath().startsWith(path) && !ed.getPath().substring(path.length()).contains("."))
4021            for (TypeRefComponent t : ed.getType()) {
4022              if (Utilities.noString(t.getCode())) // Element.id or Extension.url
4023                result.addType("System.string");
4024              else if (t.getCode().equals("Element") || t.getCode().equals("BackboneElement"))
4025                result.addType(sdi.getType()+"#"+ed.getPath());
4026              else if (t.getCode().equals("Resource"))
4027                result.addTypes(worker.getResourceNames());
4028              else
4029                result.addType(t.getCode());
4030            }
4031        }
4032      } else {
4033        path = sdi.getSnapshot().getElement().get(0).getPath()+tail+"."+name;
4034
4035        ElementDefinitionMatch ed = getElementDefinition(sdi, path, false);
4036        if (ed != null) {
4037          if (!Utilities.noString(ed.getFixedType()))
4038            result.addType(ed.getFixedType());
4039          else
4040            for (TypeRefComponent t : ed.getDefinition().getType()) {
4041              if (Utilities.noString(t.getCode())) {
4042                if (Utilities.existsInList(ed.getDefinition().getId(), "Element.id", "Extension.url") || Utilities.existsInList(ed.getDefinition().getBase().getPath(), "Resource.id", "Element.id", "Extension.url")) 
4043                  result.addType(TypeDetails.FP_NS, "string");
4044                break; // throw new PathEngineException("Illegal reference to primitive value attribute @ "+path);
4045              }
4046
4047              ProfiledType pt = null;
4048              if (t.getCode().equals("Element") || t.getCode().equals("BackboneElement"))
4049                pt = new ProfiledType(sdi.getUrl()+"#"+path);
4050              else if (t.getCode().equals("Resource"))
4051                result.addTypes(worker.getResourceNames());
4052              else
4053                pt = new ProfiledType(t.getCode());
4054              if (pt != null) {
4055                if (t.hasProfile())
4056                  pt.addProfiles(t.getProfile());
4057                if (ed.getDefinition().hasBinding())
4058                  pt.addBinding(ed.getDefinition().getBinding());
4059                result.addType(pt);
4060              }
4061            }
4062        }
4063      }
4064    }
4065    }
4066  }
4067
4068  private void getClassInfoChildTypesByName(String name, TypeDetails result) {
4069    if (name.equals("namespace"))
4070      result.addType(TypeDetails.FP_String);
4071    if (name.equals("name"))
4072      result.addType(TypeDetails.FP_String);
4073  }
4074
4075
4076  private void getSimpleTypeChildTypesByName(String name, TypeDetails result) {
4077    if (name.equals("namespace"))
4078      result.addType(TypeDetails.FP_String);
4079    if (name.equals("name"))
4080      result.addType(TypeDetails.FP_String);
4081  }
4082
4083
4084  private ElementDefinitionMatch getElementDefinition(StructureDefinition sd, String path, boolean allowTypedName) throws PathEngineException {
4085    for (ElementDefinition ed : sd.getSnapshot().getElement()) {
4086      if (ed.getPath().equals(path)) {
4087        if (ed.hasContentReference()) {
4088          return getElementDefinitionById(sd, ed.getContentReference());
4089        } else
4090          return new ElementDefinitionMatch(ed, null);
4091      }
4092      if (ed.getPath().endsWith("[x]") && path.startsWith(ed.getPath().substring(0, ed.getPath().length()-3)) && path.length() == ed.getPath().length()-3)
4093        return new ElementDefinitionMatch(ed, null);
4094      if (allowTypedName && ed.getPath().endsWith("[x]") && path.startsWith(ed.getPath().substring(0, ed.getPath().length()-3)) && path.length() > ed.getPath().length()-3) {
4095        String s = Utilities.uncapitalize(path.substring(ed.getPath().length()-3));
4096        if (primitiveTypes.contains(s))
4097          return new ElementDefinitionMatch(ed, s);
4098        else
4099        return new ElementDefinitionMatch(ed, path.substring(ed.getPath().length()-3));
4100      }
4101      if (ed.getPath().contains(".") && path.startsWith(ed.getPath()+".") && (ed.getType().size() > 0) && !isAbstractType(ed.getType())) { 
4102        // now we walk into the type.
4103        if (ed.getType().size() > 1)  // if there's more than one type, the test above would fail this
4104          throw new PathEngineException("Internal typing issue....");
4105        StructureDefinition nsd = worker.fetchResource(StructureDefinition.class, ProfileUtilities.sdNs(ed.getType().get(0).getCode(), worker.getOverrideVersionNs()));
4106            if (nsd == null) 
4107              throw new PathEngineException("Unknown type "+ed.getType().get(0).getCode());
4108        return getElementDefinition(nsd, nsd.getId()+path.substring(ed.getPath().length()), allowTypedName);
4109      }
4110      if (ed.hasContentReference() && path.startsWith(ed.getPath()+".")) {
4111        ElementDefinitionMatch m = getElementDefinitionById(sd, ed.getContentReference());
4112        return getElementDefinition(sd, m.definition.getPath()+path.substring(ed.getPath().length()), allowTypedName);
4113      }
4114    }
4115    return null;
4116  }
4117
4118  private boolean isAbstractType(List<TypeRefComponent> list) {
4119        return list.size() != 1 ? true : Utilities.existsInList(list.get(0).getCode(), "Element", "BackboneElement", "Resource", "DomainResource");
4120}
4121
4122
4123  private boolean hasType(ElementDefinition ed, String s) {
4124    for (TypeRefComponent t : ed.getType()) 
4125      if (s.equalsIgnoreCase(t.getCode()))
4126        return true;
4127    return false;
4128  }
4129
4130  private boolean hasDataType(ElementDefinition ed) {
4131    return ed.hasType() && !(ed.getType().get(0).getCode().equals("Element") || ed.getType().get(0).getCode().equals("BackboneElement"));
4132  }
4133
4134  private ElementDefinitionMatch getElementDefinitionById(StructureDefinition sd, String ref) {
4135    for (ElementDefinition ed : sd.getSnapshot().getElement()) {
4136      if (ref.equals("#"+ed.getId())) 
4137        return new ElementDefinitionMatch(ed, null);
4138    }
4139    return null;
4140  }
4141
4142
4143  public boolean hasLog() {
4144    return log != null && log.length() > 0;
4145  }
4146
4147
4148  public String takeLog() {
4149    if (!hasLog())
4150      return "";
4151    String s = log.toString();
4152    log = new StringBuilder();
4153    return s;
4154  }
4155
4156
4157  /** given an element definition in a profile, what element contains the differentiating fixed 
4158   * for the element, given the differentiating expresssion. The expression is only allowed to 
4159   * use a subset of FHIRPath
4160   * 
4161   * @param profile
4162   * @param element
4163   * @return
4164   * @throws PathEngineException 
4165   * @throws DefinitionException 
4166   */
4167  public ElementDefinition evaluateDefinition(ExpressionNode expr, StructureDefinition profile, ElementDefinition element) throws DefinitionException {
4168    StructureDefinition sd = profile;
4169    ElementDefinition focus = null;
4170
4171    if (expr.getKind() == Kind.Name) {
4172      if (element.hasSlicing()) {
4173        ElementDefinition slice = pickMandatorySlice(sd, element);
4174        if (slice == null)
4175          throw new DefinitionException("Error in discriminator at "+element.getId()+": found a sliced element while resolving the fixed value for one of the slices");
4176        element = slice;
4177      }
4178      
4179      if (expr.getName().equals("$this")) {
4180        focus = element;
4181      } else { 
4182        List<ElementDefinition> childDefinitions;
4183        childDefinitions = ProfileUtilities.getChildMap(sd, element);
4184        // if that's empty, get the children of the type
4185        if (childDefinitions.isEmpty()) {
4186
4187          sd = fetchStructureByType(element);
4188          if (sd == null)
4189            throw new DefinitionException("Problem with use of resolve() - profile '"+element.getType().get(0).getProfile()+"' on "+element.getId()+" could not be resolved");
4190          childDefinitions = ProfileUtilities.getChildMap(sd, sd.getSnapshot().getElementFirstRep());
4191        }
4192        for (ElementDefinition t : childDefinitions) {
4193          if (tailMatches(t, expr.getName())) {
4194            focus = t;
4195            break;
4196          }
4197        }
4198      }
4199    } else if (expr.getKind() == Kind.Function) {
4200      if ("resolve".equals(expr.getName())) {
4201        if (!element.hasType())
4202          throw new DefinitionException("illegal use of resolve() in discriminator - no type on element "+element.getId());
4203        if (element.getType().size() > 1)
4204          throw new DefinitionException("illegal use of resolve() in discriminator - Multiple possible types on "+element.getId());
4205        if (!element.getType().get(0).hasTarget())
4206          throw new DefinitionException("illegal use of resolve() in discriminator - type on "+element.getId()+" is not Reference ("+element.getType().get(0).getCode()+")");
4207        if (element.getType().get(0).getTargetProfile().size() > 1)
4208          throw new DefinitionException("illegal use of resolve() in discriminator - Multiple possible target type profiles on "+element.getId());
4209        sd = worker.fetchResource(StructureDefinition.class, element.getType().get(0).getTargetProfile().get(0).getValue());
4210        if (sd == null)
4211          throw new DefinitionException("Problem with use of resolve() - profile '"+element.getType().get(0).getTargetProfile()+"' on "+element.getId()+" could not be resolved");
4212        focus = sd.getSnapshot().getElementFirstRep();
4213      } else if ("extension".equals(expr.getName())) {
4214        String targetUrl = expr.getParameters().get(0).getConstant().primitiveValue();
4215//        targetUrl = targetUrl.substring(1,targetUrl.length()-1);
4216        List<ElementDefinition> childDefinitions = ProfileUtilities.getChildMap(sd, element);
4217        for (ElementDefinition t : childDefinitions) {
4218          if (t.getPath().endsWith(".extension") && t.hasSliceName()) {
4219           StructureDefinition exsd = worker.fetchResource(StructureDefinition.class, t.getType().get(0).getProfile().get(0).getValue());
4220           while (exsd!=null && !exsd.getBaseDefinition().equals("http://hl7.org/fhir/StructureDefinition/Extension"))
4221             exsd = worker.fetchResource(StructureDefinition.class, exsd.getBaseDefinition());
4222           if (exsd.getUrl().equals(targetUrl)) {
4223             if (ProfileUtilities.getChildMap(sd, t).isEmpty())
4224               sd = exsd;
4225             focus = t;
4226             break;
4227           }
4228          }
4229        }
4230      } else 
4231        throw new DefinitionException("illegal function name "+expr.getName()+"() in discriminator");
4232    } else if (expr.getKind() == Kind.Group) {
4233      throw new DefinitionException("illegal expression syntax in discriminator (group)");
4234    } else if (expr.getKind() == Kind.Constant) {
4235      throw new DefinitionException("illegal expression syntax in discriminator (const)");
4236    }
4237
4238    if (focus == null)
4239      throw new DefinitionException("Unable to resolve discriminator in definitions: "+expr.toString());      
4240    else if (expr.getInner() == null)
4241      return focus;
4242    else {
4243      return evaluateDefinition(expr.getInner(), sd, focus);
4244    }
4245  }
4246
4247  private ElementDefinition pickMandatorySlice(StructureDefinition sd, ElementDefinition element) throws DefinitionException {
4248    List<ElementDefinition> list = ProfileUtilities.getSliceList(sd, element);
4249    for (ElementDefinition ed : list) {
4250      if (ed.getMin() > 0)
4251        return ed;
4252    }
4253    return null;
4254  }
4255
4256
4257  private StructureDefinition fetchStructureByType(ElementDefinition ed) throws DefinitionException {
4258    if (ed.getType().size() == 0)
4259      throw new DefinitionException("Error in discriminator at "+ed.getId()+": no children, no type");
4260    if (ed.getType().size() > 1)
4261      throw new DefinitionException("Error in discriminator at "+ed.getId()+": no children, multiple types");
4262    if (ed.getType().get(0).getProfile().size() > 1)
4263      throw new DefinitionException("Error in discriminator at "+ed.getId()+": no children, multiple type profiles");
4264    if (ed.getType().get(0).hasProfile()) 
4265      return worker.fetchResource(StructureDefinition.class, ed.getType().get(0).getProfile().get(0).getValue());
4266    else
4267      return worker.fetchResource(StructureDefinition.class, ProfileUtilities.sdNs(ed.getType().get(0).getCode(), worker.getOverrideVersionNs()));
4268  }
4269
4270
4271  private boolean tailMatches(ElementDefinition t, String d) {
4272    String tail = tailDot(t.getPath());
4273    if (d.contains("["))
4274      return tail.startsWith(d.substring(0, d.indexOf('[')));
4275    else if (tail.equals(d))
4276      return true;
4277    else if (t.getType().size() == 1 && t.getType().get(0).getCode() != null && t.getPath() != null && t.getPath().toUpperCase().endsWith(t.getType().get(0).getCode().toUpperCase()))
4278      return tail.startsWith(d);
4279    else if (t.getPath().endsWith("[x]") && tail.startsWith(d))
4280      return true;
4281    return false;
4282  }
4283
4284  private String tailDot(String path) {
4285    return path.substring(path.lastIndexOf(".") + 1);
4286  }
4287
4288  private Equality asBool(List<Base> items) throws PathEngineException {
4289    if (items.size() == 0)
4290      return Equality.Null;
4291    else if (items.size() == 1)
4292      return asBool(items.get(0));
4293    else
4294      throw new PathEngineException("Unable to evaluate as a boolean: "+convertToString(items));
4295  }
4296  
4297  private Equality asBoolFromInt(String s) {
4298    try {
4299      int i = Integer.parseInt(s);
4300      switch (i) {
4301      case 0: return Equality.False;
4302      case 1: return Equality.True;
4303      default: return Equality.Null;
4304      }
4305    } catch (Exception e) {
4306      return Equality.Null;
4307    }
4308  }
4309
4310  private Equality asBoolFromDec(String s) {
4311    try {
4312      BigDecimal d = new BigDecimal(s);
4313      if (d.compareTo(BigDecimal.ZERO) == 0) 
4314        return Equality.False;
4315      else if (d.compareTo(BigDecimal.ONE) == 0) 
4316        return Equality.True;
4317      else
4318        return Equality.Null;
4319    } catch (Exception e) {
4320      return Equality.Null;
4321    }
4322  }
4323
4324  private Equality asBool(Base item) {
4325    if (item instanceof BooleanType) 
4326      return boolToTriState(((BooleanType) item).booleanValue());
4327    else if (item.isBooleanPrimitive()) {
4328      if (Utilities.existsInList(item.primitiveValue(), "true"))
4329        return Equality.True;
4330      else if (Utilities.existsInList(item.primitiveValue(), "false"))
4331        return Equality.False;
4332      else
4333        return Equality.Null;
4334    } else if (item instanceof IntegerType || Utilities.existsInList(item.fhirType(), "integer", "positiveint", "unsignedInt"))
4335      return asBoolFromInt(item.primitiveValue());
4336    else if (item instanceof DecimalType || Utilities.existsInList(item.fhirType(), "decimal"))
4337      return asBoolFromDec(item.primitiveValue());
4338    else if (Utilities.existsInList(item.fhirType(), FHIR_TYPES_STRING)) {
4339      if (Utilities.existsInList(item.primitiveValue(), "true", "t", "yes", "y"))
4340        return Equality.True;
4341      else if (Utilities.existsInList(item.primitiveValue(), "false", "f", "no", "n"))
4342        return Equality.False;
4343      else if (Utilities.isInteger(item.primitiveValue()))
4344        return asBoolFromInt(item.primitiveValue());
4345      else if (Utilities.isDecimal(item.primitiveValue(), true))
4346        return asBoolFromDec(item.primitiveValue());
4347      else
4348        return Equality.Null;
4349    } 
4350      return Equality.Null;
4351  }
4352          
4353  private Equality boolToTriState(boolean b) {
4354    return b ? Equality.True : Equality.False;
4355  }
4356
4357
4358  public ValidationOptions getTerminologyServiceOptions() {
4359    return terminologyServiceOptions;
4360  }
4361
4362
4363  public IWorkerContext getWorker() {
4364    return worker;
4365  }
4366  
4367}