1   /*
2    * SPDX-FileCopyrightText: none
3    * SPDX-License-Identifier: CC0-1.0
4    */
5   
6   package dev.metaschema.core.metapath.cst.items;
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.cst.AbstractExpression;
13  import dev.metaschema.core.metapath.cst.IExpressionVisitor;
14  import dev.metaschema.core.metapath.item.ISequence;
15  import dev.metaschema.core.metapath.item.function.IArrayItem;
16  import edu.umd.cs.findbugs.annotations.NonNull;
17  import edu.umd.cs.findbugs.annotations.Nullable;
18  
19  /**
20   * An implementation of the
21   * <a href="https://www.w3.org/TR/xpath-31/#id-array-constructors">Array Curly
22   * Constructor</a> supporting the creation of a Metapath {@link IArrayItem}.
23   */
24  public class ArraySequenceConstructor
25      extends AbstractExpression {
26    @Nullable
27    private final IExpression expr;
28  
29    /**
30     * Construct a new array constructor expression that uses the provided
31     * expression to initialize the array.
32     *
33     * @param text
34     *          the parsed text of the expression
35     * @param expression
36     *          the expression used to produce the array members
37     */
38    public ArraySequenceConstructor(@NonNull String text, @Nullable IExpression expression) {
39      super(text);
40      this.expr = expression;
41    }
42  
43    @SuppressWarnings("rawtypes")
44    @Override
45    public Class<IArrayItem> getBaseResultType() {
46      return IArrayItem.class;
47    }
48  
49    @SuppressWarnings("rawtypes")
50    @Override
51    public Class<IArrayItem> getStaticResultType() {
52      return IArrayItem.class;
53    }
54  
55    @SuppressWarnings("null")
56    @Override
57    public List<? extends IExpression> getChildren() {
58      return List.of(expr);
59    }
60  
61    @Override
62    protected ISequence<IArrayItem<?>> evaluate(DynamicContext dynamicContext, ISequence<?> focus) {
63      ISequence<IArrayItem<?>> retval;
64      if (expr != null) {
65        IArrayItem<?> array = IArrayItem.ofCollection(expr.accept(dynamicContext, focus));
66        retval = ISequence.of(array);
67      } else {
68        retval = ISequence.of();
69      }
70      return retval;
71    }
72  
73    @Override
74    public <RESULT, CONTEXT> RESULT accept(IExpressionVisitor<RESULT, CONTEXT> visitor, CONTEXT context) {
75      return visitor.visitArray(this, context);
76    }
77  }