From 08d22b3a1266bfbeef5f0f8ead043d8ebe49c83e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kevin=20L=C3=A4ufer?= Date: Tue, 16 Jan 2024 14:11:00 -0500 Subject: [PATCH] pyverilog: fix preprocessor output conflicts --- pyverilog/vparser/parser.py | 8 ++------ pyverilog/vparser/preprocessor.py | 26 +++++++++++++++++++++----- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/pyverilog/vparser/parser.py b/pyverilog/vparser/parser.py index 1f88e20..66a0ce5 100644 --- a/pyverilog/vparser/parser.py +++ b/pyverilog/vparser/parser.py @@ -2643,9 +2643,8 @@ class ParseError(Exception): class VerilogCodeParser(object): - def __init__(self, filelist, preprocess_output='preprocess.output', + def __init__(self, filelist, preprocess_output=None, preprocess_include=None, preprocess_define=None): - self.preprocess_output = preprocess_output self.directives = () self.preprocessor = VerilogPreprocessor(filelist, preprocess_output, preprocess_include, @@ -2654,10 +2653,7 @@ def __init__(self, filelist, preprocess_output='preprocess.output', def preprocess(self): self.preprocessor.preprocess() - with open(self.preprocess_output) as f: - text = f.read() - os.remove(self.preprocess_output) - return text + return self.preprocessor.read_output(remove=True) def parse(self, preprocess_output='preprocess.output', debug=0): text = self.preprocess() diff --git a/pyverilog/vparser/preprocessor.py b/pyverilog/vparser/preprocessor.py index 4a45548..9536a32 100644 --- a/pyverilog/vparser/preprocessor.py +++ b/pyverilog/vparser/preprocessor.py @@ -29,7 +29,7 @@ class VerilogPreprocessor(object): - def __init__(self, filelist, outputfile='pp.out', include=None, define=None): + def __init__(self, filelist, outputfile=None, include=None, define=None): if not isinstance(filelist, (tuple, list)): filelist = list(filelist) @@ -79,25 +79,41 @@ def __init__(self, filelist, outputfile='pp.out', include=None, define=None): self.iv.append('-E') self.iv.append('-o') - self.iv.append(outputfile) + + # create a temporary file if necessary + if outputfile is None: + ff = tempfile.NamedTemporaryFile('w', delete=False) + ff.close() + self.outputfile = ff.name + else: + self.outputfile = outputfile def preprocess(self): - cmd = self.iv + list(self.filelist) + cmd = self.iv + [self.outputfile] + list(self.filelist) subprocess.call(cmd) # Removing the temporary files that were created for temp_file_path in self.temp_files_paths: os.remove(temp_file_path) + def read_output(self, remove: bool) -> str: + assert(os.path.isfile(self.outputfile), f"{self.outputfile} does not exist or is not a file!") + with open(self.outputfile) as f: + text = f.read() + if remove: + os.remove(self.outputfile) + return text + def preprocess( filelist, - output='preprocess.output', + output=None, include=None, define=None ): pre = VerilogPreprocessor(filelist, output, include, define) pre.preprocess() - text = open(output).read() + with open(output) as f: + text = f.read() os.remove(output) return text