Protected helper for {@code computeFunction}.

@param fn The function object.
@param args The arguments to the function.
@param fnNode The function node. Only used for error reporting.
@return The result of the function called on the given arguments.
177837
@ForOverride
  protected SoyValue computeFunctionHelper(
      SoyJavaSourceFunction fn, List<SoyValue> args, final FunctionNode fnNode) {
    try {
      return new TofuValueFactory(fnNode, pluginInstances).computeForJava(fn, args, context);
    } catch (Exception e) {
      throw RenderException.create(
          "While computing function \"" + fnNode.toSourceString() + "\": " + e.getMessage(), e);
    }
  }
32082
@Pure
	public static <P1, RESULT> Function0<RESULT> curry(final Function1<? super P1, ? extends RESULT> function, final P1 argument) {
		if (function == null)
			throw new NullPointerException("function");
		return new Function0<RESULT>() {
			@Override
			public RESULT apply() {
				return function.apply(argument);
			}
		};
	}
889829
static <S, I, O> Optional<ADSNode<S, I, O>> compute(final MealyMachine<S, I, ?, O> automaton,
                                                        final Alphabet<I> input,
                                                        final SplitTree<S, I, O> node) throws IllegalArgumentException {

        if (node.getPartition().isEmpty()) {
            throw new IllegalArgumentException("Empty partitions should be handled by the specific algorithm");
        } else if (node.getPartition().size() == 1) {

            final S state = node.getPartition().iterator().next();

            if (!node.getMapping().containsKey(state)) {
                throw new IllegalStateException();
            }

            final ADSNode<S, I, O> result = new ADSLeafNode<>(null, node.getMapping().get(state));
            return Optional.of(result);
        } else if (node.getPartition().size() == 2) {
            return StateEquivalence.compute(automaton, input, node);
        } else if (node.getPartition().size() == automaton.getStates().size()) {
            throw new IllegalArgumentException("Call LeeYannakakis directly");
        } else {
            return BacktrackingSearch.compute(automaton, input, node);
        }
    }
168242
@javax.annotation.Nonnull
  public static double[] op(@javax.annotation.Nonnull final double[] a, @javax.annotation.Nonnull final double[] b, @javax.annotation.Nonnull final DoubleBinaryOperator fn) {
    assert a.length == b.length;
    @javax.annotation.Nonnull final double[] c = new double[a.length];
    for (int j = 0; j < a.length; j++) {
      c[j] = fn.applyAsDouble(a[j], b[j]);
    }
    return c;
  }
59140
private Node tryFoldParseNumber(
      Node n, String functionName, Node firstArg) {
    checkArgument(n.isCall());

    boolean isParseInt = functionName.equals("parseInt");
    Node secondArg = firstArg.getNext();

    // Second argument is only used as the radix for parseInt
    int radix = 0;
    if (secondArg != null) {
      if (!isParseInt) {
        return n;
      }

      // Third-argument and non-numeric second arg are problematic. Discard.
      if (secondArg.getNext() != null || !secondArg.isNumber()) {
        return n;
      } else {
        double tmpRadix = secondArg.getDouble();
        if (tmpRadix != (int) tmpRadix) {
          return n;
        }
        radix = (int) tmpRadix;
        if (radix < 0 || radix == 1 || radix > 36) {
          return n;
        }
      }
    }

    // stringVal must be a valid string.
    String stringVal = null;
    Double checkVal;
    if (firstArg.isNumber()) {
      checkVal = NodeUtil.getNumberValue(firstArg);
      if (!(radix == 0 || radix == 10) && isParseInt) {
        //Convert a numeric first argument to a different base
        stringVal = String.valueOf(checkVal.intValue());
      } else {
        // If parseFloat is called with a numeric argument,
        // replace it with just the number.
        // If parseInt is called with a numeric first argument and the radix
        // is 10 or omitted, just replace it with the number
        Node numericNode;
        if (isParseInt) {
          numericNode = IR.number(checkVal.intValue());
        } else {
          numericNode = IR.number(checkVal);
        }
        n.replaceWith(numericNode);
        reportChangeToEnclosingScope(numericNode);
        return numericNode;
      }
    } else {
      stringVal = NodeUtil.getStringValue(firstArg);
      if (stringVal == null) {
        return n;
      }

      //Check that the string is in a format we can recognize
      checkVal = NodeUtil.getStringNumberValue(stringVal);
      if (checkVal == null) {
        return n;
      }

      stringVal = NodeUtil.trimJsWhiteSpace(stringVal);
      if (stringVal.isEmpty()) {
        return n;
      }
    }

    Node newNode;
    if (stringVal.equals("0")) {
      // Special case for parseInt("0") or parseFloat("0")
      newNode = IR.number(0);
    } else if (isParseInt) {
      if (radix == 0 || radix == 16) {
        if (stringVal.length() > 1 &&
            stringVal.substring(0, 2).equalsIgnoreCase("0x")) {
          radix = 16;
          stringVal = stringVal.substring(2);
        } else if (radix == 0) {
          // if a radix is not specified or is 0 and the most
          // significant digit is "0", the string will parse
          // with a radix of 8 on some browsers, so leave
          // this case alone. This check does not apply in
          // script mode ECMA5 or greater
          if (!isEcmaScript5OrGreater() &&
              stringVal.substring(0, 1).equals("0")) {
            return n;
          }

          radix = 10;
        }
      }
      int newVal = 0;
      try {
        newVal = Integer.parseInt(stringVal, radix);
      } catch (NumberFormatException e) {
        return n;
      }

      newNode = IR.number(newVal);
    } else {
      String normalizedNewVal = "0";
      try {
        double newVal = Double.parseDouble(stringVal);
        newNode = IR.number(newVal);
        normalizedNewVal = normalizeNumericString(String.valueOf(newVal));
      } catch (NumberFormatException e) {
        return n;
      }
      // Make sure that the parsed number matches the original string
      // This prevents rounding differences between the Java implementation
      // and native script.
      if (!normalizeNumericString(stringVal).equals(normalizedNewVal)) {
        return n;
      }
    }

    n.replaceWith(newNode);
    reportChangeToEnclosingScope(newNode);

    return newNode;
  }
