1   /*
2    * SPDX-FileCopyrightText: none
3    * SPDX-License-Identifier: CC0-1.0
4    */
5   
6   package dev.metaschema.core.metapath.cst;
7   
8   import java.util.List;
9   
10  import dev.metaschema.core.metapath.DynamicContext;
11  import dev.metaschema.core.metapath.IExpression;
12  import dev.metaschema.core.metapath.function.IFunction;
13  import dev.metaschema.core.metapath.item.ISequence;
14  import dev.metaschema.core.qname.IEnhancedQName;
15  import dev.metaschema.core.util.CollectionUtil;
16  import edu.umd.cs.findbugs.annotations.NonNull;
17  
18  /**
19   * The CST node for a Metapath
20   * <a href="https://www.w3.org/TR/xpath-31/#id-named-function-ref">named
21   * function reference</a>.
22   */
23  public class NamedFunctionReference
24      extends AbstractExpression {
25    @NonNull
26    private final IEnhancedQName name;
27    private final int arity;
28  
29    /**
30     * Construct a new Metapath named function reference CST node.
31     *
32     * @param text
33     *          the parsed text of the expression
34     * @param name
35     *          the function name
36     * @param arity
37     *          the number of function arguments
38     */
39    public NamedFunctionReference(
40        @NonNull String text,
41        @NonNull IEnhancedQName name, int arity) {
42      super(text);
43      this.name = name;
44      this.arity = arity;
45    }
46  
47    /**
48     * Get the function name.
49     *
50     * @return the name of the referenced function
51     */
52    @NonNull
53    public IEnhancedQName getName() {
54      return name;
55    }
56  
57    /**
58     * Get the expected number of function arguments for this lookup.
59     *
60     * @return the number of arguments
61     */
62    public int getArity() {
63      return arity;
64    }
65  
66    @Override
67    public List<? extends IExpression> getChildren() {
68      return CollectionUtil.emptyList();
69    }
70  
71    @SuppressWarnings("null")
72    @Override
73    public String toCSTString() {
74      return String.format("%s[name=%s, arity=%d]", getClass().getName(), name, arity);
75    }
76  
77    @Override
78    public <RESULT, CONTEXT> RESULT accept(IExpressionVisitor<RESULT, CONTEXT> visitor, CONTEXT context) {
79      return visitor.visitNamedFunctionReference(this, context);
80    }
81  
82    @Override
83    protected ISequence<?> evaluate(DynamicContext dynamicContext, ISequence<?> focus) {
84      IFunction function = dynamicContext.lookupFunction(name, arity);
85      return ISequence.of(function);
86    }
87  }