Accept ternary operator syntax

 condition ? expression1 : expression2
169956
def ternary_operator(allow_assignments, wrapped)
      if (buffer = accept :exp_ternary)
        buffer += expression(allow_assignments, wrapped)[@value]
        if (else_branch = accept :exp_ternary_else)
          buffer += else_branch
          buffer += expression(allow_assignments, wrapped)[@value]
        end
        return buffer
      end
    end
627265
public static Expression ternary(
      final Expression condition, final Expression trueBranch, final Expression falseBranch) {
    checkArgument(condition.resultType().equals(Type.BOOLEAN_TYPE));
    checkArgument(trueBranch.resultType().getSort() == falseBranch.resultType().getSort());
    Features features = Features.of();
    if (Expression.areAllCheap(condition, trueBranch, falseBranch)) {
      features = features.plus(Feature.CHEAP);
    }
    if (trueBranch.isNonNullable() && falseBranch.isNonNullable()) {
      features = features.plus(Feature.NON_NULLABLE);
    }
    return new Expression(trueBranch.resultType(), features) {
      @Override
      protected void doGen(CodeBuilder mv) {
        condition.gen(mv);
        Label ifFalse = new Label();
        Label end = new Label();
        mv.visitJumpInsn(Opcodes.IFEQ, ifFalse); // if 0 goto ifFalse
        trueBranch.gen(mv); // eval true branch
        mv.visitJumpInsn(Opcodes.GOTO, end); // jump to the end
        mv.visitLabel(ifFalse);
        falseBranch.gen(mv); // eval false branch
        mv.visitLabel(end);
      }
    };
  }
749582
def compile_when_to_only_if(expression):
    '''
    
    '''

    # when: set $variable
    # when: unset $variable
    # when: failed $json_result
    # when: changed $json_result
    # when: int $x >= $z and $y < 3
    # when: int $x in $alist
    # when: float $x > 2 and $y <= $z
    # when: str $x != $y

    if type(expression) not in [ str, unicode ]:
        raise errors.AnsibleError("invalid usage of when_ operator: %s" % expression)
    tokens = expression.split()
    if len(tokens) < 2:
        raise errors.AnsibleError("invalid usage of when_ operator: %s" % expression)

    # when_set / when_unset
    if tokens[0] in [ 'set', 'unset' ]:
        tcopy = tokens[1:]
        for (i,t) in enumerate(tokens[1:]):
            if t.find("$") != -1:
                tcopy[i] = "is_%s('''%s''')" % (tokens[0], t)
            else:
                tcopy[i] = t
        return " ".join(tcopy)



    # when_failed / when_changed
    elif tokens[0] in [ 'failed', 'changed' ]:
        tcopy = tokens[1:]
        for (i,t) in enumerate(tokens[1:]):
            if t.find("$") != -1:
                tcopy[i] = "is_%s(%s)" % (tokens[0], t)
            else:
                tcopy[i] = t
        return " ".join(tcopy)



    # when_integer / when_float / when_string
    elif tokens[0] in [ 'integer', 'float', 'string' ]:
        cast = None
        if tokens[0] == 'integer':
            cast = 'int'
        elif tokens[0] == 'string':
            cast = 'str'
        elif tokens[0] == 'float':
            cast = 'float'
        tcopy = tokens[1:]
        for (i,t) in enumerate(tokens[1:]):
            if t.find("$") != -1:
                # final variable substitution will happen in Runner code
                tcopy[i] = "%s('''%s''')" % (cast, t)
            else:
                tcopy[i] = t
        return " ".join(tcopy)

    # when_boolean
    elif tokens[0] in [ 'bool', 'boolean' ]:
        tcopy = tokens[1:]
        for (i, t) in enumerate(tcopy):
            if t.find("$") != -1:
                tcopy[i] = "(is_set('''%s''') and '''%s'''.lower() not in ('false', 'no', 'n', 'none', '0', ''))" % (t, t)
        return " ".join(tcopy)

    else:
        raise errors.AnsibleError("invalid usage of when_ operator: %s" % expression)
