Main operator lookup routine; lookup an operator (either unary or binary) in its corresponding
map. If there's a matching operator, its resolve routine is called and the result is returned;
otherwise the result of a fallback function is returned.
11147
private <O> OperatorSymbol resolve(Tag tag, Map<Name, List<O>> opMap, Predicate<O> opTestFunc,
                       Function<O, OperatorSymbol> resolveFunc, Supplier<OperatorSymbol> noResultFunc) {
        return opMap.get(operatorName(tag)).stream()
                .filter(opTestFunc)
                .map(resolveFunc)
                .findFirst()
                .orElseGet(noResultFunc);
    }
917961
def is_unary_operator(oper):
    """"""
    # definition:
    # member in class
    # ret-type operator symbol()
    # ret-type operator [++ --](int)
    # globally
    # ret-type operator symbol( arg )
    # ret-type operator [++ --](X&, int)
    symbols = ['!', '&', '~', '*', '+', '++', '-', '--']
    if not isinstance(oper, calldef_members.operator_t):
        return False
    if oper.symbol not in symbols:
        return False
    if isinstance(oper, calldef_members.member_operator_t):
        if len(oper.arguments) == 0:
            return True
        elif oper.symbol in ['++', '--'] and \
                isinstance(oper.arguments[0].decl_type, cpptypes.int_t):
            return True
        return False

    if len(oper.arguments) == 1:
        return True
    elif oper.symbol in ['++', '--'] \
            and len(oper.arguments) == 2 \
            and isinstance(oper.arguments[1].decl_type, cpptypes.int_t):
        # may be I need to add additional check whether first argument is
        # reference or not?
        return True
    return False
15560
function parseBinaryExpression() {
        var expr, token, prec, stack, right, operator, left, i;

        left = parseUnaryExpression();

        token = lookahead;
        prec = binaryPrecedence(token);
        if (prec === 0) {
            return left;
        }
        token.prec = prec;
        lex();

        right = parseUnaryExpression();

        stack = [left, token, right];

        while ((prec = binaryPrecedence(lookahead)) > 0) {

            // Reduce: make a binary expression from the three topmost entries.
            while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
                right = stack.pop();
                operator = stack.pop().value;
                left = stack.pop();
                expr = delegate.createBinaryExpression(operator, left, right);
                stack.push(expr);
            }

            // Shift.
            token = lex();
            token.prec = prec;
            stack.push(token);
            expr = parseUnaryExpression();
            stack.push(expr);
        }

        // Final reduce to clean-up the stack.
        i = stack.length - 1;
        expr = stack[i];
        while (i > 1) {
            expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
            i -= 2;
        }

        return expr;
    }
910672
function map(obj, iterator, context) {
		var results = [], i, j;

		if (!obj) return results;

		// Use native .map method if it exists:
		if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);

		// Fallback for native .map:
		for (i = 0, j = obj.length; i < j; i++ ) {
			results[i] = iterator.call(context, obj[i], i, obj);
		}
		return results;
	}
