Parse and return a user defined function of the form "{arg1 arg2 . (expr)}"
424536
private AstFunction parseFunctionDefinition() {
    eatChar('{');

    // Parse the list of ids
    ArrayList<String> ids = new ArrayList<>();
    ids.add("");  // 1-based ID list
    while (skipWS() != '.') {
      String id = token();
      if (!Character.isJavaIdentifierStart(id.charAt(0)))
        throw new IllegalASTException("variable must be a valid Java identifier: " + id);
      for (char c : id.toCharArray())
        if (!Character.isJavaIdentifierPart(c))
          throw new IllegalASTException("variable must be a valid Java identifier: " + id);
      ids.add(id);
    }

    // Single dot separates the list of ids from the body of the function
    eatChar('.');

    // Parse the body
    AstRoot body = parseNext();
    if (skipWS() != '}')
      throw new IllegalASTException("Expected the end of the function, but found '" + peek(0) + "'");
    eatChar('}');

    return new AstFunction(ids, body);
  }
816815
def _build_func(eq, **args):
    
    '''
    eq_prime = eq.diff(args['x'])
    s1 = eq_prime
    s2 = eq - eq_prime*args['x']
    EQ = _syp.lambdify(args.values(), expr=eq, modules='numpy')
    S1 = _syp.lambdify(args.values(), expr=s1, modules='numpy')
    S2 = _syp.lambdify(args.values(), expr=s2, modules='numpy')
    return EQ, S1, S2
735759
function () {
	var len, attr, g, args;

	args = arguments;

	len = args.length;

	if (len === 0) {
		g = noop;
	}
	else if (len === 1) {
		attr = args[0];

		g = function (obj) {
			return obj[attr];
		};
	}
	else {
		g = function (obj) {
			var i, tuple;

			tuple = [];

			for (i = 0; i < len; ++i) {
				tuple.push(obj[args[i]]);
			}

			return tuple;
		};
	}



	return g;
}
724108
def p_bexpr_func(p):
    
    args = make_arg_list(make_argument(p[2], p.lineno(2)))
    p[0] = make_call(p[1], p.lineno(1), args)
    if p[0] is None:
        return

    if p[0].token in ('STRSLICE', 'VAR', 'STRING'):
        entry = SYMBOL_TABLE.access_call(p[1], p.lineno(1))
        entry.accessed = True
        return

    # TODO: Check that arrays really needs kind=function to be set
    # Both array accesses and functions are tagged as functions
    # functions also has the class_ attribute set to 'function'
    p[0].entry.set_kind(KIND.function, p.lineno(1))
    p[0].entry.accessed = True
1270601
def __get_scope(cls,
            expr: Union['Expression', Tuple]) -> Set[str]:
        '''
        '''
        scope = set()
        for i, atom in enumerate(expr):
            if isinstance(atom, Expression):
                scope.update(cls.__get_scope(atom._expr))
            elif type(atom) in [tuple, list]:
                scope.update(cls.__get_scope(atom))
            elif atom == 'pvar_expr':
                functor, params = expr[i+1]
                arity = len(params) if params is not None else 0
                name = '{}/{}'.format(functor, arity)
                scope.add(name)
                break
        return scope
39969
def func_args(func):
    '''
    '''
    try:
        return tuple(inspect.signature(func).parameters)
    except:
        return tuple(inspect.getargspec(func).args)
1371222
def parse_expr(e):
    
    m = relation_re.match(e)
    if m is None:
        raise ValueError("error parsing expression '{}'".format(e))
    field, op, val = m.groups()
    # Try different types
    try:
        # Integer
        val_int = int(val)
        val = val_int
    except ValueError:
        try:
            # Float
            val_float = float(val)
            val = val_float
        except ValueError:
            try:
                # Boolean
                val = {'true': True, 'false': False}[val.lower()]
            except KeyError:
                # String
                if re.match(r'".*"|\'.*\'', val):
                    # strip quotes from strings
                    val = val[1:-1]
    return field, op, val
994103
def parse(self, func, *args, **kwargs):
        
        result = []
        for element in self.xpath('child::node()'):
            if isinstance(element, Parser):
                children = element.parse(func, *args, **kwargs)
                element_result = func(element, children, *args, **kwargs)
                if element_result:
                    result.append(element_result)
            else:
                result.append(element)
        return u"".join(result)
299260
function func_expr_eval(arg_scope={}, arg_expr_tree={ type:undefined}, arg_errors=[], arg_name_str )
{
	const context = 'func_expr_eval:'

	// console.log('func_expr_eval:scope=', arg_scope)
	// console.log('func_expr_eval:arg_expr_tree=', arg_expr_tree)
	// console.log('func_expr_eval:arg_errors=', arg_errors)

	switch(arg_expr_tree.type) {
		case 'Literal':             return arg_expr_tree.value
		case 'Identifier': {
			if (arg_expr_tree.name.length > 0 && arg_expr_tree.name[0] != '_') {
				return arg_expr_tree.name
			}
			arg_errors.push('Identifier:bad value [' + arg_expr_tree.name + ']')
			return undefined
		}
		case 'BinaryExpression':{
			try{
				const op = arg_expr_tree.operator
				const left_tree   = arg_expr_tree.left
				const right_tree  = arg_expr_tree.right
				const left_value  = func_expr_eval(arg_scope, left_tree, arg_errors, arg_name_str)
				const right_value = func_expr_eval(arg_scope, right_tree, arg_errors, arg_name_str)
				switch(op){
					case '+': return left_value + right_value
					case '-': return left_value - right_value
					case '*': return left_value * right_value
					case '/': return left_value / right_value
				}
			} catch(e){
				arg_errors.push('BinaryExpression:failure [' + e + '] for op=' + op + ' left=[' + left_value + '] right=[' + right_value + ']')
				return undefined
			}
		}
		case 'UnaryExpression':{
			try{
				const op = arg_expr_tree.operator
				const left_tree   = arg_expr_tree.argument
				const left_value  = func_expr_eval(arg_scope, left_tree, arg_errors, arg_name_str)
				switch(op){
					case '+': return left_value
					case '-': return - left_value
					case '!': return ! left_value
				}
			} catch(e){
				arg_errors.push('UnaryExpression:failure [' + e + '] for op=' + op + ' left=[' + left_value + ']')
				return undefined
			}
		}
		case 'MemberExpression': {
			const obj_name = func_expr_eval(arg_scope, arg_expr_tree.object,   arg_errors, arg_name_str)
			const att_name = func_expr_eval(arg_scope, arg_expr_tree.property, arg_errors, arg_name_str)
			if (! obj_name || ! att_name)
			{
				arg_errors.push('MemberExpression:bad object/attribute name')
				return undefined
			}
			const obj = arg_scope[obj_name]
			if (! obj)
			{
				arg_errors.push('MemberExpression:object not found in scope or bad object:[' + obj_name + ']')
				return undefined
			}
			if (att_name.length > 0 && att_name[0] == '_')
			{
				arg_errors.push('MemberExpression:object method is private:[' + obj_name + '].[' + att_name + ']')
				return undefined
			}
			if (! (att_name in obj) )
			{
				arg_errors.push('MemberExpression:attribute not found')
				return undefined
			}
			return obj[att_name]
		}
		case 'CallExpression':{
			const callee = arg_expr_tree.callee
			const opds = arg_expr_tree.arguments
			// console.log('func_expr_eval:CallExpression:opds=', opds)

			// EVAL OPERANDS
			const opds_results = []
			if (arg_name_str)
			{
				opds_results.push('##NAME##' + arg_name_str)
			}
			if (opds && opds.length > 0)
			{
				opds.forEach(
					(opd, index)=>{
						// console.log('func_expr_eval:CallExpression:opd=', opd)
						const opd_result = func_expr_eval(arg_scope, opd, arg_errors, arg_name_str)
						// console.log('func_expr_eval:CallExpression:opd_result=', opd_result)
						opds_results.push(opd_result)
					}
				)
			}
			// console.log(context + 'CallExpression:opds_results=', opds_results)

			// EVAL FUNCTION
			if (callee.type == 'Identifier')
			{
				const func_name = callee.name
				const func_call = arg_scope[func_name]
				if (! func_call)
				{
					arg_errors.push('CallExpression:function not found in scope or bad function:[' + func_name + ']')
					return undefined
				}

				if (opds_results.length == 0)
				{
					// console.log(context + 'CallExpression:func_call=', func_call)
					return func_call(null)
				}
				
				// console.log(context + 'CallExpression:func_call=', func_call, opds_results)
				return func_call.call(null, ...opds_results)
			}

			// EVAL METHOD
			if (callee.type == 'MemberExpression')
			{
				const object_name = callee.object.name
				const method_name = callee.property.name

				if (method_name.length > 0 && method_name[0] == '_')
				{
					arg_errors.push('CallExpression:object method is private:[' + object_name + '].[' + method_name + ']')
					return undefined
				}
				const object_instance = arg_scope[object_name]
				if (! object_instance || ! object_instance.get_method)
				{
					arg_errors.push('CallExpression:method object not found in scope or bad object:[' + object_name + ']')
					return undefined
				}

				const object_method = object_instance.get_method(method_name)
				if (! object_method)
				{
					arg_errors.push('CallExpression:method not found in object or bad method:[' + object_name + '].[' + method_name + ']')
					return undefined
				}

				if (opds_results.length == 0)
				{
					return object_method.apply(object_instance)
				}
				
				const call_result = object_method.apply(object_instance, opds_results)
				if (call_result.error)
				{
					return call_result.errors
				}
				return call_result.value
			}
		}
		case 'ArrayExpression':{
			const items_expressions = arg_expr_tree.elements
			const items = []
			items_expressions.forEach(
				(item_expr)=>{
					items.push( func_expr_eval(arg_scope, item_expr, arg_errors, arg_name_str) )
				}
			)
			return items
		}
		default:{
			console.log('func_expr_eval:scope=', arg_scope)
			console.log('func_expr_eval:arg_expr_tree=', arg_expr_tree)
			console.log('func_expr_eval:arg_errors=', arg_errors)
			console.log('func_expr_eval:arg_name_str=', arg_name_str)
		}
	}

	return undefined
}
1340794
def _exprparser(
        expr, scope, lang=None, conf=None, configurable=None,
        safe=DEFAULT_SAFE, besteffort=DEFAULT_BESTEFFORT, tostr=False
):
    """"""

    if scope is None:
        scope = {}

    scope.update({
        'configurable': configurable,
        'conf': conf
    })

    expr = REGEX_EXPR_R.sub(
        _refrepl(
            configurable=configurable, conf=conf, safe=safe, scope=scope,
            besteffort=besteffort
        ), expr
    )

    result = resolve(
        expr=expr, name=lang, safe=safe, scope=scope, tostr=tostr,
        besteffort=besteffort
    )

    return result
740332
def p_call_expr(self, p):
        
        if len(p) == 3:
            p[0] = self.asttypes.FunctionCall(p[1], p[2])
            p[0].setpos(p)  # require yacc_tracking
        elif len(p) == 4:
            p[0] = self.asttypes.DotAccessor(p[1], p[3])
            p[0].setpos(p, 2)
        else:
            p[0] = self.asttypes.BracketAccessor(p[1], p[3])
            p[0].setpos(p, 2)
446350
def interpret(self, values={}, functions={}):
        
        return self.expr.evaluate(Environment(values, functions))
1262177
def _parse(args):
    """"""

    ordered = []
    opt_full = dict()
    opt_abbrev = dict()

    args = args + ['']  # Avoid out of range
    i = 0

    while i < len(args) - 1:
        arg = args[i]
        arg_next = args[i+1]
        if arg.startswith('--'):
            if arg_next.startswith('-'):
                raise ValueError('{} lacks value'.format(arg))
            else:
                opt_full[arg[2:]] = arg_next
                i += 2
        elif arg.startswith('-'):
            if arg_next.startswith('-'):
                raise ValueError('{} lacks value'.format(arg))
            else:
                opt_abbrev[arg[1:]] = arg_next
                i += 2
        else:
            ordered.append(arg)
            i += 1
    
    return ordered, opt_full, opt_abbrev
1321837
def dummy_func(arg1, arg2, arg3=None, arg4=[1, 2, 3], arg5={}, **kwargs):
    
    foo = kwargs.get('foo', None)
    bar = kwargs.pop('bar', 4)
    foo2 = kwargs['foo2']
    foobar = str(foo) + str(bar) + str(foo2)
    return foobar
1172661
def wrap_function(func):
    
    if is_text(func):
        return compile_expression(func)

    numarg = func.__code__.co_argcount
    if numarg == 0:

        def temp(row, rownum, rows):
            return func()

        return temp
    elif numarg == 1:

        def temp(row, rownum, rows):
            return func(row)

        return temp
    elif numarg == 2:

        def temp(row, rownum, rows):
            return func(row, rownum)

        return temp
    elif numarg == 3:
        return func
163216
def ex_call(func, args):
    
    if isinstance(func, str):
        func = ex_rvalue(func)

    args = list(args)
    for i in range(len(args)):
        if not isinstance(args[i], ast.expr):
            args[i] = ex_literal(args[i])

    if sys.version_info[:2] < (3, 5):
        return ast.Call(func, args, [], None, None)
    else:
        return ast.Call(func, args, [])
916292
def p_funcall_expr(p):
    
    if (len(p) == 5 and len(p[3]) == 1 and p[3][0].__class__ is node.expr and
            p[3][0].op == ":" and not p[3][0].args):
        # foo(:) => ravel(foo)
        p[0] = node.funcall(
            func_expr=node.ident("ravel"), args=node.expr_list([p[1]]))
    else:
        args = node.expr_list() if len(p) == 4 else p[3]
        assert isinstance(args, node.expr_list)
        p[0] = node.funcall(func_expr=p[1], args=args)