main dispatch for expression evaluation
513258
def eval(self, exp):
    ""
    # todo: this needs an AST-assert that all BaseX descendants are being handled
    if isinstance(exp,sqparse2.BinX): return evalop(exp.op.op, *map(self.eval, (exp.left, exp.right)))
    elif isinstance(exp,sqparse2.UnX): return self.eval_unx(exp)
    elif isinstance(exp,sqparse2.NameX): return self.nix.rowget(self.tables,self.c_row,exp)
    elif isinstance(exp,sqparse2.AsterX): return sum(self.c_row,[]) # todo doc: how does this get disassembled by caller?
    elif isinstance(exp,sqparse2.ArrayLit): return map(self.eval,exp.vals)
    elif isinstance(exp,(sqparse2.Literal,sqparse2.ArrayLit)): return exp.toliteral()
    elif isinstance(exp,sqparse2.CommaX):
      # todo: think about getting rid of CommaX everywhere; it complicates syntax tree navigation.
      #   a lot of things that are CommaX now should become weval.Row.
      ret = []
      for child in exp.children:
        (ret.extend if starlike(child) else ret.append)(self.eval(child))
      return ret
    elif isinstance(exp,sqparse2.CallX): return self.eval_callx(exp)
    elif isinstance(exp,sqparse2.SelectX):
      raise NotImplementedError('subqueries should have been evaluated earlier') # todo: specific error class
    elif isinstance(exp,sqparse2.AttrX):return self.nix.rowget(self.tables,self.c_row,exp)
    elif isinstance(exp,sqparse2.CaseX):
      for case in exp.cases:
        if self.eval(case.when): return self.eval(case.then)
      return self.eval(exp.elsex)
    elif isinstance(exp,sqparse2.CastX):
      if exp.to_type.type.lower() in ('text','varchar'): return unicode(self.eval(exp.expr))
      else: raise NotImplementedError('unhandled_cast_type',exp.to_type)
    elif isinstance(exp,(int,basestring,float,type(None))):
      return exp # I think Table.insert is creating this in expand_row
    # todo: why tuple, list, dict below? throw some asserts in here and see where these are coming from.
    elif isinstance(exp,tuple): return tuple(map(self.eval, exp))
    elif isinstance(exp,list): return map(self.eval, exp)
    elif isinstance(exp,dict): return exp
    elif isinstance(exp,sqparse2.NullX): return None
    elif isinstance(exp,sqparse2.ReturnX):
      # todo: I think ReturnX is *always* CommaX now; revisit this
      ret=self.eval(exp.expr)
      print "warning: not sure what I'm doing here with cardinality tweak on CommaX"
      return [ret] if isinstance(exp.expr,(sqparse2.CommaX,sqparse2.AsterX)) else [[ret]] # todo: update parser so this is always * or a commalist
    elif isinstance(exp,sqparse2.AliasX): return self.eval(exp.name) # todo: rename AliasX 'name' to 'expr'
    else: raise NotImplementedError(type(exp), exp)
838780
def main(args):
    

    args = _parse_args(args)

    # sort out logging output and level
    level = util.log_level_from_vebosity(args.verbosity)
    root = logging.getLogger()
    root.setLevel(level)
    handler = logging.StreamHandler(sys.stdout)
    handler.setLevel(level)
    handler.setFormatter(logging.Formatter('%(levelname)s %(message)s'))
    root.addHandler(handler)

    logger.debug(args)

    expression = ' '.join(args.expression)
    try:
        print(Parser().parse(expression))
    except (LexingError, ParsingError) as e:
        util.print_error(e)
        return 1

    return 0