916877
public final DRL5Expressions.operator_return operator() throws RecognitionException {
		DRL5Expressions.operator_return retval = new DRL5Expressions.operator_return();
		retval.start = input.LT(1);

		Token x=null;
		Token op=null;
		ParserRuleReturnScope rop =null;

		 if ( isNotEOF() ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR ); helper.setHasOperator( true ); 
		try {
			// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:103:3: ( (x= TILDE )? (op= EQUALS |op= NOT_EQUALS |rop= relationalOp ) )
			// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:103:5: (x= TILDE )? (op= EQUALS |op= NOT_EQUALS |rop= relationalOp )
			{
			// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:103:6: (x= TILDE )?
			int alt2=2;
			int LA2_0 = input.LA(1);
			if ( (LA2_0==TILDE) ) {
				int LA2_1 = input.LA(2);
				if ( (LA2_1==EQUALS||(LA2_1 >= GREATER && LA2_1 <= GREATER_EQUALS)||LA2_1==ID||(LA2_1 >= LESS && LA2_1 <= LESS_EQUALS)||LA2_1==NOT_EQUALS||LA2_1==TILDE) ) {
					alt2=1;
				}
			}
			switch (alt2) {
				case 1 :
					// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:103:6: x= TILDE
					{
					x=(Token)match(input,TILDE,FOLLOW_TILDE_in_operator256); if (state.failed) return retval;
					}
					break;

			}

			// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:104:5: (op= EQUALS |op= NOT_EQUALS |rop= relationalOp )
			int alt3=3;
			int LA3_0 = input.LA(1);
			if ( (LA3_0==EQUALS) ) {
				alt3=1;
			}
			else if ( (LA3_0==NOT_EQUALS) ) {
				alt3=2;
			}
			else if ( ((LA3_0 >= GREATER && LA3_0 <= GREATER_EQUALS)||(LA3_0 >= LESS && LA3_0 <= LESS_EQUALS)||LA3_0==TILDE) ) {
				alt3=3;
			}
			else if ( (LA3_0==ID) && ((((helper.validateIdentifierKey(DroolsSoftKeywords.NOT)))||((helper.isPluggableEvaluator(false)))))) {
				alt3=3;
			}

			switch (alt3) {
				case 1 :
					// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:104:7: op= EQUALS
					{
					op=(Token)match(input,EQUALS,FOLLOW_EQUALS_in_operator267); if (state.failed) return retval;
					if ( state.backtracking==0 ) { retval.negated = false; retval.opr =(x != null ? (x!=null?x.getText():null) : "")+(op!=null?op.getText():null); helper.emit(op, DroolsEditorType.SYMBOL); }
					}
					break;
				case 2 :
					// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:105:7: op= NOT_EQUALS
					{
					op=(Token)match(input,NOT_EQUALS,FOLLOW_NOT_EQUALS_in_operator286); if (state.failed) return retval;
					if ( state.backtracking==0 ) { retval.negated = false; retval.opr =(x != null ? (x!=null?x.getText():null) : "")+(op!=null?op.getText():null); helper.emit(op, DroolsEditorType.SYMBOL); }
					}
					break;
				case 3 :
					// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:106:7: rop= relationalOp
					{
					pushFollow(FOLLOW_relationalOp_in_operator301);
					rop=relationalOp();
					state._fsp--;
					if (state.failed) return retval;
					if ( state.backtracking==0 ) { retval.negated = (rop!=null?((DRL5Expressions.relationalOp_return)rop).negated:false); retval.opr =(x != null ? (x!=null?x.getText():null) : "")+(rop!=null?((DRL5Expressions.relationalOp_return)rop).opr:null); }
					}
					break;

			}

			}

			retval.stop = input.LT(-1);

			if ( state.backtracking==0 ) { if( state.backtracking == 0 && input.LA( 1 ) != DRL5Lexer.EOF) { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } }
		}

		catch (RecognitionException re) {
		    throw re;
		}

		finally {
			// do for sure before leaving
		}
		return retval;
	}
554611
final public Selector ComparisonPredicate() throws ParseException {
                                   Selector left, right; int op;
    left = Expression();
    op = ComparisonOperator();
    right = Expression();
    {if (true) return new OperatorImpl(op, left, right);}
    throw new Error("Missing return statement in function");
  }
990647
function (operator, left, right) {
			var type = (operator === '||' || operator === '&&') ? LOGICAL_EXP : BINARY_EXP;
			return {
				type: type,
				operator: operator,
				left: left,
				right: right
			};
		}
721546
def resolve(val):
    
    name = val.getName()
    if name == "number":
        try:
            return int(val.number)
        except ValueError:
            return Decimal(val.number)
    elif name == "str":
        return unwrap(val.str)
    elif name == "null":
        return None
    elif name == "binary":
        return Binary(val.binary[2:-1])
    elif name == "set":
        if val.set == "()":
            return set()
        return set([resolve(v) for v in val.set])
    elif name == "bool":
        return val.bool == "TRUE"
    elif name == "list":
        return [resolve(v) for v in val.list]
    elif name == "dict":
        dict_val = {}
        for k, v in val.dict:
            dict_val[resolve(k)] = resolve(v)
        return dict_val
    elif name == "ts_function":
        return dt_to_ts(eval_function(val.ts_function))
    elif name == "ts_expression":
        return dt_to_ts(eval_expression(val))
    else:
        raise SyntaxError("Unable to resolve value '%s'" % val)
