1
0
mirror of https://github.com/myhdl/myhdl.git synced 2025-01-24 21:52:56 +08:00

removed modules with shadowing names

This commit is contained in:
jand 2003-07-24 07:19:08 +00:00
parent 96fdfb7cb4
commit 81d6d60457
10 changed files with 0 additions and 1714 deletions

View File

@ -1,179 +0,0 @@
# This file is part of the myhdl library, a Python package for using
# Python as a Hardware Description Language.
#
# Copyright (C) 2003 Jan Decaluwe
#
# The myhdl library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of the
# License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
""" Module that provides the Cosimulation class """
__author__ = "Jan Decaluwe <jan@jandecaluwe.com>"
__revision__ = "$Revision$"
__date__ = "$Date$"
from __future__ import generators
import sys
import os
import exceptions
from myhdl import intbv, Signal
from myhdl import _simulator
_MAXLINE = 4096
class Error(Exception):
"""Cosimulation Error"""
def __init__(self, arg=""):
self.arg = arg
def __str__(self):
msg = self.__doc__
if self.arg:
msg = msg + ": " + str(self.arg)
return msg
class MultipleCosimError(Error):
"""Only a single cosimulator allowed"""
class DuplicateSigNamesError(Error):
"""Duplicate signal name in myhdl vpi call"""
class SigNotFoundError(Error):
"""Signal not found in Cosimulation arguments"""
class TimeZeroError(Error):
"""myhdl vpi call when not at time 0"""
class NoCommunicationError(Error):
"""No signals communicating to myhdl"""
class SimulationEndError(Error):
"""Premature simulation end"""
class Cosimulation(object):
""" Cosimulation class. """
def __init__(self, exe="", **kwargs):
""" Construct a cosimulation object. """
if _simulator._cosim:
raise MultipleCosimError
_simulator._cosim = 1
self._rt, self._wt = rt, wt = os.pipe()
self._rf, self._wf = rf, wf = os.pipe()
self._fromSignames = fromSignames = []
self._fromSizes = fromSizes = []
self._fromSigs = fromSigs = []
self._toSignames = toSignames = []
self._toSizes = toSizes = []
self._toSigs = toSigs = []
self._toSigDict = toSigDict = {}
self._hasChange = 0
self._getMode = 1
child_pid = self._child_pid = os.fork()
if child_pid == 0:
os.close(rt)
os.close(wf)
os.environ['MYHDL_TO_PIPE'] = str(wt)
os.environ['MYHDL_FROM_PIPE'] = str(rf)
arglist = exe.split()
p = arglist[0]
arglist[0] = os.path.basename(p)
try:
os.execvp(p, arglist)
except OSError, e:
raise Error, str(e)
else:
os.close(wt)
os.close(rf)
while 1:
s = os.read(rt, _MAXLINE)
if not s:
raise SimulationEndError
e = s.split()
if e[0] == "FROM":
if long(e[1]) != 0:
raise TimeZeroError, "$from_myhdl"
for i in range(2, len(e)-1, 2):
n = e[i]
if n in fromSignames:
raise DuplicateSigNamesError, n
if not n in kwargs:
raise SigNotFoundError, n
fromSignames.append(n)
fromSigs.append(kwargs[n])
fromSizes.append(int(e[i+1]))
os.write(wf, "OK")
elif e[0] == "TO":
if long(e[1]) != 0:
raise TimeZeroError, "$to_myhdl"
for i in range(2, len(e)-1, 2):
n = e[i]
if n in toSignames:
raise DuplicateSigNamesError, n
if not n in kwargs:
raise SigNotFoundError, n
toSignames.append(n)
toSigs.append(kwargs[n])
toSigDict[n] = kwargs[n]
toSizes.append(int(e[i+1]))
os.write(wf, "OK")
elif e[0] == "START":
if not toSignames:
raise NoCommunicationError
os.write(wf, "OK")
break
else:
raise Error, "Unexpected cosim input"
def _get(self):
if not self._getMode:
return
buf = os.read(self._rt, _MAXLINE)
if not buf:
raise SimulationEndError
e = buf.split()
for i in range(1, len(e), 2):
s, v = self._toSigDict[e[i]], e[i+1]
try:
next = long(v, 16)
except ValueError:
next = intbv(None)
s.next = next
self._getMode = 0
def _put(self, time):
buf = repr(time)
if buf[-1] == 'L':
buf = buf[:-1] # strip trailing L
if self._hasChange:
self._hasChange = 0
for s in self._fromSigs:
buf += " "
buf += hex(s)[2:]
os.write(self._wf, buf)
self._getMode = 1
def _waiter(self):
sigs = tuple(self._fromSigs)
while 1:
yield sigs
self._hasChange = 1
def __del__(self):
""" Clear flag when this object destroyed - to suite unittest. """
_simulator._cosim = 0