172316
@Override public final void compute2( ) {
    assert _key.home() : "Atomic on wrong node; SELF="+H2O.SELF+
      ", key_home="+_key.home_node()+", key_is_home="+_key.home()+", class="+getClass();
    Futures fs = new Futures(); // Must block on all invalidates eventually
    Value val1 = DKV.get(_key);
    while( true ) {
      // Run users' function.  This is supposed to read-only from val1 and
      // return new val2 to atomically install.
      Value val2 = atomic(val1);
      if( val2 == null ) break; // ABORT: they gave up
      assert val1 != val2;      // No returning the same Value
      // Attempt atomic update
      Value res = DKV.DputIfMatch(_key,val2,val1,fs);
      if( res == val1 ) {       // Success?
        onSuccess(val1);        // Call user's post-XTN function
        fs.blockForPending();   // Block for any pending invalidates on the atomic update
        break;
      }
      val1 = res;               // Otherwise try again with the current value
    }                           // and retry
    _key = null;                // No need for key no more, don't send it back
    tryComplete();              // Tell F/J this task is done
  }
818401
function(funcID)
    {
        var bridge = this;
        if (this.remoteFunctionCache[funcID] == null)
        {
            this.remoteFunctionCache[funcID] = function()
            {
                bridge.callASFunction(funcID, FABridge.argsToArray(arguments));
            }
        }
        return this.remoteFunctionCache[funcID];
    }
438748
static Set<String> findModifiedParameters(Node fnNode) {
    ImmutableSet<String> names = getFunctionParameterSet(fnNode);
    Set<String> unsafeNames = new HashSet<>();
    return findModifiedParameters(fnNode.getLastChild(), names, unsafeNames, false);
  }
61742
public static <T1, T2, T3, T4, R> Function4<T1, T2, T3, T4, R> memoizeQuadFunction(final Function4<T1, T2, T3, T4, R> fn) {
      Function1<Tuple4<T1, T2, T3, T4>, R> memoise2 = memoizeFunction((final Tuple4<T1, T2, T3, T4> quad) -> fn.apply(quad._1(), quad._2(), quad._3(), quad._4()));
        return (t1, t2, t3, t4) -> memoise2.apply(tuple(t1, t2, t3, t4));
    }
263473
@Override
  @Nonnull
  protected final SoyValue compute() {
    try {
      if (!future.isDone()) {
        futureBlockCallback.get().beforeBlock();
      }
      return SoyValueConverter.INSTANCE.convert(future.get()).resolve();
    } catch (ExecutionException e) {
      throw new SoyFutureException(e.getCause());
    } catch (Throwable e) {
      throw new SoyFutureException(e);
    }
  }
