#!/usr/bin/env python3
# =============================================================================
# ____ _ _ ____ _ _
# _ __ _ _ / ___| | | | _ \| | __| | ___ _ __ ___
# | '_ \| | | | | _| |_| | | | | | / _` |/ _ \| '_ ` _ \
# | |_) | |_| | |_| | _ | |_| | |___ | (_| | (_) | | | | | |
# | .__/ \__, |\____|_| |_|____/|_____(_)__,_|\___/|_| |_| |_|
# |_| |___/
# =============================================================================
# Authors:
# Patrick Lehmann
# Unai Martinez-Corral
#
# Package module: DOM: Interface items (e.g. generic or port)
#
# License:
# ============================================================================
# Copyright (C) 2019-2021 Tristan Gingold
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <gnu.org/licenses>.
#
# SPDX-License-Identifier: GPL-2.0-or-later
# ============================================================================
"""
A terminal application to exercise :mod:`pyGHDL.dom`.
It parses VHDL source files with *libghdl*, translates the result to the document object model and writes each document
as VHDL code, which makes it the quickest way to see what the model makes of a given file. Installed as ``ghdl-dom`` by
:file:`setup.py`.
"""
from argparse import RawDescriptionHelpFormatter
from pathlib import Path
from platform import system as platform_system
from textwrap import wrap, dedent
from pyTooling.Decorators import export, readonly
from pyTooling.Attributes import Attribute
from pyTooling.Attributes.ArgParse import ArgParseHelperMixin, DefaultHandler, CommandHandler, CommandLineArgument
from pyTooling.Attributes.ArgParse.Argument import StringArgument
from pyTooling.Attributes.ArgParse.Flag import FlagArgument
from pyTooling.TerminalUI import TerminalApplication, Severity
from pyVHDLModel import VHDLVersion
from pyVHDLModel.Formatting.VHDL import VHDLWriter
import pyGHDL
from pyGHDL import GHDLBaseException
from pyGHDL.libghdl import LibGHDLException
from pyGHDL.dom import DOMException
from pyGHDL.dom.NonStandard import Design, Document
__maintainer__ = "Tristan Gingold"
__status__ = "Alpha"
class SourceAttribute(Attribute):
"""
Attribute attaching the source selection command line arguments to a handler method.
"""
def __call__(self, func):
"""
Attaches the source selection command line arguments to the decorated handler method.
The attribute bundles the five arguments that select what to analyze and how:
* ``-f`` / ``--file`` - the filename to parse, can be used multiple times.
* ``-F`` / ``--files`` - a list of filenames to parse.
* ``-D`` / ``--directory`` - the directory to parse.
* ``-L`` / ``--library`` - the default library for files in the root directory.
* ``--std`` - the VHDL version to analyze with (``08`` or ``19``); default VHDL-2008.
* ``--tab-size`` - the number of columns between two tab stops (``1`` to ``120``); default 8.
:param func: The handler method to attach the command line arguments to.
:returns: The same handler method, with the arguments attached.
"""
self._AppendAttribute(
func,
CommandLineArgument(
"-f",
"--file",
action="append",
metavar="file",
dest="Files",
type=Path,
help="The filename to parse (can be used multiple times).",
),
)
self._AppendAttribute(
func,
CommandLineArgument(
"-F",
"--files",
metavar="files",
dest="Files",
type=Path,
nargs="+",
help="List of filenames to parse.",
),
)
self._AppendAttribute(
func,
CommandLineArgument(
"-D",
"--directory",
metavar="dir",
dest="Directory",
type=Path,
help="The directory to parse.",
),
)
self._AppendAttribute(
func,
CommandLineArgument(
"-L",
"--library",
metavar="lib",
dest="DefaultLibrary",
type=str,
help="Default library for files in the root directory.",
),
)
self._AppendAttribute(
func,
CommandLineArgument(
"--std",
metavar="std",
dest="Std",
choices=("08", "19"),
help="VHDL version to analyze with: 08 (default) or 19.",
),
)
self._AppendAttribute(
func,
CommandLineArgument(
"--tab-size",
metavar="columns",
dest="TabSize",
type=int,
help="Number of columns between two tab stops: 1..120 (default: 8).",
),
)
return func
[docs]
@export
class Application(TerminalApplication, ArgParseHelperMixin):
"""
The ``pyghdl-dom`` application.
It owns a :class:`~pyGHDL.dom.NonStandard.Design`, adds the requested source files to it, and dispatches the
sub-command the user asked for.
"""
HEADLINE = "pyGHDL.dom - Test Application"
DUNDER_MODULE = pyGHDL
# load platform information (Windows, Linux, Darwin, ...)
__PLATFORM = platform_system()
_design: Design
[docs]
def __init__(self):
"""
Initializes the application.
"""
super().__init__()
# Initialize DOM with an empty design
# --------------------------------------------------------------------------
self._design = Design()
# Call the constructor of the ArgParseMixin
# --------------------------------------------------------------------------
textWidth = min(max(self.Width, 80), 160)
description = dedent("""\
Application to test pyGHDL's DOM API.
""")
epilog = "\n".join(
wrap(
dedent("""\
pyGHDL is a Python binding for libghdl.
"""),
textWidth,
replace_whitespace=False,
)
)
class HelpFormatter(RawDescriptionHelpFormatter):
"""
Help formatter widening argparse's output to the terminal.
"""
def __init__(self, *args, **kwargs):
"""
Initializes the formatter with a wider help column and line width.
:param args: Positional arguments passed on to :class:`~argparse.RawDescriptionHelpFormatter`.
:param kwargs: Keyword arguments passed on, with the width settings overridden.
"""
kwargs["max_help_position"] = 30
kwargs["width"] = textWidth
super().__init__(*args, **kwargs)
ArgParseHelperMixin.__init__(
self,
description=description,
epilog=epilog,
formatter_class=HelpFormatter,
add_help=False,
)
# Change error and warning reporting
# --------------------------------------------------------------------------
self._LOG_MESSAGE_FORMAT__[Severity.Fatal] = "{DARK_RED}[FATAL] {message}{NOCOLOR}"
self._LOG_MESSAGE_FORMAT__[Severity.Error] = "{RED}[ERROR] {message}{NOCOLOR}"
self._LOG_MESSAGE_FORMAT__[Severity.Warning] = "{YELLOW}[WARNING] {message}{NOCOLOR}"
self._LOG_MESSAGE_FORMAT__[Severity.Normal] = "{GRAY}{message}{NOCOLOR}"
# class properties
# ============================================================================
@readonly
def Platform(self):
"""
Read-only property to access the platform the application runs on (:attr:`__PLATFORM`).
:returns: The platform's name, as :func:`platform.system` reports it.
"""
return self.__PLATFORM
# ============================================================================
# Common commands
# ============================================================================
# common arguments valid for all commands
# ----------------------------------------------------------------------------
[docs]
@FlagArgument("-d", "--debug", dest="debug", help="Enable debug mode.")
@FlagArgument("-v", "--verbose", dest="verbose", help="Print out detailed messages.")
@FlagArgument("-q", "--quiet", dest="quiet", help="Reduce messages to a minimum.")
def Run(self):
"""
Parse the command line and run the requested sub-command.
"""
ArgParseHelperMixin.Run(self)
[docs]
@DefaultHandler()
def HandleDefault(self, _):
"""
Handle an invocation with no sub-command by printing the help page.
:param _: The parsed arguments, unused.
"""
self._PrintHeadline()
self._PrintHelp()
self.WriteNormal("")
self.Exit()
# ----------------------------------------------------------------------------
# create the sub-parser for the "help" command
# ----------------------------------------------------------------------------
[docs]
@CommandHandler("help", help="Display help page(s) for the given command name.")
@StringArgument(metaName="Command", dest="Command", optional=True, help="Print help page(s) for a command.")
def HandleHelp(self, args):
"""
Handle the ``help`` sub-command: print the help page of a command, or the overview.
:param args: The parsed arguments, carrying the optional command name.
"""
self._PrintHeadline()
self._PrintHelp(args.Command)
self.WriteNormal("")
self.Exit()
# ----------------------------------------------------------------------------
# create the sub-parser for the "version" command
# ----------------------------------------------------------------------------
[docs]
@CommandHandler("version", help="Display tool and version information.")
def HandleVersion(self, args):
"""
Handle the ``version`` sub-command: print the headline, copyright, license, authors and version.
:param args: The parsed arguments, unused.
"""
self._PrintHeadline()
self._PrintVersion()
self.Exit()
# ----------------------------------------------------------------------------
# Create the sub-parser for the "pretty" command
# ----------------------------------------------------------------------------
[docs]
@CommandHandler(
"pretty",
help="Write the DOM of each source file as VHDL code to console.",
description="Translate each source file into a DOM document and write the document as VHDL code.",
)
@SourceAttribute()
def HandlePretty(self, args):
"""
Handle the ``pretty`` sub-command: translate the selected sources and write each document as VHDL code.
A file is translated on its own; a directory is scanned, and each subdirectory is reported as a library of that
name. The documents aren't added to the design, nor analyzed. Each document is written by
:class:`~pyVHDLModel.Formatting.VHDL.VHDLWriter`: its design units with their context items, in source order.
The time *libghdl* spent parsing and the time the translation took are reported per file.
A file, that can't be translated or written, is reported as an error; the remaining files are written. The
application exits with an error, if an error was reported.
:param args: The parsed arguments, carrying the selected files, directory, default library, VHDL version and tab
size.
"""
self._PrintHeadline()
if args.Std is not None or args.TabSize is not None:
try:
self._design = Design(
vhdlVersion=VHDLVersion.VHDL2008 if args.Std is None else VHDLVersion.Parse(args.Std),
tabSize=8 if args.TabSize is None else args.TabSize,
)
except ValueError as ex:
self.WriteFatal(f"Option '--tab-size': {ex}")
fileCount = 0
if args.Files is not None:
for file in args.Files:
if not file.exists():
self.WriteError(f"File '{file!s}' does not exist.")
continue
self.WriteNormal(f"Parsing file '{file!s}'")
self.writeFile(file, 1)
fileCount += 1
elif args.Directory is not None:
d: Path = args.Directory.resolve()
if not d.exists():
self.WriteFatal(f"Directory '{d!s}' does not exist.")
elif not d.is_dir():
self.WriteFatal(f"Path '{d!s}' is not a directory.")
if args.DefaultLibrary is None:
self.WriteWarning(f"Default library is not set.")
files = []
for directoryItem in d.iterdir():
if directoryItem.is_dir():
libraryName = directoryItem.name
self.WriteNormal(f"Scanning library '{libraryName}' ...")
for file in directoryItem.glob("**/*.vhd*"):
self.WriteNormal(f" Reading file '{file!s}'")
self.writeFile(file, 2)
fileCount += 1
elif directoryItem.is_file():
if directoryItem.suffix in (".vhd", ".vhdl"):
files.append(directoryItem)
if len(files) > 0 and args.DefaultLibrary is None:
self.WriteFatal("Files in root directory can't be read, due to missing default library.")
else:
libraryName = args.DefaultLibrary
self.WriteNormal(f"Processing files in root directory for library '{libraryName}' ...")
for file in files:
self.WriteNormal(f" Reading file '{file!s}'")
self.writeFile(file, 2)
fileCount += 1
if fileCount == 0:
self.WriteFatal("No files processed at all.")
self.ExitOnPreviousErrors()
self.Exit()
[docs]
def writeFile(self, filename: Path, indent: int) -> None:
"""
Translate a source file into a document and write the document as VHDL code.
An error is reported, if the file can't be translated or the document can't be written.
:param filename: The source file to translate.
:param indent: The indentation level of the timing messages.
"""
try:
document = Document(filename)
except DOMException as ex:
self.WriteError(f"File '{filename!s}' can't be translated: {ex!s}")
if isinstance(ex.__cause__, LibGHDLException):
for message in ex.__cause__.InternalErrors:
self.WriteErrorNote(f"libghdl: {message}")
return
self.WriteInfo(f"libghdl processing time: {document.LibGHDLProcessingDuration:%u} us", indent=indent)
self.WriteInfo(f"DOM translation time: {document.DOMTranslationDuration:%u} us", indent=indent)
try:
code = VHDLWriter().Format(document)
except Exception as ex:
self.WriteError(f"Document '{filename!s}' can't be written as VHDL code: {ex.__class__.__name__}: {ex}")
return
print(code)
# main program
def main(): # mccabe:disable=MC0001
"""This is the entry point for pyghdl.cli.dom written as a function.
1. It extracts common flags from the script's arguments list, before :class:`~argparse.ArgumentParser` is fully loaded.
2. It creates an instance of DOM test application and hands over to a class based execution.
All is wrapped in a big ``try..except`` block to catch every unhandled exception.
3. Shutdown the script and return its exit code.
"""
from sys import argv as sys_argv, exit as sys_exit, stderr
# debug = "-d" in sys_argv
# verbose = "-v" in sys_argv
# quiet = "-q" in sys_argv
try:
# handover to a class instance
app = Application() # debug, verbose, quiet)
except Exception as ex:
print(f"Can't create the application: {ex.__class__.__name__}: {ex}", file=stderr)
sys_exit(1)
try:
app.Run()
app.Exit()
except DOMException as ex:
print(f"DOM: {ex!s}")
ex2: LibGHDLException = ex.__cause__
if ex2 is not None:
for message in ex2.InternalErrors:
print(f"libghdl: {message}")
TerminalApplication.Exit(0)
app.Exit(6)
except LibGHDLException as ex:
print(f"LIB: {ex!s}")
for message in ex.InternalErrors:
print(f" {message}")
app.Exit(5)
except GHDLBaseException as ex:
app.PrintExceptionBase(ex)
except NotImplementedError as ex:
app.PrintNotImplementedError(ex)
# except ImportError as ex:
# printImportError(ex)
except Exception as ex:
app.PrintException(ex)
# entry point
if __name__ == "__main__":
main()