예제 #1
0
    def _generate_binop(self,
                        env: Env) -> Tuple[ast.Binop, ast.TypeAnnotation]:
        """Generates a binary operation AST node."""
        if self.rng.random() < 0.1:
            return self._generate_logical_binop(env)

        make_lhs, lhs_type = self._choose_env_value(env,
                                                    self._not_tuple_or_array)
        make_rhs, rhs_type = self._choose_env_value(env,
                                                    self._not_tuple_or_array)
        if lhs_type == rhs_type:
            return self._generate_binop_same_input_type(
                make_lhs(), make_rhs(), lhs_type)

        if self.rng.choice([True, False]):
            # Cast RHS to LHS type.
            lhs = make_lhs()
            rhs = ast.Cast(lhs_type, make_rhs())
            result_type = lhs_type
        else:
            # Cast LHS to RHS type.
            lhs = ast.Cast(rhs_type, make_lhs())
            rhs = make_rhs()
            result_type = rhs_type

        return self._generate_binop_same_input_type(lhs, rhs, result_type)
예제 #2
0
    def _generate_cast_bits_to_array(
            self, env: Env) -> Tuple[ast.Cast, ast.TypeAnnotation]:
        """Generates a cast from bits to array type."""

        # Get a random bits-typed element from the environment.
        make_arg, arg_type = self._choose_env_value(env,
                                                    self._is_builtin_unsigned)

        # Next, find factors of the bit count and select one pair.
        bit_count = builtin_type_to_bits(arg_type)
        factors = []
        for i in range(1, bit_count + 1):
            if bit_count % i == 0:
                factors.append((i, bit_count // i))

        element_size, array_size = self.rng.choice(factors)
        element_type = ast.make_builtin_type_annotation(
            self.fake_span,
            scanner.Token(scanner.TokenKind.KEYWORD,
                          value=scanner.Keyword.UN,
                          span=self.fake_span),
            (self._make_number(element_size, None), ))

        outer_array_type = self._make_array_type(element_type, array_size)

        return (ast.Cast(outer_array_type, make_arg()), outer_array_type)