702041
def p_or_p_expression(tok):
        """"""
        if len(tok) == 4:
            tok[0] = LogicalBinOpRule(tok[2], tok[1], tok[3])
        else:
            tok[0] = tok[1]
101664
function ConditionalExpression(node, print) {
  print.plain(node.test);
  this.space();
  this.push("?");
  this.space();
  print.plain(node.consequent);
  this.space();
  this.push(":");
  this.space();
  print.plain(node.alternate);
}
1089107
function (operator) {
            var name = operator.operator,
                ret = {},
                field;
            if (name === "and" || name === "or" || name === "not") {
                ret["$" + name] = this.translateExpressions(operator.expressions);
            } else if (name === "eql") {
                field = operator.field;
                ret[field] = operator.value;
            } else if (QuerytoMongoMap.hasOwnProperty(name)) {
                field = operator.field;

                ret[field] = {};
                ret[field][QuerytoMongoMap[name]] = operator.value;
            } else if (name === "between") {
                field = operator.field;
                ret[field].$gt = operator.value[0];
                ret[field].$lt = operator.value[1];
            } else if (name === "like") {
                field = operator.field;
                ret[field] = {};
                ret[field].$regex = new RegExp(".*" + operator.value + ".*", "i");
            } else {
                throw new Error("Query Operator '" + name + "' is not supported!");
            }

            return ret;
        }
950646
function parseConditionalExpression() {
        var expr, previousAllowIn, consequent;

        expr = parseLogicalORExpression();

        if (match('?')) {
            lex();
            previousAllowIn = state.allowIn;
            state.allowIn = true;
            consequent = parseAssignmentExpression();
            state.allowIn = previousAllowIn;
            expect(':');

            expr = {
                type: Syntax.ConditionalExpression,
                test: expr,
                consequent: consequent,
                alternate: parseAssignmentExpression()
            };
        }

        return expr;
    }
487873
def p_expression_binop(t):
    ''''''
    if t[2] == '+'  : t[0] = t[1] + t[3]
    elif t[2] == '-': t[0] = t[1] - t[3]
    elif t[2] == '*': t[0] = t[1] * t[3]
    elif t[2] == '/': t[0] = t[1] / t[3]
482011
private static boolean valueConstantsMatch(AbstractExpression e1, AbstractExpression e2) {
        return (e1 instanceof ParameterValueExpression && e2 instanceof ConstantValueExpression ||
                e1 instanceof ConstantValueExpression && e2 instanceof ParameterValueExpression) &&
                equalsAsCVE(e1, e2);
    }
918623
def _validate_condition_keys(self, field, value, error):
        
        if 'field' in value:
            operators = self.nonscalar_conditions + self.scalar_conditions
            matches = sum(1 for k in operators if k in value)
            if matches == 0:
                error(field, 'Must contain one of {}'.format(operators))
                return False
            elif matches > 1:
                error(
                    field,
                    'Must contain no more than one of {}'.format(operators)
                )
                return False
            return True
        elif 'and' in value:
            for condition in value['and']:
                self._validate_condition_keys(field, condition, error)
        elif 'or' in value:
            for condition in value['or']:
                self._validate_condition_keys(field, condition, error)
        else:
            error(field, "Must contain field + operator keys, 'and', or 'or'.")
            return False
876584
def validate(self):
        """"""
        _validate_operator_name(self.operator, BinaryComposition.SUPPORTED_OPERATORS)

        if not isinstance(self.left, Expression):
            raise TypeError(u'Expected Expression left, got: {} {} {}'.format(
                type(self.left).__name__, self.left, self))

        if not isinstance(self.right, Expression):
            raise TypeError(u'Expected Expression right, got: {} {}'.format(
                type(self.right).__name__, self.right))
