@Override public void visit(FunctionCall call) { result = new FunctionCall( substitute(call.getFunction()), substituteArgumentList(call.getArguments()), call.getAttributes()); }
public void testLinenoFunctionCall() { AstNode root = parse("\nfoo.\n" + "bar.\n" + "baz(1);"); ExpressionStatement stmt = (ExpressionStatement) root.getFirstChild(); FunctionCall fc = (FunctionCall) stmt.getExpression(); // Line number should get closest to the actual paren. assertEquals(3, fc.getLineno()); }
@Override public void visit(FunctionCall call) { if (includeFunctionNames) { call.getFunction().accept(this); } for (SEXP expr : call.getArguments().values()) { expr.accept(this); } }
public void testJSDocAttachment4() { AstRoot root = parse("(function() {/** should not be attached */})()"); assertNotNull(root.getComments()); assertEquals(1, root.getComments().size()); ExpressionStatement st = (ExpressionStatement) root.getFirstChild(); FunctionCall fc = (FunctionCall) st.getExpression(); ParenthesizedExpression pe = (ParenthesizedExpression) fc.getTarget(); assertNull(pe.getJsDoc()); }
/** * Set the expression defining the value of the attribute. If this is a constant, and if * validation against a schema type was requested, the validation is done immediately. * * @param select The expression defining the content of the attribute * @param config * @throws StaticError if the expression is a constant, and validation is requested, and the * constant doesn't match the required type. */ public void setSelect(Expression select, Configuration config) throws StaticError { super.setSelect(select, config); // Attempt early validation if possible if (select instanceof AtomicValue && schemaType != null && !schemaType.isNamespaceSensitive()) { CharSequence value = ((AtomicValue) select).getStringValueCS(); XPathException err = schemaType.validateContent( value, DummyNamespaceResolver.getInstance(), config.getNameChecker()); if (err != null) { StaticError se = new StaticError( "Attribute value " + Err.wrap(value, Err.VALUE) + " does not the match the required type " + schemaType.getDescription() + ". " + err.getMessage()); se.setErrorCode("XTTE1540"); throw se; } } // If value is fixed, test whether there are any special characters that might need to be // escaped when the time comes for serialization if (select instanceof StringValue) { boolean special = false; CharSequence val = ((StringValue) select).getStringValueCS(); for (int k = 0; k < val.length(); k++) { char c = val.charAt(k); if ((int) c < 33 || (int) c > 126 || c == '<' || c == '>' || c == '&' || c == '\"') { special = true; break; } } if (!special) { this.options |= ReceiverOptions.NO_SPECIAL_CHARS; } } // If attribute name is xml:id, add whitespace normalization if ((nameCode & NamePool.FP_MASK) == StandardNames.XML_ID) { Expression[] args = {select}; FunctionCall fn = SystemFunction.makeSystemFunction("normalize-space", 1, config.getNamePool()); fn.setArguments(args); select = fn; super.setSelect(select, config); } }
public static ASTNode writeFunction(boolean isSuper, FunctionCall lhs, ASTNode rhs) { if (lhs.args.size() > 0) { ASTNode first = lhs.args.first().getValue(); if (!(first instanceof SimpleAccessVariable)) { return new UpdateExpression(isSuper, lhs, rhs); } else { lhs.args.add("value", rhs); } } lhs.name = RSymbol.getSymbol(lhs.name.pretty() + "<-"); lhs.isAssignment(true); lhs.isSuper(isSuper); return lhs; }
// Builds parameter mapping. private void buildArgumentList() { arguments = new ArrayList<Expression>(4); for (int i = 0; i < fcall.getNumArguments(); i++) { arguments.add(fcall.getArgument(i)); } // Catches exceptional cases. Symbol s = SymbolTools.getSymbolOf(fcall.getName()); if (s instanceof NestedDeclarator && ((NestedDeclarator) s).isProcedure()) { PrintTools.printlnStatus(0, "[WARNING] function pointer in ", fcall); exception |= FUNCTION_POINTER; } else if (callee == null) { exception |= LIBRARY_CALL; } else if (callee.containsVarArg()) { exception |= VARIABLE_ARG_LIST; PrintTools.printlnStatus(0, "[WARNING] variable argument list ", fcall); } }
/** * Returns the statement containing the function call. * * @return the ancestor statement of the function call. */ public Statement getStatement() { Statement ret = fcall.getStatement(); // initial statement in a for statement should return the for statement. if (ret.getParent() instanceof ForLoop) { ret = (Statement) ret.getParent(); } return ret; }
/** * Executes the default the standard R initialization sequence: * * <ol> * <li>Load the base package (/org/renjin/library/base/R/base) * <li>Execute the system profile (/org/renjin/library/base/R/Rprofile) * <li>Evaluate .OptRequireMethods() * <li>Evaluate .First.Sys() * </ol> */ public void init() throws IOException { BaseFrame baseFrame = (BaseFrame) session.getBaseEnvironment().getFrame(); baseFrame.load(this); evaluate(FunctionCall.newCall(Symbol.get(".onLoad")), session.getBaseNamespaceEnv()); // evalBaseResource("/org/renjin/library/base/R/Rprofile"); // // // FunctionCall.newCall(new Symbol(".OptRequireMethods")).evaluate(this, environment); // evaluate( FunctionCall.newCall(Symbol.get(".First.sys")), environment); }
public void testRegexpLocation() { AstNode root = parse("\nvar path =\n" + " replace(\n" + "/a/g," + "'/');\n"); VariableDeclaration firstVarDecl = (VariableDeclaration) root.getFirstChild(); List<VariableInitializer> vars1 = firstVarDecl.getVariables(); VariableInitializer firstInitializer = vars1.get(0); Name firstVarName = (Name) firstInitializer.getTarget(); FunctionCall callNode = (FunctionCall) firstInitializer.getInitializer(); AstNode fnName = callNode.getTarget(); List<AstNode> args = callNode.getArguments(); RegExpLiteral regexObject = (RegExpLiteral) args.get(0); AstNode aString = args.get(1); assertEquals(1, firstVarDecl.getLineno()); assertEquals(1, firstVarName.getLineno()); assertEquals(2, callNode.getLineno()); assertEquals(2, fnName.getLineno()); assertEquals(3, regexObject.getLineno()); assertEquals(3, aString.getLineno()); }
/** * Returns the string dump of this call site. * * @return string dump. */ public String toString() { StringBuilder sb = new StringBuilder(80); sb.append(id).append(" ").append(caller.getName()).append("-->"); sb.append(fcall.getName()); if (PrintTools.getVerbosity() >= 3) { sb.append(" (").append(System.identityHashCode(fcall)).append(")"); } if (callee == null) { sb.append(" <lib>"); } else if (temp_assignments != null) { // normalized arguments String args = temp_assignments.toString().replaceAll("\n", " "); sb.append(" ").append(args); } if (PrintTools.getVerbosity() >= 3) { sb.append("\n parent = ").append(fcall.getParent()); sb.append("\n fcall = ").append(fcall); sb.append("\n args = ").append(arguments); sb.append("\n params = ").append(getParameters()); sb.append("\n nargs = ").append(norm_arguments); sb.append("\n exception = ").append(exception); } return sb.toString(); }
/** * Return the negation of the expression * * @return the negation of the expression */ public Expression negate() { FunctionCall fc = SystemFunction.makeSystemFunction("exists", getArguments()); fc.setLocationId(getLocationId()); return fc; }
private SEXP evaluateCall(FunctionCall call, Environment rho) { clearInvisibleFlag(); Function functionExpr = evaluateFunction(call.getFunction(), rho); return functionExpr.apply(this, rho, call, call.getArguments()); }
public SEXP getFunctionName() { return call.getFunction(); }
@Override public void eval(final ExecutionContext context) { /* * Eval left */ context.newCallStackFrame(LEFT_POS); left.eval(context); context.returnFromCallFrame(); /* * If it is a function pointer, then create a new function call */ final Object target = left.getAnnotation(); if (isApply && target instanceof FunctionDefinition) { final FunctionDefinition fd = (FunctionDefinition) target; /* * Currently, there is no change in the codepath when superscript is * executed: f.apply(...) is exactly equivalent to f(...). */ final FunctionCall fc; final boolean hasCall = getSuperscript() instanceof FunctionCall; final FunctionCall prevFC = hasCall ? (FunctionCall) getSuperscript() : null; if (hasCall && fd.equals(prevFC.getFunctionDefinition())) { fc = prevFC; } else { fc = new FunctionCall(fd, deepCopyBranches()); } setSuperscript(fc); fc.eval(context); setAnnotation(fc.getAnnotation()); } else { /* * Otherwise, evaluate branches and proceed to evaluation */ projectAndEval(context); /* * Check everything for fields */ final Stream<?> argsstr = getBranchesAnnotationStream(); final Object[] args = argsstr.toArray(); /* * collect any field indices */ List<Integer> list = new ArrayList<>(); for (Object o : args) { if (Field.class.isAssignableFrom(o.getClass())) { list.add(ArrayUtils.indexOf(args, o)); } } final int[] fieldIndexes = new int[list.size()]; for (Integer i : list) { fieldIndexes[i] = list.get(i); } // End /* * if there are any fields, do a field apply: */ final boolean fieldTarget = target instanceof Field; if (fieldTarget || fieldIndexes.length > 0) { /* * Run on every element of the field, and at each iteration use the * current annotation as corresponding element for the field. Once * done, set the entire field as annotation. */ final Field res = Fields.apply( new BiFunction<Object, Object[], Object>() { @Override public Object apply(Object actualT, Object[] actualA) { return ReflectionUtils.invokeBestNotStatic(actualT, methodName, actualA); } }, fieldTarget, fieldIndexes, target, args); setAnnotation(res); } else { final Object annotation = ReflectionUtils.invokeBestNotStatic(target, methodName, args); setAnnotation(annotation); } } }
private static List<String> analyzeExpression(Expression expression, String xpathString) { if (expression instanceof ComputedExpression) { try { final PathMap pathmap = new PathMap((ComputedExpression) expression, new Configuration()); logger.info("TEST XPATH PATHS - path for expression: " + xpathString); pathmap.diagnosticDump(System.out); final int dependencies = expression.getDependencies(); if ((dependencies & StaticProperty.DEPENDS_ON_CONTEXT_ITEM) != 0) { System.out.println(" xxx DEPENDS_ON_CONTEXT_ITEM"); return null; } if ((dependencies & StaticProperty.DEPENDS_ON_CURRENT_ITEM) != 0) { System.out.println(" xxx DEPENDS_ON_CURRENT_ITEM"); return null; } if ((dependencies & StaticProperty.DEPENDS_ON_CONTEXT_DOCUMENT) != 0) { System.out.println(" xxx DEPENDS_ON_CONTEXT_DOCUMENT"); return null; } if ((dependencies & StaticProperty.DEPENDS_ON_LOCAL_VARIABLES) != 0) { System.out.println(" xxx DEPENDS_ON_LOCAL_VARIABLES"); // Some day we'll have variables return null; } if ((dependencies & StaticProperty.NON_CREATIVE) != 0) { System.out.println(" xxx NON_CREATIVE"); } final List<String> instancesList = new ArrayList<String>(); final PathMap.PathMapRoot[] roots = pathmap.getPathMapRoots(); for (final PathMap.PathMapRoot root : roots) { final Expression rootExpression = root.getRootExpression(); if (rootExpression instanceof Instance || rootExpression instanceof XXFormsInstance) { final FunctionCall functionCall = (FunctionCall) rootExpression; // TODO: Saxon 9.0 expressions should test "instanceof StringValue" to "instanceof // StringLiteral" if (functionCall.getArguments()[0] instanceof StringValue) { final String instanceName = ((StringValue) functionCall.getArguments()[0]).getStringValue(); instancesList.add(instanceName); } else { // Instance name is not known at compile time return null; } } else if (rootExpression instanceof Doc) { // don't need document() function as that is XSLT final FunctionCall functionCall = (FunctionCall) rootExpression; // TODO: Saxon 9.0 expressions should test "instanceof StringValue" to "instanceof // StringLiteral" if (functionCall.getArguments()[0] instanceof StringValue) { // final String literalURI = ((StringValue) // functionCall.getArguments()[0]).getStringValue(); return null; } else { // Document name is not known at compile time return null; } } else if (rootExpression instanceof ContextItemExpression) { return null; } else if (rootExpression instanceof RootExpression) { // We depend on the current XForms model. return null; } // final PathMap.PathMapArc[] rootArcs = root.getArcs(); // // for (int j = 0; j < rootArcs.length; j++) { // final PathMapArc currentArc = rootArcs[j]; // final AxisExpression getStep // } } return instancesList; } catch (Exception e) { logger.error("EXCEPTION WHILE ANALYZING PATHS: " + xpathString); return null; } } else { logger.info("TEST XPATH PATHS - expression not a ComputedExpression: " + xpathString); return Collections.emptyList(); } }
@Override public void meet(FunctionCall fc) throws RuntimeException { // special optimizations for frequent cases with variables if ((XMLSchema.DOUBLE.toString().equals(fc.getURI()) || XMLSchema.FLOAT.toString().equals(fc.getURI())) && fc.getArgs().size() == 1) { optypes.push(ValueType.DOUBLE); fc.getArgs().get(0).visit(this); optypes.pop(); } else if ((XMLSchema.INTEGER.toString().equals(fc.getURI()) || XMLSchema.INT.toString().equals(fc.getURI())) && fc.getArgs().size() == 1) { optypes.push(ValueType.INT); fc.getArgs().get(0).visit(this); optypes.pop(); } else if (XMLSchema.BOOLEAN.toString().equals(fc.getURI()) && fc.getArgs().size() == 1) { optypes.push(ValueType.BOOL); fc.getArgs().get(0).visit(this); optypes.pop(); } else if (XMLSchema.DATE.toString().equals(fc.getURI()) && fc.getArgs().size() == 1) { optypes.push(ValueType.DATE); fc.getArgs().get(0).visit(this); optypes.pop(); } else { String fnUri = fc.getURI(); String[] args = new String[fc.getArgs().size()]; NativeFunction nf = functionRegistry.get(fnUri); if (nf != null && nf.isSupported(parent.getDialect())) { for (int i = 0; i < args.length; i++) { args[i] = new ValueExpressionEvaluator(fc.getArgs().get(i), parent, nf.getArgumentType(i)) .build(); } if (optypes.peek() != nf.getReturnType()) { builder.append(castExpression(nf.getNative(parent.getDialect(), args), optypes.peek())); } else { builder.append(nf.getNative(parent.getDialect(), args)); } } else { throw new IllegalArgumentException( "the function " + fnUri + " is not supported by the SQL translation"); } } }
/** Returns the string name of the function name. */ public String getName() { return fcall.getName().toString(); }
/** * @param result * @param expr */ private static void serialize( FastStringBuffer result, Expression expr, Map reversePrefixMapping) { if (expr instanceof Assignation) { // XXX not yet supported } else if (expr instanceof AxisExpression) { AxisExpression axisExpression = (AxisExpression) expr; result.append(Axis.axisName[axisExpression.getAxis()]); result.append("::"); final NodeTest nodeTest = axisExpression.getNodeTest(); if (nodeTest == null) { result.append("node()"); } else { result.append(fixPreFixes(nodeTest.toString(), reversePrefixMapping)); } } else if (expr instanceof BinaryExpression) { BinaryExpression binaryExpression = (BinaryExpression) expr; result.append('('); serialize(result, binaryExpression.getOperands()[0], reversePrefixMapping); result.append(Token.tokens[binaryExpression.getOperator()]); serialize(result, binaryExpression.getOperands()[1], reversePrefixMapping); result.append(')'); } else if (expr instanceof CompareToIntegerConstant) { CompareToIntegerConstant compareToIntegerConstant = (CompareToIntegerConstant) expr; result.append('('); serialize(result, compareToIntegerConstant.getOperand(), reversePrefixMapping); result.append(Token.tokens[compareToIntegerConstant.getComparisonOperator()]); result.append(Long.toString(compareToIntegerConstant.getComparand())); result.append(')'); } else if (expr instanceof ConditionalSorter) { // XXX not yet supported } else if (expr instanceof ContextItemExpression) { result.append('.'); } else if (expr instanceof ErrorExpression) { // Error do nothing } else if (expr instanceof FilterExpression) { FilterExpression filterExpression = (FilterExpression) expr; result.append('('); serialize(result, filterExpression.getControllingExpression(), reversePrefixMapping); result.append('['); serialize(result, filterExpression.getFilter(), reversePrefixMapping); result.append("])"); } else if (expr instanceof FunctionCall) { FunctionCall functionCall = (FunctionCall) expr; StructuredQName name = functionCall.getFunctionName(); if (name.getPrefix() != null && name.getPrefix().length() > 0) { result.append(name.getPrefix()); result.append(":"); } result.append(name.getLocalName()); result.append("("); Iterator iter = functionCall.iterateSubExpressions(); boolean first = true; while (iter.hasNext()) { result.append(first ? "" : ", "); SaxonXPathExpressionSerializer.serialize( result, (Expression) iter.next(), reversePrefixMapping); first = false; } result.append(")"); } else if (expr instanceof Instruction) { // This is not an XPath expression } else if (expr instanceof IntegerRangeTest) { // XXX not yet supported } else if (expr instanceof IsLastExpression) { result.append("position() eq last()"); } else if (expr instanceof Literal) { Literal literal = (Literal) expr; result.append(literal.getValue().toString()); } else if (expr instanceof NumberInstruction) { // This is not an XPath expression } else if (expr instanceof PathExpression) { PathExpression pathExpression = (PathExpression) expr; result.append('('); serialize(result, pathExpression.getControllingExpression(), reversePrefixMapping); result.append('/'); serialize(result, pathExpression.getControlledExpression(), reversePrefixMapping); result.append(')'); } else if (expr instanceof PatternMatchExpression) { // XXX not yet supported } else if (expr instanceof PatternSponsor) { // XXX not yet supported } else if (expr instanceof SimpleContentConstructor) { // This is not an XPath expression } else if (expr instanceof SimpleExpression) { // This is not an XPath expression } /* else if (expr instanceof SimpleMappingExpression) { // XXX not yet supported } */ else if (expr instanceof ParentNodeExpression) { result.append(".."); } else if (expr instanceof RootExpression) { // do nothing } else if (expr instanceof SortExpression) { // XXX not yet supported } else if (expr instanceof TailExpression) { // XXX not yet supported } else if (expr instanceof TupleExpression) { // This is not an XPath expression } else if (expr instanceof TupleSorter) { // This is not an XPath expression } else if (expr instanceof UnaryExpression) { UnaryExpression unaryExpression = (UnaryExpression) expr; serialize( result, unaryExpression.getBaseExpression(), reversePrefixMapping); // Not sure if this is correct in all cases } else if (expr instanceof VariableReference) { VariableReference variableReference = (VariableReference) expr; String d = variableReference.getDisplayName(); result.append("$"); result.append(d == null ? "$" : d); } }
public synchronized Object __rpccall__(String endpoint, Object funcobj, boolean usecache) { try { // normal case is passing a functioncall, batch case is passing a List<FunctionCall> FunctionCall func = (FunctionCall) funcobj; if (usecache && has(endpoint, func)) return get(endpoint, func); if (!can_connect) if (has(endpoint, func)) { return get(endpoint, func); } else { return null; } func.params = __marshall_args__(func.params); funcobj = func; } catch (ClassCastException ex) { try { BatchClient b = (BatchClient) funcobj; List<FunctionCall> newcalls = new Vector<FunctionCall>(); for (int i = 0; i < b.batch.size(); i++) { b.batch.get(i).params = __marshall_args__(b.batch.get(i).params); } for (FunctionCall f : b.batch) { if (!b.called.contains(f)) { newcalls.add(f); } } funcobj = newcalls; } catch (ClassCastException ex2) { } } HttpPost post = new HttpPost(endpoint); StringEntity req = null; req = new StringEntity(gson.toJson(funcobj), "UTF-8"); post.setEntity(req); post.setHeader(HTTP.CONTENT_TYPE, "application/json"); HttpResponse resp = null; HttpClient client = Http.client(); try { resp = client.execute(post, Http.context()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } Object ret = null; HttpEntity rep = resp.getEntity(); InputStreamReader is = null; try { is = new InputStreamReader(rep.getContent()); BufferedReader rd = new BufferedReader(is); String out = ""; String line = null; while ((line = rd.readLine()) != null) { out += line; } resp.getEntity().consumeContent(); ret = __parse_response__(out); } catch (IOException e) { // TODO Auto-generated catch block throw new RuntimeException(); } finally { if (is != null) try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } FunctionCall func = (FunctionCall) funcobj; if (usecache) set(endpoint, func, ret); return ret; }