504762
function evaluate(lex, EVENT$$1 = false) {

    let binds = [];


    lex.IWS = false;

    let start = lex.pos;
    while (!lex.END && lex.ty !== lex.types.str) {
        switch (lex.ch) {
            case barrier_a_start:
                if (lex.pk.ch == barrier_b_start || lex.p.ch == barrier_a_start) {

                    let sentinel = (lex.p.ch == barrier_a_start) ? barrier_a_end : barrier_b_end;

                    let pk2 = lex.p.pk;


                    if (pk2.ch == barrier_b_start) {
                        sentinel = barrier_b_end;
                        if (start < lex.p.pos)
                            binds.push(new RawValueBinding(lex.p.slice(start)));

                        lex.p.sync();
                    } else if (start < lex.pos) {

                        binds.push(new RawValueBinding(lex.slice(start)));
                    } //create text node


                    lex.sync().n;
                    lex.IWS = true; // Do not produce white space tokens during this portion.
                    let pk = lex.pk;
                    let Message= false;


                    while (!pk.END && (pk.ch !== sentinel || (pk.pk.ch !== barrier_a_end && pk.p.ch !== barrier_a_start) || (pk.p.n.ch === barrier_a_end))) { 
                        let prev = pk.ch;
                        pk.n; 
                        if(pk.ch == barrier_a_start && prev == barrier_a_end)
                            Message =true;
                    }


                    if (lex.tl < pk.off - lex.off - 1 && !Message) {
                        /***** Start Expression *******/

                        const elex = lex.copy(); //The expression Lexer

                        elex.fence(pk);

                        lex.sync();

                        if (pk.END) //Should still have `))` or `|)` in the input string
                            throw new Error("Should be more to this!");

                        processExpression(elex, binds);

                        lex.a(sentinel);
                        /***** End Expression ********/
                    } else {

                        /************************** Start Single Identifier Binding *******************************/
                        let id = lex.tx;
                        let binding = new DynamicBinding();
                        binding.tap_name = id;
                        let index = binds.push(binding) - 1;
                        lex.n.a(sentinel);

                        if (EVENT$$1) {
                            /***************************** Looking for Event Bindings ******************************************/
                            
                            if (lex.ch == barrier_a_start || lex.ch == barrier_b_start) {

                                binds[index] = new EventBinding(binds[index]);

                                let sentinel = (lex.ch == barrier_a_start) ? barrier_a_end : barrier_b_end;

                                lex.IWS = true; // Do not produce white space tokens during this portion.

                                let pk = lex.pk;

                                while (!pk.END && (pk.ch !== sentinel || (pk.pk.ch !== barrier_a_end))) { pk.n; }

                                lex.n;

                                if (lex.tl < pk.off - lex.off || BannedIdentifiers[lex.tx]) {

                                    const elex = lex.copy(); //The expression Lexer

                                    elex.fence(pk);

                                    lex.sync();

                                    if (pk.END) //Should still have `))` or `|)` in the input string
                                        throw new Error("Should be more to this!");

                                    const event_binds = [];

                                    processExpression(elex, event_binds);

                                    binds[index].bind = event_binds[0];

                                    lex.a(sentinel);

                                } else {
                                    if (lex.ch !== sentinel) {
                                        let id = lex.tx,
                                            binding;
                                        if (lex.ty !== lex.types.id) {
                                            switch (lex.ty) {
                                                case lex.types.num:
                                                    binding = new RawValueBinding(parseFloat(id));
                                                    break;
                                                case lex.types.str:
                                                    binding = new RawValueBinding(id.slice(1, -1));
                                                    break;
                                                default:
                                                    binding = new RawValueBinding(id.slice);
                                            }
                                        } else {
                                            binding = new DynamicBinding();
                                            binding.tap_name = id;
                                        }
                                        binds[index].bind = binding;
                                        lex.n;
                                    }
                                    lex.a(sentinel);
                                }
                            }
                        }
                    }

                    lex.IWS = false;
                    
                    start = lex.off + 1; //Should at the sentinel.
                    
                    lex.a(barrier_a_end);
                    
                    continue;
                }
                break;
        }
        lex.n;
    }

    if (start < lex.off) {
        lex.off = start;
        lex.END = false;
        lex.tl = 0;
        lex.END = false;

        let DATA_END = start;

        while (!lex.n.END)
            if (!(lex.ty & (lex.types.ws | lex.types.nl)))
                DATA_END = lex.off + lex.tl;
            
        if (DATA_END > start) {
            lex.sl = DATA_END;
            binds.push(new RawValueBinding(lex.slice(start)));
        }
    }

    return binds;
}
1216900
def _evaluate(expression, defines):
    
    #interpolated = _interpolate(s, defines)
    try:
        defined = {'defined': (lambda v: v in defines)}
        return_value = eval(expression, defined, defines)
    except Exception, ex:
        message = str(ex)
        if message.startswith("name '") and message.endswith("' is not defined"):
            # A common error (at least this is presumed:) is to have
            #   defined(FOO)   instead of   defined('FOO')
            # We should give a little insight into what might be wrong.
            # message == "name 'FOO' is not defined"
            #    -->  variable_name == "FOO"
            variable_name = message[len("name '"):-len("' is not defined")]
            if expression.find("defined(%s)" % variable_name) > -1:
                # "defined(FOO)" in expr instead of "defined('FOO')"
                message += ''' (perhaps you want `defined('%s')` instead of `defined(%s)`)''' % (variable_name, variable_name)
        elif message.startswith("invalid syntax"):
            message = "invalid syntax: `%s`" % expression
        raise PreprocessorError(message, defines['__FILE__'], defines['__LINE__'])

    logger.debug("evaluate %r -> %s (defines=%r)", expression, return_value, defines)
    return return_value
