Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added/Fixed Typing for all files in vunit.ui package #961

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/news.d/961.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added python typing for the vunit python API.
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,6 @@ commands=
vcomponents: {envpython} vunit/vhdl/verification_components/run.py --clean
coverage: {envpython} -m coverage run --branch --source vunit/ -m pytest tests/
"""
[[tool.mypy.overrides]]
module = "vunit.ui.*"
disallow_untyped_defs = true
2 changes: 1 addition & 1 deletion tests/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def set_env(**environ):
>>> "PLUGINS_DIR" in os.environ
False

:type environ: dict[str, unicode]
:type environ: Dict[str, unicode]
:param environ: Environment variables to set
"""
old_environ = dict(os.environ)
Expand Down
15 changes: 8 additions & 7 deletions vunit/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
import inspect
from pathlib import Path
from copy import copy
from collections import OrderedDict
from typing import Any, Callable, List, Union
from vunit.sim_if.factory import SIMULATOR_FACTORY


Expand Down Expand Up @@ -111,7 +113,7 @@ def set_vhdl_configuration_name(self, name):
"""
self.vhdl_configuration_name = name

def set_generic(self, name, value):
def set_generic(self, name: str, value: Any) -> None:
"""
Set generic
"""
Expand All @@ -128,7 +130,7 @@ def set_generic(self, name, value):
else:
self.generics[name] = value

def set_sim_option(self, name, value):
def set_sim_option(self, name: str, value: Union[str, List[str], bool]):
"""
Set sim option
"""
Expand Down Expand Up @@ -195,11 +197,10 @@ class ConfigurationVisitor(object):
def _check_enabled(self):
pass

@staticmethod
def get_configuration_dicts():
def get_configuration_dicts(self) -> "List[OrderedDict[Any, Configuration]]":
raise NotImplementedError

def set_attribute(self, name, value):
def set_attribute(self, name: str, value: Any):
"""
Set attribute
"""
Expand All @@ -226,7 +227,7 @@ def set_vhdl_configuration_name(self, value: str):
for config in configs.values():
config.set_vhdl_configuration_name(value)

def set_sim_option(self, name, value, overwrite=True):
def set_sim_option(self, name: str, value: Union[str, List[str], bool], overwrite=True) -> None:
"""
Set sim option

Expand All @@ -240,7 +241,7 @@ def set_sim_option(self, name, value, overwrite=True):
continue
config.set_sim_option(name, value)

def set_pre_config(self, value):
def set_pre_config(self, value: Callable) -> None:
"""
Set pre_config function
"""
Expand Down
11 changes: 8 additions & 3 deletions vunit/library.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,13 @@
"""

import logging
from typing import List, cast, TYPE_CHECKING
from vunit.design_unit import Entity, VHDLDesignUnit
from vunit.vhdl_standard import VHDLStandard

if TYPE_CHECKING:
from vunit.source_file import SourceFile, VHDLSourceFile, VerilogSourceFile

LOGGER = logging.getLogger(__name__)


Expand Down Expand Up @@ -46,7 +51,7 @@ def __init__(self, name: str, directory: str, vhdl_standard: VHDLStandard, is_ex

self._is_external = is_external

def add_source_file(self, source_file):
def add_source_file(self, source_file: "SourceFile") -> "SourceFile":
"""
Add source file to library unless it exists

Expand Down Expand Up @@ -104,7 +109,7 @@ def _check_duplication(self, dictionary, design_unit):
if design_unit.name in dictionary:
self._warning_on_duplication(design_unit, dictionary[design_unit.name].source_file.name)

def add_vhdl_design_units(self, design_units):
def add_vhdl_design_units(self, design_units: List[VHDLDesignUnit]):
"""
Add VHDL design units to the library
"""
Expand All @@ -119,7 +124,7 @@ def add_vhdl_design_units(self, design_units):
self._entities[design_unit.name] = design_unit

