Exemplo n.º 1
0
 @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);
 }
Exemplo n.º 2
0
  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);
   }
 }
Exemplo n.º 4
0
 @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();
   }
 }
Exemplo n.º 6
0
 @NotNull
 public JsProgram program() {
   return staticContext.getProgram();
 }
Exemplo n.º 7
0
  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));
  }
Exemplo n.º 8
0
 @Override
 public void close() throws Exception {
   interpreter.close();
   scriptContext.close();
   staticContext.close();
 }
Exemplo n.º 9
0
 public boolean isNotEcma3() {
   return staticContext.getEcmaVersion() != EcmaVersion.v3;
 }
Exemplo n.º 10
0
 public boolean isEcma5() {
   return staticContext.isEcma5();
 }
Exemplo n.º 11
0
 /**
  * Assigns a URI resolver.
  *
  * @param resolver resolver
  * @return self reference
  */
 public QueryProcessor uriResolver(final UriResolver resolver) {
   sc.resolver = resolver;
   return this;
 }
Exemplo n.º 12
0
 /**
  * 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);
 }
Exemplo n.º 13
0
  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);
            }
          }
        }
      }
    }
  }
Exemplo n.º 14
0
 @NotNull
 public Intrinsics intrinsics() {
   return staticContext.getIntrinsics();
 }
Exemplo n.º 15
0
 @NotNull
 public Namer namer() {
   return staticContext.getNamer();
 }
Exemplo n.º 16
0
 @Nullable
 public JsNameRef getQualifierForDescriptor(@NotNull DeclarationDescriptor descriptor) {
   return staticContext.getQualifierForDescriptor(descriptor);
 }
Exemplo n.º 17
0
 @NotNull
 public NamingScope getScopeForDescriptor(@NotNull DeclarationDescriptor descriptor) {
   return staticContext.getScopeForDescriptor(descriptor);
 }
Exemplo n.º 18
0
 @NotNull
 public BindingContext bindingContext() {
   return staticContext.getBindingContext();
 }
Exemplo n.º 19
0
 /**
  * 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;
 }
Exemplo n.º 20
0
 @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;
    }
  }
Exemplo n.º 22
0
  /** 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;
  }