aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorPatrick Lehmann <Patrick.Lehmann@plc2.de>2021-06-22 19:04:55 +0200
committerGitHub <noreply@github.com>2021-06-22 19:04:55 +0200
commit983236ac3dfd0c455a0ac910a9a468ea2c81e5d9 (patch)
tree2cc031d1ee5e38edc4897691a3d7029b7125c4aa
parentbcd26f428e704eef5ef665bea7448f3990b5e010 (diff)
parent79d7e4f88b5ea170386628e3d2d00a1bd9634154 (diff)
downloadghdl-983236ac3dfd0c455a0ac910a9a468ea2c81e5d9.tar.gz
ghdl-983236ac3dfd0c455a0ac910a9a468ea2c81e5d9.tar.bz2
ghdl-983236ac3dfd0c455a0ac910a9a468ea2c81e5d9.zip
Fix Codacy issues
-rwxr-xr-xlibraries/openieee/build_1164.py500
-rwxr-xr-xlibraries/openieee/build_numeric.py606
-rw-r--r--pyGHDL/dom/NonStandard.py1
-rw-r--r--pyGHDL/dom/_Utils.py2
-rw-r--r--pyGHDL/libghdl/__init__.py2
-rw-r--r--pyGHDL/libghdl/errorout.py3
-rw-r--r--pyGHDL/libghdl/std_names.py2
-rw-r--r--pyGHDL/libghdl/utils.py1
-rw-r--r--pyGHDL/libghdl/vhdl/elocations.py2
-rw-r--r--pyGHDL/libghdl/vhdl/nodes.py1
-rw-r--r--pyGHDL/libghdl/vhdl/nodes_meta.py1
-rw-r--r--pyGHDL/lsp/lsp.py2
-rw-r--r--pyGHDL/lsp/workspace.py14
-rwxr-xr-xscripts/pnodespy.py23
-rw-r--r--testsuite/gna/issue43/run.py12
-rw-r--r--testsuite/pyunit/libghdl/Initialize.py4
-rw-r--r--testsuite/pyunit/lsp/LanguageServer.py3
17 files changed, 729 insertions, 450 deletions
diff --git a/libraries/openieee/build_1164.py b/libraries/openieee/build_1164.py
index 40a7ba7e2..ed151dd64 100755
--- a/libraries/openieee/build_1164.py
+++ b/libraries/openieee/build_1164.py
@@ -20,123 +20,159 @@
import sys
# Supported versions
-V87=0
-V93=1
-V08=2
+V87 = 0
+V93 = 1
+V08 = 2
-binary_funcs = [ "and", "nand", "or", "nor", "xor" ]
+binary_funcs = ["and", "nand", "or", "nor", "xor"]
# Python modelisation of std_ulogic type.
std_logic = "UX01ZWLH-"
# Normalization map.
-ux01_map = { 'U': 'U',
- 'X': 'X', 'Z': 'X', 'W': 'X', '-': 'X',
- '0': '0', 'L': '0',
- '1': '1', 'H': '1' }
-
-def sl_and(a,b):
- """and definition"""
+ux01_map = {
+ "U": "U",
+ "X": "X",
+ "Z": "X",
+ "W": "X",
+ "-": "X",
+ "0": "0",
+ "L": "0",
+ "1": "1",
+ "H": "1",
+}
+
+
+def sl_and(a, b):
+ """'and' definition."""
na = ux01_map[a]
nb = ux01_map[b]
- if na == '0' or nb == '0':
- return '0'
- if na == 'U' or nb == 'U':
- return 'U'
- if na == 'X' or nb == 'X':
- return 'X'
- return '1'
+ if na == "0" or nb == "0":
+ return "0"
+ if na == "U" or nb == "U":
+ return "U"
+ if na == "X" or nb == "X":
+ return "X"
+ return "1"
+
def sl_not(a):
- """not definition"""
+ """'not' definition."""
na = ux01_map[a]
- if na == 'U':
- return 'U'
- if na == 'X':
- return 'X'
- if na == '1':
- return '0'
+ if na == "U":
+ return "U"
+ if na == "X":
+ return "X"
+ if na == "1":
+ return "0"
else:
- return '1'
+ return "1"
+
+
+def sl_or(a, b):
+ """'or' definition."""
+ return sl_not(sl_and(sl_not(a), sl_not(b)))
+
-def sl_or(a,b):
- "or definition"
- return sl_not(sl_and (sl_not(a), sl_not(b)))
+def sl_xor(a, b):
+ """'xor' definition."""
+ return sl_or(sl_and(a, sl_not(b)), sl_and(sl_not(a), b))
-def sl_xor(a,b):
- "xor definition"
- return sl_or(sl_and(a, sl_not(b)),
- sl_and(sl_not(a), b))
# Stream to write.
-out=sys.stdout
+out = sys.stdout
+
def w(s):
- "Write S to the output"
+ """Write S to the output."""
out.write(s)
+
def gen_log_table2(name, func):
- "Generate a logic table for binary operator NAME using its model FUNC"
- w("""
+ """Generate a logic table for binary operator NAME using its model FUNC."""
+ w(
+ """
constant {0}_table : table_2d :=
-- UX01ZWLH-
- (""".format(name))
+ (""".format(
+ name
+ )
+ )
for a in std_logic:
w('"')
for b in std_logic:
- w(func (a, b))
+ w(func(a, b))
w('"')
- if a != '-':
- w(',')
+ if a != "-":
+ w(",")
else:
- w(' ')
- w(' -- {}\n'.format(a))
- w(' ')
- w(');\n')
+ w(" ")
+ w(" -- {}\n".format(a))
+ w(" ")
+ w(");\n")
+
def gen_log_table1(name, func):
- "Generate a logic table for unary operator NAME using its model FUNC"
- w("""
+ """Generate a logic table for unary operator NAME using its model FUNC."""
+ w(
+ """
constant {0}_table : table_1d :=
-- UX01ZWLH-
- """.format(name))
+ """.format(
+ name
+ )
+ )
w('"')
for b in std_logic:
- w(func (b))
+ w(func(b))
w('";\n')
+
def disp_tables(version):
- "Generate logic tables"
+ """Generate logic tables."""
gen_log_table2("and", sl_and)
- gen_log_table2("nand", lambda a,b : sl_not(sl_and(a, b)))
+ gen_log_table2("nand", lambda a, b: sl_not(sl_and(a, b)))
gen_log_table2("or", sl_or)
- gen_log_table2("nor", lambda a,b : sl_not(sl_or(a,b)))
+ gen_log_table2("nor", lambda a, b: sl_not(sl_or(a, b)))
gen_log_table2("xor", sl_xor)
if version >= V93:
- gen_log_table2("xnor", lambda a,b : sl_not(sl_xor(a,b)))
+ gen_log_table2("xnor", lambda a, b: sl_not(sl_xor(a, b)))
gen_log_table1("not", sl_not)
-vec_types = ['ulogic', 'logic']
+
+vec_types = ["ulogic", "logic"]
+
def disp_scalar_binary(fun):
- "Generate scalar binary function body"
- w("""
+ """Generate scalar binary function body."""
+ w(
+ """
function "{0}" (l : std_ulogic; r : std_ulogic) return UX01 is
begin
return {0}_table (l, r);
- end "{0}";\n""".format(fun))
+ end "{0}";\n""".format(
+ fun
+ )
+ )
+
def disp_scalar_unary(fun):
- "Generate scalar unary function body"
- w("""
+ """Generate scalar unary function body."""
+ w(
+ """
function "{0}" (l : std_ulogic) return UX01 is
begin
return {0}_table (l);
- end "{0}";\n""".format(fun))
+ end "{0}";\n""".format(
+ fun
+ )
+ )
+
def disp_vec_binary(func, typ):
- "Generate vector binary function body"
- w("""
+ """Generate vector binary function body."""
+ w(
+ """
function "{0}" (l, r : std_{1}_vector) return std_{1}_vector
is
subtype res_type is std_{1}_vector (1 to l'length);
@@ -154,11 +190,16 @@ def disp_vec_binary(func, typ):
end loop;
end if;
return res;
- end "{0}";\n""".format(func, typ))
+ end "{0}";\n""".format(
+ func, typ
+ )
+ )
+
def disp_vec_unary(func, typ):
- "Generate vector unary function body"
- w("""
+ """Generate vector unary function body."""
+ w(
+ """
function "{0}" (l : std_{1}_vector) return std_{1}_vector
is
subtype res_type is std_{1}_vector (1 to l'length);
@@ -169,11 +210,16 @@ def disp_vec_unary(func, typ):
res (I) := {0}_table (la (I));
end loop;
return res;
- end "{0}";\n""".format(func, typ))
+ end "{0}";\n""".format(
+ func, typ
+ )
+ )
+
def disp_scal_vec_binary(func, typ):
- "Generate scalar-vector binary function body"
- w("""
+ """Generate scalar-vector binary function body."""
+ w(
+ """
function "{0}" (l : std_{1}_vector; r : std_{1})
return std_{1}_vector
is
@@ -185,11 +231,16 @@ def disp_scal_vec_binary(func, typ):
res (I) := {0}_table (la (I), r);
end loop;
return res;
- end "{0}";\n""".format(func, typ))
+ end "{0}";\n""".format(
+ func, typ
+ )
+ )
+
def disp_vec_scal_binary(func, typ):
- "Generate vector-scalar binary function body"
- w("""
+ """Generate vector-scalar binary function body."""
+ w(
+ """
function "{0}" (l : std_{1}; r : std_{1}_vector)
return std_{1}_vector
is
@@ -201,12 +252,17 @@ def disp_vec_scal_binary(func, typ):
res (I) := {0}_table (l, ra (I));
end loop;
return res;
- end "{0}";\n""".format(func, typ))
+ end "{0}";\n""".format(
+ func, typ
+ )
+ )
+
def disp_vec_reduction(func, typ):
- "Generate reduction function body"
- init = '1' if func in ['and', 'nand'] else '0'
- w("""
+ """Generate reduction function body."""
+ init = "1" if func in ["and", "nand"] else "0"
+ w(
+ """
function "{0}" (l : std_{1}_vector) return std_{1}
is
variable res : std_{1} := '{2}';
@@ -215,7 +271,11 @@ def disp_vec_reduction(func, typ):
res := {0}_table (l(I), res);
end loop;
return res;
- end "{0}";\n""".format(func, typ, init))
+ end "{0}";\n""".format(
+ func, typ, init
+ )
+ )
+
def gen_shift(is_left, plus, minus):
if is_left:
@@ -224,9 +284,11 @@ def gen_shift(is_left, plus, minus):
s = "res (1 {0} r to res'right) := la (1 to l'length {1} r);\n"
w(" " + s.format(plus, minus))
+
def disp_shift_funcs(func, typ):
- "Generate shift functions"
- w("""
+ """Generate shift functions."""
+ w(
+ """
function "{0}" (l : std_{1}_vector; r : integer)
return std_{1}_vector
is
@@ -234,29 +296,43 @@ def disp_shift_funcs(func, typ):
alias la : res_type is l;
variable res : res_type := (others => '0');
begin
- if r >= 0 then\n""".format(func, typ))
- gen_shift(func == "sll", '+', '-')
+ if r >= 0 then\n""".format(
+ func, typ
+ )
+ )
+ gen_shift(func == "sll", "+", "-")
w(" else\n")
- gen_shift(func != "sll", '-', '+')
- w(""" end if;
+ gen_shift(func != "sll", "-", "+")
+ w(
+ """ end if;
return res;
- end "{0}";\n""".format(func))
+ end "{0}";\n""".format(
+ func
+ )
+ )
+
def gen_rot(is_left, plus, minus):
if is_left:
- t = ["res (1 to res'right {1} rm) := la (rm {0} 1 to la'right);",
- "res (res'right {1} rm + 1 to res'right) := la (1 to rm);"]
+ t = [
+ "res (1 to res'right {1} rm) := la (rm {0} 1 to la'right);",
+ "res (res'right {1} rm + 1 to res'right) := la (1 to rm);",
+ ]
else:
- t = ["res (1 {0} rm to res'right) := la (1 to la'right {1} r);",
- "res (1 to rm) := la (la'right {1} rm + 1 to la'right);"]
+ t = [
+ "res (1 {0} rm to res'right) := la (1 to la'right {1} r);",
+ "res (1 to rm) := la (la'right {1} rm + 1 to la'right);",
+ ]
for s in t:
w(" ")
w(s.format(plus, minus))
- w('\n')
+ w("\n")
+
def disp_rot_funcs(func, typ):
- "Generate rotation functions"
- w("""
+ """Generate rotation functions."""
+ w(
+ """
function "{0}" (l : std_{1}_vector; r : integer)
return std_{1}_vector
is
@@ -265,16 +341,24 @@ def disp_rot_funcs(func, typ):
variable res : res_type;
constant rm : integer := r mod l'length;
begin
- if r >= 0 then\n""".format(func, typ))
- gen_rot(func == "rol", '+', '-')
+ if r >= 0 then\n""".format(
+ func, typ
+ )
+ )
+ gen_rot(func == "rol", "+", "-")
w(" else\n")
- gen_rot(func != "rol", '-', '+')
- w(""" end if;
+ gen_rot(func != "rol", "-", "+")
+ w(
+ """ end if;
return res;
- end "{0}";\n""".format(func, typ))
+ end "{0}";\n""".format(
+ func
+ )
+ )
+
def disp_all_log_funcs(version):
- "Generate all function bodies for logic operators"
+ """Generate all function bodies for logic operators."""
for f in binary_funcs:
disp_scalar_binary(f)
disp_scalar_unary("not")
@@ -293,9 +377,11 @@ def disp_all_log_funcs(version):
disp_rot_funcs("rol", v)
disp_rot_funcs("ror", v)
+
def disp_sv_to_bv_conv(typ):
- "Generate logic vector to bit vector function body"
- w("""
+ """Generate logic vector to bit vector function body."""
+ w(
+ """
function to_bitvector (s : std_{0}_vector; xmap : bit := '0')
return bit_vector
is
@@ -317,11 +403,16 @@ def disp_sv_to_bv_conv(typ):
res (I) := b;
end loop;
return res;
- end to_bitvector;\n""".format(typ))
+ end to_bitvector;\n""".format(
+ typ
+ )
+ )
+
def disp_bv_to_sv_conv(typ):
- "Generate bit vector to logic vector function body"
- w("""
+ """Generate bit vector to logic vector function body."""
+ w(
+ """
function to_std{0}vector (b : bit_vector) return std_{0}_vector is
subtype res_range is natural range b'length - 1 downto 0;
alias ab : bit_vector (res_range) is b;
@@ -331,33 +422,44 @@ def disp_bv_to_sv_conv(typ):
res (I) := bit_to_std (ab (I));
end loop;
return res;
- end to_std{0}vector;\n""".format(typ))
+ end to_std{0}vector;\n""".format(
+ typ
+ )
+ )
+
-def disp_sv_to_sv_conv(s,d):
- "Generate logic vector to logic vector function body"
- w("""
+def disp_sv_to_sv_conv(s, d):
+ """Generate logic vector to logic vector function body."""
+ w(
+ """
function to_std{1}vector (s : std_{0}_vector) return std_{1}_vector
is
subtype res_type is std_{1}_vector (s'length - 1 downto 0);
begin
return res_type (s);
- end to_std{1}vector;\n""".format(s,d))
+ end to_std{1}vector;\n""".format(
+ s, d
+ )
+ )
+
def disp_all_conv_funcs(version):
- "Generate conversion function bodies"
+ """Generate conversion function bodies."""
for v in vec_types:
disp_sv_to_bv_conv(v)
for v in vec_types:
disp_bv_to_sv_conv(v)
if version >= V08:
- disp_bv_to_sv_conv('logic')
- disp_sv_to_sv_conv('logic', 'ulogic')
- disp_sv_to_sv_conv('ulogic', 'logic')
+ disp_bv_to_sv_conv("logic")
+ disp_sv_to_sv_conv("logic", "ulogic")
+ disp_sv_to_sv_conv("ulogic", "logic")
+
def disp_conv_vec_vec(typ, v):
- "Generate function body for vector conversion"
- utyp = typ.upper();
- w("""
+ """Generate function body for vector conversion."""
+ utyp = typ.upper()
+ w(
+ """
function to_{1} (s : std_{2}_vector) return std_{2}_vector
is
subtype res_type is std_{2}_vector (1 to s'length);
@@ -368,21 +470,31 @@ def disp_conv_vec_vec(typ, v):
res (i) := std_to_{0} (sa (i));
end loop;
return res;
- end to_{1};\n""".format(typ, utyp, v))
+ end to_{1};\n""".format(
+ typ, utyp, v
+ )
+ )
+
def disp_conv_std(typ):
- "Generate function body for scalar conversion"
- utyp = typ.upper();
- w("""
+ """Generate function body for scalar conversion."""
+ utyp = typ.upper()
+ w(
+ """
function to_{1} (s : std_ulogic) return {1} is
begin
return std_to_{0} (s);
- end to_{1};\n""".format(typ, utyp))
+ end to_{1};\n""".format(
+ typ, utyp
+ )
+ )
+
def disp_conv_bv_vec(typ, v):
- "Generate function body for bit vector conversion"
- utyp = typ.upper();
- w("""
+ """Generate function body for bit vector conversion."""
+ utyp = typ.upper()
+ w(
+ """
function to_{0} (b : bit_vector) return std_{1}_vector
is
subtype res_range is natural range 1 to b'length;
@@ -393,20 +505,29 @@ def disp_conv_bv_vec(typ, v):
res (i) := bit_to_x01 (ba (i));
end loop;
return res;
- end to_{0};\n""".format(utyp, v))
+ end to_{0};\n""".format(
+ utyp, v
+ )
+ )
+
def disp_conv_b_t(typ):
- "Generate function body for bit conversion"
- utyp = typ.upper();
- w("""
- function to_{1} (b : bit) return {1} is
+ """Generate function body for bit conversion."""
+ w(
+ """
+ function to_{0} (b : bit) return {0} is
begin
return bit_to_x01 (b);
- end to_{1};\n""".format(typ, utyp))
+ end to_{0};\n""".format(
+ typ.upper()
+ )
+ )
+
def disp_conv_01():
- "Generate to_01 bodies"
- w("""
+ """Generate to_01 bodies."""
+ w(
+ """
function to_01 (s : std_{0}_vector; xmap : std_ulogic := '0')
return std_{0}_vector
is
@@ -422,9 +543,13 @@ def disp_conv_01():
end case;
end loop;
return res;
- end to_01;\n""".format("ulogic"))
+ end to_01;\n""".format(
+ "ulogic"
+ )
+ )
w("")
- w("""
+ w(
+ """
function to_01 (s : std_{0}; xmap : std_ulogic := '0')
return std_{0} is
begin
@@ -433,9 +558,13 @@ def disp_conv_01():
when '1' | 'H' => return '1';
when others => return xmap;
end case;
- end to_01;\n""".format("ulogic"))
+ end to_01;\n""".format(
+ "ulogic"
+ )
+ )
w("")
- w("""
+ w(
+ """
function to_01 (s : bit_vector; xmap : std_ulogic := '0')
return std_{0}_vector
is
@@ -446,40 +575,53 @@ def disp_conv_01():
res (i) := bit_to_std (sa (i));
end loop;
return res;
- end to_01;\n""".format("ulogic"))
+ end to_01;\n""".format(
+ "ulogic"
+ )
+ )
w("")
- w("""
+ w(
+ """
function to_01 (s : bit; xmap : std_ulogic := '0')
return std_{0} is
begin
return bit_to_std(s);
- end to_01;\n""".format("ulogic"))
+ end to_01;\n""".format(
+ "ulogic"
+ )
+ )
+
def disp_cond():
- w("""
+ w(
+ """
function "??" (l : std_ulogic) return boolean is
begin
return l = '1' or l = 'H';
- end "??";\n""")
+ end "??";\n"""
+ )
+
def disp_all_norm_funcs(version):
- "Generate all function bodies for conversion"
+ """Generate all function bodies for conversion."""
if version >= V08:
disp_conv_01()
- for typ in [ "x01", "x01z", "ux01" ]:
+ for typ in ["x01", "x01z", "ux01"]:
for v in vec_types:
disp_conv_vec_vec(typ, v)
- disp_conv_std (typ)
+ disp_conv_std(typ)
for v in vec_types:
disp_conv_bv_vec(typ, v)
disp_conv_b_t(typ)
if version >= V08:
disp_cond()
+
def disp_all_isx_funcs(version):
- "Generate all function bodies for isx functions"
+ """Generate all function bodies for isx functions."""
for v in vec_types:
- w("""
+ w(
+ """
function is_X (s : std_{0}_vector) return boolean is
begin
for i in s'range loop
@@ -488,49 +630,61 @@ def disp_all_isx_funcs(version):
end if;
end loop;
return false;
- end is_X;\n""".format(v))
+ end is_X;\n""".format(
+ v
+ )
+ )
- w("""
+ w(
+ """
function is_X (s : std_ulogic) return boolean is
begin
return std_x (s);
- end is_X;\n""")
+ end is_X;\n"""
+ )
# Patterns to replace
-pats = {' @TAB\n' : disp_tables,
- ' @LOG\n' : disp_all_log_funcs,
- ' @CONV\n': disp_all_conv_funcs,
- ' @NORM\n': disp_all_norm_funcs,
- ' @ISX\n' : disp_all_isx_funcs }
+pats = {
+ " @TAB\n": disp_tables,
+ " @LOG\n": disp_all_log_funcs,
+ " @CONV\n": disp_all_conv_funcs,
+ " @NORM\n": disp_all_norm_funcs,
+ " @ISX\n": disp_all_isx_funcs,
+}
+
+spec_file = "std_logic_1164.proto"
+proto_file = "std_logic_1164-body.proto"
-spec_file='std_logic_1164.proto'
-proto_file='std_logic_1164-body.proto'
def gen_body(filename, version):
global out
- out = open(filename, 'w')
- w('-- This -*- vhdl -*- file was generated from ' + proto_file + '\n')
+ out = open(filename, "w")
+ w("-- This -*- vhdl -*- file was generated from " + proto_file + "\n")
keep = True
for line in open(proto_file):
if line in pats:
pats[line](version)
continue
- if line == ' @BEG V08\n':
- keep = (version == V08)
+ if line == " @BEG V08\n":
+ keep = version == V08
continue
- if line == ' @END V08\n':
+ if line == " @END V08\n":
keep = True
continue
if keep:
w(line)
out.close()
-VDICT={'--V87': lambda x: x == V87,
- '--!V87': lambda x: x != V87,
- '--V93': lambda x: x == V93,
- '--V08': lambda x: x == V08,
- '--!V08': lambda x: x != V08}
+
+VDICT = {
+ "--V87": lambda x: x == V87,
+ "--!V87": lambda x: x != V87,
+ "--V93": lambda x: x == V93,
+ "--V08": lambda x: x == V08,
+ "--!V08": lambda x: x != V08,
+}
+
def preprocess_line(line, version):
for p in VDICT:
@@ -538,28 +692,30 @@ def preprocess_line(line, version):
if pos >= 0:
if not VDICT[p](version):
return None
- l = line[:pos].rstrip() + '\n'
+ l = line[:pos].rstrip() + "\n"
return l
return line
+
def copy_spec(dest, version):
- out=open(dest, 'w')
+ out = open(dest, "w")
for line in open(spec_file):
l = preprocess_line(line, version)
if l is not None:
out.write(l)
out.close()
+
# Copy spec
-copy_spec('v87/std_logic_1164.vhdl', V87)
-copy_spec('v93/std_logic_1164.vhdl', V93)
-copy_spec('v08/std_logic_1164.vhdl', V08)
+copy_spec("v87/std_logic_1164.vhdl", V87)
+copy_spec("v93/std_logic_1164.vhdl", V93)
+copy_spec("v08/std_logic_1164.vhdl", V08)
# Generate bodies
-gen_body('v87/std_logic_1164-body.vhdl', V87)
+gen_body("v87/std_logic_1164-body.vhdl", V87)
binary_funcs.append("xnor")
-gen_body('v93/std_logic_1164-body.vhdl', V93)
+gen_body("v93/std_logic_1164-body.vhdl", V93)
-vec_types = ['ulogic']
-gen_body('v08/std_logic_1164-body.vhdl', V08)
+vec_types = ["ulogic"]
+gen_body("v08/std_logic_1164-body.vhdl", V08)
diff --git a/libraries/openieee/build_numeric.py b/libraries/openieee/build_numeric.py
index df6c8515f..53700dc42 100755
--- a/libraries/openieee/build_numeric.py
+++ b/libraries/openieee/build_numeric.py
@@ -21,40 +21,44 @@
# along with GHDL; see the file COPYING.md. If not see
# <http://www.gnu.org/licenses/>.
-import re
import sys
# My python 'style' and knowledge is basic... Do not hesitate to comment.
-binary_funcs = [ "and", "nand", "or", "nor", "xor" ]
-compare_funcs = [ "=", "/=", ">", ">=", "<", "<=" ]
+binary_funcs = ["and", "nand", "or", "nor", "xor"]
+compare_funcs = ["=", "/=", ">", ">=", "<", "<="]
-vec_types = ['UNSIGNED', 'SIGNED']
+vec_types = ["UNSIGNED", "SIGNED"]
-logics = ['bit', 'std']
-logic_types = {'bit' : 'bit', 'std': 'sl_x01' }
-logic_undefs = {'bit' : "'0'", 'std': "'X'" }
+logics = ["bit", "std"]
+logic_types = {"bit": "bit", "std": "sl_x01"}
+logic_undefs = {"bit": "'0'", "std": "'X'"}
-logic = 'xx' # Current logic, either bit or std
+logic = "xx" # Current logic, either bit or std
-v93=False
+v93 = False
# Stream to write.
-out=sys.stdout
+out = sys.stdout
+
def w(s):
- "Write S to the output"
+ """Write S to the output."""
out.write(s)
+
def logic_type():
return logic_types[logic]
+
def logic_undef():
return logic_undefs[logic]
+
def disp_vec_binary(func, typ):
- "Generate the body of a vector binary logic function"
- res = """
+ """Generate the body of a vector binary logic function."""
+ res = (
+ """
function "{0}" (l, r : {1}) return {1}
is
subtype res_type is {1} (l'length - 1 downto 0);
@@ -66,7 +70,9 @@ def disp_vec_binary(func, typ):
assert false
report "NUMERIC_STD.""{0}"": arguments are not of the same length"
severity failure;
- res := (others => """ + logic_undef() + """);
+ res := (others => """
+ + logic_undef()
+ + """);
else
for I in res_type'range loop
res (I) := la (I) {0} ra (I);
@@ -74,49 +80,63 @@ def disp_vec_binary(func, typ):
end if;
return res;
end "{0}";\n"""
- w (res.format(func, typ))
+ )
+ w(res.format(func, typ))
+
def disp_non_logical_warning(func):
return """
assert NO_WARNING
report "NUMERIC_STD.""{0}"": non logical value detected"
- severity warning;""".format(func)
+ severity warning;""".format(
+ func
+ )
+
def conv_bit(expr):
- if logic == 'std':
+ if logic == "std":
return "sl_to_x01 (" + expr + ")"
else:
return expr
+
def extract_bit(name):
- res = "{0}b := " + conv_bit ("{0}a (i)") + ";"
+ res = "{0}b := " + conv_bit("{0}a (i)") + ";"
return res.format(name)
+
def init_carry(func):
- if func == '+':
+ if func == "+":
return """
carry := '0';"""
else:
return """
carry := '1';"""
-def extract_extend_bit(name,typ):
+
+def extract_extend_bit(name, typ):
res = """
if i > {0}a'left then
{0}b := """
- if typ == 'UNSIGNED':
+ if typ == "UNSIGNED":
res += "'0';"
else:
res += "{0} ({0}'left);"
- res += """
+ res += (
+ """
else
- """ + extract_bit(name) + """
+ """
+ + extract_bit(name)
+ + """
end if;"""
+ )
return res.format(name)
+
def disp_vec_vec_binary(func, typ):
- "Generate vector binary function body"
- res = """
+ """Generate vector binary function body."""
+ res = (
+ """
function "{0}" (l, r : {1}) return {1}
is
constant lft : integer := MAX (l'length, r'length) - 1;
@@ -124,27 +144,33 @@ def disp_vec_vec_binary(func, typ):
alias la : {1} (l'length - 1 downto 0) is l;
alias ra : {1} (r'length - 1 downto 0) is r;
variable res : res_type;
- variable lb, rb, carry : """ + logic_type () + """;
+ variable lb, rb, carry : """
+ + logic_type()
+ + """;
begin
if la'left < 0 or ra'left < 0 then
return null_{1};
end if;"""
+ )
res += init_carry(func)
res += """
for i in 0 to lft loop"""
- res += extract_extend_bit('l', typ)
- res += extract_extend_bit('r', typ)
-
- if logic == 'std':
- res += """
- if lb = 'X' or rb = 'X' then""" + \
- disp_non_logical_warning(func) + """
+ res += extract_extend_bit("l", typ)
+ res += extract_extend_bit("r", typ)
+
+ if logic == "std":
+ res += (
+ """
+ if lb = 'X' or rb = 'X' then"""
+ + disp_non_logical_warning(func)
+ + """
res := (others => 'X');
exit;
end if;"""
- if func == '-':
+ )
+ if func == "-":
res += """
rb := not rb;"""
res += """
@@ -154,20 +180,25 @@ def disp_vec_vec_binary(func, typ):
return res;
end "{0}";
"""
- w (res.format (func, typ))
+ w(res.format(func, typ))
+
def declare_int_var(name, typ):
res = """
variable {0}1, {0}2 : {1};
- variable {0}d : nat1;""";
+ variable {0}d : nat1;"""
if typ == "INTEGER":
res += """
constant {0}msb : nat1 := boolean'pos({0} < 0);"""
return res.format(name, typ)
+
def init_int_var(name, typ):
return """
- {0}1 := {0};""".format(name);
+ {0}1 := {0};""".format(
+ name
+ )
+
def extract_int_lsb(name, typ):
res = """
@@ -187,7 +218,8 @@ def extract_int_lsb(name, typ):
{0}1 := {0}2;"""
res += """
{0}b := nat1_to_01 ({0}d);"""
- return res.format(name,typ)
+ return res.format(name, typ)
+
def check_int_truncated(func, name, typ):
if typ == "INTEGER":
@@ -199,92 +231,109 @@ def check_int_truncated(func, name, typ):
assert NO_WARNING
report "NUMERIC_STD.""{0}"": vector is truncated"
severity warning;
- end if;""".format(func, name, v)
+ end if;""".format(
+ func, name, v
+ )
+
def create_vec_int_dict(func, left, right):
if left in vec_types:
- dic = {'vtype': left,
- 'itype': right,
- 'vparam': 'l',
- 'iparam': 'r'}
+ dic = {"vtype": left, "itype": right, "vparam": "l", "iparam": "r"}
else:
- dic = {'vtype': right,
- 'itype': left,
- 'vparam': 'r',
- 'iparam': 'l'}
- dic.update({'ltype': left,
- 'rtype': right,
- 'func': func,
- 'logic': logic_type()})
+ dic = {"vtype": right, "itype": left, "vparam": "r", "iparam": "l"}
+ dic.update({"ltype": left, "rtype": right, "func": func, "logic": logic_type()})
return dic
+
def disp_vec_int_binary(func, left, right):
- "Generate vector binary function body"
+ """Generate vector binary function body."""
dic = create_vec_int_dict(func, left, right)
- res = """
+ res = (
+ """
function "{func}" (l : {ltype}; r : {rtype}) return {vtype}
is
subtype res_type is {vtype} ({vparam}'length - 1 downto 0);
- alias {vparam}a : res_type is {vparam};""" + \
- declare_int_var (dic["iparam"], dic["itype"]) + """
+ alias {vparam}a : res_type is {vparam};"""
+ + declare_int_var(dic["iparam"], dic["itype"])
+ + """
variable res : res_type;
variable lb, rb, carry : {logic};
begin
if res'length < 0 then
return null_{vtype};
end if;"""
+ )
# Initialize carry. For subtraction, use 2-complement.
res += init_carry(func)
- res += init_int_var(dic['iparam'], dic['itype']) + """
+ res += (
+ init_int_var(dic["iparam"], dic["itype"])
+ + """
for i in res'reverse_range loop
- """ + extract_bit(dic['vparam']) + "\n" + \
- extract_int_lsb(dic['iparam'], dic['itype']);
-
- if logic == 'std':
- res += """
- if {vparam}b = 'X' then""" + \
- disp_non_logical_warning(func) + """
+ """
+ + extract_bit(dic["vparam"])
+ + "\n"
+ + extract_int_lsb(dic["iparam"], dic["itype"])
+ )
+
+ if logic == "std":
+ res += (
+ """
+ if {vparam}b = 'X' then"""
+ + disp_non_logical_warning(func)
+ + """
res := (others => 'X');
{iparam}1 := 0;
exit;
end if;"""
+ )
# 2-complement for subtraction
- if func == '-':
+ if func == "-":
res += """
rb := not rb;"""
- res += """
+ res += (
+ """
res (i) := compute_sum (carry, rb, lb);
carry := compute_carry (carry, rb, lb);
- end loop;""" + \
- check_int_truncated(func, dic['iparam'], dic['itype']) + """
+ end loop;"""
+ + check_int_truncated(func, dic["iparam"], dic["itype"])
+ + """
return res;
end "{func}";\n"""
- w(res.format (**dic))
+ )
+ w(res.format(**dic))
+
def disp_vec_int_gcompare(func, left, right):
- "Generate comparison function"
+ """Generate comparison function."""
dic = create_vec_int_dict(func, left, right)
- res = """
+ res = (
+ """
function {func} (l : {ltype}; r : {rtype}) return compare_type
is
subtype res_type is {vtype} ({vparam}'length - 1 downto 0);
- alias la : res_type is l;""" + \
- declare_int_var (dic['iparam'], dic['itype']) + """
+ alias la : res_type is l;"""
+ + declare_int_var(dic["iparam"], dic["itype"])
+ + """
variable lb, rb : {logic};
variable res : compare_type;
begin
- res := compare_eq;""";
+ res := compare_eq;"""
+ )
- res += init_int_var(dic['iparam'], dic['itype']) + """
+ res += (
+ init_int_var(dic["iparam"], dic["itype"])
+ + """
for i in {vparam}a'reverse_range loop
- """ + extract_bit (dic['vparam']) + \
- extract_int_lsb("r", right)
+ """
+ + extract_bit(dic["vparam"])
+ + extract_int_lsb("r", right)
+ )
- if logic == 'std':
+ if logic == "std":
res += """
if {vparam}b = 'X' then
return compare_unknown;
@@ -303,8 +352,11 @@ def disp_vec_int_gcompare(func, left, right):
res := compare_lt;
end if;"""
else:
- res += """
- if """ + conv_bit ("l (l'left)") + """ = '1' then
+ res += (
+ """
+ if """
+ + conv_bit("l (l'left)")
+ + """ = '1' then
if r >= 0 then
res := compare_lt;
end if;
@@ -313,21 +365,25 @@ def disp_vec_int_gcompare(func, left, right):
res := compare_gt;
end if;
end if;"""
+ )
res += """
return res;
end {func};
"""
- w(res.format (**dic))
+ w(res.format(**dic))
+
def disp_vec_int_compare(func, left, right):
- "Generate comparison function"
+ """Generate comparison function."""
dic = create_vec_int_dict(func, left, right)
- res = """
+ res = (
+ """
function "{func}" (l : {ltype}; r : {rtype}) return boolean
is
subtype res_type is {vtype} ({vparam}'length - 1 downto 0);
- alias {vparam}a : res_type is {vparam};""" + \
- declare_int_var (dic['iparam'], dic['itype']) + """
+ alias {vparam}a : res_type is {vparam};"""
+ + declare_int_var(dic["iparam"], dic["itype"])
+ + """
variable res : compare_type;
begin
if {vparam}'length = 0 then
@@ -338,6 +394,7 @@ def disp_vec_int_compare(func, left, right):
end if;
res := """
+ )
if left == "SIGNED" or right == "SIGNED":
res += "scompare"
@@ -347,12 +404,15 @@ def disp_vec_int_compare(func, left, right):
res += " (l, r);"
else:
res += " (r, l);"
- if logic == 'std':
- res += """
- if res = compare_unknown then""" + \
- disp_non_logical_warning(func) + """
+ if logic == "std":
+ res += (
+ """
+ if res = compare_unknown then"""
+ + disp_non_logical_warning(func)
+ + """
return false;
end if;"""
+ )
if left in vec_types:
res += """
@@ -363,10 +423,11 @@ def disp_vec_int_compare(func, left, right):
res += """
end "{func}";
"""
- w(res.format (**dic))
+ w(res.format(**dic))
+
def disp_vec_vec_gcompare(func, typ):
- "Generate comparison function"
+ """Generate comparison function."""
res = """
function {func} (l, r : {typ}) return compare_type
is
@@ -376,11 +437,16 @@ def disp_vec_vec_gcompare(func, typ):
variable lb, rb : {logic};
variable res : compare_type;
begin"""
- if typ == 'SIGNED':
- res += """
+ if typ == "SIGNED":
+ res += (
+ """
-- Consider sign bit as S * -(2**N).
- lb := """ + conv_bit ("la (la'left)") + """;
- rb := """ + conv_bit ("ra (ra'left)") + """;
+ lb := """
+ + conv_bit("la (la'left)")
+ + """;
+ rb := """
+ + conv_bit("ra (ra'left)")
+ + """;
if lb = '1' and rb = '0' then
return compare_lt;
elsif lb = '0' and rb = '1' then
@@ -388,18 +454,19 @@ def disp_vec_vec_gcompare(func, typ):
else
res := compare_eq;
end if;"""
+ )
else:
res += """
res := compare_eq;"""
- if typ == 'SIGNED':
+ if typ == "SIGNED":
res += """
for i in 0 to sz - 1 loop"""
else:
res += """
for i in 0 to sz loop"""
- res += extract_extend_bit('l', typ)
- res += extract_extend_bit('r', typ)
- if logic == 'std':
+ res += extract_extend_bit("l", typ)
+ res += extract_extend_bit("r", typ)
+ if logic == "std":
res += """
if lb = 'X' or rb = 'X' then
return compare_unknown;
@@ -415,10 +482,11 @@ def disp_vec_vec_gcompare(func, typ):
return res;
end {func};\n"""
- w(res.format (func=func, typ=typ, logic=logic_type()))
+ w(res.format(func=func, typ=typ, logic=logic_type()))
+
def disp_vec_vec_compare(func, typ):
- "Generate comparison function"
+ """Generate comparison function."""
res = """
function "{func}" (l, r : {typ}) return boolean
is
@@ -438,21 +506,26 @@ def disp_vec_vec_compare(func, typ):
res += "ucompare"
res += """ (l, r);"""
- if logic == 'std':
- res += """
- if res = compare_unknown then""" + \
- disp_non_logical_warning(func) + """
+ if logic == "std":
+ res += (
+ """
+ if res = compare_unknown then"""
+ + disp_non_logical_warning(func)
+ + """
return false;
end if;"""
+ )
res += """
return res {func} compare_eq;
end "{func}";\n"""
- w(res.format (func=func, typ=typ))
+ w(res.format(func=func, typ=typ))
+
def disp_vec_not(typ):
- "Generate vector binary function body"
- w("""
+ """Generate vector binary function body."""
+ w(
+ """
function "not" (l : {0}) return {0}
is
subtype res_type is {0} (l'length - 1 downto 0);
@@ -463,7 +536,11 @@ def disp_vec_not(typ):
res (I) := not la (I);
end loop;
return res;
- end "not";\n""".format(typ))
+ end "not";\n""".format(
+ typ
+ )
+ )
+
def disp_resize(typ):
res = """
@@ -480,7 +557,7 @@ def disp_resize(typ):
end if;
if arg1'length > new_size then
-- Reduction."""
- if typ == 'SIGNED':
+ if typ == "SIGNED":
res += """
res (res'left) := arg1 (arg1'left);
res (res'left - 1 downto 0) := arg1 (res'left - 1 downto 0);"""
@@ -491,7 +568,7 @@ def disp_resize(typ):
else
-- Expansion
res (arg1'range) := arg1;"""
- if typ == 'SIGNED':
+ if typ == "SIGNED":
res += """
res (res'left downto arg1'length) := (others => arg1 (arg1'left));"""
res += """
@@ -500,8 +577,9 @@ def disp_resize(typ):
end resize;\n"""
w(res.format(typ))
+
def gen_shift(dir, inv):
- if (dir == 'left') ^ inv:
+ if (dir == "left") ^ inv:
res = """
res (res'left downto {opp}count) := arg1 (arg1'left {sub} count downto 0);"""
else:
@@ -512,6 +590,7 @@ def gen_shift(dir, inv):
else:
return res.format(opp="", sub="-")
+
def disp_shift_op(name, typ, dir):
res = """
function {0} (ARG : {1}; COUNT: INTEGER) return {1}
@@ -534,6 +613,7 @@ def disp_shift_op(name, typ, dir):
end {0};\n"""
w(res.format(name, typ))
+
def disp_shift(name, typ, dir):
res = """
function {0} (ARG : {1}; COUNT: NATURAL) return {1}
@@ -541,7 +621,7 @@ def disp_shift(name, typ, dir):
subtype res_type is {1} (ARG'length - 1 downto 0);
alias arg1 : res_type is arg;
variable res : res_type := (others => """
- if typ == 'SIGNED' and dir == 'right':
+ if typ == "SIGNED" and dir == "right":
res += "arg1 (arg1'left)"
else:
res += "'0'"
@@ -558,14 +638,16 @@ def disp_shift(name, typ, dir):
end {0};\n"""
w(res.format(name, typ))
+
def disp_rotate(name, typ, dir):
- if 'rotate' in name:
- count_type = 'natural'
- op = 'rem'
+ if "rotate" in name:
+ count_type = "natural"
+ op = "rem"
else:
- count_type = 'integer'
- op = 'mod'
- res = """
+ count_type = "integer"
+ op = "mod"
+ res = (
+ """
function {0} (ARG : {1}; COUNT: {2}) return {1}
is
subtype res_type is {1} (ARG'length - 1 downto 0);
@@ -576,8 +658,11 @@ def disp_rotate(name, typ, dir):
if res'length = 0 then
return null_{1};
end if;
- cnt := count """ + op + " res'length;"
- if dir == 'left':
+ cnt := count """
+ + op
+ + " res'length;"
+ )
+ if dir == "left":
res += """
res (res'left downto cnt) := arg1 (res'left - cnt downto 0);
res (cnt - 1 downto 0) := arg1 (res'left downto res'left - cnt + 1);"""
@@ -590,24 +675,32 @@ def disp_rotate(name, typ, dir):
end {0};\n"""
w(res.format(name, typ, count_type))
+
def disp_vec_vec_mul(func, typ):
- res = """
+ res = (
+ """
function "{0}" (L, R : {1}) return {1}
is
alias la : {1} (L'Length - 1 downto 0) is l;
alias ra : {1} (R'Length - 1 downto 0) is r;
variable res : {1} (L'length + R'Length -1 downto 0) := (others => '0');
- variable rb, lb, vb, carry : """ + logic_type() + """;
+ variable rb, lb, vb, carry : """
+ + logic_type()
+ + """;
begin
if la'length = 0 or ra'length = 0 then
return null_{1};
end if;
-- Shift and add L.
for i in natural range 0 to ra'left """
- if typ == 'SIGNED':
+ )
+ if typ == "SIGNED":
res += "- 1 "
- res += """loop
- """ + extract_bit ('r') + """
+ res += (
+ """loop
+ """
+ + extract_bit("r")
+ + """
if rb = '1' then
-- Compute res := res + shift_left (l, i).
carry := '0';
@@ -617,7 +710,8 @@ def disp_vec_vec_mul(func, typ):
res (i + j) := compute_sum (carry, vb, lb);
carry := compute_carry (carry, vb, lb);
end loop;"""
- if typ == 'UNSIGNED':
+ )
+ if typ == "UNSIGNED":
res += """
-- Propagate carry.
for j in i + la'length to res'left loop
@@ -635,14 +729,15 @@ def disp_vec_vec_mul(func, typ):
res (j) := compute_sum (carry, vb, lb);
carry := compute_carry (carry, vb, lb);
end loop;"""
- if logic == 'std':
+ if logic == "std":
res += """
- elsif rb = 'X' then""" + \
- disp_non_logical_warning (func)
+ elsif rb = 'X' then""" + disp_non_logical_warning(
+ func
+ )
res += """
end if;
end loop;"""
- if typ == 'SIGNED':
+ if typ == "SIGNED":
res += """
if ra (ra'left) = '1' then
-- R is a negative number. It is considered as:
@@ -662,7 +757,8 @@ def disp_vec_vec_mul(func, typ):
res += """
return res;
end "{0}";\n"""
- w(res.format(func,typ))
+ w(res.format(func, typ))
+
def disp_vec_int_mul(left, right):
res = """
@@ -675,7 +771,8 @@ def disp_vec_int_mul(left, right):
end if;
return l * to_{0} (r, size);
end "*";\n"""
- w (res.format(left,right))
+ w(res.format(left, right))
+
def disp_int_vec_mul(left, right):
res = """
@@ -688,27 +785,35 @@ def disp_int_vec_mul(left, right):
end if;
return r * to_{1} (l, size);
end "*";\n"""
- w (res.format(left,right))
+ w(res.format(left, right))
+
def disp_neg(func):
- res = """
+ res = (
+ """
function "{func}" (ARG : SIGNED) return SIGNED
is
subtype arg_type is SIGNED (ARG'length - 1 downto 0);
alias arga : arg_type is arg;
variable res : arg_type;
- variable carry, a : """ + logic_type() + """;
+ variable carry, a : """
+ + logic_type()
+ + """;
begin
if arga'length = 0 then
return null_signed;
end if;"""
- if logic == 'std':
- res += """
- if has_0x (arga) = 'X' then""" + \
- disp_non_logical_warning("-") + """
+ )
+ if logic == "std":
+ res += (
+ """
+ if has_0x (arga) = 'X' then"""
+ + disp_non_logical_warning("-")
+ + """
return arg_type'(others => 'X');
end if;"""
- if func == 'abs':
+ )
+ if func == "abs":
res += """
if arga (arga'left) = '0' then
return arga;
@@ -724,6 +829,7 @@ def disp_neg(func):
end "{func}";\n"""
w(res.format(func=func))
+
def disp_has_0x(typ):
res = """
function has_0x (a : {0}) return {1}
@@ -731,8 +837,8 @@ def disp_has_0x(typ):
variable res : {1} := '0';
begin
for i in a'range loop"""
- if logic == 'std':
- res += """
+ if logic == "std":
+ res += """
if a (i) = 'X' then
return 'X';
end if;"""
@@ -743,8 +849,10 @@ def disp_has_0x(typ):
end has_0x;\n"""
w(res.format(typ, logic_type()))
+
def disp_size():
- w("""
+ w(
+ """
function size_unsigned (n : natural) return natural
is
-- At least one bit (even for 0).
@@ -756,9 +864,11 @@ def disp_size():
n1 := n1 / 2;
end loop;
return res;
- end size_unsigned;\n""")
+ end size_unsigned;\n"""
+ )
- w("""
+ w(
+ """
function size_signed (n : integer) return natural
is
variable res : natural := 1;
@@ -775,10 +885,13 @@ def disp_size():
n1 := n1 / 2;
end loop;
return res;
- end size_signed;\n""")
+ end size_signed;\n"""
+ )
+
def disp_divmod():
- w("""
+ w(
+ """
-- All index range are normalized (N downto 0).
-- NUM and QUOT have the same range.
-- DEM and REMAIN have the same range.
@@ -788,7 +901,9 @@ def disp_divmod():
-- An extra bit is needed so that it is always possible that DEM >= REG.
variable reg : unsigned (dem'left + 1 downto 0) := (others => '0');
variable sub : unsigned (dem'range) := (others => '0');
- variable carry, d : """ + logic_type () + """;
+ variable carry, d : """
+ + logic_type()
+ + """;
begin
for i in num'range loop
-- Shift to add a new bit from NUM to REG.
@@ -816,10 +931,13 @@ def disp_divmod():
end loop;
remain := reg (dem'range);
end divmod;
-""")
+"""
+ )
+
def disp_vec_vec_udiv(func):
- res = """
+ res = (
+ """
function "{func}" (L, R : UNSIGNED) return UNSIGNED
is
subtype l_type is UNSIGNED (L'length - 1 downto 0);
@@ -828,32 +946,39 @@ def disp_vec_vec_udiv(func):
alias ra : r_type is r;
variable quot : l_type;
variable rema : r_type;
- variable r0 : """ + logic_type() + """ := has_0x (r);
+ variable r0 : """
+ + logic_type()
+ + """ := has_0x (r);
begin
if la'length = 0 or ra'length = 0 then
return null_unsigned;
end if;"""
- if logic == 'std':
- res += """
- if has_0x (l) = 'X' or r0 = 'X' then""" + \
- disp_non_logical_warning ('/') + """
+ )
+ if logic == "std":
+ res += (
+ """
+ if has_0x (l) = 'X' or r0 = 'X' then"""
+ + disp_non_logical_warning("/")
+ + """
return l_type'(others => 'X');
end if;"""
+ )
res += """
assert r0 /= '0'
report "NUMERIC_STD.""{func}"": division by 0"
severity error;
divmod (la, ra, quot, rema);"""
- if func == '/':
- res += """
+ if func == "/":
+ res += """
return quot;"""
else:
- res += """
+ res += """
return rema;"""
res += """
end "{func}";\n"""
w(res.format(func=func))
+
def disp_vec_int_udiv(func):
res = """
function "{func}" (L : UNSIGNED; R : NATURAL) return UNSIGNED
@@ -863,7 +988,7 @@ def disp_vec_int_udiv(func):
if l'length = 0 then
return null_unsigned;
end if;"""
- if func in ['mod', 'rem']:
+ if func in ["mod", "rem"]:
res += """
return resize (l {func} to_unsigned (r, r_size), l'length);"""
else:
@@ -881,7 +1006,7 @@ def disp_vec_int_udiv(func):
if r'length = 0 then
return null_unsigned;
end if;"""
- if func == '/':
+ if func == "/":
res += """
return resize (to_unsigned (l, l_size) {func} r, r'length);"""
else:
@@ -891,8 +1016,10 @@ def disp_vec_int_udiv(func):
end "{func}";\n"""
w(res.format(func=func))
+
def disp_vec_vec_sdiv(func):
- res = """
+ res = (
+ """
function "{func}" (L, R : SIGNED) return SIGNED
is
subtype l_type is SIGNED (L'length - 1 downto 0);
@@ -905,17 +1032,23 @@ def disp_vec_vec_sdiv(func):
variable ru : r_utype;
variable quot : l_utype;
variable rema : r_utype;
- variable r0 : """ + logic_type() + """ := has_0x (r);
+ variable r0 : """
+ + logic_type()
+ + """ := has_0x (r);
begin
if la'length = 0 or ra'length = 0 then
return null_signed;
end if;"""
- if logic == 'std':
- res += """
- if has_0x (l) = 'X' or r0 = 'X' then""" + \
- disp_non_logical_warning (func) + """
+ )
+ if logic == "std":
+ res += (
+ """
+ if has_0x (l) = 'X' or r0 = 'X' then"""
+ + disp_non_logical_warning(func)
+ + """
return l_type'(others => 'X');
end if;"""
+ )
res += """
assert r0 /= '0'
report "NUMERIC_STD.""{func}"": division by 0"
@@ -932,14 +1065,14 @@ def disp_vec_vec_sdiv(func):
ru := unsigned (ra);
end if;
divmod (lu, ru, quot, rema);"""
- if func == '/':
+ if func == "/":
res += """
if (ra (ra'left) xor la (la'left)) = '1' then
return -signed (quot);
else
return signed (quot);
end if;"""
- elif func == 'rem':
+ elif func == "rem":
res += """
-- Result of rem has the sign of the dividend.
if la (la'left) = '1' then
@@ -947,7 +1080,7 @@ def disp_vec_vec_sdiv(func):
else
return signed (rema);
end if;"""
- elif func == 'mod':
+ elif func == "mod":
res += """
-- Result of mod has the sign of the divisor.
if rema = r_utype'(others => '0') then
@@ -972,6 +1105,7 @@ def disp_vec_vec_sdiv(func):
end "{func}";\n"""
w(res.format(func=func))
+
def disp_vec_int_sdiv(func):
res = """
function "{func}" (L : SIGNED; R : INTEGER) return SIGNED
@@ -981,11 +1115,11 @@ def disp_vec_int_sdiv(func):
if l'length = 0 then
return null_signed;
end if;"""
- if func == '/':
- res += """
+ if func == "/":
+ res += """
return l {func} to_signed (r, r_size);"""
else:
- res += """
+ res += """
return resize (l {func} to_signed (r, r_size), l'length);"""
res += """
end "{func}";\n"""
@@ -999,7 +1133,7 @@ def disp_vec_int_sdiv(func):
if r'length = 0 then
return null_signed;
end if;"""
- if func == '/':
+ if func == "/":
res += """
return resize (to_signed (l, max (l_size, r'length)) {func} r, r'length);"""
else:
@@ -1009,8 +1143,9 @@ def disp_vec_int_sdiv(func):
end "{func}";\n"""
w(res.format(func=func))
+
def disp_all_log_funcs():
- "Generate all function bodies for logic operators"
+ """Generate all function bodies for logic operators."""
for t in vec_types:
disp_resize(t)
for v in vec_types:
@@ -1030,15 +1165,16 @@ def disp_all_log_funcs():
disp_vec_int_compare(f, "SIGNED", "INTEGER")
disp_vec_int_compare(f, "INTEGER", "SIGNED")
for t in vec_types:
- for d in ['left', 'right']:
- disp_shift('shift_' + d, t, d);
- for d in ['left', 'right']:
- disp_rotate('rotate_' + d, t, d);
+ for d in ["left", "right"]:
+ disp_shift("shift_" + d, t, d)
+ for d in ["left", "right"]:
+ disp_rotate("rotate_" + d, t, d)
if v93:
- disp_shift_op('"sll"', t, 'left')
- disp_shift_op('"srl"', t, 'right')
- disp_rotate('"rol"', t, 'left')
- disp_rotate('"ror"', t, 'right')
+ disp_shift_op('"sll"', t, "left")
+ disp_shift_op('"srl"', t, "right")
+ disp_rotate('"rol"', t, "left")
+ disp_rotate('"ror"', t, "right")
+
def disp_match(typ):
res = """
@@ -1070,75 +1206,83 @@ def disp_match(typ):
def disp_all_match_funcs():
- disp_match('std_ulogic_vector');
- disp_match('std_logic_vector');
- disp_match('UNSIGNED');
- disp_match('SIGNED');
+ disp_match("std_ulogic_vector")
+ disp_match("std_logic_vector")
+ disp_match("UNSIGNED")
+ disp_match("SIGNED")
+
def disp_all_arith_funcs():
- "Generate all function bodies for logic operators"
- for op in ['+', '-']:
+ """Generate all function bodies for logic operators."""
+ for op in ["+", "-"]:
disp_vec_vec_binary(op, "UNSIGNED")
disp_vec_vec_binary(op, "SIGNED")
disp_vec_int_binary(op, "UNSIGNED", "NATURAL")
disp_vec_int_binary(op, "NATURAL", "UNSIGNED")
disp_vec_int_binary(op, "SIGNED", "INTEGER")
disp_vec_int_binary(op, "INTEGER", "SIGNED")
- disp_vec_vec_mul('*', 'UNSIGNED')
- disp_vec_vec_mul('*', 'SIGNED')
- disp_vec_int_mul('UNSIGNED', 'NATURAL')
- disp_vec_int_mul('SIGNED', 'INTEGER')
- disp_int_vec_mul('NATURAL', 'UNSIGNED')
- disp_int_vec_mul('INTEGER', 'SIGNED')
- disp_has_0x('UNSIGNED')
+ disp_vec_vec_mul("*", "UNSIGNED")
+ disp_vec_vec_mul("*", "SIGNED")
+ disp_vec_int_mul("UNSIGNED", "NATURAL")
+ disp_vec_int_mul("SIGNED", "INTEGER")
+ disp_int_vec_mul("NATURAL", "UNSIGNED")
+ disp_int_vec_mul("INTEGER", "SIGNED")
+ disp_has_0x("UNSIGNED")
disp_divmod()
disp_size()
- disp_vec_vec_udiv('/')
- disp_vec_int_udiv('/')
- disp_vec_vec_udiv('rem')
- disp_vec_int_udiv('rem')
- disp_vec_vec_udiv('mod')
- disp_vec_int_udiv('mod')
- disp_has_0x('SIGNED')
+ disp_vec_vec_udiv("/")
+ disp_vec_int_udiv("/")
+ disp_vec_vec_udiv("rem")
+ disp_vec_int_udiv("rem")
+ disp_vec_vec_udiv("mod")
+ disp_vec_int_udiv("mod")
+ disp_has_0x("SIGNED")
disp_neg("-")
disp_neg("abs")
- disp_vec_vec_sdiv('/')
- disp_vec_int_sdiv('/')
- disp_vec_vec_sdiv('rem')
- disp_vec_int_sdiv('rem')
- disp_vec_vec_sdiv('mod')
- disp_vec_int_sdiv('mod')
+ disp_vec_vec_sdiv("/")
+ disp_vec_int_sdiv("/")
+ disp_vec_vec_sdiv("rem")
+ disp_vec_int_sdiv("rem")
+ disp_vec_vec_sdiv("mod")
+ disp_vec_int_sdiv("mod")
+
# Patterns to replace
-pats = {' @LOG\n' : disp_all_log_funcs,
- ' @ARITH\n' : disp_all_arith_funcs,
- ' @MATCH\n' : disp_all_match_funcs }
+pats = {
+ " @LOG\n": disp_all_log_funcs,
+ " @ARITH\n": disp_all_arith_funcs,
+ " @MATCH\n": disp_all_match_funcs,
+}
+
+spec_file = "numeric_std.vhdl"
+# proto_file='numeric_std-body.proto'
-spec_file='numeric_std.vhdl'
-#proto_file='numeric_std-body.proto'
def gen_body(proto_file):
- w('-- This -*- vhdl -*- file was generated from ' + proto_file + '\n')
+ w("-- This -*- vhdl -*- file was generated from " + proto_file + "\n")
for line in open(proto_file):
if line in pats:
pats[line]()
continue
w(line)
+
# Copy spec
for log in logics:
- for std in ['87', '93']:
- out=open('v' + std + '/numeric_' + log + '.vhdl', 'w')
- for line in open('numeric_' + log + '.proto'):
- if line == ' @COMMON\n':
- for lcom in open('numeric_common.proto'):
- if lcom[0:2] == '--':
+ for std in ["87", "93"]:
+ out = open("v" + std + "/numeric_" + log + ".vhdl", "w")
+ for line in open("numeric_" + log + ".proto"):
+ if line == " @COMMON\n":
+ for lcom in open("numeric_common.proto"):
+ if lcom[0:2] == "--":
pass
- elif std == '87' and ('"xnor"' in lcom
- or '"sll"' in lcom
- or '"srl"' in lcom
- or '"rol"' in lcom
- or '"ror"' in lcom):
+ elif std == "87" and (
+ '"xnor"' in lcom
+ or '"sll"' in lcom
+ or '"srl"' in lcom
+ or '"rol"' in lcom
+ or '"ror"' in lcom
+ ):
w("--" + lcom[2:])
else:
w(lcom)
@@ -1147,17 +1291,17 @@ for log in logics:
out.close()
# Generate bodies
-v93=False
+v93 = False
for l in logics:
logic = l
- out=open('v87/numeric_{0}-body.vhdl'.format(l), 'w')
- gen_body('numeric_{0}-body.proto'.format(l))
+ out = open("v87/numeric_{0}-body.vhdl".format(l), "w")
+ gen_body("numeric_{0}-body.proto".format(l))
out.close()
-v93=True
+v93 = True
binary_funcs.append("xnor")
for l in logics:
logic = l
- out=open('v93/numeric_{0}-body.vhdl'.format(l), 'w')
- gen_body('numeric_{0}-body.proto'.format(l))
+ out = open("v93/numeric_{0}-body.vhdl".format(l), "w")
+ gen_body("numeric_{0}-body.proto".format(l))
out.close()
diff --git a/pyGHDL/dom/NonStandard.py b/pyGHDL/dom/NonStandard.py
index 9010e392b..63a35dc7f 100644
--- a/pyGHDL/dom/NonStandard.py
+++ b/pyGHDL/dom/NonStandard.py
@@ -81,7 +81,6 @@ class Design(VHDLModel_Design):
def __ghdl_init(self):
"""Initialization: set options and then load libraries."""
-
# Initialize libghdl
libghdl_finalize()
libghdl_initialize()
diff --git a/pyGHDL/dom/_Utils.py b/pyGHDL/dom/_Utils.py
index 0e0cbc95b..e75c5f36a 100644
--- a/pyGHDL/dom/_Utils.py
+++ b/pyGHDL/dom/_Utils.py
@@ -61,7 +61,7 @@ def GetIirKindOfNode(node: Iir) -> nodes.Iir_Kind:
@export
def GetNameOfNode(node: Iir) -> str:
- """Return the python string from node :obj:`node` identifier"""
+ """Return the python string from node :obj:`node` identifier."""
identifier = nodes.Get_Identifier(node)
return name_table.Get_Name_Ptr(identifier)
diff --git a/pyGHDL/libghdl/__init__.py b/pyGHDL/libghdl/__init__.py
index 1477d9361..0d3c75fa1 100644
--- a/pyGHDL/libghdl/__init__.py
+++ b/pyGHDL/libghdl/__init__.py
@@ -52,7 +52,7 @@ class LibGHDLException(GHDLBaseException):
def _get_libghdl_name() -> Path:
- """Get the name of the libghdl library (with version and extension)"""
+ """Get the name of the libghdl library (with version and extension)."""
ver = __version__.replace("-", "_").replace(".", "_")
ext = {"win32": "dll", "cygwin": "dll", "darwin": "dylib"}.get(sys.platform, "so")
return Path("libghdl-{version}.{ext}".format(version=ver, ext=ext))
diff --git a/pyGHDL/libghdl/errorout.py b/pyGHDL/libghdl/errorout.py
index a4f034d46..94143b29e 100644
--- a/pyGHDL/libghdl/errorout.py
+++ b/pyGHDL/libghdl/errorout.py
@@ -5,9 +5,6 @@ from enum import IntEnum, unique
from pydecor import export
from pyGHDL.libghdl._decorator import BindToLibGHDL
-from enum import IntEnum, unique
-
-from pyGHDL.libghdl import libghdl
@export
diff --git a/pyGHDL/libghdl/std_names.py b/pyGHDL/libghdl/std_names.py
index 256a1c425..b9bdb95d3 100644
--- a/pyGHDL/libghdl/std_names.py
+++ b/pyGHDL/libghdl/std_names.py
@@ -4,8 +4,6 @@
from enum import IntEnum, unique
from pydecor import export
-from pyGHDL.libghdl._decorator import BindToLibGHDL
-
@export
class Name:
diff --git a/pyGHDL/libghdl/utils.py b/pyGHDL/libghdl/utils.py
index e964f3ce3..98e350e03 100644
--- a/pyGHDL/libghdl/utils.py
+++ b/pyGHDL/libghdl/utils.py
@@ -206,7 +206,6 @@ def declarations_iter(n) -> Generator[Any, None, None]:
yield n1
# Handle nested declarations: record elements, physical units,
# enumeration literals...
- typ = nodes.Get_Type_Definition(n1)
for n2 in declarations_iter(n1):
yield n2
else:
diff --git a/pyGHDL/libghdl/vhdl/elocations.py b/pyGHDL/libghdl/vhdl/elocations.py
index c2cda3940..dd3600ecf 100644
--- a/pyGHDL/libghdl/vhdl/elocations.py
+++ b/pyGHDL/libghdl/vhdl/elocations.py
@@ -1,10 +1,8 @@
# Auto generated Python source file from Ada sources
# Call 'make' in 'src/vhdl' to regenerate:
#
-from enum import IntEnum, unique
from pydecor import export
-from pyGHDL.libghdl._decorator import BindToLibGHDL
from pyGHDL.libghdl import libghdl
diff --git a/pyGHDL/libghdl/vhdl/nodes.py b/pyGHDL/libghdl/vhdl/nodes.py
index 8f4648790..1a4cf043f 100644
--- a/pyGHDL/libghdl/vhdl/nodes.py
+++ b/pyGHDL/libghdl/vhdl/nodes.py
@@ -5,6 +5,7 @@ from enum import IntEnum, unique
from pydecor import export
from pyGHDL.libghdl._decorator import BindToLibGHDL
+
from typing import TypeVar
from ctypes import c_int32
from pyGHDL.libghdl import libghdl
diff --git a/pyGHDL/libghdl/vhdl/nodes_meta.py b/pyGHDL/libghdl/vhdl/nodes_meta.py
index 08724ccdf..0ad2b247e 100644
--- a/pyGHDL/libghdl/vhdl/nodes_meta.py
+++ b/pyGHDL/libghdl/vhdl/nodes_meta.py
@@ -5,6 +5,7 @@ from enum import IntEnum, unique
from pydecor import export
from pyGHDL.libghdl._decorator import BindToLibGHDL
+
from pyGHDL.libghdl import libghdl
from pyGHDL.libghdl._types import IirKind
diff --git a/pyGHDL/lsp/lsp.py b/pyGHDL/lsp/lsp.py
index a2598f186..43b8c47c8 100644
--- a/pyGHDL/lsp/lsp.py
+++ b/pyGHDL/lsp/lsp.py
@@ -117,7 +117,7 @@ class LanguageProtocolServer(object):
params = {}
try:
response = fmethod(**params)
- except Exception as e:
+ except Exception:
log.exception(
"Caught exception while handling %s with params %s:", method, params
)
diff --git a/pyGHDL/lsp/workspace.py b/pyGHDL/lsp/workspace.py
index bef20a872..cb392be9b 100644
--- a/pyGHDL/lsp/workspace.py
+++ b/pyGHDL/lsp/workspace.py
@@ -4,7 +4,7 @@ import json
from ctypes import byref
import pyGHDL.libghdl as libghdl
import pyGHDL.libghdl.errorout_memory as errorout_memory
-import pyGHDL.libghdl.flags
+import pyGHDL.libghdl.flags as flags
import pyGHDL.libghdl.errorout as errorout
import pyGHDL.libghdl.files_map as files_map
import pyGHDL.libghdl.libraries as libraries
@@ -12,7 +12,7 @@ import pyGHDL.libghdl.name_table as name_table
import pyGHDL.libghdl.vhdl.nodes as nodes
import pyGHDL.libghdl.vhdl.lists as lists
import pyGHDL.libghdl.vhdl.std_package as std_package
-import pyGHDL.libghdl.vhdl.parse
+import pyGHDL.libghdl.vhdl.parse as parse
import pyGHDL.libghdl.vhdl.sem_lib as sem_lib
import pyGHDL.libghdl.utils as pyutils
@@ -44,15 +44,15 @@ class Workspace(object):
self._prj = {}
self._last_linted_doc = None
errorout_memory.Install_Handler()
- libghdl.flags.Flag_Elocations.value = True
- # libghdl.Flags.Verbose.value = True
+ flags.Flag_Elocations.value = True
+ # flags.Verbose.value = True
# We do analysis even in case of errors.
- libghdl.vhdl.parse.Flag_Parse_Parenthesis.value = True
+ parse.Flag_Parse_Parenthesis.value = True
# Force analysis to get more feedback + navigation even in case
# of errors.
- libghdl.flags.Flag_Force_Analysis.value = True
+ flags.Flag_Force_Analysis.value = True
# Do not consider analysis order issues.
- libghdl.flags.Flag_Elaborate_With_Outdated.value = True
+ flags.Flag_Elaborate_With_Outdated.value = True
libghdl.errorout.Enable_Warning(errorout.Msgid.Warnid_Unused, True)
self.read_project()
self.set_options_from_project()
diff --git a/scripts/pnodespy.py b/scripts/pnodespy.py
index dabe94446..f443d36c5 100755
--- a/scripts/pnodespy.py
+++ b/scripts/pnodespy.py
@@ -30,16 +30,15 @@ def print_enum(name, vals):
print(" {0} = {1}".format(k, n))
-def print_file_header():
+def print_file_header(includeIntEnumUnique=True, includeBindToLibGHDL=True):
print(dedent("""\
# Auto generated Python source file from Ada sources
# Call 'make' in 'src/vhdl' to regenerate:
#
- from enum import IntEnum, unique
- from pydecor import export
-
- from pyGHDL.libghdl._decorator import BindToLibGHDL
- """), end=''
+ """) + "{sysImports}from pydecor import export\n{moduleImports}".format(
+ sysImports = "from enum import IntEnum, unique\n" if includeIntEnumUnique else "",
+ moduleImports = "\nfrom pyGHDL.libghdl._decorator import BindToLibGHDL\n" if includeBindToLibGHDL else "",
+ )
)
@@ -97,7 +96,7 @@ def do_iirs_subprg():
def do_libghdl_elocations():
classname = "vhdl__elocations"
- print_file_header()
+ print_file_header(includeIntEnumUnique=False, includeBindToLibGHDL=False)
print("from pyGHDL.libghdl import libghdl")
print()
for k in pnodes.funcs:
@@ -147,7 +146,7 @@ def do_class_fields():
def read_enum(filename, type_name, prefix, class_name, g=lambda m: m.group(1)):
- """Read an enumeration declaration from :param filename:"""
+ """Read an enumeration declaration from :param filename:."""
pat_decl = re.compile(r" type {0} is$".format(type_name))
pat_enum = re.compile(r" {0}(\w+),?( *-- .*)?$".format(prefix))
pat_comment = re.compile(r" *-- .*$")
@@ -183,7 +182,7 @@ def read_enum(filename, type_name, prefix, class_name, g=lambda m: m.group(1)):
def read_spec_enum(type_name, prefix, class_name):
- """Read an enumeration declaration from iirs.ads"""
+ """Read an enumeration declaration from iirs.ads."""
read_enum(pnodes.kind_file, type_name, prefix, class_name)
@@ -335,7 +334,7 @@ def do_libghdl_names():
val_max = max(val_max, val)
dict[name_def] = val
res.append((name_def, val))
- print_file_header()
+ print_file_header(includeBindToLibGHDL=False)
print(dedent("""
@export
@@ -358,10 +357,6 @@ def do_libghdl_tokens():
def do_libghdl_errorout():
print_file_header()
print(dedent("""\
- from enum import IntEnum, unique
-
- from pyGHDL.libghdl import libghdl
-
@export
@BindToLibGHDL("errorout__enable_warning")
def Enable_Warning(Id: int, Enable: bool) -> None:
diff --git a/testsuite/gna/issue43/run.py b/testsuite/gna/issue43/run.py
index f1cb5ec01..d37c1cbaa 100644
--- a/testsuite/gna/issue43/run.py
+++ b/testsuite/gna/issue43/run.py
@@ -1,14 +1,6 @@
-import os
-import sys
-from string import join
from vunit import VUnit
-
-
-# Create VUnit instance by parsing command line arguments
vu = VUnit.from_argv()
vu.add_com()
-lib = vu.add_library("lib")
-lib.add_source_files("*.vhd")
-
-vu.main() \ No newline at end of file
+vu.add_library("lib").add_source_files("*.vhd")
+vu.main()
diff --git a/testsuite/pyunit/libghdl/Initialize.py b/testsuite/pyunit/libghdl/Initialize.py
index 4d5bb521a..369faee07 100644
--- a/testsuite/pyunit/libghdl/Initialize.py
+++ b/testsuite/pyunit/libghdl/Initialize.py
@@ -18,11 +18,11 @@ class Instantiate(TestCase):
@staticmethod
def getIdentifier(node):
- """Return the Python string from node :obj:`node` identifier"""
+ """Return the Python string from node :obj:`node` identifier."""
return name_table.Get_Name_Ptr(nodes.Get_Identifier(node))
def test_InitializeGHDL(self) -> None:
- """Initialization: set options and then load libaries"""
+ """Initialization: set options and then load libaries."""
libghdl.initialize()
# Print error messages on the console.
diff --git a/testsuite/pyunit/lsp/LanguageServer.py b/testsuite/pyunit/lsp/LanguageServer.py
index 36ee6da2a..c1bcf1898 100644
--- a/testsuite/pyunit/lsp/LanguageServer.py
+++ b/testsuite/pyunit/lsp/LanguageServer.py
@@ -1,5 +1,4 @@
import os
-import string
from sys import executable
from io import BytesIO
from json import load as json_load, loads as json_loads, dumps as json_dumps
@@ -7,7 +6,7 @@ from pathlib import Path
from urllib.parse import quote
from subprocess import run as subprocess_run, PIPE
from typing import Optional
-from unittest import TestCase, skip
+from unittest import TestCase
from pyGHDL.lsp.lsp import LanguageProtocolServer, LSPConn