View File

@ -1,428 +0,0 @@
# This file is part of the myhdl library, a Python package for using
# Python as a Hardware Description Language.
#
# Copyright (C) 2003 Jan Decaluwe
#
# The myhdl library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of the
# License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
""" Module that provides the Signal class and related objects.
This module provides the following objects:
Signal -- class to model hardware signals
posedge -- callable to model a rising edge on a signal in a yield statement
negedge -- callable to model a falling edge on a signal in a yield statement
"""
__author__ = "Jan Decaluwe <jan@jandecaluwe.com>"
__revision__ = "$Revision$"
__date__ = "$Date$"
from __future__ import generators
from copy import deepcopy as copy
from myhdl import _simulator as sim
from myhdl._simulator import _siglist, _futureEvents, now
from myhdl._Waiter import _WaiterList
from myhdl import intbv, bin
_schedule = _futureEvents.append
def posedge(sig):
""" Return a posedge trigger object """
return sig.posedge
def negedge(sig):
""" Return a negedge trigger object """
return sig.negedge
class Signal(object):
""" Signal class.
Properties:
val -- current value (read-only)
next -- next value (read-write)
"""
__slots__ = ('_next', '_val', '_min', '_max', '_type',
'_eventWaiters', '_posedgeWaiters', '_negedgeWaiters',
'_code', '_tracing', '_nrbits', '_checkVal',
'_printVcd'
)
def __new__(cls, val, delay=0):
""" Return a new Signal (default or delay 0) or DelayedSignal """
if delay:
return object.__new__(DelayedSignal)
else:
return object.__new__(cls)
def __init__(self, val):
""" Construct a signal.
val -- initial value
"""
self._next = self._val = val
self._min = self._max = self._nrbits = None
self._type = (int, long, intbv)
self._printVcd = self._printVcdStr
if type(val) is bool:
self._checkVal = self._checkBool
self._printVcd = self._printVcdBit
self._nrbits = 1
elif isinstance(val, (int, long)):
self._checkVal = self._checkInt
elif isinstance(val, intbv):
self._min = val._min
self._max = val._max
self._nrbits = val._len
if self._nrbits:
self._checkVal = self._checkIntbvBounds
self._printVcd = self._printVcdVec
else:
self._checkVal = self._checkInt
self._printVcd = self._printVcdHex
else:
self._type = type(val)
self._checkVal = self._checkType
self._eventWaiters = _WaiterList()
self._posedgeWaiters = _WaiterList()
self._negedgeWaiters = _WaiterList()
self._code = ""
self._tracing = 0
def _update(self):
if self._val != self._next:
waiters = self._eventWaiters[:]
del self._eventWaiters[:]
if not self._val and self._next:
waiters.extend(self._posedgeWaiters[:])
del self._posedgeWaiters[:]
elif not self._next and self._val:
waiters.extend(self._negedgeWaiters[:])
del self._negedgeWaiters[:]
self._val = self._next
if self._tracing:
self._printVcd()
return waiters
else:
return []
# support for the 'val' attribute
def _get_val(self):
return self._val
val = property(_get_val, None, None, "'val' access methods")
# support for the 'next' attribute
def _get_next(self):
if self._next is self._val:
self._next = copy(self._val)
_siglist.append(self)
return self._next
def _set_next(self, val):
if isinstance(val, Signal):
val = val._val
self._checkVal(val)
self._next = val
_siglist.append(self)
next = property(_get_next, _set_next, None, "'next' access methods")
# support for the 'posedge' attribute
def _get_posedge(self):
return self._posedgeWaiters
posedge = property(_get_posedge, None, None, "'posedge' access methods")
# support for the 'negedge' attribute
def _get_negedge(self):
return self._negedgeWaiters
negedge = property(_get_negedge, None, None, "'negedge' access methods")
# support for the 'min' and 'max' attribute
def _get_max(self):
return self._max
max = property(_get_max, None)
def _get_min(self):
return self._min
min = property(_get_min, None)
# check methods
def _checkBool(self, val):
if not val in (0, 1):
raise ValueError("Expected value 0 or 1, got %s" % val)
def _checkInt(self, val):
if not isinstance(val, (int, long, intbv)):
raise TypeError("Expected int or intbv, got %s" % type(val))
def _checkIntbvBounds(self, val):
if not isinstance(val, (int, long, intbv)):
raise TypeError("Expected int or intbv, got %s" % type(val))
if self._max is not None and val >= self._max:
raise ValueError("Expected value < %s, got %s" % (self._max, val))
if self._min is not None and val < self._min:
raise ValueError("Expected value >= %s, got %s" % (self._min, val))
def _checkType(self, val):
if not isinstance(val, self._type):
raise TypeError("Expected %s, got %s" % (self._type, type(val)))
# vcd print methods
def _printVcdStr(self):
print >> sim._tf, "s%s %s" % (str(self._val), self._code)
def _printVcdHex(self):
print >> sim._tf, "s%s %s" % (hex(self._val), self._code)
def _printVcdBit(self):
print >> sim._tf, "%d%s" % (self._val, self._code)
def _printVcdVec(self):
print >> sim._tf, "b%s %s" % (bin(self._val, self._nrbits), self._code)
# hashing not supported
def __hash__(self):
return hash(self._val)
### operators for which delegation to current value is appropriate ###
def __nonzero__(self):
if self._val:
return 1
else:
return 0
# length defined as bit width
def __len__(self):
return self._nrbits
# indexing and slicing methods
def __getitem__(self, i):
return self._val[i]
def __getslice__(self, i, j):
return self._val[i:j]
# integer-like methods
def __add__(self, other):
if isinstance(other, Signal):
return self._val + other._val
else:
return self._val + other
def __radd__(self, other):
return other + self._val
def __sub__(self, other):
if isinstance(other, Signal):
return self._val - other._val
else:
return self._val - other
def __rsub__(self, other):
return other - self._val
def __mul__(self, other):
if isinstance(other, Signal):
return self._val * other._val
else:
return self._val * other
def __rmul__(self, other):
return other * self._val
def __div__(self, other):
if isinstance(other, Signal):
return self._val / other._val
else:
return self._val / other
def __rdiv__(self, other):
return other / self._val
def __mod__(self, other):
if isinstance(other, Signal):
return self._val % other._val
else:
return self._val % other
def __rmod__(self, other):
return other % self._val
# XXX divmod
def __pow__(self, other):
if isinstance(other, Signal):
return self._val ** other._val
else:
return self._val ** other
def __rpow__(self, other):
return other ** self._val
def __lshift__(self, other):
if isinstance(other, Signal):
return self._val << other._val
else:
return self._val << other
def __rlshift__(self, other):
return other << self._val
def __rshift__(self, other):
if isinstance(other, Signal):
return self._val >> other._val
else:
return self._val >> other
def __rrshift__(self, other):
return other >> self._val
def __and__(self, other):
if isinstance(other, Signal):
return self._val & other._val
else:
return self._val & other
def __rand__(self, other):
return other & self._val
def __or__(self, other):
if isinstance(other, Signal):
return self._val | other._val
else:
return self._val | other
def __ror__(self, other):
return other | self._val
def __xor__(self, other):
if isinstance(other, Signal):
return self._val ^ other._val
else:
return self._val ^ other
def __rxor__(self, other):
return other ^ self._val
def __neg__(self):
return -self._val
def __pos__(self):
return +self._val
def __abs__(self):
return abs(self._val)
def __invert__(self):
return ~self._val
# conversions
def __int__(self):
return int(self._val)
def __long__(self):
return long(self._val)
def __float__(self):
return float(self._val)
def __oct__(self):
return oct(self._val)
def __hex__(self):
return hex(self._val)
# comparison
def __cmp__(self, other):
return cmp(self._val, other)
# representation
def __str__(self):
return str(self._val)
def __repr__(self):
return "Signal(" + repr(self._val) + ")"
# augmented assignment not supported
def _augm(self):
raise TypeError, "Signal object doesn't support augmented assignment"
__iadd__ = __isub__ = __idiv__ = __imul__ = __ipow__ = __imod__ = _augm
__ior__ = __iand__ = __ixor__ = __irshift__ = __ilshift__ = _augm
# index and slice assignment not supported
def __setitem__(self, i, val):
raise TypeError, "Signal object doesn't support item assignment"
def __setslice__(self, i, j, val):
raise TypeError, "Signal object doesn't support slice assignment"
class DelayedSignal(Signal):
__slots__ = ('_nextZ', '_delay', '_timeStamp',
)
def __init__(self, val, delay):
""" Construct a new DelayedSignal.
Automatically invoked through the Signal new method.
val -- initial value
delay -- non-zero delay value
"""
Signal.__init__(self, val)
self._nextZ = val
self._delay = delay
self._timeStamp = 0
def _update(self):
if self._next != self._nextZ:
self._timeStamp = sim._time
self._nextZ = self._next
t = sim._time + self._delay
_schedule((t, _SignalWrap(self, self._next, self._timeStamp)))
return []
def _apply(self, next, timeStamp):
if timeStamp == self._timeStamp and self._val != next:
waiters = self._eventWaiters[:]
del self._eventWaiters[:]
if not self._val and next:
waiters.extend(self._posedgeWaiters[:])
del self._posedgeWaiters[:]
elif not next and self._val:
waiters.extend(self._negedgeWaiters[:])
del self._negedgeWaiters[:]
self._val = copy(next)
return waiters
else:
return []
# support for the 'delay' attribute
def _get_delay(self):
return self._delay
def _set_delay(self, delay):
self._delay = delay
delay = property(_get_delay, _set_delay, None, "'delay' access methods")
class _SignalWrap(object):
def __init__(self, sig, next, timeStamp):
self.sig = sig
self.next = next
self.timeStamp = timeStamp
def apply(self):
return self.sig._apply(self.next, self.timeStamp)