344701
def evaluate(self, data):
        """"""
        expression_engine = data.process.requirements.get('expression-engine', None)
        if expression_engine is not None:
            expression_engine = self.get_expression_engine(expression_engine)

        # Parse steps.
        steps = data.process.run.get('program', None)
        if steps is None:
            return

        if not isinstance(steps, list):
            raise ExecutionError('Workflow program must be a list of steps.')

        # Expression engine evaluation context.
        context = {
            'input': data.input,
            'steps': collections.OrderedDict(),
        }

        for index, step in enumerate(steps):
            try:
                step_id = step['id']
                step_slug = step['run']
            except KeyError as error:
                raise ExecutionError('Incorrect definition of step "{}", missing property "{}".'.format(
                    step.get('id', index), error
                ))

            # Fetch target process.
            process = Process.objects.filter(slug=step_slug).order_by('-version').first()
            if not process:
                raise ExecutionError('Incorrect definition of step "{}", invalid process "{}".'.format(
                    step_id, step_slug
                ))

            # Process all input variables.
            step_input = step.get('input', {})
            if not isinstance(step_input, dict):
                raise ExecutionError('Incorrect definition of step "{}", input must be a dictionary.'.format(
                    step_id
                ))

            data_input = self._evaluate_expressions(expression_engine, step_id, step_input, context)

            # Create the data object.
            data_object = Data.objects.create(
                process=process,
                contributor=data.contributor,
                tags=data.tags,
                input=data_input,
            )
            DataDependency.objects.create(
                parent=data,
                child=data_object,
                kind=DataDependency.KIND_SUBPROCESS,
            )

            # Copy permissions.
            copy_permissions(data, data_object)

            # Copy collections.
            for collection in data.collection_set.all():
                collection.data.add(data_object)

            context['steps'][step_id] = data_object.pk

        # Immediately set our status to done and output all data object identifiers.
        data.output = {
            'steps': list(context['steps'].values()),
        }
        data.status = Data.STATUS_DONE
276755
function(expression){
      var t = this,
          value = null;

      // Evaluate the expression
      try {
        value = eval(expression);
      } catch (e) {
        throw new Error('Unable to evaluate: ' + expression);
      }

      // Return the value
      return value;
    }
1042772
public static Object evaluateValueExpression(String expression, Object target) {
		
		// Executeur des methodes sur le contexte
		DAOValidatorMethodExpressionExecutor methodExecutor = new DAOValidatorMethodExpressionExecutor();
		
		// Resolver
		DAOValidatorBeanELResolver resolver = new DAOValidatorBeanELResolver(null);
		
		// Contexte d'evaluation
		DAOValidatorELContext context = new DAOValidatorELContext();

		// Fabrique d'expression
		ExpressionFactoryImpl expressionFactory = new ExpressionFactoryImpl();
		
		// Si l'expression est nulle
		if(expression == null || expression.trim().length() == 0) return null;
		
		// Si l'objet cible est null
		if(target == null) return null;
		
		// Expression Locale
		String localExpression = expression;
		
		// Nom de la fonction
		String functionName = null;

		// Objet resultat
		Object result = null;
		
		// Si l'expression contient une fonction
		if(DAOValidatorHelper.isExpressionContainPattern(expression, DAOValidatorHelper.FUNC_CHAIN_PATTERN)) {
			
			// Resultat de l'evaluation des parametres
			Object parameterEvaluation = null;
			
			// Obtention du Nom de la fonction
			functionName = DAOValidatorHelper.extractFunctionName(expression);
			
			// On extrait le parametre
			String functionParameter = DAOValidatorHelper.extractParameter(expression);
			
			// Si le parametre est une fonction
			if(DAOValidatorHelper.isExpressionContainPattern(functionParameter, DAOValidatorHelper.FUNC_CHAIN_PATTERN)) {
				
				// Appel recursif
				parameterEvaluation = evaluateValueExpression(functionParameter, target);
				
			} else if(DAOValidatorHelper.isExpressionContainPattern(functionParameter, DAOValidatorHelper.ENV_CHAIN_PATTERN)) {
				
				// Appel recursif
				parameterEvaluation = evaluateValueExpression(functionParameter, target);
				
			} else if(functionParameter != null && functionParameter.equals("$$")) {
				
				// Appel recursif
				parameterEvaluation = target;
				
			}
			
			// Si l'executeur de fonction possede cette fonction
			if(methodExecutor.getMethodsName().contains(functionName)) {
				
				// Si la chaene parametre est vide
				if(functionParameter == null || functionParameter.trim().length() == 0) result = methodExecutor.invoke(functionName);
				
				// On evalue la fonction
				result = methodExecutor.invoke(functionName, parameterEvaluation);
				
			} else {
				
				// On recupere le parametre
				result = parameterEvaluation;
				
			}
			
		} else if(DAOValidatorHelper.isExpressionContainPattern(expression, DAOValidatorHelper.ENV_CHAIN_PATTERN)) {
			
			// Initialisation de la cible dans le resolver
			resolver.setBase(target);
			
			// Initialisation du resolver dans le contexte
			context.setELResolver(resolver);
			
			// Instanciation d'une expression
			ValueExpression ve = expressionFactory.createValueExpression(context, localExpression, Object.class);
			
			// On calcule le resultat
			result = ve.getValue(context);
			
		}
		
		// On retourne le resultat de l'evalo
		return result;
	}
