texact 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
configuration.py ADDED
@@ -0,0 +1,177 @@
1
+ from collections.abc import Mapping
2
+ from dataclasses import dataclass, field
3
+ from pathlib import Path
4
+ import re
5
+ import tomllib
6
+
7
+
8
+ _CONFIG_FILENAMES = (".texact.toml", "texact.toml", "pyproject.toml")
9
+ _RULE_CODE_PATTERN = re.compile(r"[A-Z]{2,3}\d{3,}")
10
+
11
+
12
+ class ConfigurationError(ValueError):
13
+ """Raised when a TeXact configuration cannot be used."""
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class LintConfig:
18
+ """Lint settings loaded from a TeXact configuration."""
19
+
20
+ ignore: frozenset[str] = frozenset()
21
+ casing: tuple[str, ...] = ()
22
+ we_count: int = 5
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class FormatConfig:
27
+ """Output formatting settings loaded from a TeXact configuration."""
28
+
29
+ html_style: bool = False
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class ToolsConfig:
34
+ """External tool settings loaded from a TeXact configuration."""
35
+
36
+ chktex_path: str | None = None
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class TexactConfig:
41
+ """Complete, immutable TeXact configuration."""
42
+
43
+ lint: LintConfig = field(default_factory=LintConfig)
44
+ format: FormatConfig = field(default_factory=FormatConfig)
45
+ tools: ToolsConfig = field(default_factory=ToolsConfig)
46
+ source_path: Path | None = None
47
+
48
+
49
+ def load_config(
50
+ config_path: Path | None = None,
51
+ directory: Path | None = None,
52
+ ) -> TexactConfig:
53
+ """Load explicit or automatically discovered TeXact configuration."""
54
+ if config_path is not None:
55
+ path = Path(config_path)
56
+ if not path.is_file():
57
+ raise ConfigurationError(f"Configuration file not found: {path}")
58
+ config = _load_file(path)
59
+ return config or TexactConfig(source_path=path)
60
+
61
+ search_directory = Path.cwd() if directory is None else Path(directory)
62
+ for filename in _CONFIG_FILENAMES:
63
+ path = search_directory / filename
64
+ if not path.is_file():
65
+ continue
66
+ config = _load_file(path)
67
+ if config is not None:
68
+ return config
69
+
70
+ return TexactConfig()
71
+
72
+
73
+ def _load_file(path: Path) -> TexactConfig | None:
74
+ try:
75
+ with path.open("rb") as config_file:
76
+ data = tomllib.load(config_file)
77
+ except tomllib.TOMLDecodeError as error:
78
+ raise ConfigurationError(f"Invalid TOML in {path}: {error}") from error
79
+ except OSError as error:
80
+ raise ConfigurationError(
81
+ f"Could not read configuration {path}: {error}"
82
+ ) from error
83
+
84
+ if path.name == "pyproject.toml":
85
+ tool = data.get("tool")
86
+ if tool is None:
87
+ return None
88
+ if not isinstance(tool, Mapping):
89
+ raise ConfigurationError(f"{path}: 'tool' must be a TOML table")
90
+ data = tool.get("texact")
91
+ if data is None:
92
+ return None
93
+
94
+ if not isinstance(data, Mapping):
95
+ raise ConfigurationError(f"{path}: configuration must be a TOML table")
96
+
97
+ return _parse_config(data, path)
98
+
99
+
100
+ def _parse_config(data: Mapping[str, object], path: Path) -> TexactConfig:
101
+ _check_keys(data, {"lint", "format", "tools"}, path, "")
102
+
103
+ lint_data = _table(data.get("lint"), path, "lint")
104
+ format_data = _table(data.get("format"), path, "format")
105
+ tools_data = _table(data.get("tools"), path, "tools")
106
+
107
+ _check_keys(lint_data, {"ignore", "casing", "we_count"}, path, "lint")
108
+ _check_keys(format_data, {"html-style"}, path, "format")
109
+ _check_keys(tools_data, {"chktex_path"}, path, "tools")
110
+
111
+ ignore = _string_list(lint_data.get("ignore", []), path, "lint.ignore")
112
+ invalid_codes = [code for code in ignore if not _RULE_CODE_PATTERN.fullmatch(code)]
113
+ if invalid_codes:
114
+ raise ConfigurationError(
115
+ f"{path}: lint.ignore contains invalid rule code(s): "
116
+ f"{', '.join(invalid_codes)}"
117
+ )
118
+
119
+ casing = _string_list(lint_data.get("casing", []), path, "lint.casing")
120
+ we_count = lint_data.get("we_count", 5)
121
+ if isinstance(we_count, bool) or not isinstance(we_count, int):
122
+ raise ConfigurationError(f"{path}: lint.we_count must be an integer")
123
+ if we_count < 0:
124
+ raise ConfigurationError(f"{path}: lint.we_count must be non-negative")
125
+
126
+ html_style = format_data.get("html-style", False)
127
+ if not isinstance(html_style, bool):
128
+ raise ConfigurationError(f"{path}: format.html-style must be a boolean")
129
+
130
+ chktex_path = tools_data.get("chktex_path")
131
+ if chktex_path is not None and not isinstance(chktex_path, str):
132
+ raise ConfigurationError(f"{path}: tools.chktex_path must be a string")
133
+ if chktex_path == "":
134
+ raise ConfigurationError(f"{path}: tools.chktex_path must not be empty")
135
+
136
+ return TexactConfig(
137
+ lint=LintConfig(
138
+ ignore=frozenset(ignore),
139
+ casing=casing,
140
+ we_count=we_count,
141
+ ),
142
+ format=FormatConfig(html_style=html_style),
143
+ tools=ToolsConfig(chktex_path=chktex_path),
144
+ source_path=path,
145
+ )
146
+
147
+
148
+ def _table(
149
+ value: object,
150
+ path: Path,
151
+ name: str,
152
+ ) -> Mapping[str, object]:
153
+ if value is None:
154
+ return {}
155
+ if not isinstance(value, Mapping):
156
+ raise ConfigurationError(f"{path}: [{name}] must be a TOML table")
157
+ return value
158
+
159
+
160
+ def _string_list(value: object, path: Path, name: str) -> tuple[str, ...]:
161
+ if not isinstance(value, list):
162
+ raise ConfigurationError(f"{path}: {name} must be an array of strings")
163
+ if any(not isinstance(item, str) for item in value):
164
+ raise ConfigurationError(f"{path}: {name} must be an array of strings")
165
+ return tuple(value)
166
+
167
+
168
+ def _check_keys(
169
+ data: Mapping[str, object],
170
+ allowed: set[str],
171
+ path: Path,
172
+ section: str,
173
+ ) -> None:
174
+ for key in data:
175
+ if key not in allowed:
176
+ option = f"{section}.{key}" if section else key
177
+ raise ConfigurationError(f"{path}: unsupported option '{option}'")
printer.py ADDED
@@ -0,0 +1,78 @@
1
+ """Class for printing output."""
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from colorama import Fore, Style, init as colorama_init
6
+
7
+ if TYPE_CHECKING: # Only for type hints
8
+ from reviewers.reviewer import Diagnostic, Status
9
+
10
+
11
+ class Printer:
12
+ """Formats TeXact output for terminal or HTML display."""
13
+
14
+ GREEN = Fore.GREEN
15
+ DARK_RED = Fore.RED
16
+ YELLOW = Fore.YELLOW
17
+ RESET = Style.RESET_ALL
18
+ HTML_GREEN = "#008000"
19
+ HTML_DARK_RED = "#800000"
20
+ HTML_YELLOW = "#808000"
21
+
22
+ def __init__(self, html_style: bool = False) -> None:
23
+ self.html_style = html_style
24
+ if not self.html_style:
25
+ colorama_init()
26
+
27
+ def print(self, message: str) -> None:
28
+ if self.html_style:
29
+ print(f"{message}<br>")
30
+ else:
31
+ print(message)
32
+
33
+ def print_no(self, line_no: int, warning_number: int, message: str) -> None:
34
+ line_label = f"L{line_no + 1}:"
35
+ warning_label = f"[{warning_number}]"
36
+ if self.html_style:
37
+ print(
38
+ f"{self.green(line_label)} {self.yellow(warning_label)} {message}<br>"
39
+ )
40
+ else:
41
+ print(f"{self.green(line_label)} {self.yellow(warning_label)} {message}")
42
+
43
+ def print_diagnostic(self, diagnostic: "Diagnostic") -> None:
44
+ line_label = self.green(f"L{diagnostic.line}")
45
+ color = self.yellow if diagnostic.severity.value == "warning" else self.dark_red
46
+ warning_label = color(f"[{diagnostic.code}]")
47
+ message = f"{line_label} {warning_label}: {diagnostic.message}"
48
+ if self.html_style:
49
+ print(f"{message}<br>")
50
+ else:
51
+ print(message)
52
+
53
+ def green(self, message: str) -> str:
54
+ if self.html_style:
55
+ return self.html_color(message, self.HTML_GREEN)
56
+ return f"{self.GREEN}{message}{self.RESET}"
57
+
58
+ def yellow(self, message: str) -> str:
59
+ if self.html_style:
60
+ return self.html_color(message, self.HTML_YELLOW)
61
+ return f"{self.YELLOW}{message}{self.RESET}"
62
+
63
+ def dark_red(self, message: str) -> str:
64
+ if self.html_style:
65
+ return self.html_color(message, self.HTML_DARK_RED)
66
+ return f"{self.DARK_RED}{message}{self.RESET}"
67
+
68
+ def html_color(self, text: str, color: str) -> str:
69
+ return f'<span style="color:{color}">{text}</span>'
70
+
71
+ def status_str(self, status: "Status") -> str:
72
+ name = getattr(status, "name", str(status))
73
+ if name == "PASSED":
74
+ return self.green(name)
75
+ elif name == "FAILED":
76
+ return self.dark_red(name)
77
+ else:
78
+ return self.yellow(name)
reviewers/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Reviewer implementations for TeXact."""
reviewers/reviewer.py ADDED
@@ -0,0 +1,76 @@
1
+ from abc import ABC, abstractmethod
2
+ from dataclasses import dataclass, replace
3
+ from pathlib import Path
4
+ from enum import Enum, auto
5
+
6
+ from printer import Printer
7
+ from .rules import Rule, Severity
8
+
9
+
10
+ class Status(Enum):
11
+ """Result states for reviewers."""
12
+
13
+ PASSED = auto()
14
+ FAILED = auto()
15
+ WARNING = auto()
16
+ UNCHECKED = auto()
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Diagnostic:
21
+ """One rule finding and its source location."""
22
+
23
+ line_no: int
24
+ rule: Rule
25
+ message: str
26
+ source_path: Path | None = None
27
+ severity_override: Severity | None = None
28
+
29
+ @property
30
+ def code(self) -> str:
31
+ return self.rule.code
32
+
33
+ @property
34
+ def severity(self) -> Severity:
35
+ return self.severity_override or self.rule.severity
36
+
37
+ @property
38
+ def line(self) -> int:
39
+ return self.line_no + 1
40
+
41
+ @property
42
+ def filename(self) -> str | None:
43
+ if self.source_path is None:
44
+ return None
45
+ return str(self.source_path)
46
+
47
+ def with_source(self, source_path: Path) -> "Diagnostic":
48
+ return replace(self, source_path=source_path)
49
+
50
+
51
+ class Reviewer(ABC):
52
+ """Base interface for reviewers."""
53
+
54
+ @abstractmethod
55
+ def __init__(self, printer: Printer) -> None:
56
+ raise NotImplementedError
57
+
58
+ @abstractmethod
59
+ def process_line(self, line_no: int, line: str) -> None:
60
+ raise NotImplementedError
61
+
62
+ @abstractmethod
63
+ def get_comments(self) -> list[Diagnostic]:
64
+ raise NotImplementedError
65
+
66
+ @abstractmethod
67
+ def get_summary(self) -> str:
68
+ raise NotImplementedError
69
+
70
+ @abstractmethod
71
+ def get_status(self) -> Status:
72
+ raise NotImplementedError
73
+
74
+ @abstractmethod
75
+ def get_name(self) -> str:
76
+ raise NotImplementedError
@@ -0,0 +1,165 @@
1
+ import re
2
+
3
+ from .reviewer import Diagnostic, Reviewer, Status
4
+ from .rules import RULE_CAS001
5
+ from printer import Printer
6
+
7
+
8
+ class Reviewer_Casing(Reviewer):
9
+ """Checks the casing of known terms."""
10
+
11
+ # Canonical spellings to enforce
12
+ CORRECT_SPELLINGS = (
13
+ "ASIC",
14
+ "CMOS",
15
+ "CORDIC",
16
+ "FPGA",
17
+ "VLSI",
18
+ "FloPoCo",
19
+ "RTL",
20
+ "HDL",
21
+ "FSM",
22
+ "DNN",
23
+ "CNN",
24
+ "ReLU",
25
+ "PWL",
26
+ "RAM",
27
+ "RMS",
28
+ "Verilog",
29
+ "SystemVerilog",
30
+ "VHDL",
31
+ "FIR",
32
+ "IIR",
33
+ "LWDF",
34
+ # "AXI", # collides with the word axis
35
+ "SRAM",
36
+ "DSP",
37
+ "FIFO",
38
+ "ALU",
39
+ "PDK",
40
+ "PLL",
41
+ "HLS",
42
+ "AI",
43
+ "ML",
44
+ "AMD",
45
+ "Intel",
46
+ "Xilinx",
47
+ "Altera",
48
+ "Lattice",
49
+ "LSTM",
50
+ "TSMC",
51
+ "FD-SOI",
52
+ "Synopsys",
53
+ "Cadence",
54
+ "Vivado",
55
+ "Quartus",
56
+ "APyTypes",
57
+ "URL",
58
+ "DNS",
59
+ "BRAM",
60
+ "DRAM",
61
+ "NaN",
62
+ "LUT",
63
+ "LNS",
64
+ "MNIST",
65
+ "MHz",
66
+ "kHz",
67
+ "GHz",
68
+ "GiB",
69
+ "MiB",
70
+ "Basys",
71
+ "Virtex",
72
+ "Spartan",
73
+ "MIPS",
74
+ "TOML",
75
+ "CSV",
76
+ "RISC",
77
+ "CISC",
78
+ "EDA",
79
+ "Python",
80
+ "GitHub",
81
+ "GitLab",
82
+ "VSCode",
83
+ "IEE",
84
+ "FOSSi",
85
+ "ELLIIT",
86
+ "VCD",
87
+ "FST",
88
+ "GHW",
89
+ "WASM",
90
+ "HTML",
91
+ )
92
+ _PATTERN_LATEX_IGNORED_COMMANDS = re.compile(
93
+ r"\\(?:cite|ref|label|url|usepackage)\{[^}]*\}"
94
+ )
95
+
96
+ def __init__(
97
+ self,
98
+ printer: Printer,
99
+ additional_spellings: tuple[str, ...] = (),
100
+ ) -> None:
101
+ self.printer = printer
102
+ self.correct_spellings = tuple(
103
+ dict.fromkeys((*self.CORRECT_SPELLINGS, *additional_spellings))
104
+ )
105
+ self.comments: list[Diagnostic] = []
106
+ self.mismatch_count = 0
107
+
108
+ def process_line(self, line_no: int, line: str) -> None:
109
+ # Remove comments (everything after %)
110
+ if "%" in line:
111
+ line = line[: line.index("%")]
112
+
113
+ # Ignore casing checks inside \cite{...}, \ref{...}, \label{...}, and \url{...}
114
+ line = self._PATTERN_LATEX_IGNORED_COMMANDS.sub(
115
+ lambda match: " " * len(match.group(0)),
116
+ line,
117
+ )
118
+
119
+ # Check each word in the line
120
+ for correct_spelling in self.correct_spellings:
121
+ word_lower = correct_spelling.lower()
122
+ # Create regex pattern to match the word with optional suffixes:
123
+ # - plural 's': fpgas
124
+ # - possessive 's: fpga's
125
+ # - colon suffix: fpga:s
126
+ # - hyphenated compounds: fpga-design
127
+ pattern = re.compile(
128
+ r"(?<![a-zA-Z])(?P<base>"
129
+ + re.escape(word_lower)
130
+ + r")(?P<suffix>s|'s|:s)?(?=\W|$)",
131
+ re.IGNORECASE,
132
+ )
133
+
134
+ for match in pattern.finditer(line):
135
+ matched_text = match.group(0)
136
+ matched_base = match.group("base")
137
+ matched_suffix = match.group("suffix") or ""
138
+ normalized_suffix = matched_suffix.lower()
139
+ expected_text = f"{correct_spelling}{normalized_suffix}"
140
+ if matched_base != correct_spelling:
141
+ self.comments.append(
142
+ Diagnostic(
143
+ line_no,
144
+ RULE_CAS001,
145
+ RULE_CAS001.render_message(
146
+ actual=self.printer.dark_red(matched_text),
147
+ expected=self.printer.yellow(expected_text),
148
+ ),
149
+ )
150
+ )
151
+ self.mismatch_count += 1
152
+
153
+ def get_comments(self) -> list[Diagnostic]:
154
+ return self.comments
155
+
156
+ def get_summary(self) -> str:
157
+ if self.mismatch_count == 0:
158
+ return ""
159
+ return f"Casing errors: {self.mismatch_count}"
160
+
161
+ def get_status(self) -> Status:
162
+ return Status.PASSED if self.mismatch_count == 0 else Status.FAILED
163
+
164
+ def get_name(self) -> str:
165
+ return "Casing"