View File

@ -1,243 +0,0 @@
# This file is part of the myhdl library, a Python package for using
# Python as a Hardware Description Language.
#
# Copyright (C) 2003 Jan Decaluwe
#
# The myhdl library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of the
# License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
""" Module that provides the Simulation class """
__author__ = "Jan Decaluwe <jan@jandecaluwe.com>"
__revision__ = "$Revision$"
__date__ = "$Date$"
from __future__ import generators
import sys
import os
from warnings import warn
from types import GeneratorType
from myhdl import delay, Signal, Cosimulation, join
from myhdl import _simulator
from myhdl._simulator import _siglist, _futureEvents
from myhdl._Waiter import _Waiter, _WaiterList
from myhdl.util import StopSimulation, SuspendSimulation
## try:
## import simrunc
## except:
## pass
schedule = _futureEvents.append
class Error(Exception):
"""Simulation Error"""
def __init__(self, arg=""):
self.arg = arg
def __str__(self):
msg = self.__doc__
if self.arg:
msg = msg + ": " + str(self.arg)
return msg
class MultipleCosimError(Error):
"""Only a single cosimulator argument allowed"""
class Simulation(object):
""" Simulation class.
Methods:
run -- run a simulation for some duration
"""
def __init__(self, *args):
""" Construct a simulation object.
*args -- list of arguments. Each argument is a generator or
a nested sequence of generators.
"""
_simulator._time = 0
self._waiters, self._cosim = _flatten(*args)
if not self._cosim and _simulator._cosim:
warn("Cosimulation not registered as Simulation argument")
del _futureEvents[:]
del _siglist[:]
def _finalize(self):
cosim = self._cosim
if cosim:
_simulator._cosim = 0
os.close(cosim._rt)
os.close(cosim._wf)
os.waitpid(cosim._child_pid, 0)
if _simulator._tracing:
_simulator._tracing = 0
_simulator._tf.close()
def runc(self, duration=0, quiet=0):
simrunc.run(sim=self, duration=duration, quiet=quiet)
def run(self, duration=None, quiet=0):
""" Run the simulation for some duration.
duration -- specified simulation duration (default: forever)
quiet -- don't print StopSimulation messages (default: off)
"""
waiters = self._waiters
maxTime = None
if duration:
stop = _Waiter(None)
stop.hasRun = 1
maxTime = _simulator._time + duration
schedule((maxTime, stop))
cosim = self._cosim
t = _simulator._time
actives = {}
tracing = _simulator._tracing
tracefile = _simulator._tf
while 1:
try:
for s in _siglist:
waiters.extend(s._update())
del _siglist[:]
while waiters:
waiter = waiters.pop()
if waiter.hasRun or not waiter.hasGreenLight():
continue
try:
clauses, clone = waiter.next()
except StopIteration:
if waiter.caller:
waiters.append(waiter.caller)
continue
nr = len(clauses)
for clause in clauses:
if type(clause) is _WaiterList:
clause.append(clone)
if nr > 1:
actives[id(clause)] = clause
elif isinstance(clause, Signal):
wl = clause._eventWaiters
wl.append(clone)
if nr > 1:
actives[id(wl)] = wl
elif type(clause) is delay:
schedule((t + clause._time, clone))
elif type(clause) is GeneratorType:
waiters.append(_Waiter(clause, clone))
elif type(clause) is join:
waiters.append(_Waiter(clause._generator(), clone))
elif clause is None:
waiters.append(clone)
else:
raise TypeError, "yield clause '%s'" % `clause`
if cosim:
cosim._get()
if _siglist or cosim._hasChange:
cosim._put(t)
continue
elif _siglist:
continue
if actives:
for wl in actives.values():
wl.purge()
actives = {}
if _futureEvents:
if t == maxTime:
raise SuspendSimulation, \
"Simulated for duration %s" % duration
_futureEvents.sort()
t = _simulator._time = _futureEvents[0][0]
if tracing:
print >> tracefile, "#%s" % t
if cosim:
cosim._put(t)
while _futureEvents:
newt, event = _futureEvents[0]
if newt == t:
if type(event) is _Waiter:
waiters.append(event)
else:
waiters.extend(event.apply())
del _futureEvents[0]
else:
break
else:
raise StopSimulation, "No more events"
except SuspendSimulation:
if not quiet:
printExcInfo()
if tracing:
tracefile.flush()
return 1
except StopSimulation:
if not quiet:
printExcInfo()
self._finalize()
return 0
except:
self._finalize()
raise
def printExcInfo():
kind, value, traceback = sys.exc_info()
msg = str(kind)
msg = msg[msg.rindex('.')+1:]
if str(value):
msg += ": %s" % value
print msg
def _flatten(*args):
waiters = []
cosim = None
for arg in args:
if type(arg) is GeneratorType:
waiters.append(_Waiter(arg))
elif type(arg) is Cosimulation:
if cosim:
raise MultipleCosimError
cosim = arg
waiters.append(_Waiter(cosim._waiter()))
else:
for item in arg:
w, c = _flatten(item)
if cosim and c:
raise MultipleCosimError
cosim = c
waiters.extend(w)
return waiters, cosim

