001package org.hl7.fhir.r5.utils;
002
003import java.util.ArrayList;
004import java.util.HashMap;
005import java.util.List;
006import java.util.Map;
007
008/*-
009 * #%L
010 * org.hl7.fhir.r5
011 * %%
012 * Copyright (C) 2014 - 2019 Health Level 7
013 * %%
014 * Licensed under the Apache License, Version 2.0 (the "License");
015 * you may not use this file except in compliance with the License.
016 * You may obtain a copy of the License at
017 * 
018 *      http://www.apache.org/licenses/LICENSE-2.0
019 * 
020 * Unless required by applicable law or agreed to in writing, software
021 * distributed under the License is distributed on an "AS IS" BASIS,
022 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
023 * See the License for the specific language governing permissions and
024 * limitations under the License.
025 * #L%
026 */
027
028import org.hl7.fhir.exceptions.FHIRException;
029import org.hl7.fhir.exceptions.PathEngineException;
030import org.hl7.fhir.r5.context.IWorkerContext;
031import org.hl7.fhir.r5.model.Base;
032import org.hl7.fhir.r5.model.ExpressionNode;
033import org.hl7.fhir.r5.model.Resource;
034import org.hl7.fhir.r5.model.Tuple;
035import org.hl7.fhir.r5.model.TypeDetails;
036import org.hl7.fhir.r5.model.ValueSet;
037import org.hl7.fhir.r5.utils.FHIRPathEngine.ExpressionNodeWithOffset;
038import org.hl7.fhir.r5.utils.FHIRPathEngine.IEvaluationContext;
039import org.hl7.fhir.utilities.Utilities;
040import org.hl7.fhir.utilities.xhtml.NodeType;
041import org.hl7.fhir.utilities.xhtml.XhtmlNode;
042
043public class LiquidEngine implements IEvaluationContext {
044
045  public interface ILiquidEngineIcludeResolver {
046    public String fetchInclude(LiquidEngine engine, String name);
047  }
048  
049  private IEvaluationContext externalHostServices;
050  private FHIRPathEngine engine;
051  private ILiquidEngineIcludeResolver includeResolver; 
052
053  private class LiquidEngineContext {
054    private Object externalContext;
055    private Map<String, Base> vars = new HashMap<>();
056
057    public LiquidEngineContext(Object externalContext) {
058      super();
059      this.externalContext = externalContext;
060    }
061
062    public LiquidEngineContext(LiquidEngineContext existing) {
063      super();
064      externalContext = existing.externalContext;
065      vars.putAll(existing.vars);
066    }
067  }
068
069  public LiquidEngine(IWorkerContext context, IEvaluationContext hostServices) {
070    super();
071    this.externalHostServices = hostServices;
072    engine = new FHIRPathEngine(context);
073    engine.setHostServices(this);
074  }
075  
076  public ILiquidEngineIcludeResolver getIncludeResolver() {
077    return includeResolver;
078  }
079
080  public void setIncludeResolver(ILiquidEngineIcludeResolver includeResolver) {
081    this.includeResolver = includeResolver;
082  }
083
084  public LiquidDocument parse(String source, String sourceName) throws FHIRException {
085    return new LiquidParser(source).parse(sourceName);
086  }
087
088  public String evaluate(LiquidDocument document, Resource resource, Object appContext) throws FHIRException {
089    StringBuilder b = new StringBuilder();
090    LiquidEngineContext ctxt = new LiquidEngineContext(appContext);
091    for (LiquidNode n : document.body) {
092      n.evaluate(b, resource, ctxt);
093    }
094    return b.toString();
095  }
096
097  private abstract class LiquidNode {
098    protected void closeUp() {}
099
100    public abstract void evaluate(StringBuilder b, Resource resource, LiquidEngineContext ctxt) throws FHIRException;
101  }
102
103  private class LiquidConstant extends LiquidNode {
104    private String constant;
105    private StringBuilder b = new StringBuilder();
106
107    @Override
108    protected void closeUp() {
109      constant = b.toString();
110      b = null;
111    }
112
113    public void addChar(char ch) {
114      b.append(ch);
115    }
116
117    @Override
118    public void evaluate(StringBuilder b, Resource resource, LiquidEngineContext ctxt) {
119      b.append(constant);
120    }
121  }
122
123  private class LiquidStatement extends LiquidNode {
124    private String statement;
125    private ExpressionNode compiled;
126
127    @Override
128    public void evaluate(StringBuilder b, Resource resource, LiquidEngineContext ctxt) throws FHIRException {
129      if (compiled == null)
130        compiled = engine.parse(statement);
131      b.append(engine.evaluateToString(ctxt, resource, resource, resource, compiled));
132    }
133  }
134
135  private class LiquidIf extends LiquidNode {
136    private String condition;
137    private ExpressionNode compiled;
138    private List<LiquidNode> thenBody = new ArrayList<>();
139    private List<LiquidNode> elseBody = new ArrayList<>();
140
141    @Override
142    public void evaluate(StringBuilder b, Resource resource, LiquidEngineContext ctxt) throws FHIRException {
143      if (compiled == null)
144        compiled = engine.parse(condition);
145      boolean ok = engine.evaluateToBoolean(ctxt, resource, resource, resource, compiled); 
146      List<LiquidNode> list = ok ? thenBody : elseBody;
147      for (LiquidNode n : list) {
148        n.evaluate(b, resource, ctxt);
149      }
150    }
151  }
152
153  private class LiquidLoop extends LiquidNode {
154    private String varName;
155    private String condition;
156    private ExpressionNode compiled;
157    private List<LiquidNode> body = new ArrayList<>();
158    @Override
159    public void evaluate(StringBuilder b, Resource resource, LiquidEngineContext ctxt) throws FHIRException {
160      if (compiled == null)
161        compiled = engine.parse(condition);
162      List<Base> list = engine.evaluate(ctxt, resource, resource, resource, compiled);
163      LiquidEngineContext lctxt = new LiquidEngineContext(ctxt);
164      for (Base o : list) {
165        lctxt.vars.put(varName, o);
166        for (LiquidNode n : body) {
167          n.evaluate(b, resource, lctxt);
168        }
169      }
170    }
171  }
172
173  private class LiquidInclude extends LiquidNode {
174    private String page;
175    private Map<String, ExpressionNode> params = new HashMap<>();
176
177    @Override
178    public void evaluate(StringBuilder b, Resource resource, LiquidEngineContext ctxt) throws FHIRException {
179      String src = includeResolver.fetchInclude(LiquidEngine.this, page);
180      LiquidParser parser = new LiquidParser(src);
181      LiquidDocument doc = parser.parse(page);
182      LiquidEngineContext nctxt =  new LiquidEngineContext(ctxt.externalContext);
183      Tuple incl = new Tuple();
184      nctxt.vars.put("include", incl);
185      for (String s : params.keySet()) {
186        incl.addProperty(s, engine.evaluate(ctxt, resource, resource, resource, params.get(s)));
187      }
188      for (LiquidNode n : doc.body) {
189        n.evaluate(b, resource, nctxt);
190      }
191    }
192  }
193
194  public static class LiquidDocument  {
195    private List<LiquidNode> body = new ArrayList<>();
196
197  }
198
199  private class LiquidParser {
200
201    private String source;
202    private int cursor;
203    private String name;
204
205    public LiquidParser(String source) {
206      this.source = source;
207      cursor = 0;
208    }
209
210    private char next1() {
211      if (cursor >= source.length())
212        return 0;
213      else
214        return source.charAt(cursor);
215    }
216
217    private char next2() {
218      if (cursor >= source.length()-1)
219        return 0;
220      else
221        return source.charAt(cursor+1);
222    }
223
224    private char grab() {
225      cursor++;
226      return source.charAt(cursor-1);
227    }
228
229    public LiquidDocument parse(String name) throws FHIRException {
230      this.name = name;
231      LiquidDocument doc = new LiquidDocument();
232      parseList(doc.body, new String[0]);
233      return doc;
234    }
235
236    private String parseList(List<LiquidNode> list, String[] terminators) throws FHIRException {
237      String close = null;
238      while (cursor < source.length()) {
239        if (next1() == '{' && (next2() == '%' || next2() == '{' )) {
240          if (next2() == '%') { 
241            String cnt = parseTag('%');
242            if (Utilities.existsInList(cnt, terminators)) {
243              close = cnt;
244              break;
245            } else if (cnt.startsWith("if "))
246              list.add(parseIf(cnt));
247            else if (cnt.startsWith("loop "))
248              list.add(parseLoop(cnt.substring(4).trim()));
249            else if (cnt.startsWith("include "))
250              list.add(parseInclude(cnt.substring(7).trim()));
251            else
252              throw new FHIRException("Script "+name+": Script "+name+": Unknown flow control statement "+cnt);
253          } else { // next2() == '{'
254            list.add(parseStatement());
255          }
256        } else {
257          if (list.size() == 0 || !(list.get(list.size()-1) instanceof LiquidConstant))
258            list.add(new LiquidConstant());
259          ((LiquidConstant) list.get(list.size()-1)).addChar(grab());
260        }
261      }
262      for (LiquidNode n : list)
263        n.closeUp();
264      if (terminators.length > 0)
265        if (!Utilities.existsInList(close, terminators))
266          throw new FHIRException("Script "+name+": Script "+name+": Found end of script looking for "+terminators);
267      return close;
268    }
269
270    private LiquidNode parseIf(String cnt) throws FHIRException {
271      LiquidIf res = new LiquidIf();
272      res.condition = cnt.substring(3).trim();
273      String term = parseList(res.thenBody, new String[] { "else", "endif"} );
274      if ("else".equals(term))
275        term = parseList(res.elseBody, new String[] { "endif"} );
276      return res;
277    }
278
279    private LiquidNode parseInclude(String cnt) throws FHIRException {
280      int i = 1;
281      while (i < cnt.length() && !Character.isWhitespace(cnt.charAt(i)))
282        i++;
283      if (i == cnt.length() || i == 0)
284        throw new FHIRException("Script "+name+": Error reading include: "+cnt);
285      LiquidInclude res = new LiquidInclude();
286      res.page = cnt.substring(0, i);
287      while (i < cnt.length() && Character.isWhitespace(cnt.charAt(i)))
288        i++;
289      while (i < cnt.length()) {
290        int j = i;
291        while (i < cnt.length() && cnt.charAt(i) != '=')
292          i++;
293        if (i >= cnt.length() || j == i) 
294          throw new FHIRException("Script "+name+": Error reading include: "+cnt);
295        String n = cnt.substring(j, i);
296          if (res.params.containsKey(n)) 
297            throw new FHIRException("Script "+name+": Error reading include: "+cnt);
298          i++;
299          ExpressionNodeWithOffset t = engine.parsePartial(cnt, i);
300          i = t.getOffset();
301          res.params.put(n, t.getNode());
302          while (i < cnt.length() && Character.isWhitespace(cnt.charAt(i)))
303            i++;
304      }
305      return res;
306    }
307  
308
309    private LiquidNode parseLoop(String cnt) throws FHIRException {
310      int i = 0;
311      while (!Character.isWhitespace(cnt.charAt(i)))
312        i++;
313      LiquidLoop res = new LiquidLoop();
314      res.varName = cnt.substring(0, i);
315      while (Character.isWhitespace(cnt.charAt(i)))
316        i++;
317      int j = i;
318      while (!Character.isWhitespace(cnt.charAt(i)))
319        i++;
320      if (!"in".equals(cnt.substring(j, i)))
321        throw new FHIRException("Script "+name+": Script "+name+": Error reading loop: "+cnt);
322      res.condition = cnt.substring(i).trim();
323      parseList(res.body, new String[] { "endloop"} );
324      return res;
325    }
326
327    private String parseTag(char ch) throws FHIRException {
328      grab(); 
329      grab();
330      StringBuilder b = new StringBuilder();
331      while (cursor < source.length() && !(next1() == '%' && next2() == '}')) {
332        b.append(grab());
333      }
334      if (!(next1() == '%' && next2() == '}')) 
335        throw new FHIRException("Script "+name+": Unterminated Liquid statement {% "+b.toString());
336      grab(); 
337      grab();
338      return b.toString().trim();
339    }
340
341    private LiquidStatement parseStatement() throws FHIRException {
342      grab(); 
343      grab();
344      StringBuilder b = new StringBuilder();
345      while (cursor < source.length() && !(next1() == '}' && next2() == '}')) {
346        b.append(grab());
347      }
348      if (!(next1() == '}' && next2() == '}')) 
349        throw new FHIRException("Script "+name+": Unterminated Liquid statement {{ "+b.toString());
350      grab(); 
351      grab();
352      LiquidStatement res = new LiquidStatement();
353      res.statement = b.toString().trim();
354      return res;
355    }
356
357  }
358
359  @Override
360  public Base resolveConstant(Object appContext, String name, boolean beforeContext) throws PathEngineException {
361    LiquidEngineContext ctxt = (LiquidEngineContext) appContext;
362    if (ctxt.vars.containsKey(name))
363      return ctxt.vars.get(name);
364    if (externalHostServices == null)
365      return null;
366    return externalHostServices.resolveConstant(ctxt.externalContext, name, beforeContext);
367  }
368
369  @Override
370  public TypeDetails resolveConstantType(Object appContext, String name) throws PathEngineException {
371    if (externalHostServices == null)
372      return null;
373    LiquidEngineContext ctxt = (LiquidEngineContext) appContext;
374    return externalHostServices.resolveConstantType(ctxt.externalContext, name);
375  }
376
377  @Override
378  public boolean log(String argument, List<Base> focus) {
379    if (externalHostServices == null)
380      return false;
381    return externalHostServices.log(argument, focus);
382  }
383
384  @Override
385  public FunctionDetails resolveFunction(String functionName) {
386    if (externalHostServices == null)
387      return null;
388    return externalHostServices.resolveFunction(functionName);
389  }
390
391  @Override
392  public TypeDetails checkFunction(Object appContext, String functionName, List<TypeDetails> parameters) throws PathEngineException {
393    if (externalHostServices == null)
394      return null;
395    LiquidEngineContext ctxt = (LiquidEngineContext) appContext;
396    return externalHostServices.checkFunction(ctxt.externalContext, functionName, parameters);
397  }
398
399  @Override
400  public List<Base> executeFunction(Object appContext, String functionName, List<List<Base>> parameters) {
401    if (externalHostServices == null)
402      return null;
403    LiquidEngineContext ctxt = (LiquidEngineContext) appContext;
404    return externalHostServices.executeFunction(ctxt.externalContext, functionName, parameters);
405  }
406
407  @Override
408  public Base resolveReference(Object appContext, String url) throws FHIRException {
409    if (externalHostServices == null)
410      return null;
411    LiquidEngineContext ctxt = (LiquidEngineContext) appContext;
412    return resolveReference(ctxt.externalContext, url);
413  }
414
415  @Override
416  public boolean conformsToProfile(Object appContext, Base item, String url) throws FHIRException {
417    if (externalHostServices == null)
418      return false;
419    LiquidEngineContext ctxt = (LiquidEngineContext) appContext;
420    return conformsToProfile(ctxt.externalContext, item, url);
421  }
422
423  @Override
424  public ValueSet resolveValueSet(Object appContext, String url) {
425    LiquidEngineContext ctxt = (LiquidEngineContext) appContext;
426    if (externalHostServices != null)
427      return externalHostServices.resolveValueSet(ctxt.externalContext, url);
428    else
429      return engine.getWorker().fetchResource(ValueSet.class, url);
430  }
431
432  /**
433   * Lightweight method to replace fixed constants in resources
434   * 
435   * @param node
436   * @param vars
437   * @return
438   */
439  public boolean replaceInHtml(XhtmlNode node, Map<String, String> vars) {
440    boolean replaced = false;
441    if (node.getNodeType() == NodeType.Text || node.getNodeType() == NodeType.Comment) {
442      String cnt = node.getContent();
443      for (String n : vars.keySet()) {
444        cnt = cnt.replace(n, vars.get(n));
445      }
446      if (!cnt.equals(node.getContent())) {
447        node.setContent(cnt);
448        replaced = true;
449      }
450    } else if (node.getNodeType() == NodeType.Element || node.getNodeType() == NodeType.Document) {
451      for (XhtmlNode c : node.getChildNodes()) {
452        if (replaceInHtml(c, vars)) {
453          replaced = true;
454        }
455      }
456      for (String an : node.getAttributes().keySet()) {
457        String cnt = node.getAttributes().get(an);
458        for (String n : vars.keySet()) {
459          cnt = cnt.replace(n, vars.get(n));
460        }
461        if (!cnt.equals(node.getAttributes().get(an))) {
462          node.getAttributes().put(an, cnt);
463          replaced = true;
464        }        
465      }
466    }
467    return replaced;
468  }
469
470}