1230002
def evaluate_handler(handler)
      case handler
      when Symbol
        target.method(handler)
      when Proc
        if handler.arity.zero?
          proc { instance_exec(&handler) }
        else
          proc { |_exception| instance_exec(_exception, &handler) }
        end
      end
    end
415921
protected function evalExpression()
    {
        $this->log("Evaluating PHP expression: " . $this->expression, $this->logLevel);
        if (!StringHelper::endsWith(';', trim($this->expression))) {
            $this->expression .= ';';
        }

        if ($this->returnProperty !== null) {
            $retval = null;
            eval('$retval = ' . $this->expression);
            $this->project->setProperty($this->returnProperty, $retval);
        } else {
            eval($this->expression);
        }
    }
67787
def execute(self, array_in, expression, **kwargs):
        """"""

        context = self.get_context(array_in, expression, kwargs)
        context.update(kwargs)
        return ma.masked_where(self.evaluate_expression(expression, context), array_in)
1439
public Object evaluate(String expression) throws CompilationFailedException {
        GroovyShell shell = new GroovyShell(getClass().getClassLoader(), binding);
        return shell.evaluate(expression);
    }
73200
def compile_expression(source):
    

    # FORCE MODULES TO BE IN NAMESPACE
    _ = coalesce
    _ = listwrap
    _ = Date
    _ = convert
    _ = Log
    _ = Data
    _ = EMPTY_DICT
    _ = re
    _ = wrap_leaves
    _ = is_data

    fake_locals = {}
    try:
        exec(
"""
def output(row, rownum=None, rows=None):
    _source = """ + convert.value2quote(source) + """
    try:
        return """ + source + """
    except Exception as e:
        Log.error("Problem with dynamic function {{func|quote}}",  func=_source, cause=e)
""",
            globals(),
            fake_locals
        )
    except Exception as e:
        Log.error("Bad source: {{source}}", source=source, cause=e)
    return fake_locals['output']
1365770
def p_expression_inlist(self, p):
        '''  
        '''
        _LOGGER.debug("expresion -> expresion IN lexp")

        if self._autodefine_vars:
            self._init_vars(TypedList([]), p[3])

        if p[3].type != TypedClass.LIST: raise TypeError("expected list for IN operator")
        
        retval = False
        for v in p[3].value:
            if p[1] == v:
                retval = True
                break
        
        p[0] = TypedClass(retval, TypedClass.BOOLEAN)
600364
def do_execute(self):
        
        expr = str(self.resolve_option("expression"))
        expr = expr.replace("{X}", str(self.input.payload))
        self._output.append(Token(eval(expr)))
        return None
827706
@Override
	public Value evaluate(String line, Context ctxt) throws Exception
	{
		PExp expr = parseExpression(line, getDefaultName());
		PublicClassEnvironment globals = new PublicClassEnvironment(assistantFactory, classes, null);
		Environment env = new PrivateClassEnvironment(assistantFactory, defaultClass, globals);

		try
		{
			typeCheck(expr, env);
		} catch (VDMErrorsException e)
		{
			// We don't care... we just needed to type check it.
		}

		ctxt.threadState.init();
		try
		{
			return expr.apply(VdmRuntime.getExpressionEvaluator(), ctxt);
		} catch (Exception e)
		{
			throw e;
		}
	}
365618
private void evaluateExpressions() throws JspException {
        /* 
         * Note: we don't check for type mismatches here; we assume
         * the expression evaluator will return the expected type
         * (by virtue of knowledge we give it about what that type is).
         * A ClassCastException here is truly unexpected, so we let it
         * propagate up.
         */

        name = (String) ExpressionUtil.evalNotNull(
                "import", "name", name_, String.class, this, pageContext);
        value = (String) ExpressionUtil.evalNotNull(
                "import", "value", value_, String.class, this, pageContext);
    }
179283
def _all_expressions_evaluated(self):
        
        def present(expr):
            return expr.stmt == expr.column and expr.column in self.data
        return all(present(expr) for expr in self.expressions)