View File

@ -1,152 +0,0 @@
# This file is part of the myhdl library, a Python package for using
# Python as a Hardware Description Language.
#
# Copyright (C) 2003 Jan Decaluwe
#
# The myhdl library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of the
# License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
""" Module with the always_comb function. """
__author__ = "Jan Decaluwe <jan@jandecaluwe.com>"
__revision__ = "$Revision$"
__date__ = "$Date$"
from __future__ import generators
import inspect
from types import FunctionType
import compiler
from myhdl import Signal
from myhdl.util import _isgeneratorfunction
class Error(Exception):
"""always_comb Error"""
def __init__(self, arg=""):
self.arg = arg
def __str__(self):
msg = self.__doc__
if self.arg:
msg = msg + ": " + str(self.arg)
return msg
class ArgumentError(Error):
""" always_comb argument should be a normal (non-generator) function"""
class NrOfArgsError(Error):
""" always_comb argument should be a function without arguments"""
class ScopeError(Error):
"""always_comb argument should be a local function"""
class SignalAsInoutError(Error):
"""signal used as inout in always_comb function argument"""
def always_comb(func):
f = inspect.getouterframes(inspect.currentframe())[1][0]
if type(func) is not FunctionType:
raise ArgumentError
if _isgeneratorfunction(func):
raise ArgumentError
if func.func_code.co_argcount:
raise NrOfArgsError
if func.func_name not in f.f_locals:
raise ScopeError
varnames = func.func_code.co_varnames
sigdict = {}
for dict in (f.f_locals, f.f_globals):
for n, v in dict.items():
if isinstance(v, Signal) and n not in varnames:
sigdict[n] = v
c = _AlwaysComb(func, sigdict)
return c.genfunc()
INPUT, OUTPUT, INOUT = range(3)
class _SigNameVisitor(object):
def __init__(self, sigdict):
self.inputs = []
self.outputs = []
self.sigdict = sigdict
def visitModule(self, node):
inputs = self.inputs
outputs = self.outputs
self.visit(node.node)
for n in inputs:
if n in outputs:
raise SignalAsInoutError(n)
def visitName(self, node, access=INPUT):
if node.name not in self.sigdict:
return
if access == INPUT:
self.inputs.append(node.name)
elif access == OUTPUT:
self.outputs.append(node.name)
elif access == INOUT:
raise SignalAsInoutError(node.name)
else:
raise Error
def visitAssign(self, node, access=OUTPUT):
for n in node.nodes:
self.visit(n, OUTPUT)
self.visit(node.expr, INPUT)
def visitAssAttr(self, node, access=OUTPUT):
self.visit(node.expr, OUTPUT)
def visitSubscript(self, node, access=INPUT):
self.visit(node.expr, access)
for n in node.subs:
self.visit(n, INPUT)
def visitSlice(self, node, access=INPUT):
self.visit(node.expr, access)
if node.lower:
self.visit(node.lower, INPUT)
if node.upper:
self.visit(node.upper, INPUT)
def visitAugAssign(self, node, access=INPUT):
self.visit(node.node, INOUT)
self.visit(node.expr, INPUT)
class _AlwaysComb(object):
def __init__(self, func, sigdict):
self.func = func
self.sigdict = sigdict
s = inspect.getsource(func)
s = s.lstrip()
tree = compiler.parse(s)
v = _SigNameVisitor(sigdict)
compiler.walk(tree, v)
v.inputs.sort()
v.outputs.sort()
self.inputs = v.inputs
self.outputs = v.outputs
def genfunc(self):
inputsigs = tuple([self.sigdict[n] for n in self.inputs])
func = self.func
while 1:
func()
yield inputsigs

