def test_array_vs_multidim_bits_equality(self): a = ArrayType(BitsType(signed=False, size=5), 7) self.assertEqual(str(a), 'uN[5][7]') self.assertEqual(7 * 5, a.get_total_bit_count()) self.assertEqual(7, a.size) self.assertEqual(5, a.get_element_type().size) # pytype: disable=attribute-error self.assertEqual((7, 5), a.get_all_dims()) self.assertEqual((), TupleType(()).get_all_dims())
def test_arrayness(self): tabular = [ # (type, is_array, element_count) (TupleType(members=()), False, None), (BitsType(signed=False, size=5), False, None), (ArrayType(BitsType(False, 5), 7), True, 7), (ArrayType(TupleType(members=()), 7), True, 7), ] for t, is_array, element_count in tabular: self.assertEqual(isinstance(t, ArrayType), is_array, msg=str(t)) if is_array: self.assertEqual(t.size, element_count, msg=str(t))
def map_size(t: ConcreteType, m: ast.Module, f: Callable[[Dim], Dim]) -> ConcreteType: """Runs f on all dimensions within t (transively for contained types).""" assert isinstance(m, ast.Module), m rec = functools.partial(map_size, m=m, f=f) if isinstance(t, ArrayType): return ArrayType(rec(t.get_element_type()), f(t.size)) elif isinstance(t, BitsType): return BitsType(t.signed, f(t.size)) elif isinstance(t, TupleType): nominal = t.get_nominal_type() if t.named: return TupleType( tuple((name, rec(type_)) for name, type_ in t.members), nominal) assert nominal is None, nominal return TupleType(tuple(rec(e) for e in t.members)) elif isinstance(t, EnumType): return EnumType(t.get_nominal_type(), f(t.size)) elif isinstance(t, FunctionType): mapped_params = tuple(rec(p) for p in t.params) mapped_return_type = rec(t.return_type) return FunctionType(mapped_params, mapped_return_type) else: raise NotImplementedError(t.__class__)
def concrete_type_from_dims(primitive: Token, dims: Tuple[int, ...]) -> 'ConcreteType': """Creates a concrete type from the primitive type token and dims. Args: primitive: The token holding the primitive type as a keyword. dims: Dimensions to apply to the primitive type; e.g. () is scalar, (5) is 1-D array of 5 elements having the primitive type. Returns: A concrete type object. Raises: ValueError: If the primitive keyword is unrecognized or dims are empty. """ if primitive.is_keyword(Keyword.BITS) or primitive.is_keyword(Keyword.UN): base_type = BitsType(signed=False, size=dims[-1]) elif primitive.is_keyword(Keyword.SN): base_type = BitsType(signed=True, size=dims[-1]) else: assert primitive.kind == TokenKind.KEYWORD signedness, bits = TYPE_KEYWORDS_TO_SIGNEDNESS_AND_BITS[primitive.value] element_type = BitsType(signedness, bits) while dims: dims, minor = dims[:-1], dims[-1] element_type = ArrayType(element_type, minor) return element_type result = concrete_type_from_element_type_and_dims(base_type, dims[:-1]) logging.vlog(4, '%r %r => %r', primitive, dims, result) return result
def concrete_type_from_element_type_and_dims( element_type: ConcreteType, dims: Tuple[int, ...]) -> ConcreteType: """Wraps element_type in arrays according to `dims`, dims[0] as most minor.""" t = element_type for dim in dims: t = ArrayType(t, dim) return t
def fsig(arg_types: ArgTypes, name: Text, span: Span, ctx: DeduceCtx, _: Optional[ParametricBindings]) -> ConcreteType: _Checker(arg_types, name, span).len(1).is_array(0) t = arg_types[0].get_element_type() # pytype: disable=attribute-error e = TupleType((ConcreteType.U32, t)) return_type = ArrayType(e, arg_types[0].size) # pytype: disable=attribute-error return FunctionType(arg_types, return_type)
def test_generate_array_argument(self): rng = ast_generator.RngState(0) args = ast_generator.generate_arguments( (ArrayType(BitsType(signed=True, size=4), 24), ), rng) self.assertLen(args, 1) self.assertTrue(args[0].is_array()) self.assertLen(args[0].get_elements(), 24) self.assertTrue(args[0].index(0).is_sbits()) self.assertTrue(args[0].index(0).get_bit_count(), 4)
def test_generate_array_argument(self): rng = random.Random(0) args = sample_generator.generate_arguments( (ArrayType(BitsType(signed=True, size=4), 24),), rng) self.assertLen(args, 1) self.assertTrue(args[0].is_array()) self.assertLen(args[0].array_payload.elements, 24) self.assertTrue(args[0].array_payload.index(0).is_sbits()) self.assertTrue(args[0].array_payload.index(0).get_bit_count(), 4)
def test_sign_convert_array_value(self): t = ArrayType(BitsType(signed=True, size=8), 3) self.assertEqual( sample_runner.sign_convert_value( t, Value.make_array( (Value.make_ubits(8, 0x42), Value.make_ubits(8, 0x43), Value.make_ubits(8, 0x44)))), Value.make_array( (Value.make_sbits(8, 0x42), Value.make_sbits(8, 0x43), Value.make_sbits(8, 0x44))))
def test_stringify(self): u32 = BitsType(signed=False, size=32) tabular = [ # type size total_bit_count str (ArrayType(u32, 7), 7, 32 * 7, 'uN[32][7]'), (u32, 32, 32, 'uN[32]'), ] for t, size, total_bit_count, s in tabular: self.assertEqual(t.size, size) self.assertEqual(t.get_total_bit_count(), total_bit_count) self.assertEqual(str(t), s)
def fsig( arg_types: ArgTypes, name: Text, span: Span, ctx: DeduceCtx, parametric_bindings: Optional[ParametricBindings] ) -> Tuple[ConcreteType, parametric_instantiator.SymbolicBindings]: """Returns the inferred/checked return type for a map-style signature.""" logging.vlog(5, 'Instantiating for builtin %r @ %s', name, span) _Checker(arg_types, name, span).len(2).is_array(0).is_fn(1, argc=1) t = arg_types[0].get_element_type() # pytype: disable=attribute-error u, symbolic_bindings = parametric_instantiator.instantiate_function( span, arg_types[1], (t, ), ctx, parametric_bindings) return_type = ArrayType(u, arg_types[0].size) # pytype: disable=attribute-error return FunctionType(arg_types, return_type), symbolic_bindings
def concrete_type_from_value(value: Value) -> ConcreteType: """Returns the concrete type of 'value'. Note that: * Non-zero-length arrays are assumed (for zero length arrays we can't currently deduce the type from the value because the concrete element type is not reified in the array value. * Enums are strength-reduced to their underlying bits (storage) type. Args: value: Value to determine the concrete type for. """ if value.tag in (Tag.UBITS, Tag.SBITS): signed = value.tag == Tag.SBITS return BitsType(signed, value.bits_payload.bit_count) elif value.tag == Tag.ARRAY: element_type = concrete_type_from_value(value.array_payload.index(0)) return ArrayType(element_type, len(value)) elif value.tag == Tag.TUPLE: return TupleType( tuple(concrete_type_from_value(m) for m in value.tuple_members)) else: assert value.tag == Tag.ENUM, value return _strength_reduce_enum(value.type_, value.bits_payload.bit_count)
def test_array_of_tuple_all_dims(self): a = ArrayType(TupleType(()), 7) self.assertEqual((7, ), a.get_all_dims())
def test_array_bit_count(self): e = BitsType(signed=False, size=4) a = ArrayType(e, 3) self.assertEqual(a.get_total_bit_count(), 12)