622336
def expression(allow_assignments = true, wrapped = true, whitespace = true)
      buffer = ''

      # Build a ruby expression out of accepted literals
      while (term = (whitespace ? accept(:whitespace) : nil) ||
                    modifier ||
                    identifier ||
                    method_call ||
                    paranthesis ||
                    array ||
                    hash ||
                    symbol ||
                    percent ||
                    primary_term)
        buffer += term

        # Accept operations which have a right term and raise an error if
        # we have an unfinished expression such as "a +", "b - 1 >" and other
        # expressions following the same pattern
        if wrapped && (op = operation ||
          (allow_assignments ? accept_stripped(:exp_assignment) : nil))

          buffer += op
          if (right_term = expression(allow_assignments, wrapped)).nil?
            Logger.error :parse, @code, @i, @j, :expression
          else
            buffer += right_term[@value]
          end
        elsif (op = array || op = method_call || op = ternary_operator(allow_assignments, wrapped))
          buffer += op
        end

        # Do not continue if the expression has whitespace method calls in
        # an unwrapped context because this will confuse the parser
        unless buffer.strip.empty?
          break if lookahead(:exp_identifier_lookahead).nil?
        end
      end

      if buffer.strip.empty?
        undo buffer
      else
        [:expression, buffer.strip, {}]
      end
    end
552729
def p_expr_ternary_op(p):
    ''
    p[0] = ast.TernaryOp(p[1], p[3], p[5], lineno=p.lineno(2))
670743
public static Expression ifMissing(Expression expression1, Expression expression2, Expression... others) {
        return build("IFMISSING", expression1, expression2, others);
    }
1324225
private boolean validConditionalExpression(Node expr) {
    // The expression must have four children:
    // - The cond keyword
    // - A boolean expression
    // - A type transformation expression with the 'if' branch
    // - A type transformation expression with the 'else' branch
    if (!checkParameterCount(expr, Keywords.COND)) {
      return false;
    }
    // Check for the validity of the boolean and the expressions
    if (!validBooleanExpression(getCallArgument(expr, 0))) {
      warnInvalidInside("conditional", expr);
      return false;
    }
    if (!validTypeTransformationExpression(getCallArgument(expr, 1))) {
      warnInvalidInside("conditional", expr);
      return false;
    }
    if (!validTypeTransformationExpression(getCallArgument(expr, 2))) {
      warnInvalidInside("conditional", expr);
      return false;
    }
    return true;
  }
192048
function (item, expression) {
            var ret = 1,
                operator = expression.operator;

            if (expression instanceof Query.Where) {
                if (operator === "or") {
                    ret = 0;
                }
                var tmp;
                for (var i = 0; i < expression.expressions.length; i++) {
                    tmp = this._filterItem(item, expression.expressions[i]);
                    if (operator === "and") {
                        ret = ret * tmp;
                    } else if (operator === "or" && tmp) {
                        return 1;
                    } else if (operator === "not") {
                        return tmp ? 0 : 1;
                    }
                }
            } else if (expression instanceof Query.Comparator) {
                // TODO: add type check
                var value = expression.value,
                    field = expression.field,
                    itemValue = this._getValueForItemField(item, field);

                if (typeof(itemValue) === "undefined") {
                    return 0;
                }

                switch (operator) {
                    case "eql":
                        return itemValue == value;
                    case "gt":
                        return itemValue > value;
                    case "lt":
                        return itemValue < value;
                    case "gte":
                        return itemValue >= value;
                    case "lte":
                        return itemValue <= value;
                    case "in":
                        if (!(itemValue instanceof Array)) {
                            itemValue = [itemValue];
                        }
                        for (var j = 0; j < itemValue.length; j++) {
                            for (var k in value) {
                                if (value.hasOwnProperty(k)) {
                                    if (itemValue[j] == value[k]) {
                                        return 1;
                                    }
                                }
                            }
                        }
                        return 0;
                    case "between":
                        return itemValue >= value[0] && itemValue <= value[1];
                    case "like":
                        return new RegExp(value, "i").test(itemValue);
                    case "ne":
                        return itemValue != value;
                    default :
                        return 1;
                }

            }

            return ret;
        }
990922
def p_ex_expression(tok):
        """"""
        if len(tok) == 3:
            tok[0] = UnaryOperationRule(tok[1], tok[2])
        else:
            tok[0] = tok[1]