View File

@ -1,60 +0,0 @@
# This file is part of the myhdl library, a Python package for using
# Python as a Hardware Description Language.
#
# Copyright (C) 2003 Jan Decaluwe
#
# The myhdl library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of the
# License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
""" module with the bin function.
"""
__author__ = "Jan Decaluwe <jan@jandecaluwe.com>"
__revision__ = "$Revision$"
__date__ = "$Date$"
def _int2bitstring(num):
if num == 0:
return '0'
if abs(num) == 1:
return '1'
bits = []
p, q = divmod(num, 2)
bits.append(str(q))
while not (abs(p) == 1):
p, q = divmod(p, 2)
bits.append(str(q))
bits.append('1')
bits.reverse()
return ''.join(bits)
def bin(num, width=0):
"""Return a binary string representation.
num -- number to convert
Optional parameter:
width -- specifies the desired string (sign bit padding)
"""
num = long(num)
s = _int2bitstring(num)
if width:
pad = '0'
if num < 0:
pad = '1'
return (width - len(s)) * pad + s
return s

View File

@ -1,41 +0,0 @@
# This file is part of the myhdl library, a Python package for using
# Python as a Hardware Description Language.
#
# Copyright (C) 2003 Jan Decaluwe
#
# The myhdl library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of the
# License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
""" Module that provides the delay class."""
__author__ = "Jan Decaluwe <jan@jandecaluwe.com>"
__revision__ = "$Revision$"
__date__ = "$Date$"
_errmsg = "arg of delay constructor should be a natural integeer"
class delay(object):
""" Class to model delay in yield statements. """
def __init__(self, val):
""" Return a delay instance.
Required parameters:
val -- a natural integer representing the desired delay
"""
if type(val) != int or val < 0:
raise TypeError, _errmsg
self._time = val