1049815
def _do_operator_comparison(operator_type, operator_name, comparison_value):
    
    def fallback(*args, **kwargs):
        raise AssertionError("Operator {0} does not exist for type {1}".format(
            operator_name, operator_type.__class__.__name__))
    method = getattr(operator_type, operator_name, fallback)
    if getattr(method, 'input_type', '') == FIELD_NO_INPUT:
        return method()
    return method(comparison_value)
306547
private static Method lookup( String method, String url ) {
    String s = method+url;
    for( String x : _handlers.keySet() )
      if( x.equals(s) )         // TODO: regex
        return _handlers.get(x);
    return null;
  }
585773
public static function doUnaryOperation($operator, &$value)
    {
        if (self::$unaryOperations === null) {
            self::$unaryOperations = [
                    self::BITWISE_NOT   => function (&$i) { return ~$i; },
                    self::NOT           => function (&$i) { return !$i; },
                    self::INCREMENT     => function (&$i) { return $i++; },
                    self::DECREMENT     => function (&$i) { return $i--; },
                    self::PRE_INCREMENT => function (&$i) { return ++$i; },
                    self::PRE_DECREMENT => function (&$i) { return --$i; },
                    self::NEGATION      => function (&$i) { return -$i; },
                    self::PLUS          => function (&$i) { return +$i; },
            ];
        }

        if (!isset(self::$unaryOperations[$operator])) {
            throw new PinqException('Unary operator \'%s\' is not supported', $operator);
        }

        $operation = self::$unaryOperations[$operator];

        return $operation($value);
    }
783426
def lookup( value, stride )
      if value.is_a? Variable
        Lookup.new self, value, stride
      else
        Lookup.new @p.lookup( value, stride ), @index, @stride
      end
    end
649479
def check(code):
    """"""
    def safe_lookup(op):
        try:
            return instructions.lookup(op)
        except Exception:
            return op

    for i, a in enumerate(code):
        b = code[i+1] if i+1 < len(code) else None

        # Does instruction exist?
        if not isconstant(a):
            try:
                instructions.lookup(a)
            except KeyError as err:
                # Skip embedded push closures
                if not (len(err.args)==1 and is_embedded_push(err.args[0])):
                    raise CompileError("Instruction at index %d is unknown: %s"
                            % (i, a))

        # Invalid: <str> int
        if isstring(a) and safe_lookup(b) == instructions.cast_int:
            raise CompileError(
                "Cannot convert string to integer (index %d): %s %s" % (i, a,
                    b))

        # Invalid: <int> <binary op>
        boolean_ops = [instructions.boolean_not,
                      instructions.boolean_or,
                      instructions.boolean_and]

        if not isbool(a) and safe_lookup(b) in boolean_ops:
            raise CompileError(
                "Can only use binary operators on booleans (index %d): %s %s" %
                    (i, a, b))
    return code
1041167
def match_operators(inp, relate, cut):
    
    logger_misc.info("enter match_operators")
    ops = {'>': operator.gt,
           '<': operator.lt,
           '>=': operator.ge,
           '<=': operator.le,
           '=': operator.eq
           }
    try:
        truth = ops[relate](inp, cut)
    except KeyError as e:
        truth = False
        logger_misc.warn("get_truth: KeyError: Invalid operator input: {}, {}".format(relate, e))
    logger_misc.info("exit match_operators")
    return truth
