Debian Codegraph @

net/sf/saxon/pattern/PatternParser30.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.pattern;
9
10 import net.sf.saxon.expr.*;
11 import net.sf.saxon.expr.instruct.Choose;
12 import net.sf.saxon.expr.parser.*;
13 import net.sf.saxon.functions.Doc;
14 import net.sf.saxon.functions.KeyFn;
15 import net.sf.saxon.functions.Root_1;
16 import net.sf.saxon.functions.SuperId;
17 import net.sf.saxon.lib.Feature;
18 import net.sf.saxon.lib.NamespaceConstant;
19 import net.sf.saxon.om.AxisInfo;
20 import net.sf.saxon.om.StructuredQName;
21 import net.sf.saxon.trans.XPathException;
22 import net.sf.saxon.type.ItemType;
23 import net.sf.saxon.type.NumericType;
24 import net.sf.saxon.type.TypeHierarchy;
25 import net.sf.saxon.value.BooleanValue;
26 import net.sf.saxon.value.Int64Value;
27 import net.sf.saxon.value.SequenceType;
28
29 /**
30 * Parser for XSLT patterns. This is created by overriding selected parts of the standard ExpressionParser.
31 */
32
33 public class PatternParser30 extends XPathParser implements PatternParser {
34
35 int inPredicate = 0;
36
37 /**
38 * Parse a string representing an XSLT pattern
39 *
40 *
41 * @param pattern the pattern expressed as a String
42 * @param env the static context for the pattern
43 * @return a Pattern object representing the result of parsing
44 * @throws net.sf.saxon.trans.XPathException
45 * if the pattern contains a syntax error
46 */
47
48 /*@NotNull*/
49 public Pattern parsePattern(String pattern, StaticContext env) throws XPathException {
50 this.env = env;
51 charChecker = env.getConfiguration().getValidCharacterChecker();
52 language = XSLT_PATTERN;
53 String trimmed = pattern.trim();
54 if (trimmed.startsWith("(:")) {
55 t = new Tokenizer();
56 t.languageLevel = 30;
57 t.tokenize(trimmed, 0, -1);
58
59 int start = t.currentTokenStartOffset;
60 trimmed = trimmed.substring(start);
61 }
62 allowSaxonExtensions = env.getConfiguration().getBooleanProperty(Feature.ALLOW_SYNTAX_EXTENSIONS);
63 if (isSelectionPattern(trimmed)) {
64 Expression e = parse(pattern, 0, Token.EOF, env);
65 if (e instanceof ContextItemExpression) {
66 return new UniversalPattern();
67 } else if (e instanceof FilterExpression) {
68 Expression predicate = null;
69 while (e instanceof FilterExpression) {
70 Expression filter = ((FilterExpression) e).getActionExpression();
71 e = ((FilterExpression) e).getSelectExpression();
72 // Need to consider the possibility of a numeric predicate
73 ItemType filterType = filter.getItemType();
74 TypeHierarchy th = env.getConfiguration().getTypeHierarchy();
75 int rel = th.relationship(filterType, NumericType.getInstance());
76 if (rel != TypeHierarchy.DISJOINT) {
77 // the predicate may be numeric
78 if (rel == TypeHierarchy.SAME_TYPE || rel == TypeHierarchy.SUBSUMED_BY) {
79 // the predicate IS numeric: rewrite as N eq 1, since other values don't match
80 filter = new ValueComparison(filter, Token.FEQ, Literal.makeLiteral(Int64Value.PLUS_ONE));
81 } else {
82 // the predicate MIGHT BE numeric: rewrite as
83 // let $P := predicate return if ($P instance of xs:numeric) then ($P eq 1) else $P
84 LetExpression let = new LetExpression();
85 StructuredQName varName =
86 new StructuredQName("vv", NamespaceConstant.SAXON_GENERATED_VARIABLE, "v" + filter.hashCode());
87 let.setVariableQName(varName);
88 InstanceOfExpression condition =
89 new InstanceOfExpression(new LocalVariableReference(let), SequenceType.SINGLE_NUMERIC);
90 LocalVariableReference ref = new LocalVariableReference(let);
91 ref.setStaticType(SequenceType.SINGLE_NUMERIC, null, 0);
92 ValueComparison comparison =
93 new ValueComparison(ref, Token.FEQ, Literal.makeLiteral(Int64Value.PLUS_ONE));
94 Choose choice = new Choose(new Expression[]{condition, Literal.makeLiteral(BooleanValue.TRUE)},
95 new Expression[]{comparison, new LocalVariableReference(let)});
96 let.setSequence(filter);
97 let.setAction(choice);
98 let.setRequiredType(SequenceType.ANY_SEQUENCE);
99 let.setRetainedStaticContext(env.makeRetainedStaticContext());
100 filter = let;
101 }
102 }
103 if (predicate == null) {
104 predicate = filter;
105 } else {
106 predicate = new AndExpression(filter, predicate);
107 }
108 }
109 if (e instanceof ContextItemExpression) {
110 return new BooleanExpressionPattern(predicate);
111 }
112 }
113 grumble("Pattern starting with '.' must be followed by a sequence of predicates");
114 return null;
115 } else {
116 Expression exp = parse(pattern, 0, Token.EOF, env);
117 exp.setRetainedStaticContext(env.makeRetainedStaticContext());
118
119 // If we have a union pattern, check that neither operand is a PredicatePattern
120 if (exp instanceof VennExpression) {
121 checkNoPredicatePattern(((VennExpression) exp).getLhsExpression());
122 checkNoPredicatePattern(((VennExpression) exp).getRhsExpression());
123 }
124 ExpressionVisitor visitor = ExpressionVisitor.make(env);
125 visitor.setOptimizeForPatternMatching(true);
126 ContextItemStaticInfo cit = visitor.getConfiguration().makeContextItemStaticInfo(AnyNodeTest.getInstance(), true);
127 Pattern pat;
128 try {
129 pat = PatternMaker.fromExpression(exp.simplify().typeCheck(visitor, cit), env.getConfiguration(), true);
130 } catch (XPathException e) {
131 pat = PatternMaker.fromExpression(exp.simplify(), env.getConfiguration(), true);
132 }
133 if (exp instanceof FilterExpression && ((FilterExpression)exp).getBase() instanceof ContextItemExpression) {
134 if (allowSaxonExtensions && (pattern.startsWith("tuple") || pattern.startsWith("map") || pattern.startsWith("array"))) {
135 // no action, this is OK
136 } else {
137 grumble("A predicatePattern can appear only at the outermost level (parentheses not allowed)");
138 }
139 }
140 if (exp instanceof FilterExpression && pat instanceof NodeTestPattern) {
141 // the pattern has been simplified but needs to retain a default priority based on its syntactic form (test match-058)
142 pat.setPriority(0.5);
143 }
144 return pat;
145 }
146 }
147
148 private boolean isSelectionPattern(String pattern) throws XPathException {
149 if (pattern.startsWith(".")) {
150 return true;
151 }
152 if (pattern.startsWith("~")) {
153 checkSyntaxExtensions("type alias");
154 return true;
155 }
156 if (pattern.matches("^(tuple|map|array)\\s*\\(.+")) {
157 checkSyntaxExtensions("Patterns matching tuple, array, and map types");
158 return true;
159 }
160
161 return false;
162 }
163
164 private void checkNoPredicatePattern(Expression exp) throws XPathException {
165 if (exp instanceof ContextItemExpression) {
166 grumble("A predicatePattern can appear only at the outermost level (union operator not allowed)");
167 }
168 if (exp instanceof FilterExpression) {
169 checkNoPredicatePattern(((FilterExpression) exp).getBase());
170 }
171 if (exp instanceof VennExpression) {
172 checkNoPredicatePattern(((VennExpression) exp).getLhsExpression());
173 checkNoPredicatePattern(((VennExpression) exp).getRhsExpression());
174 }
175 }
176
177 /**
178 * Callback to tailor the tokenizer
179 */
180
181 protected void customizeTokenizer(Tokenizer t) {
182 // no action
183 }
184
185 /**
186 * Override the parsing of top-level expressions
187 *
188 * @return the parsed expression
189 * @throws net.sf.saxon.trans.XPathException
190 *
191 */
192
193 /*@NotNull*/
194 public Expression parseExpression() throws XPathException {
195 Tokenizer t = getTokenizer();
196 if (inPredicate > 0) {
197 return super.parseExpression();
198 } else if (allowSaxonExtensions && t.currentToken == Token.NODEKIND &&
199 (t.currentTokenValue.equals("tuple") || t.currentTokenValue.equals("map") || t.currentTokenValue.equals("array"))) {
200 ItemType type = parserExtension.parseExtendedItemType(this);
201 Expression expr = new InstanceOfExpression(
202 new ContextItemExpression(), SequenceType.makeSequenceType(type, StaticProperty.EXACTLY_ONE));
203 expr = new FilterExpression(new ContextItemExpression(), expr);
204 setLocation(expr);
205 while (t.currentToken == Token.LSQB) {
206 expr = parsePredicate(expr);
207 }
208 return expr;
209 } else {
210 return parseBinaryExpression(parsePathExpression(), 10);
211 }
212 }
213
214 /**
215 * Parse a basic step expression (without the predicates)
216 *
217 * @param firstInPattern true only if we are parsing the first step in a
218 * RelativePathPattern in the XSLT Pattern syntax
219 * @return the resulting subexpression
220 * @throws net.sf.saxon.trans.XPathException
221 * if any error is encountered
222 */
223
224 /*@NotNull*/
225 protected Expression parseBasicStep(boolean firstInPattern) throws XPathException {
226 if (inPredicate > 0) {
227 return super.parseBasicStep(firstInPattern);
228 } else {
229 switch (t.currentToken) {
230 case Token.DOLLAR:
231 if (!firstInPattern) {
232 grumble("In an XSLT 3.0 pattern, a variable reference is allowed only as the first step in a path");
233 return null;
234 } else {
235 return super.parseBasicStep(firstInPattern);
236 }
237
238 case Token.STRING_LITERAL:
239 case Token.NUMBER:
240 case Token.KEYWORD_CURLY:
241 case Token.ELEMENT_QNAME:
242 case Token.ATTRIBUTE_QNAME:
243 case Token.NAMESPACE_QNAME:
244 case Token.PI_QNAME:
245 case Token.TAG:
246 case Token.NAMED_FUNCTION_REF:
247 case Token.DOTDOT:
248 grumble("Token " + currentTokenDisplay() + " not allowed here in an XSLT pattern");
249 return null;
250 case Token.FUNCTION:
251 if (!firstInPattern) {
252 grumble("In an XSLT pattern, a function call is allowed only as the first step in a path");
253 }
254 return super.parseBasicStep(firstInPattern);
255 case Token.TILDE:
256 return parserExtension.parseTildePattern(this);
257 default:
258 return super.parseBasicStep(firstInPattern);
259
260 }
261 }
262 }
263
264 @Override
265 protected void testPermittedAxis(byte axis, String errorCode) throws XPathException {
266 if (inPredicate == 0) {
267 if (!AxisInfo.isSubtreeAxis[axis]) {
268 grumble("The " + AxisInfo.axisName[axis] + " is not allowed in a pattern");
269 }
270 }
271 }
272
273 /**
274 * Parse an expression appearing within a predicate. This enables full XPath parsing, without
275 * the normal rules that apply within an XSLT pattern
276 *
277 * @return the parsed expression that appears within the predicate
278 * @throws net.sf.saxon.trans.XPathException
279 *
280 */
281
282 /*@NotNull*/
283 protected Expression parsePredicate() throws XPathException {
284 boolean disallow = t.disallowUnionKeyword;
285 t.disallowUnionKeyword = false;
286 ++inPredicate;
287 Expression exp = parseExpression();
288 --inPredicate;
289 t.disallowUnionKeyword = disallow;
290 return exp;
291 }
292
293 /**
294 * Parse a function call appearing within a pattern. Unless within a predicate, this
295 * imposes the constraints on which function calls are allowed to appear in a pattern
296 *
297 * @return the expression that results from the parsing (usually a FunctionCall)
298 * @throws net.sf.saxon.trans.XPathException
299 *
300 * @param prefixArgument
301 */
302
303 /*@NotNull*/
304 public Expression parseFunctionCall(Expression prefixArgument) throws XPathException {
305 Expression fn = super.parseFunctionCall(prefixArgument);
306 if (inPredicate <= 0 && !fn.isCallOn(SuperId.class) && !fn.isCallOn(KeyFn.class) &&
307 !fn.isCallOn(Doc.class) && !fn.isCallOn(Root_1.class)) {
308 grumble("The " + fn.toString() + " function is not allowed at the head of a pattern");
309 }
310 return fn;
311 }
312
313 public Expression parseFunctionArgument() throws XPathException {
314 if (inPredicate > 0) {
315 return super.parseFunctionArgument();
316 } else {
317 switch (t.currentToken) {
318 case Token.DOLLAR:
319 return parseVariableReference();
320
321 case Token.STRING_LITERAL:
322 return parseStringLiteral(true);
323
324 case Token.NUMBER:
325 return parseNumericLiteral(true);
326
327 default:
328 grumble("A function argument in an XSLT pattern must be a variable reference or literal");
329 return null;
330 }
331 }
332 }
333
334 public Expression makeTracer(int startOffset, Expression exp, int construct, StructuredQName qName) {
335 // Suppress tracing of pattern evaluation
336 return exp;
337 }
338 }