@NotNull public static TranslationContext rootContext(@NotNull StaticContext staticContext) { JsProgram program = staticContext.getProgram(); JsBlock globalBlock = program.getGlobalBlock(); DynamicContext rootDynamicContext = DynamicContext.rootContext(staticContext.getRootScope(), globalBlock); AliasingContext rootAliasingContext = AliasingContext.getCleanContext(); return new TranslationContext(staticContext, rootDynamicContext, rootAliasingContext); }
public void checkArguments(ExpressionVisitor visitor) throws XPathException { StaticContext env = visitor.getStaticContext(); if (checked) return; checked = true; super.checkArguments(visitor); if (argument[1] instanceof StringLiteral) { // picture is known statically - optimize for this common case picture = ((StringLiteral) argument[1]).getStringValue(); } if (argument.length == 3) { if (argument[2] instanceof StringLiteral) { // common case, decimal format name is supplied as a string literal String lexicalName = ((StringLiteral) argument[2]).getStringValue(); StructuredQName qName; try { qName = StructuredQName.fromLexicalQName( lexicalName, false, visitor.getConfiguration().getNameChecker(), env.getNamespaceResolver()); } catch (XPathException e) { XPathException se = new XPathException("Invalid decimal format name. " + e.getMessage()); se.setErrorCode("XTDE1280"); throw se; } DecimalFormatManager dfm = ((ExpressionContext) env).getXSLStylesheet().getDecimalFormatManager(); requireFixup = true; dfm.registerUsage(qName, this); // this causes a callback to the fixup() method, either now, or later if it's a forwards // reference } else { // we need to save the namespace context nsContext = env.getNamespaceResolver(); } } else { // two arguments only: it uses the default decimal format if (env instanceof ExpressionContext) { // this is XSLT DecimalFormatManager dfm = ((ExpressionContext) env).getXSLStylesheet().getDecimalFormatManager(); dfm.registerUsage(DecimalFormatManager.DEFAULT_NAME, this); // Note: if using the "default default", there will be no fixup call. } else { // using saxon:decimal-format in some other environment } } }
@Override public void setBeanName(String aName) { try { if (beanName != null) { StaticContext.unbind(beanName); } beanName = aName; if (beanName != null) { StaticContext.bind(beanName, this); } } catch (Exception e) { throw new IllegalStateException(e); } }
@NotNull public JsName getNameForDescriptor(@NotNull DeclarationDescriptor descriptor) { JsName alias = aliasingContext.getAliasForDescriptor(descriptor); if (alias != null) { return alias; } return staticContext.getNameForDescriptor(descriptor); }
public void checkArguments(StaticContext env) throws XPathException { if (checked) return; checked = true; super.checkArguments(env); Optimizer opt = env.getConfiguration().getOptimizer(); argument[1] = ExpressionTool.unsorted(opt, argument[1], false); if (argument[0] instanceof StringValue) { // common case, key name is supplied as a constant try { keyFingerprint = ((ExpressionContext) env) .getFingerprint(((StringValue) argument[0]).getStringValue(), false); } catch (XPathException e) { StaticError err = new StaticError( "Error in key name " + ((StringValue) argument[0]).getStringValue() + ": " + e.getMessage()); err.setLocator(this); err.setErrorCode("XTDE1260"); throw err; } if (keyFingerprint == -1) { StaticError err = new StaticError( "Key " + ((StringValue) argument[0]).getStringValue() + " has not been defined"); err.setLocator(this); err.setErrorCode("XTDE1260"); throw err; } } else { // we need to save the namespace context nsContext = env.getNamespaceResolver(); } }
@NotNull public JsProgram program() { return staticContext.getProgram(); }
public PythonRunner( Map<String, String> environment, Repositories repositories, Scheduler scheduler, Hierarchy loggerRepository, String pythonPath, BufferedWriter out, BufferedWriter err) throws Exception { init(); this.staticContext = new StaticContext(scheduler, loggerRepository).repository(repositories); this.environment = environment; final PySystemState systemState = new PySystemState(); interpreter = new PythonInterpreter(null, systemState); for (String path : pythonPath.split(":")) { systemState.path.add(new PyString(path)); } interpreter.setOut(out); interpreter.setErr(err); scriptContext = staticContext.scriptContext(); // XPM module final PyModule xpmModule = new PyModule("xpm", (PyObject) null); systemState.modules.__setitem__("xpm", xpmModule); // Add classes for (PyType type : TYPES.values()) { xpmModule.__setattr__(type.getName(), type); } // Add constants Scripting.forEachConstant( (name, value) -> { xpmModule.__setattr__(name, wrap(value)); }); // Add functions Scripting.forEachFunction( m -> { xpmModule.__setattr__(m.getKey(), new PythonMethod(null, m)); }); // Add Python specific functions for (MethodFunction m : Scripting.getMethodFunctions(PythonFunctions.class)) { xpmModule.__setattr__(m.getKey(), new PythonMethod(null, m)); } // XPM object: wrap properties final XPM xpm = new XPM(); ClassDescription xpmDescription = ClassDescription.analyzeClass(XPM.class); for (Map.Entry<Object, MethodFunction> x : xpmDescription.getMethods().entrySet()) { final Object key = x.getKey(); if (key instanceof String) { xpmModule.__setattr__((String) key, new PythonMethod(xpm, x.getValue())); } else { throw new XPMRuntimeException("Could not handle key ", key); } } // Add properties xpmModule.__setattr__("tasks", wrap(new Tasks())); xpmModule.__setattr__("logger", wrap(new ScriptingLogger("xpm"))); xpmModule.__setattr__("env", wrap(environment)); }
@Override public void close() throws Exception { interpreter.close(); scriptContext.close(); staticContext.close(); }
public boolean isNotEcma3() { return staticContext.getEcmaVersion() != EcmaVersion.v3; }
public boolean isEcma5() { return staticContext.isEcma5(); }
/** * Assigns a URI resolver. * * @param resolver resolver * @return self reference */ public QueryProcessor uriResolver(final UriResolver resolver) { sc.resolver = resolver; return this; }
/** * Default constructor. * * @param query query string * @param uri base uri (can be {@code null}) * @param ctx database context */ public QueryProcessor(final String query, final String uri, final Context ctx) { this.query = query; qc = pushJob(new QueryContext(ctx)); sc = new StaticContext(qc); sc.baseURI(uri); }
protected static void checkContentSequence( StaticContext env, Expression content, int validation, SchemaType type) throws XPathException { Expression[] components; if (content instanceof Block) { components = ((Block) content).getChildren(); } else { components = new Expression[] {content}; } int elementCount = 0; boolean isXSLT = content.getHostLanguage() == Configuration.XSLT; TypeHierarchy th = env.getConfiguration().getTypeHierarchy(); for (int i = 0; i < components.length; i++) { ItemType it = components[i].getItemType(th); if (it instanceof NodeTest) { int possibleNodeKinds = ((NodeTest) it).getNodeKindMask(); if (possibleNodeKinds == 1 << Type.ATTRIBUTE) { XPathException de = new XPathException("Cannot create an attribute node whose parent is a document node"); de.setErrorCode(isXSLT ? "XTDE0420" : "XPTY0004"); de.setLocator(components[i]); throw de; } else if (possibleNodeKinds == 1 << Type.NAMESPACE) { XPathException de = new XPathException("Cannot create a namespace node whose parent is a document node"); de.setErrorCode(isXSLT ? "XTDE0420" : "XQTY0024"); de.setLocator(components[i]); throw de; } if (possibleNodeKinds == 1 << Type.ELEMENT) { elementCount++; if (elementCount > 1 && (validation == Validation.STRICT || validation == Validation.LAX || type != null)) { XPathException de = new XPathException("A valid document must have only one child element"); if (isXSLT) { de.setErrorCode("XTTE1550"); } else { de.setErrorCode("XQDY0061"); } de.setLocator(components[i]); throw de; } if (validation == Validation.STRICT && components[i] instanceof FixedElement) { SchemaDeclaration decl = env.getConfiguration() .getElementDeclaration( ((FixedElement) components[i]).getNameCode(null) & NamePool.FP_MASK); if (decl != null) { ((FixedElement) components[i]) .getContentExpression() .checkPermittedContents(decl.getType(), env, true); } } } } } }
@NotNull public Intrinsics intrinsics() { return staticContext.getIntrinsics(); }
@NotNull public Namer namer() { return staticContext.getNamer(); }
@Nullable public JsNameRef getQualifierForDescriptor(@NotNull DeclarationDescriptor descriptor) { return staticContext.getQualifierForDescriptor(descriptor); }
@NotNull public NamingScope getScopeForDescriptor(@NotNull DeclarationDescriptor descriptor) { return staticContext.getScopeForDescriptor(descriptor); }
@NotNull public BindingContext bindingContext() { return staticContext.getBindingContext(); }
/** * Declares a namespace. A namespace is undeclared if the {@code uri} is an empty string. The * default element namespaces is set if the {@code prefix} is empty. * * @param prefix namespace prefix * @param uri namespace uri * @return self reference * @throws QueryException query exception */ public QueryProcessor namespace(final String prefix, final String uri) throws QueryException { sc.namespace(prefix, uri); return this; }
@NotNull public JsFunction getFunctionObject(@NotNull CallableDescriptor descriptor) { return staticContext.getFunctionWithScope(descriptor); }
/** * Check that any elements and attributes constructed or returned by this expression are * acceptable in the content model of a given complex type. It's always OK to say yes, since the * check will be repeated at run-time. The process of checking element and attribute constructors * against the content model of a complex type also registers the type of content expected of * those constructors, so the static validation can continue recursively. */ public void checkPermittedContents(SchemaType parentType, StaticContext env, boolean whole) throws XPathException { int fp = nameCode & NamePool.FP_MASK; if (fp == StandardNames.XSI_TYPE || fp == StandardNames.XSI_SCHEMA_LOCATION || fp == StandardNames.XSI_NIL || fp == StandardNames.XSI_NO_NAMESPACE_SCHEMA_LOCATION) { return; } if (parentType instanceof SimpleType) { StaticError err = new StaticError( "Attribute " + env.getNamePool().getDisplayName(nameCode) + " is not permitted in the content model of the simple type " + parentType.getDescription()); err.setIsTypeError(true); err.setLocator(this); if (getHostLanguage() == Configuration.XSLT) { err.setErrorCode("XTTE1510"); } else { err.setErrorCode("XQDY0027"); } throw err; } SchemaType type; try { type = ((ComplexType) parentType).getAttributeUseType(fp); } catch (SchemaException e) { throw new StaticError(e); } if (type == null) { StaticError err = new StaticError( "Attribute " + env.getNamePool().getDisplayName(nameCode) + " is not permitted in the content model of the complex type " + parentType.getDescription()); err.setIsTypeError(true); err.setLocator(this); if (getHostLanguage() == Configuration.XSLT) { err.setErrorCode("XTTE1510"); } else { err.setErrorCode("XQDY0027"); } throw err; } if (type instanceof AnyType) { return; } try { select.checkPermittedContents(type, env, true); // TODO: does this allow for the fact that the content will be atomized? } catch (XPathException e) { if (e.getLocator() == null || e.getLocator() == e) { e.setLocator(this); } throw e; } }
/** Type-check the expression */ public Expression typeCheck(ExpressionVisitor visitor, ItemType contextItemType) throws XPathException { Configuration config = visitor.getConfiguration(); NamePool namePool = config.getNamePool(); StaticContext env = visitor.getStaticContext(); if (contextItemType == null) { typeError( visitor, "Axis step " + toString(namePool) + " cannot be used here: the context item is undefined", "XPDY0002", null); } if (contextItemType.isAtomicType()) { typeError( visitor, "Axis step " + toString(namePool) + " cannot be used here: the context item is an atomic value", "XPTY0020", null); } if (this.contextItemType == contextItemType && doneWarnings) { return this; } this.contextItemType = contextItemType; doneWarnings = true; if (contextItemType instanceof NodeTest) { int origin = contextItemType.getPrimitiveType(); if (origin != Type.NODE) { if (Axis.isAlwaysEmpty(axis, origin)) { env.issueWarning( "The " + Axis.axisName[axis] + " axis starting at " + (origin == Type.ELEMENT || origin == Type.ATTRIBUTE ? "an " : "a ") + NodeKindTest.nodeKindName(origin) + " node will never select anything", getSourceLocator()); return Literal.makeEmptySequence(); } } if (test != null) { int kind = test.getPrimitiveType(); if (kind != Type.NODE) { if (!Axis.containsNodeKind(axis, kind)) { env.issueWarning( "The " + Axis.axisName[axis] + " axis will never select any " + NodeKindTest.nodeKindName(kind) + " nodes", getSourceLocator()); return Literal.makeEmptySequence(); } } if (axis == Axis.SELF && kind != Type.NODE && origin != Type.NODE && kind != origin) { env.issueWarning( "The self axis will never select any " + NodeKindTest.nodeKindName(kind) + " nodes when starting at " + (origin == Type.ELEMENT || origin == Type.ATTRIBUTE ? "an " : "a ") + NodeKindTest.nodeKindName(origin) + " node", getSourceLocator()); return Literal.makeEmptySequence(); } if (axis == Axis.SELF) { itemType = new CombinedNodeTest(test, Token.INTERSECT, (NodeTest) contextItemType); } // If the content type of the context item is known, see whether the node test can select // anything if (contextItemType instanceof DocumentNodeTest && kind == Type.ELEMENT) { NodeTest elementTest = ((DocumentNodeTest) contextItemType).getElementTest(); Set<Integer> outermostElementNames = elementTest.getRequiredNodeNames(); if (outermostElementNames != null) { Set<Integer> selectedElementNames = test.getRequiredNodeNames(); if (selectedElementNames != null) { if (axis == Axis.CHILD) { // check that the name appearing in the step is one of the names allowed by the // nodetest if (SetUtils.intersect(selectedElementNames, outermostElementNames).isEmpty()) { env.issueWarning( "Starting at a document node, the step is selecting an element whose name " + "is not among the names of child elements permitted for this document node type", getSourceLocator()); return Literal.makeEmptySequence(); } itemType = elementTest; return this; } else if (axis == Axis.DESCENDANT) { // check that the name appearing in the step is one of the names allowed by the // nodetest boolean canMatchOutermost = !SetUtils.intersect(selectedElementNames, outermostElementNames).isEmpty(); if (!canMatchOutermost) { // The expression /descendant::x starting at the document node doesn't match the // outermost // element, so replace it by child::*/descendant::x, and check that PathExpression path = new PathExpression( new AxisExpression(Axis.CHILD, elementTest), new AxisExpression(Axis.DESCENDANT, test)); ExpressionTool.copyLocationInfo(this, path); return path.typeCheck(visitor, contextItemType); } } } } } } } return this; }