for architecture in self._architectures[design_unit.name].values():
design_unit.add_architecture(architecture)
cast(Entity, design_unit).add_architecture(architecture)

else:
if design_unit.unit_type == "architecture":
Expand Down
22 changes: 12 additions & 10 deletions vunit/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
"""
Functionality to represent and operate on a HDL code project
"""
from typing import Optional, Union
from collections import OrderedDict
from typing import List, Optional, Union
from pathlib import Path
import logging
from collections import OrderedDict
from vunit.hashing import hash_string
from vunit.dependency_graph import DependencyGraph, CircularDependencyException
from vunit.vhdl_parser import VHDLParser
Expand Down Expand Up @@ -45,15 +45,15 @@ def __init__(self, depend_on_package_body=False, database=None):
self._database = database
self._vhdl_parser = VHDLParser(database=self._database)
self._verilog_parser = VerilogParser(database=self._database)
self._libraries = OrderedDict()
self._libraries: OrderedDict[str, Library] = OrderedDict()
# Mapping between library lower case name and real library name
self._lower_library_names_dict = {}
self._source_files_in_order = []
self._source_files_in_order: List[SourceFile] = []
self._manual_dependencies = []
self._depend_on_package_body = depend_on_package_body
self._builtin_libraries = set(["ieee", "std"])

def _validate_new_library_name(self, library_name):
def _validate_new_library_name(self, library_name: str) -> None:
"""
Check that the library_name is valid or raise RuntimeError
"""
Expand All @@ -74,15 +74,15 @@ def _validate_new_library_name(self, library_name):
f"Library name {self._lower_library_names_dict[lower_name]!r} previously defined"
)

def add_builtin_library(self, logical_name):
def add_builtin_library(self, logical_name: str) -> None:
"""
Add a builtin library name that does not give missing dependency warnings
"""
self._builtin_libraries.add(logical_name)

def add_library(
self,
logical_name,
logical_name: str,
directory: Union[str, Path],
vhdl_standard: VHDLStandard = VHDL.STD_2008,
is_external=False,
Expand Down Expand Up @@ -118,7 +118,7 @@ def add_source_file( # pylint: disable=too-many-arguments
defines=None,
vhdl_standard: Optional[VHDLStandard] = None,
no_parse=False,
):
) -> SourceFile:
"""
Add a file_name as a source file in library_name with file_type

Expand Down Expand Up @@ -515,7 +515,9 @@ def _get_files_to_recompile(self, files, dependency_graph, incremental):
result_list.append(source_file)
return result_list

def get_dependencies_in_compile_order(self, target_files=None, implementation_dependencies=False):
def get_dependencies_in_compile_order(
self, target_files=None, implementation_dependencies=False
) -> List[SourceFile]:
"""
Get a list of dependencies of target files including the
target files.
Expand Down Expand Up @@ -591,7 +593,7 @@ def comparison_key(source_file):

return sorted(files, key=comparison_key)

def get_source_files_in_order(self):
def get_source_files_in_order(self) -> List[SourceFile]:
"""
Get a list of source files in the order they were added to the project
"""
Expand Down
8 changes: 5 additions & 3 deletions vunit/sim_if/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@
from os import environ, listdir, pathsep
import subprocess
from pathlib import Path
from typing import List
from typing import Any, List, Union
from ..ostools import Process, simplify_path
from ..exceptions import CompileError
from ..color_printer import NO_COLOR_PRINTER

OptionType = Union[str, List[str], bool]


class Option(object):
"""
Expand Down Expand Up @@ -184,7 +186,7 @@ def supports_coverage():
"""
return False

def merge_coverage(self, file_name, args): # pylint: disable=unused-argument
def merge_coverage(self, file_name, args):
"""
Hook for simulator interface to creating coverage reports
"""
Expand Down Expand Up @@ -416,7 +418,7 @@ def validate(self, value):
raise ValueError(f"Option {self.name!r} must be one of {self._legal_values!s}. Got {value!r}")