700547
function(args, fn, type) {
    this.args = args;
    this.fn = fn;
    this.type = type;

    this.id = prefix + _code_node_id_count++;
}
993139
public Object extFunction(String ns, String funcName, Vector argVec,
        Object methodKey) throws javax.xml.transform.TransformerException {
        try {

            if ( funcName == null ) {
                String fmsg = XSLMessages.createXPATHMessage(
                    XPATHErrorResources.ER_ARG_CANNOT_BE_NULL,
                    new Object[] {"Function Name"} );
                throw new NullPointerException ( fmsg ); 
            }
            //Find the XPathFunction corresponding to namespace and funcName
            javax.xml.namespace.QName myQName = new QName( ns, funcName );

            // JAXP 1.3 spec says When XMLConstants.FEATURE_SECURE_PROCESSING 
            // feature is set then invocation of extension functions need to
            // throw XPathFunctionException
            if ( extensionInvocationDisabled ) {
                String fmsg = XSLMessages.createXPATHMessage(
                    XPATHErrorResources.ER_EXTENSION_FUNCTION_CANNOT_BE_INVOKED,
                    new Object[] { myQName.toString() } );
                throw new XPathFunctionException ( fmsg );
            }

            // Assuming user is passing all the needed parameters ( including
            // default values )
            int arity = argVec.size();

            javax.xml.xpath.XPathFunction xpathFunction = 
                resolver.resolveFunction ( myQName, arity );

            // not using methodKey
            ArrayList argList = new ArrayList( arity);
            for ( int i=0; i<arity; i++ ) {
                Object argument = argVec.elementAt( i );
                // XNodeSet object() returns NodeVector and not NodeList
                // Explicitly getting NodeList by using nodelist()
                if ( argument instanceof XNodeSet ) {
                    argList.add ( i, ((XNodeSet)argument).nodelist() );
                } else if ( argument instanceof XObject ) {
                    Object passedArgument = ((XObject)argument).object();
                    argList.add ( i, passedArgument );
                } else {
                    argList.add ( i, argument );
                }
            }

            return ( xpathFunction.evaluate ( argList ));
        } catch ( XPathFunctionException xfe ) {
            // If we get XPathFunctionException then we want to terminate
            // further execution by throwing WrappedRuntimeException 
            throw new org.apache.xml.utils.WrappedRuntimeException ( xfe );
        } catch ( Exception e ) {
            throw new javax.xml.transform.TransformerException ( e );
        }
    
    }
449961
public static Node getFunctionBody(Node fn) {
    checkArgument(fn.isFunction(), fn);
    return fn.getLastChild();
  }
692248
public static AbstractType<?> getTypeByFunction(String functionName)
    {
        Function function;

        try
        {
            function = Function.valueOf(functionName.toUpperCase());
        }
        catch (IllegalArgumentException e)
        {
            String message = String.format("Function '%s' not found. Available functions: %s", functionName, Function.getFunctionNames());
            throw new RuntimeException(message, e);
        }

        return function.getValidator();
    }
234608
static <S, I, O> Optional<ADSNode<S, I, O>> compute(final MealyMachine<S, I, ?, O> automaton,
                                                        final Alphabet<I> input,
                                                        final SplitTree<S, I, O> node) {

        final Iterator<S> targetStateIterator = node.getPartition().iterator();
        final S s1 = targetStateIterator.next();
        final S s2 = targetStateIterator.next();

        final Word<I> separatingWord = Automata.findSeparatingWord(automaton, s1, s2, input);

        // sep word may be non existent, if current hypothesis is not consistent
        if (separatingWord == null) {
            return Optional.empty();
        }

        final Word<O> s1Output = automaton.computeStateOutput(s1, separatingWord);
        final Word<O> s2Output = automaton.computeStateOutput(s2, separatingWord);
        final Word<O> sharedOutput = s1Output.longestCommonPrefix(s2Output);
        final Word<I> trace = separatingWord.prefix(sharedOutput.length() + 1);

        final Pair<ADSNode<S, I, O>, ADSNode<S, I, O>> ads = ADSUtil.buildFromTrace(automaton, trace, s1);

        final ADSNode<S, I, O> head = ads.getFirst();
        final ADSNode<S, I, O> tail = ads.getSecond();

        final ADSNode<S, I, O> s1FinalNode = new ADSLeafNode<>(tail, node.getMapping().get(s1));
        final ADSNode<S, I, O> s2FinalNode = new ADSLeafNode<>(tail, node.getMapping().get(s2));

        tail.getChildren().put(s1Output.getSymbol(sharedOutput.length()), s1FinalNode);
        tail.getChildren().put(s2Output.getSymbol(sharedOutput.length()), s2FinalNode);

        return Optional.of(head);
    }