View File

@ -1,72 +0,0 @@
# This file is part of the myhdl library, a Python package for using
# Python as a Hardware Description Language.
#
# Copyright (C) 2003 Jan Decaluwe
#
# The myhdl library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of the
# License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
""" Module that implements enum.
"""
__author__ = "Jan Decaluwe <jan@jandecaluwe.com>"
__revision__ = "$Revision$"
__date__ = "$Date$"
from types import StringType
def enum(*args):
# args = args
# only default encoding for now
argdict = {}
encoding = {}
i = 0
for arg in args:
if type(arg) is not StringType:
raise TypeError
if encoding.has_key(arg):
raise ValueError("enum literals should be unique")
argdict[i] = arg
encoding[arg] = i
i += 1
class EnumItem(object):
def __init__(self, arg):
self._val = encoding[arg]
def __repr__(self):
return argdict[self._val]
__str__ = __repr__
class Enum(object):
def __init__(self):
for slot in args:
self.__dict__[slot] = EnumItem(slot)
def __setattr__(self, attr, val):
raise AttributeError("Cannot assign to enum attributes")
def __len__(self):
return len(args)
def __repr__(self):
return "<Enum: %s>" % ", ".join(args)
__str__ = __repr__
return Enum()

View File

@ -1,436 +0,0 @@
# This file is part of the myhdl library, a Python package for using
# Python as a Hardware Description Language.
#
# Copyright (C) 2003 Jan Decaluwe
#
# The myhdl library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of the
# License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
""" Module with the intbv class """
__author__ = "Jan Decaluwe <jan@jandecaluwe.com>"
__revision__ = "$Revision$"
__date__ = "$Date$"
import sys
maxint = sys.maxint
from types import StringType
import operator
from myhdl import bin
from __builtin__ import max as maxfunc
class intbv(object):
__slots__ = ('_val', '_min', '_max', '_len', '_nrbits')
def __init__(self, val=0, min=None, max=None, _len=0):
nrbits = 0
if _len:
self._min = 0
self._max = 2**_len
else:
self._min = min
if min is not None:
_len = len(bin(min))
self._max = max
if max is not None:
_len = maxfunc(len(bin(max-1)), _len)
if isinstance(val, (int, long)):
self._val = val
elif type(val) is StringType:
self._val = long(val, 2)
_len = len(val)
elif isinstance(val, intbv):
self._val = val._val
elif val is None:
self._val = None # for Cosimulation and X, Z support perhaps
else:
raise TypeError("intbv constructor arg should be int or string")
self._len = _len
self._checkBounds()
# support for the 'min' and 'max' attribute
def _get_max(self):
return self._max
max = property(_get_max, None)
def _get_min(self):
return self._min
min = property(_get_min, None)
def _checkBounds(self):
if self._max is not None:
if self._val >= self._max:
raise ValueError("intbv value %s >= maximum %s" %
(self._val, self._max))
if self._min is not None:
if self._val < self._min:
raise ValueError("intbv value %s < minimum %s" %
(self._val, self._min))
# concat method
def concat(self, *args):
v = self._val
basewidth = width = self._len
for a in args:
if type(a) is intbv:
w = a._len
if not w:
raise TypeError, "intbv arg to concat should have length"
else:
v = v * (2**w) + a._val
width += w
elif type(a) is StringType:
w = len(a)
v= v*(2**w) + long(a, 2)
width += w
else:
raise TypeError
if basewidth:
return intbv(v, _len=basewidth + width)
else:
return intbv(v)
# hash
def __hash__(self):
return hash(self._val)
# copy methods
def __copy__(self):
return intbv(self._val)
def __deepcopy__(self, visit):
return intbv(self._val)
# iterator method
def __iter__(self):
if not self._len:
raise TypeError, "Cannot iterate over unsized intbv"
return iter([self[i] for i in range(self._len, -1, -1)])
# logical testing
def __nonzero__(self):
if self._val:
return 1
else:
return 0
# length
def __len__(self):
return self._len
# indexing and slicing methods
def __getitem__(self, i):
res = intbv((self._val >> i) & 0x1, _len=1)
return res
def __getslice__(self, i, j):
if j == maxint: # default
j = 0
if j < 0:
raise ValueError, "intbv[i:j] requires j >= 0\n" \
" j == %s" % j
if i == 0: # default
return intbv(self._val >> j)
if i <= j:
raise ValueError, "intbv[i:j] requires i > j\n" \
" i, j == %s, %s" % (i, j)
res = intbv((self._val & 2**i-1) >> j, _len=i-j)
return res
def __setitem__(self, i, val):
if val not in (0, 1):
raise ValueError, "intbv[i] = v requires v in (0, 1)\n" \
" i == %s " % i
if val:
self._val |= (2**i)
else:
self._val &= ~(2**i)
def __setslice__(self, i, j, val):
if j == maxint: # default
j = 0
if j < 0:
raise ValueError, "intbv[i:j] = v requires j >= 0\n" \
" j == %s" % j
if i == 0: # default
q = self._val % (2**j)
self._val = val * 2**j + q
self._checkBounds()
return
if i <= j:
raise ValueError, "intbv[i:j] = v requires i > j\n" \
" i, j, v == %s, %s, %s" % (i, j, val)
if val >= 2**(i-j) or val < -2**(i-j):
raise ValueError, "intbv[i:j] = v abs(v) too large\n" \
" i, j, v == %s, %s, %s" % (i, j, val)
mask = (2**(i-j))-1
mask *= 2**j
self._val &= ~mask
self._val |= val * 2**j
self._checkBounds()
# integer-like methods
def __add__(self, other):
if isinstance(other, intbv):
return self._val + other._val
else:
return self._val + other
def __radd__(self, other):
return other + self._val
def __sub__(self, other):
if isinstance(other, intbv):
return self._val - other._val
else:
return self._val - other
def __rsub__(self, other):
return other - self._val
def __mul__(self, other):
if isinstance(other, intbv):
return self._val * other._val
else:
return self._val * other
def __rmul__(self, other):
return other * self._val
def __div__(self, other):
if isinstance(other, intbv):
return self._val / other._val
else:
return self._val / other
def __rdiv__(self, other):
return other / self._val
def __truediv__(self, other):
if isinstance(other, intbv):
return operator.truediv(self._val, other._val)
else:
return operator.truediv(self._val, other)
def __rtruediv__(self, other):
return operator.truediv(other, self._val)
def __floordiv__(self, other):
if isinstance(other, intbv):
return self._val // other._val
else:
return self._val // other
def __rfloordiv__(self, other):
return other // self._val
def __mod__(self, other):
if isinstance(other, intbv):
return self._val % other._val
else:
return self._val % other
def __rmod__(self, other):
return other % self._val
# divmod
def __pow__(self, other):
if isinstance(other, intbv):
return self._val ** other._val
else:
return self._val ** other
def __rpow__(self, other):
return other ** self._val
def __lshift__(self, other):
if isinstance(other, intbv):
return self._val << other._val
else:
return self._val << other
def __rlshift__(self, other):
return other << self._val
def __rshift__(self, other):
if isinstance(other, intbv):
return self._val >> other._val
else:
return self._val >> other
def __rrshift__(self, other):
return other >> self._val
def __and__(self, other):
if isinstance(other, intbv):
return intbv(self._val & other._val, _len=self._len)
else:
return intbv(self._val & other, _len=self._len)
def __rand__(self, other):
return intbv(other & self._val, _len=self._len)
def __or__(self, other):
if isinstance(other, intbv):
return intbv(self._val | other._val, _len=self._len)
else:
return intbv(self._val | other, _len=self._len)
def __ror__(self, other):
return intbv(other | self._val, _len=self._len)
def __xor__(self, other):
if isinstance(other, intbv):
return intbv(self._val ^ other._val, _len=self._len)
else:
return intbv(self._val ^ other, _len=self._len)
def __rxor__(self, other):
return intbv(other ^ self._val, _len=self._len)
def __iadd__(self, other):
if isinstance(other, intbv):
self._val += other._val
else:
self._val += other
self._checkBounds()
return self
def __isub__(self, other):
if isinstance(other, intbv):
self._val -= other._val
else:
self._val -= other
self._checkBounds()
return self
def __imul__(self, other):
if isinstance(other, intbv):
self._val *= other._val
else:
self._val *= other
self._checkBounds()
return self
def __ifloordiv__(self, other):
if isinstance(other, intbv):
self._val //= other._val
else:
self._val //= other
self._checkBounds()
return self
def __idiv__(self, other):
raise TypeError("intbv: Augmented classic division not supported")
def __itruediv__(self, other):
raise TypeError("intbv: Augmented true division not supported")
def __imod__(self, other):
if isinstance(other, intbv):
self._val %= other._val
else:
self._val %= other
self._checkBounds()
return self
def __ipow__(self, other, modulo=None):
# XXX why 3rd param required?
# unused but needed in 2.2, not in 2.3
if isinstance(other, intbv):
self._val **= other._val
else:
self._val **= other
if not isinstance(self._val, (int, long)):
raise ValueError("intbv value should be integer")
self._checkBounds()
return self
def __iand__(self, other):
if isinstance(other, intbv):
self._val &= other._val
else:
self._val &= other
self._checkBounds()
return self
def __ior__(self, other):
if isinstance(other, intbv):
self._val |= other._val
else:
self._val |= other
self._checkBounds()
return self
def __ixor__(self, other):
if isinstance(other, intbv):
self._val ^= other._val
else:
self._val ^= other
self._checkBounds()
return self
def __ilshift__(self, other):
if isinstance(other, intbv):
self._val <<= other._val
else:
self._val <<= other
self._checkBounds()
return self
def __irshift__(self, other):
if isinstance(other, intbv):
self._val >>= other._val
else:
self._val >>= other
self._checkBounds()
return self
def __neg__(self):
return -self._val
def __pos__(self):
return +self._val
def __abs__(self):
return abs(self._val)
def __invert__(self):
if self._len:
return intbv(~self._val & (2**self._len)-1)
else:
return intbv(~self._val)
def __int__(self):
return int(self._val)
def __long__(self):
return long(self._val)
def __float__(self):
return float(self._val)
# XXX __complex__ seems redundant ??? (complex() works as such?)
def __oct__(self):
return oct(self._val)
def __hex__(self):
return hex(self._val)
def __cmp__(self, other):
if isinstance(other, intbv):
return cmp(self._val, other._val)
else:
return cmp(self._val, other)
# representation
def __str__(self):
return str(self._val)
def __repr__(self):
return "intbv(" + repr(self._val) + ")"

