Coverage for hdl_registers/parser/toml.py: 89%

19 statements  

« prev     ^ index     » next       coverage.py v7.6.8, created at 2024-12-01 20:50 +0000

1# -------------------------------------------------------------------------------------------------- 

2# Copyright (c) Lukas Vik. All rights reserved. 

3# 

4# This file is part of the hdl-registers project, an HDL register generator fast enough to run 

5# in real time. 

6# https://hdl-registers.com 

7# https://github.com/hdl-registers/hdl-registers 

8# -------------------------------------------------------------------------------------------------- 

9 

10# Standard libraries 

11from pathlib import Path 

12from typing import TYPE_CHECKING, Any, Optional 

13 

14# Third party libraries 

15import rtoml 

16 

17# Local folder libraries 

18from .parser import RegisterParser 

19 

20if TYPE_CHECKING: 

21 # First party libraries 

22 from hdl_registers.register import Register 

23 from hdl_registers.register_list import RegisterList 

24 

25 

26def from_toml( 

27 name: str, toml_file: Path, default_registers: Optional[list["Register"]] = None 

28) -> "RegisterList": 

29 """ 

30 Parse a TOML file with register data. 

31 

32 Arguments: 

33 name: The name of the register list. 

34 toml_file: The TOML file path. 

35 default_registers: List of default registers. 

36 

37 Return: 

38 The resulting register list. 

39 """ 

40 parser = RegisterParser( 

41 name=name, source_definition_file=toml_file, default_registers=default_registers 

42 ) 

43 toml_data = _load_toml_file(file_path=toml_file) 

44 

45 return parser.parse(register_data=toml_data) 

46 

47 

48def _load_toml_file(file_path: Path) -> dict[str, Any]: 

49 """ 

50 Load and parse the TOML data into a dictionary. Raise exceptions if things dont work. 

51 """ 

52 if not file_path.exists(): 

53 raise FileNotFoundError(f"Requested TOML file does not exist: {file_path}") 

54 

55 try: 

56 return rtoml.load(file_path) 

57 except Exception as exception_info: 

58 message = f"Error while parsing TOML file {file_path}:\n{exception_info}" 

59 raise ValueError(message) from exception_info