1313719
public Object invokeFunction(EvaluationContext ctx, String name, List<Object> args) {
        // find function with given name
        Method func = getFunction(name);
        if (func == null) {
            throw new EvaluationError("Undefined function: " + name);
        }

        List<Object> parameters = new ArrayList<>();
        List<Object> remainingArgs = new ArrayList<>(args);


        for (Parameter param : Parameter.fromMethod(func)) {
            BooleanDefault defaultBool = param.getAnnotation(BooleanDefault.class);
            IntegerDefault defaultInt = param.getAnnotation(IntegerDefault.class);
            StringDefault defaultStr = param.getAnnotation(StringDefault.class);

            if (param.getType().equals(EvaluationContext.class)) {
                parameters.add(ctx);
            }
            else if (param.getType().isArray()) {
                // we've reach a varargs param
                parameters.add(remainingArgs.toArray(new Object[remainingArgs.size()]));
                remainingArgs.clear();
                break;
            }
            else if (remainingArgs.size() > 0) {
                Object arg = remainingArgs.remove(0);
                parameters.add(arg);
            }
            else if (defaultBool != null) {
                parameters.add(defaultBool.value());
            }
            else if (defaultInt != null) {
                parameters.add(defaultInt.value());
            }
            else if (defaultStr != null) {
                parameters.add(defaultStr.value());
            }
            else {
                throw new EvaluationError("Too few arguments provided for function " + name);
            }
        }

        if (!remainingArgs.isEmpty()) {
            throw new EvaluationError("Too many arguments provided for function " + name);
        }

        try {
            return func.invoke(null, parameters.toArray(new Object[parameters.size()]));
        } catch (Exception e) {
            List<String> prettyArgs = new ArrayList<>();
            for (Object arg : args) {
                String pretty;
                if (arg instanceof String) {
                    pretty = "\"" + arg + "\"";
                }
                else {
                    try {
                        pretty = Conversions.toString(arg, ctx);
                    }
                    catch (EvaluationError ex) {
                        pretty = arg.toString();
                    }
                }
                prettyArgs.add(pretty);
            }
            throw new EvaluationError("Error calling function " + name + " with arguments " + StringUtils.join(prettyArgs, ", "), e);
        }
    }
81473
function S(fn, value) {
    var owner = Owner, clock = RunningClock === null ? RootClock : RunningClock, running = RunningNode;
    if (owner === null)
        console.warn("computations created without a root or parent will never be disposed");
    var node = new ComputationNode(clock, fn, value);
    Owner = RunningNode = node;
    if (RunningClock === null) {
        toplevelComputation(node);
    }
    else {
        node.value = node.fn(node.value);
    }
    if (owner && owner !== UNOWNED) {
        if (owner.owned === null)
            owner.owned = [node];
        else
            owner.owned.push(node);
    }
    Owner = owner;
    RunningNode = running;
    return function computation() {
        if (RunningNode !== null) {
            var rclock = RunningClock, sclock = node.clock;
            while (rclock.depth > sclock.depth + 1)
                rclock = rclock.parent;
            if (rclock === sclock || rclock.parent === sclock) {
                if (node.preclocks !== null) {
                    for (var i = 0; i < node.preclocks.count; i++) {
                        var preclock = node.preclocks.clocks[i];
                        updateClock(preclock);
                    }
                }
                if (node.age === node.clock.time()) {
                    if (node.state === RUNNING)
                        throw new Error("circular dependency");
                    else
                        updateNode(node); // checks for state === STALE internally, so don't need to check here
                }
                if (node.preclocks !== null) {
                    for (var i = 0; i < node.preclocks.count; i++) {
                        var preclock = node.preclocks.clocks[i];
                        if (rclock === sclock)
                            logNodePreClock(preclock, RunningNode);
                        else
                            logClockPreClock(preclock, rclock, RunningNode);
                    }
                }
            }
            else {
                if (rclock.depth > sclock.depth)
                    rclock = rclock.parent;
                while (sclock.depth > rclock.depth + 1)
                    sclock = sclock.parent;
                if (sclock.parent === rclock) {
                    logNodePreClock(sclock, RunningNode);
                }
                else {
                    if (sclock.depth > rclock.depth)
                        sclock = sclock.parent;
                    while (rclock.parent !== sclock.parent)
                        rclock = rclock.parent, sclock = sclock.parent;
                    logClockPreClock(sclock, rclock, RunningNode);
                }
                updateClock(sclock);
            }
            logComputationRead(node, RunningNode);
        }
        return node.value;
    };
}