Search is not available for this dataset
text
stringlengths
75
104k
def isPow2(num) -> bool: """ Check if number or constant is power of two """ if not isinstance(num, int): num = int(num) return num != 0 and ((num & (num - 1)) == 0)
def addCases(self, tupesValStmnts): """ Add multiple case statements from iterable of tuleles (caseVal, statements) """ s = self for val, statements in tupesValStmnts: s = s.Case(val, statements) return s
def Case(self, caseVal, *statements): "c-like case of switch statement" assert self.parentStm is None caseVal = toHVal(caseVal, self.switchOn._dtype) assert isinstance(caseVal, Value), caseVal assert caseVal._isFullVld(), "Cmp with invalid value" assert caseVal not in se...
def Default(self, *statements): """c-like default of switch statement """ assert self.parentStm is None self.rank += 1 self.default = [] self._register_stements(statements, self.default) return self
def Trans(self, stateFrom, *condAndNextState): """ :param stateFrom: apply when FSM is in this state :param condAndNextState: tupes (condition, newState), last does not to have condition :attention: transitions has priority, first has the biggest :attention: if state...
def vcdTypeInfoForHType(t) -> Tuple[str, int, Callable[[RtlSignalBase, Value], str]]: """ :return: (vcd type name, vcd width) """ if isinstance(t, (SimBitsT, Bits, HBool)): return (VCD_SIG_TYPE.WIRE, t.bit_length(), vcdBitsFormatter) elif isinstance(t, HEnum): return (VCD_SIG_TYPE.RE...
def vcdRegisterInterfaces(self, obj: Union[Interface, Unit], parent: Optional[VcdVarWritingScope]): """ Register signals from interfaces for Interface or Unit instances """ if hasattr(obj, "_interfaces") and obj._interfaces: name = obj._name ...
def beforeSim(self, simulator, synthesisedUnit): """ This method is called before first step of simulation. """ vcd = self.vcdWriter vcd.date(datetime.now()) vcd.timescale(1) self.vcdRegisterInterfaces(synthesisedUnit, None) self.vcdRegisterRemainingSigna...
def logChange(self, nowTime, sig, nextVal): """ This method is called for every value change of any signal. """ try: self.vcdWriter.logChange(nowTime, sig, nextVal) except KeyError: # not every signal has to be registered pass
def HWProcess(cls, proc, ctx): """ Serialize HWProcess instance :param scope: name scope to prevent name collisions """ body = proc.statements childCtx = ctx.withIndent() statemets = [cls.asHdl(s, childCtx) for s in body] proc.name = ctx.scope.checkedName...
def setLevel(self, lvl): """ Trim or extend scope lvl = 1 -> only one scope (global) """ while len(self) != lvl: if len(self) > lvl: self.pop() else: self.append(NameScopeItem(len(self)))
def _size(self): """ :return: how many bits is this slice selecting """ assert isinstance(self, Value) return int(self.val[0]) - int(self.val[1])
def autoAddAgents(unit): """ Walk all interfaces on unit and instantiate agent for every interface. :return: all monitor/driver functions which should be added to simulation as processes """ proc = [] for intf in unit._interfaces: if not intf._isExtern: continue ...
def valuesToInts(values): """ Iterable of values to ints (nonvalid = None) """ res = [] append = res.append for d in values: if isinstance(d, int): append(d) else: append(valToInt(d)) return res
def _getAssociatedRst(self): """ If interface has associated rst(_n) return it otherwise try to find rst(_n) on parent recursively """ a = self._associatedRst if a is not None: return a p = self._parent assert p is not None if isinst...
def _getAssociatedClk(self): """ If interface has associated clk return it otherwise try to find clk on parent recursively """ a = self._associatedClk if a is not None: return a p = self._parent assert p is not None if isinstance(p, ...
def Architecture_var(cls, v, serializerVars, extraTypes, extraTypes_serialized, ctx, childCtx): """ :return: list of extra discovered processes """ v.name = ctx.scope.checkedName(v.name, v) serializedVar = cls.SignalItem(v, childCtx, declaration=True) ...
def distinctBy(iterable, fn): """ uniq operation with key selector """ s = set() for i in iterable: r = fn(i) if r not in s: s.add(r) yield i
def single(iterable, fn): """ Get value from iterable where fn(item) and check if there is not fn(other item) :raise DuplicitValueExc: when there are multiple items satisfying fn() :raise NoValueExc: when no value satisfying fn(item) found """ found = False ret = None for i in iter...
def take(iterrable, howMay): """ :return: generator of first n items from iterrable """ assert howMay >= 0 if not howMay: return last = howMay - 1 for i, item in enumerate(iterrable): yield item if i == last: return
def iter_with_last(iterable): """ :return: generator of tuples (isLastFlag, item) """ # Ensure it's an iterator and get the first field iterable = iter(iterable) prev = next(iterable) for item in iterable: # Lag by one item so I know I'm not at the end yield False, prev ...
def groupedby(collection, fn): """ same like itertools.groupby :note: This function does not needs initial sorting like itertools.groupby :attention: Order of pairs is not deterministic. """ d = {} for item in collection: k = fn(item) try: arr = d[k] exc...
def flatten(iterables, level=inf): """ Flatten nested lists, tuples, generators and maps :param level: maximum depth of flattening """ if level >= 0 and isinstance(iterables, (list, tuple, GeneratorType, map, zip)): level -= 1 for i in it...
def _cut_off_drivers_of(self, sig: RtlSignalBase): """ Doc on parent class :meth:`HdlStatement._cut_off_drivers_of` """ if len(self._outputs) == 1 and sig in self._outputs: self.parentStm = None return self # try to cut off all statements which are driver...
def _discover_enclosure(self): """ Doc on parent class :meth:`HdlStatement._discover_enclosure` """ outputs = self._outputs self._ifTrue_enclosed_for = self._discover_enclosure_for_statements( self.ifTrue, outputs) elif_encls = self._elIfs_enclosed_for = [] ...
def _discover_sensitivity(self, seen: set) -> None: """ Doc on parent class :meth:`HdlStatement._discover_sensitivity` """ assert self._sensitivity is None, self ctx = self._sensitivity = SensitivityCtx() self._discover_sensitivity_sig(self.cond, seen, ctx) if ct...
def _iter_stms(self): """ Doc on parent class :meth:`HdlStatement._iter_stms` """ yield from self.ifTrue for _, stms in self.elIfs: yield from stms if self.ifFalse is not None: yield from self.ifFalse
def _try_reduce(self) -> Tuple[bool, List[HdlStatement]]: """ Doc on parent class :meth:`HdlStatement._try_reduce` """ # flag if IO of statement has changed io_change = False self.ifTrue, rank_decrease, _io_change = self._try_reduce_list( self.ifTrue) ...
def _merge_nested_if_from_else(self, ifStm: "IfContainer"): """ Merge nested IfContarner form else branch to this IfContainer as elif and else branches """ self.elIfs.append((ifStm.cond, ifStm.ifTrue)) self.elIfs.extend(ifStm.elIfs) self.ifFalse = ifStm.ifFalse
def _merge_with_other_stm(self, other: "IfContainer") -> None: """ :attention: statements has to be mergable (to check use _is_mergable method) """ merge = self._merge_statement_lists self.ifTrue = merge(self.ifTrue, other.ifTrue) new_elifs = [] for ((c, elifA), ...
def isSame(self, other: HdlStatement) -> bool: """ :return: True if other has same meaning as this statement """ if self is other: return True if self.rank != other.rank: return False if isinstance(other, IfContainer): if self.cond is...
def removeUnconnectedSignals(netlist): """ If signal is not driving anything remove it """ toDelete = set() toSearch = netlist.signals while toSearch: _toSearch = set() for sig in toSearch: if not sig.endpoints: try: if sig._inte...
def checkIfIsTooSimple(proc): """check if process is just unconditional assignments and it is useless to merge them""" try: a, = proc.statements if isinstance(a, Assignment): return True except ValueError: pass return False
def tryToMerge(procA: HWProcess, procB: HWProcess): """ Try merge procB into procA :raise IncompatibleStructure: if merge is not possible :attention: procA is now result if merge has succeed :return: procA which is now result of merge """ if (checkIfIsTooSimple(procA) or checkIf...
def reduceProcesses(processes): """ Try to merge processes as much is possible :param processes: list of processes instances """ # sort to make order of merging same deterministic processes.sort(key=lambda x: (x.name, maxStmId(x)), reverse=True) # now try to reduce processes with nearly sam...
def onWriteReq(self, sim, addr, data): """ on writeReqRecieved in monitor mode """ self.requests.append((WRITE, addr, data))
def asHdl(cls, obj, ctx: HwtSerializerCtx): """ Convert object to HDL string :param obj: object to serialize :param ctx: HwtSerializerCtx instance """ if isinstance(obj, RtlSignalBase): return cls.SignalItem(obj, ctx) elif isinstance(obj, Value): ...
def Entity(cls, ent: Entity, ctx: HwtSerializerCtx): """ Entity is just forward declaration of Architecture, it is not used in most HDL languages as there is no recursion in hierarchy """ cls.Entity_prepare(ent, ctx, serialize=False) ent.name = ctx.scope.checkedName(ent....
def toRtl(unitOrCls: Unit, name: str=None, serializer: GenericSerializer=VhdlSerializer, targetPlatform=DummyPlatform(), saveTo: str=None): """ Convert unit to RTL using specified serializer :param unitOrCls: unit instance or class, which should be converted :param name: name overri...
def name_for_process_and_mark_outputs(statements: List[HdlStatement])\ -> str: """ Resolve name for process and mark outputs of statemens as not hidden """ out_names = [] for stm in statements: for sig in stm._outputs: if not sig.hasGenericName: out_names....
def cut_off_drivers_of(dstSignal, statements): """ Cut off drivers from statements """ separated = [] stm_filter = [] for stm in statements: stm._clean_signal_meta() d = stm._cut_off_drivers_of(dstSignal) if d is not None: separated.append(d) f = d is...
def statements_to_HWProcesses(statements: List[HdlStatement])\ -> Generator[HWProcess, None, None]: """ Pack statements into HWProcess instances, * for each out signal resolve it's drivers and collect them * split statements if there is and combinational loop * merge statements if it is poss...
def markVisibilityOfSignals(ctx, ctxName, signals, interfaceSignals): """ * check if all signals are driven by something * mark signals with hidden = False if they are connecting statements or if they are external interface """ for sig in signals: driver_cnt = len(sig.drivers) ...
def sig(self, name, dtype=BIT, clk=None, syncRst=None, defVal=None): """ Create new signal in this context :param clk: clk signal, if specified signal is synthesized as SyncSignal :param syncRst: synchronous reset signal """ if isinstance(defVal, RtlSignal): ...
def synthesize(self, name, interfaces, targetPlatform): """ Build Entity and Architecture instance out of netlist representation """ ent = Entity(name) ent._name = name + "_inst" # instance name # create generics for _, v in self.params.items(): ent....
def toHVal(op: Any, suggestedType: Optional[HdlType]=None): """Convert python or hdl value/signal object to hdl value/signal object""" if isinstance(op, Value) or isinstance(op, SignalItem): return op elif isinstance(op, InterfaceBase): return op._sig else: if isinstance(op, int)...
def Value(cls, val, ctx: SerializerCtx): """ :param dst: is signal connected with value :param val: value object, can be instance of Signal or Value """ t = val._dtype if isinstance(val, RtlSignalBase): return cls.SignalItem(val, ctx) c = cls.Value_t...
def getMaxStmIdForStm(stm): """ Get maximum _instId from all assigments in statement """ maxId = 0 if isinstance(stm, Assignment): return stm._instId elif isinstance(stm, WaitStm): return maxId else: for _stm in stm._iter_stms(): maxId = max(maxId, getMaxS...
def maxStmId(proc): """ get max statement id, used for sorting of processes in architecture """ maxId = 0 for stm in proc.statements: maxId = max(maxId, getMaxStmIdForStm(stm)) return maxId
def monitor(self, sim): """Collect data from interface""" if self.notReset(sim) and self._enabled: self.wrRd(sim.write, 1) yield sim.waitOnCombUpdate() d = self.doRead(sim) self.data.append(d) else: self.wrRd(sim.write, 0)
def doWrite(self, sim, data): """write data to interface""" sim.write(data, self.intf.data)
def driver(self, sim): """Push data to interface""" r = sim.read if self.actualData is NOP and self.data: self.actualData = self.data.popleft() do = self.actualData is not NOP if do: self.doWrite(sim, self.actualData) else: self.doWri...
def fromPy(cls, val, typeObj, vldMask=None): """ :param val: value of python type int or None :param typeObj: instance of Integer :param vldMask: None vldMask is resolved from val, if is 0 value is invalidated if is 1 value has to be valid """ asse...
def _m(self): """ Note that this interface will be master :return: self """ assert not hasattr(self, "_interfaces") or not self._interfaces, \ "Too late to change direction of interface" self._direction = DIRECTION.asIntfDirection(DIRECTION.opposite(self._mas...
def _loadDeclarations(self): """ load declaratoins from _declr method This function is called first for parent and then for children """ if not hasattr(self, "_interfaces"): self._interfaces = [] self._setAttrListener = self._declrCollector self._declr...
def _clean(self, rmConnetions=True, lockNonExternal=True): """ Remove all signals from this interface (used after unit is synthesized and its parent is connecting its interface to this unit) """ if self._interfaces: for i in self._interfaces: i._clean...
def _signalsForInterface(self, context, prefix='', typeTransform=None): """ generate _sig for each interface which has no subinterface if already has _sig return it instead :param context: instance of RtlNetlist where signals should be created :param prefix: name prefix for crea...
def _getPhysicalName(self): """Get name in HDL """ if hasattr(self, "_boundedEntityPort"): return self._boundedEntityPort.name else: return self._getFullName().replace('.', self._NAME_SEPARATOR)
def _replaceParam(self, p, newP): """ Replace parameter on this interface (in configuration stage) :ivar pName: actual name of param on me :ivar newP: new Param instance by which should be old replaced """ i = self._params.index(p) pName = p._scopes[self][1] ...
def _updateParamsFrom(self, otherObj, updater=_default_param_updater, exclude=None, prefix=""): """ :note: doc in :func:`~hwt.synthesizer.interfaceLevel.propDeclCollector._updateParamsFrom` """ PropDeclrCollector._updateParamsFrom(self, otherObj, updater, exclud...
def _bit_length(self): """Sum of all width of interfaces in this interface""" try: interfaces = self._interfaces except AttributeError: interfaces = None if interfaces is None: # not loaded interface _intf = self._clone() _intf...
def _connectTo(self, master, exclude=None, fit=False): """ connect to another interface interface (on rtl level) works like self <= master in VHDL """ return list(self._connectToIter(master, exclude, fit))
def sensitivityByOp(op): """ get sensitivity type for operator """ if op == AllOps.RISING_EDGE: return SENSITIVITY.RISING elif op == AllOps.FALLING_EDGE: return SENSITIVITY.FALLING else: raise TypeError()
def eval(self, operator, simulator=None): """Load all operands and process them by self._evalFn""" def getVal(v): while not isinstance(v, Value): v = v._val return v operands = list(map(getVal, operator.operands)) if isEventDependentOp(operator....
def convertBits(self, sigOrVal, toType): """ Cast signed-unsigned, to int or bool """ if isinstance(sigOrVal, Value): return convertBits__val(self, sigOrVal, toType) elif isinstance(toType, HBool): if self.bit_length() == 1: v = 0 if sigOrVal._dtype.negated else 1 ...
def reinterpret_bits_to_hstruct(sigOrVal, hStructT): """ Reinterpret signal of type Bits to signal of type HStruct """ container = hStructT.fromPy(None) offset = 0 for f in hStructT.fields: t = f.dtype width = t.bit_length() if f.name is not None: s = sigOrVal...
def reinterpretBits(self, sigOrVal, toType): """ Cast object of same bit size between to other type (f.e. bits to struct, union or array) """ if isinstance(sigOrVal, Value): return reinterpretBits__val(self, sigOrVal, toType) elif isinstance(toType, Bits): return fitTo_t(sigOrVal...
def iterSort(iterators, cmpFn): """ Sort items from iterators(generators) by alwas selecting item with lowest value (min first) :return: generator of tuples (origin index, item) where origin index is index of iterator in "iterators" from where item commes from """ actual = [] _itera...
def groupIntoChoices(splitsOnWord, wordWidth: int, origin: OneOfTransaction): """ :param splitsOnWord: list of lists of parts (fields splited on word boundaries) :return: generators of ChoicesOfFrameParts for each word which are not crossing word boundaries """ def cmpWordIndex(a, b)...
def fullWordCnt(self, start: int, end: int): """Count of complete words between two addresses """ assert end >= start, (start, end) gap = max(0, (end - start) - (start % self.wordWidth)) return gap // self.wordWidth
def groupByWordIndex(self, transaction: 'TransTmpl', offset: int): """ Group transaction parts splited on words to words :param transaction: TransTmpl instance which parts should be grupped into words :return: generator of tuples (wordIndex, list of transaction parts ...
def splitOnWords(self, transaction, addrOffset=0): """ :return: generator of TransPart instance """ wordWidth = self.wordWidth end = addrOffset for tmp in transaction.walkFlatten(offset=addrOffset): if isinstance(tmp, OneOfTransaction): split =...
def fromPy(cls, val, typeObj, vldMask=None): """ :param val: value of python type bool or None :param typeObj: instance of HdlType :param vldMask: None vldMask is resolved from val, if is 0 value is invalidated if is 1 value has to be valid """ vld...
def pprintInterface(intf, prefix="", indent=0, file=sys.stdout): """ Pretty print interface """ try: s = intf._sig except AttributeError: s = "" if s is not "": s = " " + repr(s) file.write("".join([getIndent(indent), prefix, repr(intf._getFullName()), ...
def framesFromTransTmpl(transaction: 'TransTmpl', wordWidth: int, maxFrameLen: Union[int, float]=inf, maxPaddingWords: Union[int, float]=inf, trimPaddingWordsOnStart: bool=False, t...
def walkWords(self, showPadding: bool=False): """ Walk enumerated words in this frame :attention: not all indexes has to be present, only words with items will be generated when not showPadding :param showPadding: padding TransParts are also present :return: generato...
def fieldToDataDict(dtype, data, res): """ Construct dictionary {StructField:value} for faster lookup of values for fields """ # assert data is None or isinstance(data, dict) for f in dtype.fields: try: fVal = data[f.name] except Ke...
def packData(self, data): """ Pack data into list of BitsVal of specified dataWidth :param data: dict of values for struct fields {fieldName: value} :return: list of BitsVal which are representing values of words """ typeOfWord = simBitsT(self.wordWidth, None) f...
def isSameHVal(a: Value, b: Value) -> bool: """ :return: True if two Value instances are same :note: not just equal """ return a is b or (isinstance(a, Value) and isinstance(b, Value) and a.val == b.val and a.vldMask == b.vldMask)
def areSameHVals(a: Union[None, List[Value]], b: Union[None, List[Value]]) -> bool: """ :return: True if two vectors of Value instances are same :note: not just equal """ if a is b: return True if a is None or b is None: return False if len(a) == len(b): ...
def isSameStatementList(stmListA: List[HdlStatement], stmListB: List[HdlStatement]) -> bool: """ :return: True if two lists of HdlStatement instances are same """ if stmListA is stmListB: return True if stmListA is None or stmListB is None: return False f...
def statementsAreSame(statements: List[HdlStatement]) -> bool: """ :return: True if all statements are same """ iterator = iter(statements) try: first = next(iterator) except StopIteration: return True return all(first.isSame(rest) for rest in iterator)
def _get_stm_with_branches(stm_it): """ :return: first statement with rank > 0 or None if iterator empty """ last = None while last is None or last.rank == 0: try: last = next(stm_it) except StopIteration: last = None break return last
def _clean_signal_meta(self): """ Clean informations about enclosure for outputs and sensitivity of this statement """ self._enclosed_for = None self._sensitivity = None for stm in self._iter_stms(): stm._clean_signal_meta()
def _collect_io(self) -> None: """ Collect inputs/outputs from all child statements to :py:attr:`~_input` / :py:attr:`_output` attribure on this object """ in_add = self._inputs.extend out_add = self._outputs.extend for stm in self._iter_stms(): in_ad...
def _discover_enclosure_for_statements(statements: List['HdlStatement'], outputs: List['HdlStatement']): """ Discover enclosure for list of statements :param statements: list of statements in one code branch :param outputs: list of outputs whic...
def _discover_sensitivity_seq(self, signals: List[RtlSignalBase], seen: set, ctx: SensitivityCtx)\ -> None: """ Discover sensitivity for list of signals """ casualSensitivity = set() for s in signals...
def _get_rtl_context(self): """ get RtlNetlist context from signals """ for sig in chain(self._inputs, self._outputs): if sig.ctx: return sig.ctx else: # Param instances does not have context continue raise H...
def _on_reduce(self, self_reduced: bool, io_changed: bool, result_statements: List["HdlStatement"]) -> None: """ Update signal IO after reuce atempt :param self_reduced: if True this object was reduced :param io_changed: if True IO of this object may changed ...
def _on_merge(self, other): """ After merging statements update IO, sensitivity and context :attention: rank is not updated """ self._inputs.extend(other._inputs) self._outputs.extend(other._outputs) if self._sensitivity is not None: self._sensitivit...
def _is_mergable_statement_list(cls, stmsA, stmsB): """ Walk statements and compare if they can be merged into one statement list """ if stmsA is None and stmsB is None: return True elif stmsA is None or stmsB is None: return False a_it = iter(st...
def _merge_statements(statements: List["HdlStatement"])\ -> Tuple[List["HdlStatement"], int]: """ Merge statements in list to remove duplicated if-then-else trees :return: tuple (list of merged statements, rank decrease due merging) :note: rank decrease is sum of ranks of re...
def _merge_statement_lists(stmsA: List["HdlStatement"], stmsB: List["HdlStatement"])\ -> List["HdlStatement"]: """ Merge two lists of statements into one :return: list of merged statements """ if stmsA is None and stmsB is None: return None tmp =...
def _try_reduce_list(statements: List["HdlStatement"]): """ Simplify statements in the list """ io_change = False new_statements = [] for stm in statements: reduced, _io_change = stm._try_reduce() new_statements.extend(reduced) io_chan...
def _on_parent_event_dependent(self): """ After parrent statement become event dependent propagate event dependency flag to child statements """ if not self._is_completly_event_dependent: self._is_completly_event_dependent = True for stm in self._iter_stms...
def _set_parent_stm(self, parentStm: "HdlStatement"): """ Assign parent statement and propagate dependency flags if necessary """ was_top = self.parentStm is None self.parentStm = parentStm if not self._now_is_event_dependent\ and parentStm._now_is_event_d...
def _register_stements(self, statements: List["HdlStatement"], target: List["HdlStatement"]): """ Append statements to this container under conditions specified by condSet """ for stm in flatten(statements): assert stm.parentStm is None, stm...
def _destroy(self): """ Disconnect this statement from signals and delete it from RtlNetlist context :attention: signal endpoints/drivers will be altered that means they can not be used for iteration """ ctx = self._get_rtl_context() for i in self._inputs: ...
def fromPy(cls, val, typeObj, vldMask=None): """ :param val: python string or None :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 """ as...
def _reg(self, name, dtype=BIT, defVal=None, clk=None, rst=None): """ Create register in this unit :param defVal: default value of this register, if this value is specified reset of this component is used (unit has to have single interface of class Rst or Rst_n) ...