"""HUGR integer types and operations."""from__future__importannotationsfromdataclassesimportdataclass,fieldfromtypingimportTYPE_CHECKING,ClassVarfromtyping_extensionsimportSelfimporthugr.modelasmodelfromhugrimportext,tys,valfromhugr.opsimportAsExtOp,DataflowOp,ExtOp,RegisteredOpfromhugr.stdimport_load_extensionifTYPE_CHECKING:fromhugr.opsimportCommand,ComWireCONVERSIONS_EXTENSION=_load_extension("arithmetic.conversions")INT_TYPES_EXTENSION=_load_extension("arithmetic.int.types")_INT_PARAM=tys.BoundedNatParam(7)INT_T_DEF=INT_TYPES_EXTENSION.types["int"]
[docs]defint_t(width:int)->tys.ExtType:"""Create an integer type with a fixed log bit width. Args: width: The log bit width of the integer. Returns: The integer type. Examples: >>> int_t(5).type_def.name # 32 bit integer 'int' """returnINT_T_DEF.instantiate([tys.BoundedNatArg(n=width)],)
def_int_tv(index:int)->tys.ExtType:returnINT_T_DEF.instantiate([tys.VariableArg(idx=index,param=_INT_PARAM)],)#: HUGR 32-bit integer type.INT_T=int_t(5)def_to_unsigned(val:int,bits:int)->int:"""Convert a signed integer to its unsigned representation in twos-complement form. Positive integers are unchanged, while negative integers are converted by adding 2^bits to the value. Raises ValueError if the value is out of range for the given bit width (valid range is [-2^(bits-1), 2^(bits-1)-1]). """half_max=1<<(bits-1)min_val=-half_maxmax_val=half_max-1ifval<min_valorval>max_val:msg=f"Value {val} out of range for {bits}-bit signed integer."raiseValueError(msg)#ifval<0:return(1<<bits)+valreturnval
[docs]@dataclassclassIntVal(val.ExtensionValue):"""Custom value for a signed integer."""v:intwidth:int=field(default=5)
INT_OPS_EXTENSION=_load_extension("arithmetic.int")@dataclass(frozen=True)class_DivModDef(RegisteredOp):"""DivMod operation, has two inputs and two outputs."""width:int=5const_op_def:ClassVar[ext.OpDef]=INT_OPS_EXTENSION.operations["idivmod_u"]deftype_args(self)->list[tys.TypeArg]:return[tys.BoundedNatArg(n=self.width)]defcached_signature(self)->tys.FunctionType|None:row:list[tys.Type]=[int_t(self.width)]*2returntys.FunctionType.endo(row)@classmethoddeffrom_ext(cls,custom:ExtOp)->Self|None:ifcustom.op_def()!=cls.op_def():returnNonematchcustom.args:case[tys.BoundedNatArg(n=a1)]:returncls(width=a1)case_:msg=f"Invalid args: {custom.args}"raiseAsExtOp.InvalidExtOp(msg)def__call__(self,a:ComWire,b:ComWire)->Command:returnDataflowOp.__call__(self,a,b)#: DivMod operation.DivMod=_DivModDef()