517324
@Override
  public Description matchReturn(ReturnTree tree, VisitorState state) {
    if (!matchWithinClass) {
      return Description.NO_MATCH;
    }
    handler.onMatchReturn(this, tree, state);
    ExpressionTree retExpr = tree.getExpression();
    // let's do quick checks on returned expression first
    if (retExpr == null) {
      return Description.NO_MATCH;
    }
    // now let's check the enclosing method
    TreePath enclosingMethodOrLambda =
        NullabilityUtil.findEnclosingMethodOrLambdaOrInitializer(state.getPath());
    if (enclosingMethodOrLambda == null) {
      throw new RuntimeException("no enclosing method, lambda or initializer!");
    }
    if (!(enclosingMethodOrLambda.getLeaf() instanceof MethodTree
        || enclosingMethodOrLambda.getLeaf() instanceof LambdaExpressionTree)) {
      throw new RuntimeException(
          "return statement outside of a method or lambda! (e.g. in an initializer block)");
    }
    Tree leaf = enclosingMethodOrLambda.getLeaf();
    Symbol.MethodSymbol methodSymbol;
    if (leaf instanceof MethodTree) {
      MethodTree enclosingMethod = (MethodTree) leaf;
      methodSymbol = ASTHelpers.getSymbol(enclosingMethod);
    } else {
      // we have a lambda
      methodSymbol =
          NullabilityUtil.getFunctionalInterfaceMethod(
              (LambdaExpressionTree) leaf, state.getTypes());
    }
    return checkReturnExpression(tree, retExpr, methodSymbol, state);
  }
942288
def resolve_operands(self, encoding_map, operation, pc):
        
        convert = Encoder.to_binary
        branch_replace = False
        jump_replace = False

        for operand, value in encoding_map.iteritems():
            if (operand == 'rs' or operand == 'rt' or operand == 'rd'):
                encoding_map[operand] = MIPS.registers[value]

            elif (operand == 'imm'):
                encoding_map[operand] = convert(int(value), MIPS.IMMEDIATE_SIZE)

            elif (operand == 'addr'):
                encoding_map[operand] = convert(int(value), MIPS.ADDRESS_SIZE)

            elif (operand == 'shamt'):
                encoding_map[operand] = convert(int(value), MIPS.SHAMT_SIZE)

            elif (operand == 'label'):
                label = encoding_map[operand]
                hit, index = self.label_cache.query(label)

                if not hit:
                    raise RuntimeError('No address found for label: {}'.format(label))

                if ((operation == 'beq') or (operation == 'bne')):
                    # Calculate the relative instruction offset. The MIPS ISA uses
                    # PC + 4 + (branch offset) to resolve branch targets.
                    if index > pc:
                        encoding_map[operand] = convert(index - pc - 1, MIPS.IMMEDIATE_SIZE)
                    elif index < pc:
                        encoding_map[operand] = convert((pc + 1) - index, MIPS.IMMEDIATE_SIZE)
                    else:
                        # Not sure why a branch would resolve to itself, but ok
                        # (PC + 4) - 4 = 
                        encoding_map[operand] = convert(-1, MIPS.IMMEDIATE_SIZE)

                    branch_replace = True

                elif ((operation == 'j') or (operation == 'jal')):
                    # Jump addresses are absolute
                    encoding_map[operand] = convert(index, MIPS.ADDRESS_SIZE)
                    jump_replace = True

        # Need to convert references to 'label' back to references the instruction
        # encoding string recognizes, otherwise we end up with the default value (zero)
        # This doesn't feel very clean, but working on a fix.
        if branch_replace:
            encoding_map['imm'] = encoding_map['label']
        elif jump_replace:
            encoding_map['addr'] = encoding_map['label']
1136169
def _handle_return(state: GlobalState) -> None:
        
        stack = state.mstate.stack
        try:
            offset, length = get_concrete_int(stack[-1]), get_concrete_int(stack[-2])
        except TypeError:
            return
        for element in state.mstate.memory[offset : offset + length]:
            if not isinstance(element, Expression):
                continue
            for annotation in element.annotations:
                if isinstance(annotation, OverUnderflowAnnotation):
                    state.annotate(
                        OverUnderflowStateAnnotation(
                            annotation.overflowing_state,
                            annotation.operator,
                            annotation.constraint,
                        )
                    )