Search is not available for this dataset
text
stringlengths
75
104k
def _sig(self, name, dtype=BIT, defVal=None): """ Create signal in this unit """ if isinstance(dtype, HStruct): if defVal is not None: raise NotImplementedError() container = dtype.fromPy(None) for f in dtype.fields: if ...
def _cleanAsSubunit(self): """Disconnect internal signals so unit can be reused by parent unit""" for pi in self._entity.ports: pi.connectInternSig() for i in chain(self._interfaces, self._private_interfaces): i._clean()
def HStruct_selectFields(structT, fieldsToUse): """ Select fields from structure (rest will become spacing) :param structT: HStruct type instance :param fieldsToUse: dict {name:{...}} or set of names to select, dictionary is used to select nested fields in HStruct or HUnion fields ...
def walkFlattenFields(sigOrVal, skipPadding=True): """ Walk all simple values in HStruct or HArray """ t = sigOrVal._dtype if isinstance(t, Bits): yield sigOrVal elif isinstance(t, HUnion): yield from walkFlattenFields(sigOrVal._val, skipPadding=skipPadding) elif isinstance(t...
def HStruct_unpack(structT, data, getDataFn=None, dataWidth=None): """ opposite of packAxiSFrame """ if getDataFn is None: assert dataWidth is not None def _getDataFn(x): return toHVal(x)._auto_cast(Bits(dataWidth)) getDataFn = _getDataFn val = structT.fromPy(N...
def _convSign(self, signed): """ Convert signum, no bit manipulation just data are represented differently :param signed: if True value will be signed, if False value will be unsigned, if None value will be vector without any sign specification """ ...
def fromPy(cls, val, typeObj, vldMask=None): """ Construct value from pythonic value (int, bytes, enum.Enum member) """ assert not isinstance(val, Value) if val is None: vld = 0 val = 0 assert vldMask is None or vldMask == 0 else: ...
def _concat(self, other): """ Concatenate this with other to one wider value/signal """ w = self._dtype.bit_length() try: other_bit_length = other._dtype.bit_length except AttributeError: raise TypeError("Can not concat bits and", other._dtype) ...
def sensitivity(proc: HWProcess, *sensitiveTo): """ register sensitivity for process """ for s in sensitiveTo: if isinstance(s, tuple): sen, s = s if sen == SENSITIVITY.ANY: s.simSensProcs.add(proc) elif sen == SENSITIVITY.RISING: ...
def simEvalCond(simulator, *conds): """ Evaluate list of values as condition """ _cond = True _vld = True for v in conds: val = bool(v.val) fullVld = v.vldMask == 1 if fullVld: if not val: return False, True else: return Fal...
def connectSimPort(simUnit, subSimUnit, srcName, dstName, direction): """ Connect ports of simulation models by name """ if direction == DIRECTION.OUT: origPort = getattr(subSimUnit, srcName) newPort = getattr(simUnit, dstName) setattr(subSimUnit, srcName, newPort) else: ...
def mkUpdater(nextVal: Value, invalidate: bool): """ Create value updater for simulation :param nextVal: instance of Value which will be asssiggned to signal :param invalidate: flag which tells if value has been compromised and if it should be invaidated :return: function(value) -> tuple(va...
def mkArrayUpdater(nextItemVal: Value, indexes: Tuple[Value], invalidate: bool): """ Create value updater for simulation for value of array type :param nextVal: instance of Value which will be asssiggned to signal :param indexes: tuple on indexes where value should be updated ...
def fromPy(cls, val, typeObj, vldMask=None): """ :param val: None or dictionary {index:value} or iterrable of values :param vldMask: if is None validity is resolved from val if is 0 value is invalidated if is 1 value has to be valid """ size = evalParam(ty...
def _getitem__val(self, key): """ :atention: this will clone item from array, iterate over .val if you need to modify items """ try: kv = key.val if not key._isFullVld(): raise KeyError() else: if kv >= self....
def vec(val, width, signed=None): """create hdl vector value""" return Bits(width, signed, forceVector=True).fromPy(val)
def monitor(self, sim): """ Collect data from interface """ r = sim.read if self.notReset(sim): # update rd signal only if required if self._lastRd is not 1: self.wrRd(sim.write, 1) self._lastRd = 1 # try to...
def driver(self, sim): """ Push data to interface set vld high and wait on rd in high then pass new data """ r = sim.read # pop new data if there are not any pending if self.actualData is NOP and self.data: self.actualData = self.data.popleft() ...
def HWProcess(cls, proc: HWProcess, ctx: ResourceContext) -> None: """ Gues resource usage by HWProcess """ seen = ctx.seen for stm in proc.statements: encl = stm._enclosed_for full_ev_dep = stm._is_completly_event_dependent now_ev_dep = stm._n...
def bit_length(self): """ :return: bit width for this type """ try: itemSize = self.elmType.bit_length except AttributeError: itemSize = None if itemSize is None: raise TypeError( "Can not determine size of array because...
def evalParam(p): """ Get value of parameter """ while isinstance(p, Param): p = p.get() if isinstance(p, RtlSignalBase): return p.staticEval() # use rather param inheritance instead of param as param value return toHVal(p)
def set(self, val): """ set value of this param """ assert not self.__isReadOnly, \ ("This parameter(%s) was locked" " and now it can not be changed" % self.name) assert self.replacedWith is None, \ ("This param was replaced with new one and t...
def HTypeFromIntfMap(interfaceMap): """ Generate flattened register map for HStruct :param interfaceMap: sequence of tuple (type, name) or (will create standard struct field member) interface or (will create a struct field from interface) instance of hdl type (is used as padding) ...
def registerMUX(self, stm: Union[HdlStatement, Operator], sig: RtlSignal, inputs_cnt: int): """ mux record is in format (self.MUX, n, m) where n is number of bits of this mux and m is number of possible inputs """ assert inputs_cnt > 1 res = se...
def finalize(self): """ Resolve ports of discovered memories """ ff_to_remove = 0 res = self.resources for m, addrDict in self.memories.items(): rwSyncPorts, rSyncPorts, wSyncPorts = 0, 0, 0 rwAsyncPorts, rAsyncPorts, wAsyncPorts = 0, 0, 0 ...
def naryOp(self, operator, opCreateDelegate, *otherOps) -> RtlSignalBase: """ Try lookup operator with this parameters in _usedOps if not found create new one and soter it in _usedOps :param operator: instance of OpDefinition :param opCreateDelegate: function (*ops) to create op...
def _eq(self, other): """ __eq__ is not overloaded because it will destroy hashability of object """ return self.naryOp(AllOps.EQ, tv(self)._eq, other)
def _getIndexCascade(self): """ Find out if this signal is something indexed """ try: # now I am result of the index xxx[xx] <= source # get index op d = self.singleDriver() try: op = d.operator except Attribute...
def fromPy(self, v, vldMask=None): """ Construct value of this type. Delegated on value class for this type """ return self.getValueCls().fromPy(v, self, vldMask=vldMask)
def auto_cast(self, sigOrVal, toType): """ Cast value or signal of this type to another compatible type. :param sigOrVal: instance of signal or value to cast :param toType: instance of HdlType to cast into """ if sigOrVal._dtype == toType: return sigOrVal ...
def reinterpret_cast(self, sigOrVal, toType): """ Cast value or signal of this type to another type of same size. :param sigOrVal: instance of signal or value to cast :param toType: instance of HdlType to cast into """ try: return self.auto_cast(sigOrVal, toT...
def walkParams(intf, discovered): """ walk parameter instances on this interface """ for si in intf._interfaces: yield from walkParams(si, discovered) for p in intf._params: if p not in discovered: discovered.add(p) yield p
def connectPacked(srcPacked, dstInterface, exclude=None): """ Connect 1D vector signal to this structuralized interface :param packedSrc: vector which should be connected :param dstInterface: structuralized interface where should packedSrc be connected to :param exclude: sub interfaces of s...
def walkFlatten(interface, shouldEnterIntfFn): """ :param shouldEnterIntfFn: function (actual interface) returns tuple (shouldEnter, shouldYield) """ _shouldEnter, _shouldYield = shouldEnterIntfFn(interface) if _shouldYield: yield interface if shouldEnterIntfFn: for intf...
def packIntf(intf, masterDirEqTo=DIRECTION.OUT, exclude=None): """ Concatenate all signals to one big signal, recursively :param masterDirEqTo: only signals with this direction are packed :param exclude: sequence of signals/interfaces to exclude """ if not intf._interfaces: if intf._mas...
def hardcodeRomIntoProcess(cls, rom): """ Due to verilog restrictions it is not posible to use array constants and rom memories has to be hardcoded as process """ processes = [] signals = [] for e in rom.endpoints: assert isinstance(e, Operator) and e....
def Architecture_var(cls, v, serializerVars, extraTypes, extraTypes_serialized, ctx, childCtx): """ :return: list of extra discovered processes """ t = v._dtype # if type requires extra definition if isinstance(t, HArray) and v.defVal.vldMask: ...
def _toRtl(self, targetPlatform: DummyPlatform): """ synthesize all subunits, make connections between them, build entity and component for this unit """ assert not self._wasSynthetised() self._targetPlatform = targetPlatform if not hasattr(self, "_name"): ...
def _loadDeclarations(self): """ Load all declarations from _decl() method, recursively for all interfaces/units. """ if not hasattr(self, "_interfaces"): self._interfaces = [] if not hasattr(self, "_private_interfaces"): self._private_interfaces =...
def _registerIntfInImpl(self, iName, intf): """ Register interface in implementation phase """ self._registerInterface(iName, intf, isPrivate=True) self._loadInterface(intf, False) intf._signalsForInterface(self._ctx)
def reverseByteOrder(signalOrVal): """ Reverse byteorder (littleendian/bigendian) of signal or value """ w = signalOrVal._dtype.bit_length() i = w items = [] while i > 0: # take last 8 bytes or rest lower = max(i - 8, 0) items.append(signalOrVal[i:lower]) i -...
def tryReduceAnd(sig, val): """ Return sig and val reduced by & operator or None if it is not possible to statically reduce expression """ m = sig._dtype.all_mask() if val._isFullVld(): v = val.val if v == m: return sig elif v == 0: return val
def tryReduceXor(sig, val): """ Return sig and val reduced by ^ operator or None if it is not possible to statically reduce expression """ m = sig._dtype.all_mask() if not val.vldMask: return val if val._isFullVld(): v = val.val if v == m: return ~sig ...
def getBaseNameScope(cls): """ Get root of name space """ s = NameScope(False) s.setLevel(1) s[0].update(cls._keywords_dict) return s
def asHdl(cls, obj, ctx: SerializerCtx): """ Convert object to HDL string :param obj: object to serialize :param ctx: SerializerCtx instance """ if isinstance(obj, RtlSignalBase): return cls.SignalItem(obj, ctx) elif isinstance(obj, Value): ...
def Entity(cls, ent: Entity, ctx: SerializerCtx): """ Entity is just forward declaration of Architecture, it is not used in most HDL languages as there is no recursion in hierarchy """ ent.name = ctx.scope.checkedName(ent.name, ent, isGlobal=True) return ""
def serializationDecision(cls, obj, serializedClasses, serializedConfiguredUnits): """ Decide if this unit should be serialized or not eventually fix name to fit same already serialized unit :param obj: object to serialize :param serializedClasses: ...
def HdlType(cls, typ: HdlType, ctx: SerializerCtx, declaration=False): """ Serialize HdlType instance """ if isinstance(typ, Bits): sFn = cls.HdlType_bits elif isinstance(typ, HEnum): sFn = cls.HdlType_enum elif isinstance(typ, HArray): ...
def IfContainer(cls, ifc: IfContainer, ctx: SerializerCtx): """ Srialize IfContainer instance """ childCtx = ctx.withIndent() def asHdl(statements): return [cls.asHdl(s, childCtx) for s in statements] try: cond = cls.condAsHdl(ifc.cond, True, ctx...
def pullDownAfter(sig, initDelay=6 * Time.ns): """ :return: simulation driver which keeps signal value high for initDelay then it sets value to 0 """ def _pullDownAfter(s): s.write(True, sig) yield s.wait(initDelay) s.write(False, sig) return _pullDownAfter
def getBaseCond(c): """ if is negated return original cond and negated flag """ isNegated = False try: drivers = c.drivers except AttributeError: return (c, isNegated) if len(drivers) == 1: d = list(c.drivers)[0] if isinstance(d, Operator) and d.operator == A...
def simBitsT(width: int, signed: Union[bool, None]): """ Construct SimBitsT with cache """ k = (width, signed) try: return __simBitsTCache[k] except KeyError: t = SimBitsT(width, signed) __simBitsTCache[k] = t return t
def fromPy(cls, val, typeObj, vldMask=None): """ :param val: None or dict {field name: field value} :param typeObj: instance of String HdlType :param vldMask: if is None validity is resolved from val if is 0 value is invalidated if is 1 value has to be valid ...
def VectSignal(width, signed=None, masterDir=D.OUT, loadConfig=True): """ Create basic :class:`.Signal` interface where type is vector """ return Signal(masterDir, Bits(width, signed, forceVector=True), loadConfig)
def getConstName(self, val): """ Get constant name for value name of constant is reused if same value was used before """ try: return self._cache[val] except KeyError: if isinstance(val.val, int): name = "const_%d_" % val.val ...
def _cut_off_drivers_of(self, sig: RtlSignalBase): """ Cut off statements which are driver of specified signal """ if self.dst is sig: self.parentStm = None return self else: return None
def _loadFromArray(self, dtype: HdlType, bitAddr: int) -> int: """ Parse HArray type to this transaction template instance :return: address of it's end """ self.itemCnt = evalParam(dtype.size).val self.children = TransTmpl( dtype.elmType, 0, parent=self, orig...
def _loadFromHStruct(self, dtype: HdlType, bitAddr: int): """ Parse HStruct type to this transaction template instance :return: address of it's end """ for f in dtype.fields: t = f.dtype origin = f isPadding = f.name is None if is...
def _loadFromUnion(self, dtype: HdlType, bitAddr: int) -> int: """ Parse HUnion type to this transaction template instance :return: address of it's end """ for field in dtype.fields.values(): ch = TransTmpl(field.dtype, 0, parent=self, origin=field) self....
def _loadFromHStream(self, dtype: HStream, bitAddr: int) -> int: """ Parse HUnion type to this transaction template instance :return: address of it's end """ ch = TransTmpl(dtype.elmType, 0, parent=self, origin=self.origin) self.children.append(ch) return bitAddr...
def _loadFromHType(self, dtype: HdlType, bitAddr: int) -> None: """ Parse any HDL type to this transaction template instance """ self.bitAddr = bitAddr childrenAreChoice = False if isinstance(dtype, Bits): ld = self._loadFromBits elif isinstance(dtype,...
def getItemWidth(self) -> int: """ Only for transactions derived from HArray :return: width of item in original array """ if not isinstance(self.dtype, HArray): raise TypeError() return (self.bitAddrEnd - self.bitAddr) // self.itemCnt
def walkFlatten(self, offset: int=0, shouldEnterFn=_default_shouldEnterFn, otherObjItCtx: ObjIteratorCtx =_DummyIteratorCtx() ) -> Generator[ Union[Tuple[Tuple[int, int], 'TransTmpl'], 'OneOfTransaction'], None, None]: """ ...
def walkFlattenChilds(self) -> Generator[ Union[Tuple[Tuple[int, int], TransTmpl], 'OneOfTransaction'], None, None]: """ :return: generator of generators of tuples ((startBitAddress, endBitAddress), TransTmpl instance) for each possiblility in this transac...
def signFix(val, width): """ Convert negative int to positive int which has same bits set """ if val > 0: msb = 1 << (width - 1) if val & msb: val -= mask(width) + 1 return val
def bitsCmp(self, other, op, evalFn=None): """ :attention: If other is Bool signal convert this to bool (not ideal, due VHDL event operator) """ other = toHVal(other) t = self._dtype ot = other._dtype iamVal = isinstance(self, Value) otherIsVal = isinstance(other, Value) if...
def bitsBitOp(self, other, op, getVldFn, reduceCheckFn): """ :attention: If other is Bool signal, convert this to bool (not ideal, due VHDL event operator) """ other = toHVal(other) iamVal = isinstance(self, Value) otherIsVal = isinstance(other, Value) if iamVal and otherIsVal: ...
def fromPy(cls, val, typeObj, vldMask=None): """ :param val: value of python type bool or None :param typeObj: instance of HEnum :param vldMask: if is None validity is resolved from val if is 0 value is invalidated if is 1 value has to be valid """ ...
def _discover_sensitivity(self, seen) -> None: """ Doc on parent class :meth:`HdlStatement._discover_sensitivity` """ assert self._sensitivity is None, self ctx = self._sensitivity = SensitivityCtx() casual_sensitivity = set() self.switchOn._walk_sensitivity(casu...
def _fill_enclosure(self, enclosure: Dict[RtlSignalBase, HdlStatement]) -> None: """ :attention: enclosure has to be discoverd first use _discover_enclosure() method """ select = [] outputs = self._outputs for e in enclosure.keys(): if e in outputs: ...
def _iter_stms(self): """ Doc on parent class :meth:`HdlStatement._iter_stms` """ for _, stms in self.cases: yield from stms if self.default is not None: yield from self.default
def _is_mergable(self, other) -> bool: """ :return: True if other can be merged into this statement else False """ if not isinstance(other, SwitchContainer): return False if not (self.switchOn is other.switchOn and len(self.cases) == len(other.cases) ...
def _merge_with_other_stm(self, other: "IfContainer") -> None: """ Merge other statement to this statement """ merge = self._merge_statement_lists newCases = [] for (c, caseA), (_, caseB) in zip(self.cases, other.cases): newCases.append((c, merge(caseA, caseB)...
def _try_reduce(self) -> Tuple[List["HdlStatement"], bool]: """ Doc on parent class :meth:`HdlStatement._try_reduce` """ io_change = False new_cases = [] for val, statements in self.cases: _statements, rank_decrease, _io_change = self._try_reduce_list( ...
def _condHasEffect(self) -> bool: """ :return: True if statements in branches has different effect """ if not self.cases: return False # [TODO] type_domain_covered = bool(self.default) or len( self.cases) == self.switchOn._dtype.domain_size() ...
def isSame(self, other: HdlStatement) -> bool: """ Doc on parent class :meth:`HdlStatement.isSame` """ if self is other: return True if self.rank != other.rank: return False if isinstance(other, SwitchContainer) \ and isSameHVal(s...
def discoverEventDependency(sig): """ :return: generator of tuples (event operator, signal) """ try: drivers = sig.drivers except AttributeError: return if len(drivers) == 1: d = drivers[0] if isinstance(d, Operator): if isEventDependentOp(d.operator...
def getIndent(indentNum): """ Cached indent getter function """ try: return _indentCache[indentNum] except KeyError: i = "".join([_indent for _ in range(indentNum)]) _indentCache[indentNum] = i return i
def verilogTypeOfSig(signalItem): """ Check if is register or wire """ driver_cnt = len(signalItem.drivers) if signalItem._const or driver_cnt > 1 or\ arr_any(signalItem.drivers, _isEventDependentDriver): return SIGNAL_TYPE.REG else: if driver_cnt == 1: d = sig...
def toHdlConversion(self, top, topName: str, saveTo: str) -> List[str]: """ :param top: object which is represenation of design :param topName: name which should be used for ipcore :param saveTo: path of directory where generated files should be stored :return: list of file name...
def serializeType(self, hdlType: HdlType) -> str: """ :see: doc of method on parent class """ def createTmpVar(suggestedName, dtype): raise NotImplementedError( "Can not seraialize hdl type %r into" "ipcore format" % (hdlType)) return...
def getVectorFromType(self, dtype) -> Union[bool, None, Tuple[int, int]]: """ :see: doc of method on parent class """ if dtype == BIT: return False elif isinstance(dtype, Bits): return [evalParam(dtype.width) - 1, hInt(0)]
def getExprVal(self, val, do_eval=False): """ :see: doc of method on parent class """ ctx = VhdlSerializer.getBaseContext() def createTmpVar(suggestedName, dtype): raise NotImplementedError( "Width value can not be converted do ipcore format (%r)", ...
def getTypeWidth(self, dtype: HdlType, do_eval=False) -> Tuple[int, Union[int, RtlSignal], bool]: """ :see: doc of method on parent class """ width = dtype.width if isinstance(width, int): widthStr = str(width) else: widthStr = self.getExprVal(widt...
def getObjDebugName(self, obj: Union[Interface, Unit, Param]) -> str: """ :see: doc of method on parent class """ return obj._getFullName()
def serialzeValueToTCL(self, val, do_eval=False) -> Tuple[str, str, bool]: """ :see: doc of method on parent class """ if isinstance(val, int): val = hInt(val) if do_eval: val = val.staticEval() if isinstance(val, RtlSignalBase): ctx =...
def nameAvailabilityCheck(obj, propName, prop): """ Check if not redefining property on obj """ if getattr(obj, propName, None) is not None: raise IntfLvlConfErr("%r already has property %s old:%s new:%s" % (obj, propName, repr(getattr(obj, propName)), prop))
def _registerParameter(self, pName, parameter) -> None: """ Register Param object on interface level object """ nameAvailabilityCheck(self, pName, parameter) # resolve name in this scope try: hasName = parameter._name is not None except AttributeError:...
def _paramsShared(self, exclude=None, prefix="") -> MakeParamsShared: """ Auto-propagate params by name to child components and interfaces Usage: .. code-block:: python with self._paramsShared(): # your interfaces and unit which should share all params with ...
def _make_association(self, clk=None, rst=None) -> None: """ Associate this object with specified clk/rst """ if clk is not None: assert self._associatedClk is None self._associatedClk = clk if rst is not None: assert self._associatedRst is No...
def _updateParamsFrom(self, otherObj:"PropDeclrCollector", updater, exclude:set, prefix:str) -> None: """ Update all parameters which are defined on self from otherObj :param otherObj: other object which Param instances should be updated :param updater: updater function(self, myParamete...
def _registerUnit(self, uName, unit): """ Register unit object on interface level object """ nameAvailabilityCheck(self, uName, unit) assert unit._parent is None unit._parent = self unit._name = uName self._units.append(unit)
def _registerInterface(self, iName, intf, isPrivate=False): """ Register interface object on interface level object """ nameAvailabilityCheck(self, iName, intf) assert intf._parent is None intf._parent = self intf._name = iName intf._ctx = self._ctx ...
def _registerArray(self, name, items): """ Register array of items on interface level object """ items._parent = self items._name = name for i, item in enumerate(items): setattr(self, "%s_%d" % (name, i), item)
def _registerUnitInImpl(self, uName, u): """ :attention: unit has to be parametrized before it is registered (some components can change interface by parametrization) """ self._registerUnit(uName, u) u._loadDeclarations() self._lazyLoaded.extend(u._toRtl(self....
def singleDriver(self): """ Returns a first driver if signal has only one driver. """ # [TODO] no driver exception drv_cnt = len(self.drivers) if not drv_cnt: raise NoDriverErr(self) elif drv_cnt != 1: raise MultipleDriversErr(self) ...
def registerSignals(self, outputs=[]): """ Register potential signals to drivers/endpoints """ for o in self.operands: if isinstance(o, RtlSignalBase): if o in outputs: o.drivers.append(self) else: o.endp...
def staticEval(self): """ Recursively statistically evaluate result of this operator """ for o in self.operands: o.staticEval() self.result._val = self.evalFn()
def withRes(opDef, operands, resT, outputs=[]): """ Create operator with result signal :ivar resT: data type of result signal :ivar outputs: iterable of singnals which are outputs from this operator """ op = Operator(opDef, operands) out = RtlSignal(g...
def withIndent(self, indent=1): """ Create copy of this context with increased indent """ ctx = copy(self) ctx.indent += indent return ctx