def is_string_not_iterable(value):
def is_string_not_iterable(value: Any) -> bool:
"""
Returns True if value is a string and not another iterable
"""
Expand Down
11 changes: 6 additions & 5 deletions vunit/sim_if/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,14 @@
"""

import os
from typing import Dict, List, Union
from .activehdl import ActiveHDLInterface
from .ghdl import GHDLInterface
from .incisive import IncisiveInterface
from .modelsim import ModelSimInterface
from .nvc import NVCInterface
from .rivierapro import RivieraProInterface
from . import BooleanOption, ListOfStringOption, VHDLAssertLevelOption
from . import BooleanOption, ListOfStringOption, Option, VHDLAssertLevelOption


class SimulatorFactory(object):
Expand All @@ -37,7 +38,7 @@ def supported_simulators():
NVCInterface,
]

def _extract_compile_options(self):
def _extract_compile_options(self) -> Dict[str, Option]:
"""
Return all supported compile options
"""
Expand All @@ -51,7 +52,7 @@ def _extract_compile_options(self):
result[opt.name] = opt
return result

def _extract_sim_options(self):
def _extract_sim_options(self) -> Dict[str, Option]:
"""
Return all supported sim options
"""
Expand All @@ -75,7 +76,7 @@ def _extract_sim_options(self):

return result

def check_sim_option(self, name, value):
def check_sim_option(self, name: str, value: Union[str, List[str], bool]):
"""
Check that sim_option has legal name and value
"""
Expand All @@ -94,7 +95,7 @@ def check_compile_option_name(self, name):
if name not in known_options:
raise ValueError(f"Unknown compile_option {name!r}, expected one of {known_options!r}")

def check_compile_option(self, name, value):
def check_compile_option(self, name: str, value: Union[str, List[str], bool]) -> None:
"""
Check that the compile option is valid
"""
Expand Down
16 changes: 10 additions & 6 deletions vunit/source_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@
Functionality to represent and operate on VHDL and Verilog source files
"""
from pathlib import Path
from typing import Union
from typing import Dict, Union
import logging
from copy import copy
import traceback
from vunit.sim_if import OptionType
from vunit.sim_if.factory import SIMULATOR_FACTORY
from vunit.hashing import hash_string
from vunit.vhdl_parser import VHDLReference
Expand All @@ -35,7 +36,7 @@ def __init__(self, name, library, file_type):
self.file_type = file_type
self.design_units = []
self._content_hash = None
self._compile_options = {}
self._compile_options: Dict[str, OptionType] = {}

# The file name before preprocessing
self.original_name = name
Expand Down Expand Up @@ -70,14 +71,14 @@ def __hash__(self):
def __repr__(self):
return f"SourceFile({self.name!s}, {self.library.name!s})"

def set_compile_option(self, name, value):
def set_compile_option(self, name: str, value: OptionType):
"""
Set compile option
"""
SIMULATOR_FACTORY.check_compile_option(name, value)
self._compile_options[name] = copy(value)

def add_compile_option(self, name, value):
def add_compile_option(self, name: str, value: OptionType):
"""
Add compile option
"""
Expand All @@ -86,7 +87,7 @@ def add_compile_option(self, name, value):
if name not in self._compile_options:
self._compile_options[name] = copy(value)
else:
self._compile_options[name] += value
self._compile_options[name] += value # type: ignore

@property
def compile_options(self):
Expand Down Expand Up @@ -118,6 +119,9 @@ def content_hash(self):
"""
return hash_string(self._content_hash + self._compile_options_hash())

def add_to_library(self, library: Library):
raise NotImplementedError


class VerilogSourceFile(SourceFile):
"""
Expand Down Expand Up @@ -347,7 +351,7 @@ def add_to_library(self, library):
FILE_TYPES = ("vhdl",) + VERILOG_FILE_TYPES


def file_type_of(file_name):
def file_type_of(file_name: Union[str, Path]) -> str:
"""
Return the file type of file_name based on the file ending
"""
Expand Down
Loading
Loading