View File

@ -1,43 +0,0 @@
# This file is part of the myhdl library, a Python package for using
# Python as a Hardware Description Language.
#
# Copyright (C) 2003 Jan Decaluwe
#
# The myhdl library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of the
# License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
""" Module that provides the Simulation class """
__author__ = "Jan Decaluwe <jan@jandecaluwe.com>"
__revision__ = "$Revision$"
__date__ = "$Date$"
from __future__ import generators
class join(object):
""" Join trigger objects to form a single trigger object. """
def __init__(self, *args):
""" Construct join object
*args -- list of trigger object arguments.
"""
self._args = args
def _generator(self):
yield join(*self._args)

View File

@ -1,60 +0,0 @@
# This file is part of the myhdl library, a Python package for using
# Python as a Hardware Description Language.
#
# Copyright (C) 2003 Jan Decaluwe
#
# The myhdl library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of the
# License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
""" myhdl miscellaneous objects.
This module provides the following myhdl objects:
instances -- function that returns instances in a generator function
these are all generators in the local namespace
processes -- function that returns processes in a generator function
these are generators obtained by calling local generator functions
"""
__author__ = "Jan Decaluwe <jan@jandecaluwe.com>"
__revision__ = "$Revision$"
__date__ = "$Date$"
import inspect
from types import GeneratorType
from myhdl import Cosimulation
from myhdl.util import _isgeneratorfunction, _isGenSeq
def instances():
f = inspect.currentframe()
d = inspect.getouterframes(f)[1][0].f_locals
l = []
for v in d.values():
if type(v) in (GeneratorType, Cosimulation):
l.append(v)
elif _isGenSeq(v):
l.append(v)
return l
def processes():
f = inspect.currentframe()
d = inspect.getouterframes(f)[1][0].f_locals
l = []
for v in d.values():
if _isgeneratorfunction(v):
l.append(v()) # call it
return l