_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q272100
Cmd.do_help
test
def do_help(self, command): """Display this help message.""" if command: doc = getattr(self, 'do_' + command).__doc__ print(cyan(doc.replace(' ' * 8, ''))) else: print(magenta('Available commands:')) print(magenta('Type "HELP <command>" to get more info.')) names = self.get_names() names.sort() for name in names: if name[:3] != 'do_': continue doc = getattr(self, name).__doc__ doc = doc.split('\n')[0] print('{} {}'.format(yellow(name[3:]), cyan(doc.replace(' ' * 8, ' ') .replace('\n', ''))))
python
{ "resource": "" }
q272101
Cmd.do_DBINFO
test
def do_DBINFO(self, *args): """Print some useful infos from Redis DB.""" info = DB.info() keys = [ 'keyspace_misses', 'keyspace_hits', 'used_memory_human', 'total_commands_processed', 'total_connections_received', 'connected_clients'] for key in keys: print('{}: {}'.format(white(key), blue(info[key]))) nb_of_redis_db = int(DB.config_get('databases')['databases']) for db_index in range(nb_of_redis_db - 1): db_name = 'db{}'.format(db_index) if db_name in info: label = white('nb keys (db {})'.format(db_index)) print('{}: {}'.format(label, blue(info[db_name]['keys'])))
python
{ "resource": "" }
q272102
Cmd.do_DBKEY
test
def do_DBKEY(self, key): """Print raw content of a DB key. DBKEY g|u09tyzfe""" type_ = DB.type(key).decode() if type_ == 'set': out = DB.smembers(key) elif type_ == 'string': out = DB.get(key) else: out = 'Unsupported type {}'.format(type_) print('type:', magenta(type_)) print('value:', white(out))
python
{ "resource": "" }
q272103
Cmd.do_GEOHASH
test
def do_GEOHASH(self, latlon): """Compute a geohash from latitude and longitude. GEOHASH 48.1234 2.9876""" try: lat, lon = map(float, latlon.split()) except ValueError: print(red('Invalid lat and lon {}'.format(latlon))) else: print(white(geohash.encode(lat, lon, config.GEOHASH_PRECISION)))
python
{ "resource": "" }
q272104
Cmd.do_GET
test
def do_GET(self, _id): """Get document from index with its id. GET 772210180J""" doc = doc_by_id(_id) if not doc: return self.error('id "{}" not found'.format(_id)) for key, value in doc.items(): if key == config.HOUSENUMBERS_FIELD: continue print('{} {}'.format(white(key), magenta(value))) if doc.get('housenumbers'): def sorter(v): try: return int(re.match(r'^\d+', v['raw']).group()) except AttributeError: return -1 housenumbers = sorted(doc['housenumbers'].values(), key=sorter) print(white('housenumbers'), magenta(', '.join(v['raw'] for v in housenumbers)))
python
{ "resource": "" }
q272105
Cmd.do_INDEX
test
def do_INDEX(self, _id): """Get index details for a document by its id. INDEX 772210180J""" doc = doc_by_id(_id) if not doc: return self.error('id "{}" not found'.format(_id)) for field in config.FIELDS: key = field['key'] if key in doc: self._print_field_index_details(doc[key], _id)
python
{ "resource": "" }
q272106
Cmd.do_BESTSCORE
test
def do_BESTSCORE(self, word): """Return document linked to word with higher score. BESTSCORE lilas""" key = keys.token_key(indexed_string(word)[0]) for _id, score in DB.zrevrange(key, 0, 20, withscores=True): result = Result(_id) print(white(result), blue(score), green(result._id))
python
{ "resource": "" }
q272107
Cmd.do_STRDISTANCE
test
def do_STRDISTANCE(self, s): """Print the distance score between two strings. Use | as separator. STRDISTANCE rue des lilas|porte des lilas""" s = s.split('|') if not len(s) == 2: print(red('Malformed string. Use | between the two strings.')) return one, two = s print(white(compare_str(one, two)))
python
{ "resource": "" }
q272108
send
test
def send(r, stream=False): """Just sends the request using its send method and returns its response. """ r.send(stream=stream) return r.response
python
{ "resource": "" }
q272109
map
test
def map(requests, stream=True, pool=None, size=1, exception_handler=None): """Concurrently converts a list of Requests to Responses. :param requests: a collection of Request objects. :param stream: If False, the content will not be downloaded immediately. :param size: Specifies the number of workers to run at a time. If 1, no parallel processing. :param exception_handler: Callback function, called when exception occured. Params: Request, Exception """ pool = pool if pool else Pool(size) requests = list(requests) requests = pool.map(send, requests) ret = [] for request in requests: if request.response is not None: ret.append(request.response) elif exception_handler and hasattr(request, 'exception'): ret.append(exception_handler(request, request.exception)) else: ret.append(None) if not pool: pool.close() return ret
python
{ "resource": "" }
q272110
getBits_from_array
test
def getBits_from_array(array, wordWidth, start, end, reinterpretElmToType=None): """ Gets value of bits between selected range from memory :param start: bit address of start of bit of bits :param end: bit address of first bit behind bits :return: instance of BitsVal (derived from SimBits type) which contains copy of selected bits """ inPartOffset = 0 value = Bits(end - start, None).fromPy(None) while start != end: assert start < end, (start, end) dataWordIndex = start // wordWidth v = array[dataWordIndex] if reinterpretElmToType is not None: v = v._reinterpret_cast(reinterpretElmToType) endOfWord = (dataWordIndex + 1) * wordWidth width = min(end, endOfWord) - start offset = start % wordWidth val = selectBitRange(v.val, offset, width) vldMask = selectBitRange(v.vldMask, offset, width) updateTime = v.updateTime m = mask(width) value.val |= (val & m) << inPartOffset value.vldMask |= (vldMask & m) << inPartOffset value.updateMask = max(value.updateTime, updateTime) inPartOffset += width start += width return value
python
{ "resource": "" }
q272111
reinterptet_harray_to_bits
test
def reinterptet_harray_to_bits(typeFrom, sigOrVal, bitsT): """ Cast HArray signal or value to signal or value of type Bits """ size = int(typeFrom.size) widthOfElm = typeFrom.elmType.bit_length() w = bitsT.bit_length() if size * widthOfElm != w: raise TypeConversionErr( "Size of types is different", size * widthOfElm, w) partT = Bits(widthOfElm) parts = [p._reinterpret_cast(partT) for p in sigOrVal] return Concat(*reversed(parts))._reinterpret_cast(bitsT)
python
{ "resource": "" }
q272112
slice_to_SLICE
test
def slice_to_SLICE(sliceVals, width): """convert python slice to value of SLICE hdl type""" if sliceVals.step is not None: raise NotImplementedError() start = sliceVals.start stop = sliceVals.stop if sliceVals.start is None: start = INT.fromPy(width) else: start = toHVal(sliceVals.start) if sliceVals.stop is None: stop = INT.fromPy(0) else: stop = toHVal(sliceVals.stop) startIsVal = isinstance(start, Value) stopIsVal = isinstance(stop, Value) indexesAreValues = startIsVal and stopIsVal if indexesAreValues: updateTime = max(start.updateTime, stop.updateTime) else: updateTime = -1 return Slice.getValueCls()((start, stop), SLICE, 1, updateTime)
python
{ "resource": "" }
q272113
find_files
test
def find_files(directory, pattern, recursive=True): """ Find files by pattern in directory """ if not os.path.isdir(directory): if os.path.exists(directory): raise IOError(directory + ' is not directory') else: raise IOError(directory + " does not exists") if recursive: for root, _, files in os.walk(directory): for basename in files: if fnmatch.fnmatch(basename, pattern): filename = os.path.join(root, basename) yield filename else: root = directory for basename in os.listdir(root): if fnmatch.fnmatch(basename, pattern): filename = os.path.join(root, basename) if os.path.isfile(filename): yield filename
python
{ "resource": "" }
q272114
In
test
def In(sigOrVal, iterable): """ Hdl convertible in operator, check if any of items in "iterable" equals "sigOrVal" """ res = None for i in iterable: i = toHVal(i) if res is None: res = sigOrVal._eq(i) else: res = res | sigOrVal._eq(i) assert res is not None, "Parameter iterable is empty" return res
python
{ "resource": "" }
q272115
StaticForEach
test
def StaticForEach(parentUnit, items, bodyFn, name=""): """ Generate for loop for static items :param parentUnit: unit where this code should be instantiated :param items: items which this "for" itering on :param bodyFn: function which fn(item, index) or fn(item) returns (statementList, ack). It's content is performed in every iteration. When ack is high loop will fall to next iteration """ items = list(items) itemsCnt = len(items) if itemsCnt == 0: # if there are no items there is nothing to generate return [] elif itemsCnt == 1: # if there is only one item do not generate counter logic generate return bodyFn(items[0], 0) else: # if there is multiple items we have to generate counter logic index = parentUnit._reg(name + "for_index", Bits(log2ceil(itemsCnt + 1), signed=False), defVal=0) ackSig = parentUnit._sig(name + "for_ack") statementLists = [] for i, (statementList, ack) in [(i, bodyFn(item, i)) for i, item in enumerate(items)]: statementLists.append(statementList + [(ackSig(ack)), ]) If(ackSig, If(index._eq(itemsCnt - 1), index(0) ).Else( index(index + 1) ) ) return Switch(index)\ .addCases( enumerate(statementLists) ).Default( bodyFn(items[0], 0)[0], ackSig(True) )
python
{ "resource": "" }
q272116
sll
test
def sll(sig, howMany) -> RtlSignalBase: "Logical shift left" width = sig._dtype.bit_length() return sig[(width - howMany):]._concat(vec(0, howMany))
python
{ "resource": "" }
q272117
log2ceil
test
def log2ceil(x): """ Returns no of bits required to store x-1 for example x=8 returns 3 """ if not isinstance(x, (int, float)): x = int(x) if x == 0 or x == 1: res = 1 else: res = math.ceil(math.log2(x)) return hInt(res)
python
{ "resource": "" }
q272118
isPow2
test
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)
python
{ "resource": "" }
q272119
Switch.Case
test
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 self._case_value_index, ( "Switch statement already has case for value ", caseVal) self.rank += 1 case = [] self._case_value_index[caseVal] = len(self.cases) self.cases.append((caseVal, case)) cond = self.switchOn._eq(caseVal) self._inputs.append(cond) cond.endpoints.append(self) self._register_stements(statements, case) return self
python
{ "resource": "" }
q272120
Switch.Default
test
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
python
{ "resource": "" }
q272121
VcdHdlSimConfig.vcdRegisterInterfaces
test
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 parent_ = self.vcdWriter if parent is None else parent subScope = parent_.varScope(name) self._obj2scope[obj] = subScope with subScope: # register all subinterfaces for chIntf in obj._interfaces: self.vcdRegisterInterfaces(chIntf, subScope) if isinstance(obj, (Unit, SimModel)): # register interfaces from all subunits for u in obj._units: self.vcdRegisterInterfaces(u, subScope) return subScope else: t = obj._dtype if isinstance(t, self.supported_type_classes): tName, width, formatter = vcdTypeInfoForHType(t) try: parent.addVar(obj, getSignalName(obj), tName, width, formatter) except VarAlreadyRegistered: pass
python
{ "resource": "" }
q272122
VcdHdlSimConfig.beforeSim
test
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.vcdRegisterRemainingSignals(synthesisedUnit) vcd.enddefinitions()
python
{ "resource": "" }
q272123
VcdHdlSimConfig.logChange
test
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
python
{ "resource": "" }
q272124
SystemCSerializer_statements.HWProcess
test
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(proc.name, proc) return cls.methodTmpl.render( indent=getIndent(ctx.indent), name=proc.name, statements=statemets )
python
{ "resource": "" }
q272125
autoAddAgents
test
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 intf._initSimAgent() assert intf._ag is not None, intf agents = [intf._ag, ] if intf._direction == INTF_DIRECTION.MASTER: agProcs = list(map(lambda a: a.getMonitors(), agents)) elif intf._direction == INTF_DIRECTION.SLAVE: agProcs = list(map(lambda a: a.getDrivers(), agents)) else: raise NotImplementedError("intf._direction %r for %r" % ( intf._direction, intf)) for p in agProcs: proc.extend(p) return proc
python
{ "resource": "" }
q272126
InterfaceceImplDependentFns._getAssociatedClk
test
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, UnitBase): return getClk(p) else: return p._getAssociatedClk()
python
{ "resource": "" }
q272127
distinctBy
test
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
python
{ "resource": "" }
q272128
groupedby
test
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] except KeyError: arr = [] d[k] = arr arr.append(item) yield from d.items()
python
{ "resource": "" }
q272129
flatten
test
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 iterables: yield from flatten(i, level=level) else: yield iterables
python
{ "resource": "" }
q272130
IfContainer._merge_nested_if_from_else
test
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
python
{ "resource": "" }
q272131
removeUnconnectedSignals
test
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._interface is not None: # skip interfaces before we want to check them, # they should not be optimized out from design continue except AttributeError: pass for e in sig.drivers: # drivers of this signal are useless rm them if isinstance(e, Operator): inputs = e.operands if e.result is sig: e.result = None else: inputs = e._inputs netlist.statements.discard(e) for op in inputs: if not isinstance(op, Value): try: op.endpoints.remove(e) except KeyError: # this operator has 2x+ same operand continue _toSearch.add(op) toDelete.add(sig) if toDelete: for sig in toDelete: if sig.ctx == netlist: netlist.signals.remove(sig) _toSearch.discard(sig) toDelete = set() toSearch = _toSearch
python
{ "resource": "" }
q272132
checkIfIsTooSimple
test
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
python
{ "resource": "" }
q272133
tryToMerge
test
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 checkIfIsTooSimple(procB) or areSetsIntersets(procA.outputs, procB.sensitivityList) or areSetsIntersets(procB.outputs, procA.sensitivityList) or not HdlStatement._is_mergable_statement_list(procA.statements, procB.statements)): raise IncompatibleStructure() procA.statements = HdlStatement._merge_statement_lists( procA.statements, procB.statements) procA.outputs.extend(procB.outputs) procA.inputs.extend(procB.inputs) procA.sensitivityList.extend(procB.sensitivityList) return procA
python
{ "resource": "" }
q272134
reduceProcesses
test
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 same structure of statements into one # to minimize number of processes for _, procs in groupedby(processes, lambda p: p.rank): for iA, pA in enumerate(procs): if pA is None: continue for iB, pB in enumerate(islice(procs, iA + 1, None)): if pB is None: continue try: pA = tryToMerge(pA, pB) except IncompatibleStructure: continue procs[iA + 1 + iB] = None # procs[iA] = pA for p in procs: if p is not None: yield p
python
{ "resource": "" }
q272135
BramPort_withoutClkAgent.onWriteReq
test
def onWriteReq(self, sim, addr, data): """ on writeReqRecieved in monitor mode """ self.requests.append((WRITE, addr, data))
python
{ "resource": "" }
q272136
toRtl
test
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 override of top unit (if is None name is derived form class name) :param serializer: serializer which should be used for to RTL conversion :param targetPlatform: metainformatins about target platform, distributed on every unit under _targetPlatform attribute before Unit._impl() is called :param saveTo: directory where files should be stored If None RTL is returned as string. :raturn: if saveTo returns RTL string else returns list of file names which were created """ if not isinstance(unitOrCls, Unit): u = unitOrCls() else: u = unitOrCls u._loadDeclarations() if name is not None: assert isinstance(name, str) u._name = name globScope = serializer.getBaseNameScope() mouduleScopes = {} # unitCls : unitobj serializedClasses = {} # (unitCls, paramsValues) : unitObj # where paramsValues are dict name:value serializedConfiguredUnits = {} doSerialize = True createFiles = saveTo is not None if createFiles: os.makedirs(saveTo, exist_ok=True) files = UniqList() else: codeBuff = [] for obj in u._toRtl(targetPlatform): doSerialize = serializer.serializationDecision( obj, serializedClasses, serializedConfiguredUnits) if doSerialize: if isinstance(obj, Entity): s = globScope.fork(1) s.setLevel(2) ctx = serializer.getBaseContext() ctx.scope = s mouduleScopes[obj] = ctx ctx.currentUnit = obj.origin sc = serializer.Entity(obj, ctx) if createFiles: fName = obj.name + serializer.fileExtension fileMode = 'w' elif isinstance(obj, Architecture): try: ctx = mouduleScopes[obj.entity] except KeyError: raise SerializerException( "Entity should be serialized" " before architecture of %s" % (obj.getEntityName())) sc = serializer.Architecture(obj, ctx) if createFiles: fName = obj.getEntityName() + serializer.fileExtension fileMode = 'a' else: if hasattr(obj, "_hdlSources"): for fn in obj._hdlSources: if isinstance(fn, str): shutil.copy2(fn, saveTo) files.append(fn) continue else: sc = serializer.asHdl(obj) if sc: if createFiles: fp = os.path.join(saveTo, fName) files.append(fp) with open(fp, fileMode) as f: if fileMode == 'a': f.write("\n") f.write( serializer.formatter(sc) ) else: codeBuff.append(sc) elif not createFiles: try: name = '"%s"' % obj.name except AttributeError: name = "" codeBuff.append(serializer.comment( "Object of class %s, %s was not serialized as specified" % ( obj.__class__.__name__, name))) if createFiles: return files else: return serializer.formatter( "\n".join(codeBuff) )
python
{ "resource": "" }
q272137
name_for_process_and_mark_outputs
test
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.append(sig.name) if out_names: return min(out_names) else: return ""
python
{ "resource": "" }
q272138
cut_off_drivers_of
test
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 not stm stm_filter.append(f) return list(compress(statements, stm_filter)), separated
python
{ "resource": "" }
q272139
RtlNetlist.sig
test
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): assert defVal._const, \ "Initial value of register has to be constant" _defVal = defVal._auto_cast(dtype) elif isinstance(defVal, Value): _defVal = defVal._auto_cast(dtype) elif isinstance(defVal, InterfaceBase): _defVal = defVal._sig else: _defVal = dtype.fromPy(defVal) if clk is not None: s = RtlSyncSignal(self, name, dtype, _defVal) if syncRst is not None and defVal is None: raise SigLvlConfErr( "Probably forgotten default value on sync signal %s", name) if syncRst is not None: r = If(syncRst._isOn(), RtlSignal.__call__(s, _defVal) ).Else( RtlSignal.__call__(s, s.next) ) else: r = [RtlSignal.__call__(s, s.next)] If(clk._onRisingEdge(), r ) else: if syncRst: raise SigLvlConfErr( "Signal %s has reset but has no clk" % name) s = RtlSignal(self, name, dtype, defVal=_defVal) self.signals.add(s) return s
python
{ "resource": "" }
q272140
RtlNetlist.synthesize
test
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.generics.append(v) # interface set for faster lookup if isinstance(interfaces, set): intfSet = interfaces else: intfSet = set(interfaces) # create ports for s in interfaces: pi = portItemfromSignal(s, ent) pi.registerInternSig(s) ent.ports.append(pi) s.hidden = False removeUnconnectedSignals(self) markVisibilityOfSignals(self, name, self.signals, intfSet) for proc in targetPlatform.beforeHdlArchGeneration: proc(self) arch = Architecture(ent) for p in statements_to_HWProcesses(self.statements): arch.processes.append(p) # add signals, variables etc. in architecture for s in self.signals: if s not in intfSet and not s.hidden: arch.variables.append(s) # instantiate subUnits in architecture for u in self.subUnits: arch.componentInstances.append(u) # add components in architecture for su in distinctBy(self.subUnits, lambda x: x.name): arch.components.append(su) self.synthesised = True return [ent, arch]
python
{ "resource": "" }
q272141
getMaxStmIdForStm
test
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, getMaxStmIdForStm(_stm)) return maxId
python
{ "resource": "" }
q272142
maxStmId
test
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
python
{ "resource": "" }
q272143
RdSyncedAgent.doWrite
test
def doWrite(self, sim, data): """write data to interface""" sim.write(data, self.intf.data)
python
{ "resource": "" }
q272144
Interface._m
test
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._masterDir)) return self
python
{ "resource": "" }
q272145
Interface._loadDeclarations
test
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() self._setAttrListener = None for i in self._interfaces: i._isExtern = self._isExtern i._loadDeclarations() for p in self._params: p.setReadOnly() if self._isExtern: # direction from inside of unit (reverset compared to outside direction) if self._direction == INTF_DIRECTION.UNKNOWN: self._direction = INTF_DIRECTION.MASTER self._setDirectionsLikeIn(self._direction)
python
{ "resource": "" }
q272146
Interface._signalsForInterface
test
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 created signals :param typeTransform: optional function (type) returns modified type for signal """ sigs = [] if self._interfaces: for intf in self._interfaces: sigs.extend( intf._signalsForInterface(context, prefix, typeTransform=typeTransform)) else: if hasattr(self, '_sig'): sigs = [self._sig] else: t = self._dtype if typeTransform is not None: t = typeTransform(t) s = context.sig(prefix + self._getPhysicalName(), t) s._interface = self self._sig = s if hasattr(self, '_boundedEntityPort'): self._boundedEntityPort.connectSig(self._sig) sigs = [s] return sigs
python
{ "resource": "" }
q272147
Interface._getPhysicalName
test
def _getPhysicalName(self): """Get name in HDL """ if hasattr(self, "_boundedEntityPort"): return self._boundedEntityPort.name else: return self._getFullName().replace('.', self._NAME_SEPARATOR)
python
{ "resource": "" }
q272148
Interface._bit_length
test
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._loadDeclarations() interfaces = _intf._interfaces if interfaces: w = 0 for i in interfaces: w += i._bit_length() return w else: return self._dtype.bit_length()
python
{ "resource": "" }
q272149
sensitivityByOp
test
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()
python
{ "resource": "" }
q272150
OpDefinition.eval
test
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.operator): operands.append(simulator.now) elif operator.operator == AllOps.IntToBits: operands.append(operator.result._dtype) return self._evalFn(*operands)
python
{ "resource": "" }
q272151
convertBits
test
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 return sigOrVal._eq(self.getValueCls().fromPy(v, self)) elif isinstance(toType, Bits): if self.bit_length() == toType.bit_length(): return sigOrVal._convSign(toType.signed) elif toType == INT: return Operator.withRes(AllOps.BitsToInt, [sigOrVal], toType) return default_auto_cast_fn(self, sigOrVal, toType)
python
{ "resource": "" }
q272152
reinterpret_bits_to_hstruct
test
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[(width + offset):offset] s = s._reinterpret_cast(t) setattr(container, f.name, s) offset += width return container
python
{ "resource": "" }
q272153
TransTmplWordIterator.fullWordCnt
test
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
python
{ "resource": "" }
q272154
TransTmplWordIterator.groupByWordIndex
test
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 in this word) """ actualW = None partsInWord = [] wordWidth = self.wordWidth for item in self.splitOnWords(transaction, offset): _actualW = item.startOfPart // wordWidth if actualW is None: actualW = _actualW partsInWord.append(item) elif _actualW > actualW: yield (actualW, partsInWord) actualW = _actualW partsInWord = [item, ] else: partsInWord.append(item) if partsInWord: yield (actualW, partsInWord)
python
{ "resource": "" }
q272155
pprintInterface
test
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()), s])) file.write("\n") if isinstance(intf, HObjList): for i, p in enumerate(intf): # interfaces have already name of this array and index in it's name pprintInterface(p, prefix=prefix, indent=indent + 1, file=file) else: for i in intf._interfaces: pprintInterface(i, indent=indent + 1, file=file)
python
{ "resource": "" }
q272156
FrameTmpl.framesFromTransTmpl
test
def framesFromTransTmpl(transaction: 'TransTmpl', wordWidth: int, maxFrameLen: Union[int, float]=inf, maxPaddingWords: Union[int, float]=inf, trimPaddingWordsOnStart: bool=False, trimPaddingWordsOnEnd: bool=False) -> Generator[ 'FrameTmpl', None, None]: """ Convert transaction template into FrameTmpls :param transaction: transaction template used which are FrameTmpls created from :param wordWidth: width of data signal in target interface where frames will be used :param maxFrameLen: maximum length of frame in bits, if exceeded another frame will be created :param maxPaddingWords: maximum of continual padding words in frame, if exceed frame is split and words are cut of :attention: if maxPaddingWords<inf trimPaddingWordsOnEnd or trimPaddingWordsOnStart has to be True to decide where padding should be trimmed :param trimPaddingWordsOnStart: trim padding from start of frame at word granularity :param trimPaddingWordsOnEnd: trim padding from end of frame at word granularity """ isFirstInFrame = True partsPending = False startOfThisFrame = 0 assert maxFrameLen > 0 assert maxPaddingWords >= 0 if maxPaddingWords < inf: assert trimPaddingWordsOnStart or trimPaddingWordsOnEnd, \ "Padding has to be cut off somewhere" it = TransTmplWordIterator(wordWidth) lastWordI = 0 endOfThisFrame = maxFrameLen parts = [] for wordI, word in it.groupByWordIndex(transaction, 0): if wordI * wordWidth >= endOfThisFrame: # now in first+ word behind the frame # cut off padding at end of frame paddingWords = wordI - lastWordI if trimPaddingWordsOnEnd and paddingWords > maxPaddingWords: # cut off padding and align end of frame to word _endOfThisFrame = (lastWordI + 1) * wordWidth else: _endOfThisFrame = wordI * wordWidth yield FrameTmpl(transaction, wordWidth, startOfThisFrame, _endOfThisFrame, parts) # prepare for start of new frame parts = [] isFirstInFrame = True partsPending = False # start on new word startOfThisFrame = _endOfThisFrame endOfThisFrame = startOfThisFrame + maxFrameLen lastWordI = wordI # check if padding at potential end of frame can be cut off if (not isFirstInFrame and trimPaddingWordsOnEnd and wordI - lastWordI > 1): # there is too much continual padding, # cut it out and start new frame _endOfThisFrame = (lastWordI + 1) * wordWidth yield FrameTmpl(transaction, wordWidth, startOfThisFrame, _endOfThisFrame, parts) # prepare for start of new frame parts = [] isFirstInFrame = True partsPending = False # start on new word startOfThisFrame = _endOfThisFrame endOfThisFrame = startOfThisFrame + maxFrameLen lastWordI = wordI - 1 if isFirstInFrame: partsPending = True isFirstInFrame = False # cut off padding at start of frame paddingWords = wordI - lastWordI if trimPaddingWordsOnStart and paddingWords > maxPaddingWords: startOfThisFrame += paddingWords * wordWidth endOfThisFrame = startOfThisFrame + maxFrameLen # resolve end of this part parts.extend(word) lastWordI = wordI # reminder in "parts" after last iteration endOfThisFrame = transaction.bitAddrEnd withPadding = not (trimPaddingWordsOnEnd or trimPaddingWordsOnStart) if partsPending or (withPadding and endOfThisFrame != startOfThisFrame): # cut off padding at end of frame endOfLastWord = (lastWordI + 1) * wordWidth if endOfThisFrame < endOfLastWord: endOfThisFrame = endOfLastWord else: paddingWords = it.fullWordCnt(endOfLastWord, endOfThisFrame) if trimPaddingWordsOnEnd and paddingWords > maxPaddingWords: endOfThisFrame -= paddingWords * wordWidth # align end of frame to word endOfThisFrame = min(startOfThisFrame + maxFrameLen, endOfThisFrame) yield FrameTmpl(transaction, wordWidth, startOfThisFrame, endOfThisFrame, parts) parts = [] startOfThisFrame = endOfThisFrame # final padding on the end while withPadding and startOfThisFrame < transaction.bitAddrEnd: endOfThisFrame = min(startOfThisFrame + maxFrameLen, transaction.bitAddrEnd) yield FrameTmpl(transaction, wordWidth, startOfThisFrame, endOfThisFrame, []) startOfThisFrame = endOfThisFrame
python
{ "resource": "" }
q272157
FrameTmpl.walkWords
test
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: generator of tuples (wordIndex, list of TransParts in this word) """ wIndex = 0 lastEnd = self.startBitAddr parts = [] for p in self.parts: end = p.startOfPart if showPadding and end != lastEnd: # insert padding while end != lastEnd: assert end >= lastEnd, (end, lastEnd) endOfWord = ceil( (lastEnd + 1) / self.wordWidth) * self.wordWidth endOfPadding = min(endOfWord, end) _p = TransPart(self, None, lastEnd, endOfPadding, 0) parts.append(_p) if endOfPadding >= endOfWord: yield (wIndex, parts) wIndex += 1 parts = [] lastEnd = endOfPadding if self._wordIndx(lastEnd) != self._wordIndx(p.startOfPart): yield (wIndex, parts) wIndex += 1 parts = [] lastEnd = p.endOfPart parts.append(p) lastEnd = p.endOfPart if lastEnd % self.wordWidth == 0: yield (wIndex, parts) wIndex += 1 parts = [] if showPadding and (parts or lastEnd != self.endBitAddr or lastEnd % self.wordWidth != 0): # align end to end of last word end = ceil(self.endBitAddr / self.wordWidth) * self.wordWidth while end != lastEnd: assert end >= lastEnd, (end, lastEnd) endOfWord = ((lastEnd // self.wordWidth) + 1) * self.wordWidth endOfPadding = min(endOfWord, end) _p = TransPart(self, None, lastEnd, endOfPadding, 0) _p.parent = self parts.append(_p) if endOfPadding >= endOfWord: yield (wIndex, parts) wIndex += 1 parts = [] lastEnd = endOfPadding if parts: # in the case end of frame is not aligned to end of word yield (wIndex, parts)
python
{ "resource": "" }
q272158
FrameTmpl.packData
test
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) fieldToVal = self._fieldToTPart if fieldToVal is None: fieldToVal = self._fieldToTPart = self.fieldToDataDict( self.origin.dtype, data, {}) for _, transParts in self.walkWords(showPadding=True): actualVldMask = 0 actualVal = 0 for tPart in transParts: high, low = tPart.getBusWordBitRange() fhigh, flow = tPart.getFieldBitRange() if not tPart.isPadding: val = fieldToVal.get(tPart.tmpl.origin, None) else: val = None if val is None: newBits = 0 vld = 0 else: newBits = selectBitRange(val, flow, fhigh - flow) vld = mask(high - low) << low actualVal = setBitRange(actualVal, low, high - low, newBits) actualVldMask = setBitRange(actualVal, low, high - low, vld) yield typeOfWord.getValueCls()(actualVal, typeOfWord, actualVldMask, -1)
python
{ "resource": "" }
q272159
HdlStatement._clean_signal_meta
test
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()
python
{ "resource": "" }
q272160
HdlStatement._discover_enclosure_for_statements
test
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 which should be driven from this statement list :return: set of signals for which this statement list have always some driver (is enclosed) """ result = set() if not statements: return result for stm in statements: stm._discover_enclosure() for o in outputs: has_driver = False for stm in statements: if o in stm._outputs: assert not has_driver has_driver = False if o in stm._enclosed_for: result.add(o) else: pass return result
python
{ "resource": "" }
q272161
HdlStatement._discover_sensitivity_seq
test
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: s._walk_sensitivity(casualSensitivity, seen, ctx) if ctx.contains_ev_dependency: break # if event dependent sensitivity found do not add other sensitivity if not ctx.contains_ev_dependency: ctx.extend(casualSensitivity)
python
{ "resource": "" }
q272162
HdlStatement._get_rtl_context
test
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 HwtSyntaxError( "Statement does not have any signal in any context", self)
python
{ "resource": "" }
q272163
HdlStatement._on_reduce
test
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 and has to be updated :param result_statements: list of statements which are result of reduce operation on this statement """ parentStm = self.parentStm if self_reduced: was_top = parentStm is None # update signal drivers/endpoints if was_top: # disconnect self from signals ctx = self._get_rtl_context() ctx.statements.remove(self) ctx.statements.update(result_statements) for i in self._inputs: i.endpoints.discard(self) for o in self._outputs: o.drivers.remove(self) for stm in result_statements: stm.parentStm = parentStm if parentStm is None: # conect signals to child statements for inp in stm._inputs: inp.endpoints.append(stm) for outp in stm._outputs: outp.drivers.append(stm) else: # parent has to update it's inputs/outputs if io_changed: self._inputs = UniqList() self._outputs = UniqList() self._collect_io()
python
{ "resource": "" }
q272164
HdlStatement._on_merge
test
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._sensitivity.extend(other._sensitivity) else: assert other._sensitivity is None if self._enclosed_for is not None: self._enclosed_for.update(other._enclosed_for) else: assert other._enclosed_for is None other_was_top = other.parentStm is None if other_was_top: other._get_rtl_context().statements.remove(other) for s in other._inputs: s.endpoints.discard(other) s.endpoints.append(self) for s in other._outputs: s.drivers.discard(other) s.drivers.append(self)
python
{ "resource": "" }
q272165
HdlStatement._is_mergable_statement_list
test
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(stmsA) b_it = iter(stmsB) a = _get_stm_with_branches(a_it) b = _get_stm_with_branches(b_it) while a is not None or b is not None: if a is None or b is None or not a._is_mergable(b): return False a = _get_stm_with_branches(a_it) b = _get_stm_with_branches(b_it) # lists are empty return True
python
{ "resource": "" }
q272166
HdlStatement._merge_statements
test
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 reduced statements :attention: statement list has to me mergable """ order = {} for i, stm in enumerate(statements): order[stm] = i new_statements = [] rank_decrease = 0 for rank, stms in groupedby(statements, lambda s: s.rank): if rank == 0: new_statements.extend(stms) else: if len(stms) == 1: new_statements.extend(stms) continue # try to merge statements if they are same condition tree for iA, stmA in enumerate(stms): if stmA is None: continue for iB, stmB in enumerate(islice(stms, iA + 1, None)): if stmB is None: continue if stmA._is_mergable(stmB): rank_decrease += stmB.rank stmA._merge_with_other_stm(stmB) stms[iA + 1 + iB] = None new_statements.append(stmA) else: new_statements.append(stmA) new_statements.append(stmB) new_statements.sort(key=lambda stm: order[stm]) return new_statements, rank_decrease
python
{ "resource": "" }
q272167
HdlStatement._merge_statement_lists
test
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 = [] a_it = iter(stmsA) b_it = iter(stmsB) a = None b = None a_empty = False b_empty = False while not a_empty and not b_empty: while not a_empty: a = next(a_it, None) if a is None: a_empty = True break elif a.rank == 0: # simple statement does not require merging tmp.append(a) a = None else: break while not b_empty: b = next(b_it, None) if b is None: b_empty = True break elif b.rank == 0: # simple statement does not require merging tmp.append(b) b = None else: break if a is not None or b is not None: a._merge_with_other_stm(b) tmp.append(a) a = None b = None return tmp
python
{ "resource": "" }
q272168
HdlStatement._try_reduce_list
test
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_change |= _io_change new_statements, rank_decrease = HdlStatement._merge_statements( new_statements) return new_statements, rank_decrease, io_change
python
{ "resource": "" }
q272169
HdlStatement._on_parent_event_dependent
test
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(): stm._on_parent_event_dependent()
python
{ "resource": "" }
q272170
HdlStatement._set_parent_stm
test
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_dependent: self._on_parent_event_dependent() topStatement = parentStm while topStatement.parentStm is not None: topStatement = topStatement.parentStm parent_out_add = topStatement._outputs.append parent_in_add = topStatement._inputs.append if was_top: for inp in self._inputs: inp.endpoints.discard(self) inp.endpoints.append(topStatement) parent_in_add(inp) for outp in self._outputs: outp.drivers.discard(self) outp.drivers.append(topStatement) parent_out_add(outp) ctx = self._get_rtl_context() ctx.statements.discard(self) parentStm.rank += self.rank
python
{ "resource": "" }
q272171
HdlStatement._register_stements
test
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 stm._set_parent_stm(self) target.append(stm)
python
{ "resource": "" }
q272172
HdlStatement._destroy
test
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: i.endpoints.discard(self) for o in self._outputs: o.drivers.remove(self) ctx.statements.remove(self)
python
{ "resource": "" }
q272173
UnitImplHelpers._reg
test
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) :param clk: optional clok signal specification :param rst: optional reset signal specification :note: rst/rst_n resolution is done from signal type, if it is negated type it is rst_n :note: if clk or rst is not specifid default signal from parent unit will be used """ if clk is None: clk = getClk(self) if defVal is None: # if no value is specified reset is not required rst = None else: rst = getRst(self)._sig if isinstance(dtype, HStruct): if defVal is not None: raise NotImplementedError() container = dtype.fromPy(None) for f in dtype.fields: if f.name is not None: r = self._reg("%s_%s" % (name, f.name), f.dtype) setattr(container, f.name, r) return container return self._ctx.sig(name, dtype=dtype, clk=clk._sig, syncRst=rst, defVal=defVal)
python
{ "resource": "" }
q272174
UnitImplHelpers._sig
test
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 f.name is not None: r = self._sig("%s_%s" % (name, f.name), f.dtype) setattr(container, f.name, r) return container return self._ctx.sig(name, dtype=dtype, defVal=defVal)
python
{ "resource": "" }
q272175
UnitImplHelpers._cleanAsSubunit
test
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()
python
{ "resource": "" }
q272176
walkFlattenFields
test
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, HStruct): for f in t.fields: isPadding = f.name is None if not isPadding or not skipPadding: if isPadding: v = f.dtype.fromPy(None) else: v = getattr(sigOrVal, f.name) yield from walkFlattenFields(v) elif isinstance(t, HArray): for item in sigOrVal: yield from walkFlattenFields(item) else: raise NotImplementedError(t)
python
{ "resource": "" }
q272177
HStruct_unpack
test
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(None) fData = iter(data) # actual is storage variable for items from frameData actualOffset = 0 actual = None for v in walkFlattenFields(val, skipPadding=False): # walk flatten fields and take values from fData and parse them to # field required = v._dtype.bit_length() if actual is None: actualOffset = 0 try: actual = getDataFn(next(fData)) except StopIteration: raise Exception("Input data too short") if dataWidth is None: dataWidth = actual._dtype.bit_length() actuallyHave = dataWidth else: actuallyHave = actual._dtype.bit_length() - actualOffset while actuallyHave < required: # collect data for this field try: d = getDataFn(next(fData)) except StopIteration: raise Exception("Input data too short") actual = d._concat(actual) actuallyHave += dataWidth if actuallyHave >= required: # parse value of actual to field # skip padding _v = actual[(required + actualOffset):actualOffset] _v = _v._auto_cast(v._dtype) v.val = _v.val v.vldMask = _v.vldMask v.updateTime = _v.updateTime # update slice out what was taken actuallyHave -= required actualOffset += required if actuallyHave == 0: actual = None if actual is not None: assert actual._dtype.bit_length( ) - actualOffset < dataWidth, "It should be just a padding at the end of frame" return val
python
{ "resource": "" }
q272178
BitsVal._convSign
test
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 """ if isinstance(self, Value): return self._convSign__val(signed) else: if self._dtype.signed == signed: return self t = copy(self._dtype) t.signed = signed if signed is None: cnv = AllOps.BitsAsVec elif signed: cnv = AllOps.BitsAsSigned else: cnv = AllOps.BitsAsUnsigned return Operator.withRes(cnv, [self], t)
python
{ "resource": "" }
q272179
sensitivity
test
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: s.simRisingSensProcs.add(proc) elif sen == SENSITIVITY.FALLING: s.simFallingSensProcs.add(proc) else: raise AssertionError(sen) else: s.simSensProcs.add(proc)
python
{ "resource": "" }
q272180
simEvalCond
test
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 False, False _cond = _cond and val _vld = _vld and fullVld return _cond, _vld
python
{ "resource": "" }
q272181
connectSimPort
test
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: origPort = getattr(subSimUnit, dstName) newPort = getattr(simUnit, srcName) setattr(subSimUnit, dstName, newPort) subSimUnit._ctx.signals.remove(origPort)
python
{ "resource": "" }
q272182
mkUpdater
test
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(valueHasChangedFlag, nextVal) """ def updater(currentVal): _nextVal = nextVal.clone() if invalidate: _nextVal.vldMask = 0 return (valueHasChanged(currentVal, _nextVal), _nextVal) return updater
python
{ "resource": "" }
q272183
mkArrayUpdater
test
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 in target array :return: function(value) -> tuple(valueHasChangedFlag, nextVal) """ def updater(currentVal): if len(indexes) > 1: raise NotImplementedError("[TODO] implement for more indexes") _nextItemVal = nextItemVal.clone() if invalidate: _nextItemVal.vldMask = 0 index = indexes[0] change = valueHasChanged(currentVal._getitem__val(index), _nextItemVal) currentVal._setitem__val(index, _nextItemVal) return (change, currentVal) return updater
python
{ "resource": "" }
q272184
vec
test
def vec(val, width, signed=None): """create hdl vector value""" return Bits(width, signed, forceVector=True).fromPy(val)
python
{ "resource": "" }
q272185
ResourceAnalyzer.HWProcess
test
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._now_is_event_dependent ev_dep = full_ev_dep or now_ev_dep out_mux_dim = count_mux_inputs_for_outputs(stm) for o in stm._outputs: if o in seen: continue i = out_mux_dim[o] if isinstance(o._dtype, HArray): assert i == 1, (o, i, " only one ram port per HWProcess") for a in walk_assignments(stm, o): assert len(a.indexes) == 1, "one address per RAM port" addr = a.indexes[0] ctx.registerRAM_write_port(o, addr, ev_dep) elif ev_dep: ctx.registerFF(o) if i > 1: ctx.registerMUX(stm, o, i) elif o not in encl: ctx.registerLatch(o) if i > 1: ctx.registerMUX(stm, o, i) elif i > 1: ctx.registerMUX(stm, o, i) else: # just a connection continue if isinstance(stm, SwitchContainer): caseEqs = set([stm.switchOn._eq(c[0]) for c in stm.cases]) inputs = chain( [sig for sig in stm._inputs if sig not in caseEqs], [stm.switchOn]) else: inputs = stm._inputs for i in inputs: # discover only internal signals in this statements for # operators if not i.hidden or i in seen: continue cls.HWProcess_operators(i, ctx, ev_dep)
python
{ "resource": "" }
q272186
evalParam
test
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)
python
{ "resource": "" }
q272187
Param.set
test
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 this " "should not exists") val = toHVal(val) self.defVal = val self._val = val.staticEval() self._dtype = self._val._dtype
python
{ "resource": "" }
q272188
HTypeFromIntfMap
test
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) tuple (list of interface, name) :param DATA_WIDTH: width of word :param terminalNodes: None or set whre are placed StructField instances which are derived directly from interface :return: generator of tuple (type, name, BusFieldInfo) """ structFields = [] for m in interfaceMap: f = HTypeFromIntfMapItem(m) structFields.append(f) return HStruct(*structFields)
python
{ "resource": "" }
q272189
ResourceContext.finalize
test
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 rSync_wAsyncPorts, rAsync_wSyncPorts = 0, 0 for _, (rSync, wSync, rAsync, wAsync) in addrDict.items(): if rSync: ff_to_remove += rSync * m._dtype.elmType.bit_length() # resolve port count for this addr signal rwSync = min(rSync, wSync) rSync -= rwSync wSync -= rwSync rwAsync = min(rAsync, wAsync) rAsync -= rwAsync wAsync -= rwAsync rSync_wAsync = min(rSync, wAsync) rSync -= rSync_wAsync wAsync -= rSync_wAsync rAsync_wSync = min(rAsync, wSync) rAsync -= rAsync_wSync wSync -= rAsync_wSync # update port counts for mem rwSyncPorts += rwSync rSyncPorts += rSync wSyncPorts += wSync rwAsyncPorts += rwAsync rAsyncPorts += rAsync wAsyncPorts += wAsync rSync_wAsyncPorts += rSync_wAsync rAsync_wSyncPorts += rAsync_wSync k = ResourceRAM(m._dtype.elmType.bit_length(), int(m._dtype.size), rwSyncPorts, rSyncPorts, wSyncPorts, rSync_wAsyncPorts, rwAsyncPorts, rAsyncPorts, wAsyncPorts, rAsync_wSyncPorts) res[k] = res.get(k, 0) + 1 self.memories.clear() # remove register on read ports which will be merged into ram if ff_to_remove: ff_cnt = res[ResourceFF] ff_cnt -= ff_to_remove if ff_cnt: res[ResourceFF] = ff_cnt else: del res[ResourceFF]
python
{ "resource": "" }
q272190
RtlSignalOps._getIndexCascade
test
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 AttributeError: return if op == AllOps.INDEX: # get signal on which is index applied indexedOn = d.operands[0] if isinstance(indexedOn, RtlSignalBase): # [TODO] multidimensional indexing return indexedOn, [d.operands[1]] else: raise Exception( "can not drive static value %r" % indexedOn) except (MultipleDriversErr, NoDriverErr): pass
python
{ "resource": "" }
q272191
HdlType.fromPy
test
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)
python
{ "resource": "" }
q272192
HdlType.auto_cast
test
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 try: c = self._auto_cast_fn except AttributeError: c = self.get_auto_cast_fn() self._auto_cast_fn = c return c(self, sigOrVal, toType)
python
{ "resource": "" }
q272193
HdlType.reinterpret_cast
test
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, toType) except TypeConversionErr: pass try: r = self._reinterpret_cast_fn except AttributeError: r = self.get_reinterpret_cast_fn() self._reinterpret_cast_fn = r return r(self, sigOrVal, toType)
python
{ "resource": "" }
q272194
walkParams
test
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
python
{ "resource": "" }
q272195
connectPacked
test
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 self which should be excluded """ offset = 0 connections = [] for i in reversed(list(walkPhysInterfaces(dstInterface))): if exclude is not None and i in exclude: continue sig = i._sig t = sig._dtype if t == BIT: s = srcPacked[offset] offset += 1 else: w = t.bit_length() s = srcPacked[(w + offset): offset] offset += w connections.append(sig(s)) return connections
python
{ "resource": "" }
q272196
packIntf
test
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._masterDir == masterDirEqTo: return intf._sig return None res = None for i in intf._interfaces: if exclude is not None and i in exclude: continue if i._interfaces: if i._masterDir == DIRECTION.IN: d = DIRECTION.opposite(masterDirEqTo) else: d = masterDirEqTo s = i._pack(d, exclude=exclude) else: if i._masterDir == masterDirEqTo: s = i._sig else: s = None if s is not None: if res is None: res = s else: res = res._concat(s) return res
python
{ "resource": "" }
q272197
VerilogSerializer.hardcodeRomIntoProcess
test
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.operator == AllOps.INDEX, e me, index = e.operands assert me is rom # construct output of the rom romValSig = rom.ctx.sig(rom.name, dtype=e.result._dtype) signals.append(romValSig) romValSig.hidden = False # construct process which will represent content of the rom cases = [(toHVal(i), [romValSig(v), ]) for i, v in enumerate(rom.defVal.val)] statements = [SwitchContainer(index, cases), ] for (_, (stm, )) in cases: stm.parentStm = statements[0] p = HWProcess(rom.name, statements, {index, }, {index, }, {romValSig, }) processes.append(p) # override usage of original index operator on rom # to use signal generated from this process def replaceOrigRomIndexExpr(x): if x is e.result: return romValSig else: return x for _e in e.result.endpoints: _e.operands = tuple(map(replaceOrigRomIndexExpr, _e.operands)) e.result = romValSig return processes, signals
python
{ "resource": "" }
q272198
Unit._toRtl
test
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"): self._name = self._getDefaultName() for proc in targetPlatform.beforeToRtl: proc(self) self._ctx.params = self._buildParams() self._externInterf = [] # prepare subunits for u in self._units: yield from u._toRtl(targetPlatform) for u in self._units: subUnitName = u._name u._signalsForMyEntity(self._ctx, "sig_" + subUnitName) # prepare signals for interfaces for i in self._interfaces: signals = i._signalsForInterface(self._ctx) if i._isExtern: self._externInterf.extend(signals) for proc in targetPlatform.beforeToRtlImpl: proc(self) self._loadMyImplementations() yield from self._lazyLoaded if not self._externInterf: raise IntfLvlConfErr( "Can not find any external interface for unit %s" "- unit without interfaces are not allowed" % self._name) for proc in targetPlatform.afterToRtlImpl: proc(self) yield from self._synthetiseContext(self._externInterf) self._checkArchCompInstances() for proc in targetPlatform.afterToRtl: proc(self)
python
{ "resource": "" }
q272199
Unit._registerIntfInImpl
test
def _registerIntfInImpl(self, iName, intf): """ Register interface in implementation phase """ self._registerInterface(iName, intf, isPrivate=True) self._loadInterface(intf, False) intf._signalsForInterface(self._ctx)
python
{ "resource": "" }