formal-lib 1.0.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.
- formal_lib/__about__.py +3 -0
- formal_lib/__init__.py +30 -0
- formal_lib/__main__.py +112 -0
- formal_lib/issue.py +199 -0
- formal_lib/issue_parser.py +285 -0
- formal_lib/logging.py +5 -0
- formal_lib/program_trace.py +33 -0
- formal_lib/py.typed +0 -0
- formal_lib/regex.py +6 -0
- formal_lib/specs/__init__.py +55 -0
- formal_lib/specs/base.py +254 -0
- formal_lib/specs/cbmc.py +57 -0
- formal_lib/specs/clang.py +29 -0
- formal_lib/specs/esbmc.py +127 -0
- formal_lib/specs/pytest.py +56 -0
- formal_lib/verifier_output.py +104 -0
- formal_lib/verifier_runner.py +206 -0
- formal_lib-1.0.0.dist-info/METADATA +185 -0
- formal_lib-1.0.0.dist-info/RECORD +22 -0
- formal_lib-1.0.0.dist-info/WHEEL +4 -0
- formal_lib-1.0.0.dist-info/entry_points.txt +2 -0
- formal_lib-1.0.0.dist-info/licenses/LICENSE +700 -0
formal_lib/__about__.py
ADDED
formal_lib/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# Author: Yiannis Charalambous
|
|
2
|
+
|
|
3
|
+
from formal_lib.__about__ import __version__
|
|
4
|
+
from formal_lib.verifier_runner import VerifierRunner
|
|
5
|
+
from formal_lib.verifier_output import VerifierOutput
|
|
6
|
+
from formal_lib.issue_parser import IssueSpecOutputParser
|
|
7
|
+
from formal_lib.issue import Issue, VerifierIssue
|
|
8
|
+
from formal_lib.specs import (
|
|
9
|
+
SPECS,
|
|
10
|
+
detect_spec,
|
|
11
|
+
cbmc_spec,
|
|
12
|
+
clang_spec,
|
|
13
|
+
esbmc_spec,
|
|
14
|
+
pytest_spec,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"__version__",
|
|
19
|
+
"VerifierRunner",
|
|
20
|
+
"VerifierOutput",
|
|
21
|
+
"IssueSpecOutputParser",
|
|
22
|
+
"Issue",
|
|
23
|
+
"VerifierIssue",
|
|
24
|
+
"SPECS",
|
|
25
|
+
"detect_spec",
|
|
26
|
+
"cbmc_spec",
|
|
27
|
+
"clang_spec",
|
|
28
|
+
"esbmc_spec",
|
|
29
|
+
"pytest_spec",
|
|
30
|
+
]
|
formal_lib/__main__.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# Author: Yiannis Charalambous
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
from subprocess import PIPE, STDOUT, run
|
|
7
|
+
from time import perf_counter
|
|
8
|
+
|
|
9
|
+
from formal_lib.issue import VerifierIssue
|
|
10
|
+
from formal_lib.issue_parser import IssueSpecOutputParser
|
|
11
|
+
from formal_lib.verifier_output import VerifierOutput
|
|
12
|
+
from formal_lib.specs import SPECS, detect_spec
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def pretty_print(result: VerifierOutput) -> None:
|
|
16
|
+
status = "SUCCESS" if result.successful else "FAILURE"
|
|
17
|
+
print(f"Verification: {status}")
|
|
18
|
+
|
|
19
|
+
if not result.issues:
|
|
20
|
+
print("No issues found.")
|
|
21
|
+
for hint in result.hints:
|
|
22
|
+
print(f"Hint: {hint}")
|
|
23
|
+
return
|
|
24
|
+
|
|
25
|
+
print(f"Issues: {result.issue_count}\n")
|
|
26
|
+
|
|
27
|
+
for i, issue in enumerate(result.issues, 1):
|
|
28
|
+
print(f"--- Issue {i} [{issue.severity}] ---")
|
|
29
|
+
print(f"Type: {issue.error_type}")
|
|
30
|
+
if issue.message:
|
|
31
|
+
print(f"Message: {issue.message}")
|
|
32
|
+
if issue.stack_trace:
|
|
33
|
+
print(f"Location: {issue.file_path}:{issue.line_number}")
|
|
34
|
+
if issue.function_name:
|
|
35
|
+
print(f"Function: {issue.function_name}")
|
|
36
|
+
sep = " " if not issue.stack_trace else "\n"
|
|
37
|
+
print(f"Stack trace:{sep}{issue.stack_trace_formatted}")
|
|
38
|
+
if isinstance(issue, VerifierIssue):
|
|
39
|
+
print(f"Counterexample:\n{issue.counterexample_formatted}")
|
|
40
|
+
print()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def main() -> None:
|
|
44
|
+
parser = argparse.ArgumentParser(
|
|
45
|
+
prog="pf",
|
|
46
|
+
epilog="Made by Yiannis Charalambous (https://yiannis.info) for academia",
|
|
47
|
+
description="Pretty Formal: CLI frontend for the formal-lib library. "
|
|
48
|
+
"Provides a frontend that parses verifier output into structured "
|
|
49
|
+
"different formats. Reads from stdin, or runs a command directly when "
|
|
50
|
+
"given after '--'.",
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
parser.add_argument(
|
|
54
|
+
"-b",
|
|
55
|
+
"--backend",
|
|
56
|
+
choices=list(SPECS),
|
|
57
|
+
default=None,
|
|
58
|
+
help="Verifier backend. Auto-detected from output when omitted.",
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
parser.add_argument(
|
|
62
|
+
"-f",
|
|
63
|
+
"--format",
|
|
64
|
+
choices=["pretty", "json", "json-compact"],
|
|
65
|
+
default="pretty",
|
|
66
|
+
help="Output format (default: pretty).",
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
parser.add_argument(
|
|
70
|
+
"command",
|
|
71
|
+
nargs=argparse.REMAINDER,
|
|
72
|
+
help="Command to run (after '--'). Captures exit code and duration.",
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
args = parser.parse_args()
|
|
76
|
+
|
|
77
|
+
command: list[str] = args.command
|
|
78
|
+
if command and command[0] == "--":
|
|
79
|
+
command = command[1:]
|
|
80
|
+
|
|
81
|
+
if command:
|
|
82
|
+
start_time = perf_counter()
|
|
83
|
+
process = run(command, stdout=PIPE, stderr=STDOUT, check=False)
|
|
84
|
+
duration = perf_counter() - start_time
|
|
85
|
+
output = process.stdout.decode("utf-8")
|
|
86
|
+
elif sys.stdin.isatty():
|
|
87
|
+
parser.error("no input: pipe verifier output or pass a command after '--'")
|
|
88
|
+
else:
|
|
89
|
+
output = sys.stdin.read()
|
|
90
|
+
duration = 0.0
|
|
91
|
+
|
|
92
|
+
try:
|
|
93
|
+
spec = SPECS[args.backend] if args.backend else detect_spec(output)
|
|
94
|
+
except ValueError as e:
|
|
95
|
+
parser.error(str(e))
|
|
96
|
+
|
|
97
|
+
result = IssueSpecOutputParser(spec).parse_output(
|
|
98
|
+
output=output,
|
|
99
|
+
duration=duration,
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
match args.format:
|
|
103
|
+
case "pretty":
|
|
104
|
+
pretty_print(result)
|
|
105
|
+
case "json":
|
|
106
|
+
print(json.dumps(result.model_dump(mode="json"), indent=2))
|
|
107
|
+
case "json-compact":
|
|
108
|
+
print(json.dumps(result.model_dump(mode="json"), separators=(",", ":")))
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
if __name__ == "__main__":
|
|
112
|
+
main()
|
formal_lib/issue.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
# Author: Yiannis Charalambous
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
from typing import Literal
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from pydantic import Field, BaseModel
|
|
8
|
+
|
|
9
|
+
from formal_lib.program_trace import ProgramTrace, CounterexampleProgramTrace
|
|
10
|
+
|
|
11
|
+
IssueSeverities = Literal["error", "warning", "info"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ErrorLocation(BaseModel):
|
|
15
|
+
"""Explicit error-location header captured from the verifier's output.
|
|
16
|
+
|
|
17
|
+
Some verifiers print a dedicated "this is where the failure is" line
|
|
18
|
+
separate from any call stack (ESBMC's ``Violated property:``, clang's
|
|
19
|
+
diagnostic header, etc.). When the spec captures one, the parsed
|
|
20
|
+
``ErrorLocation`` is the canonical violation site — preferred over
|
|
21
|
+
the stack trace's last frame for ``file_path`` / ``line_index`` /
|
|
22
|
+
``line_number`` resolution.
|
|
23
|
+
|
|
24
|
+
Distinct from ``ProgramTrace`` because the violation site is a
|
|
25
|
+
location, not a call frame: it has no caller relationship, no symbol
|
|
26
|
+
resolution, and exists once per issue, not once per visited frame.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
path: Path = Field()
|
|
30
|
+
"""The source file the violation is reported in."""
|
|
31
|
+
line_idx: int = Field()
|
|
32
|
+
"""The 0-based line index of the violation."""
|
|
33
|
+
column_idx: int | None = Field(default=None)
|
|
34
|
+
"""Optional 0-based column index, when the verifier prints one."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Issue(BaseModel):
|
|
38
|
+
"""Generic issue/error representation.
|
|
39
|
+
|
|
40
|
+
Location data is taken from ``error_location`` when the spec captured
|
|
41
|
+
one (the verifier's explicit error-location header), falling back to
|
|
42
|
+
``stack_trace[-1]`` otherwise. ``stack_trace`` continues to describe
|
|
43
|
+
the call chain leading to the failure.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
error_type: str = Field(description="Category/type of error.")
|
|
47
|
+
"""Category/type of error."""
|
|
48
|
+
message: str = Field(description="Error description.")
|
|
49
|
+
"""Error description."""
|
|
50
|
+
stack_trace: list[ProgramTrace] = Field(
|
|
51
|
+
description="Stack trace as structured data.",
|
|
52
|
+
)
|
|
53
|
+
"""Stack trace as structured data."""
|
|
54
|
+
severity: IssueSeverities = Field(default="error", description="Severity level.")
|
|
55
|
+
"""Severity level."""
|
|
56
|
+
stack_trace_hint: str = Field(default="", exclude=True)
|
|
57
|
+
"""Hint shown inline when stack_trace is empty (e.g. missing verifier flag)."""
|
|
58
|
+
error_location: ErrorLocation | None = Field(default=None)
|
|
59
|
+
"""Explicit error-location header parsed from the verifier output, when
|
|
60
|
+
the spec provides one. ``Issue`` location properties prefer this over
|
|
61
|
+
the stack trace's last frame."""
|
|
62
|
+
|
|
63
|
+
# Convenience properties.
|
|
64
|
+
# Location-bearing properties read from ``error_location`` when the
|
|
65
|
+
# spec captured one, else fall back to ``stack_trace[-1]``. Defined
|
|
66
|
+
# via _loc to keep the five primitive accessors uniform — adding a
|
|
67
|
+
# sixth means one line, not another if/else.
|
|
68
|
+
|
|
69
|
+
def _loc(self, el_attr: str, frame_attr: str):
|
|
70
|
+
"""Return ``error_location.<el_attr>`` if set, else
|
|
71
|
+
``stack_trace[-1].<frame_attr>``. Raises ``IndexError`` if both
|
|
72
|
+
are absent — callers that need a None-safe fallback should guard
|
|
73
|
+
on ``stack_trace`` themselves."""
|
|
74
|
+
if self.error_location is not None:
|
|
75
|
+
return getattr(self.error_location, el_attr)
|
|
76
|
+
return getattr(self.stack_trace[-1], frame_attr)
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def severity_level(self) -> int:
|
|
80
|
+
match self.severity:
|
|
81
|
+
case "info":
|
|
82
|
+
return 0
|
|
83
|
+
case "warning":
|
|
84
|
+
return 1
|
|
85
|
+
case "error":
|
|
86
|
+
return 2
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def file_path(self) -> Path:
|
|
90
|
+
return self._loc("path", "path")
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def line_index(self) -> int:
|
|
94
|
+
return self._loc("line_idx", "line_idx")
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def line_number(self) -> int:
|
|
98
|
+
return self.line_index + 1
|
|
99
|
+
|
|
100
|
+
@property
|
|
101
|
+
def column_index(self) -> int | None:
|
|
102
|
+
# Stack-trace frames don't carry columns, so this is error_location-only.
|
|
103
|
+
return self.error_location.column_idx if self.error_location else None
|
|
104
|
+
|
|
105
|
+
@property
|
|
106
|
+
def column_number(self) -> int | None:
|
|
107
|
+
idx = self.column_index
|
|
108
|
+
return idx + 1 if idx is not None else None
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def function_name(self) -> str | None:
|
|
112
|
+
"""Function name at the violation site.
|
|
113
|
+
|
|
114
|
+
When ``error_location`` is set, prefer a stack frame whose path
|
|
115
|
+
matches and whose ``name`` is non-None — this skips wrapper /
|
|
116
|
+
instrumentation frames at the top of the trace (e.g. ESBMC's
|
|
117
|
+
``__ESBMC_contracts_original_*`` under --enforce-contracts, whose
|
|
118
|
+
name doesn't resolve via the spec's name regex). Otherwise the
|
|
119
|
+
innermost frame's name is the right answer.
|
|
120
|
+
"""
|
|
121
|
+
if self.error_location is not None:
|
|
122
|
+
for frame in reversed(self.stack_trace):
|
|
123
|
+
if (
|
|
124
|
+
frame.path == self.error_location.path
|
|
125
|
+
and frame.name is not None
|
|
126
|
+
):
|
|
127
|
+
return frame.name
|
|
128
|
+
if self.stack_trace:
|
|
129
|
+
return self.stack_trace[-1].name
|
|
130
|
+
return None
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def stack_trace_formatted(self) -> str:
|
|
134
|
+
"""Returns a formatted string representation of the stack trace.
|
|
135
|
+
|
|
136
|
+
Format: Each trace on a new line showing function name and location.
|
|
137
|
+
Example:
|
|
138
|
+
at main in file.c:15
|
|
139
|
+
at helper in file.c:42
|
|
140
|
+
"""
|
|
141
|
+
if not self.stack_trace:
|
|
142
|
+
hint = f" ({self.stack_trace_hint})" if self.stack_trace_hint else ""
|
|
143
|
+
return f"Not available{hint}"
|
|
144
|
+
lines = []
|
|
145
|
+
for trace in self.stack_trace:
|
|
146
|
+
func_name = trace.name if trace.name else "<unknown>"
|
|
147
|
+
line_num = trace.line_idx + 1 # Convert to 1-based
|
|
148
|
+
lines.append(f"\tat {func_name} in {trace.path}:{line_num}")
|
|
149
|
+
return "\n".join(lines)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class VerifierIssue(Issue):
|
|
153
|
+
"""Verifier-specific issue with additional verification data.
|
|
154
|
+
|
|
155
|
+
This class extends Issue to support verifiers like ESBMC that can provide
|
|
156
|
+
counterexamples in addition to stack traces:
|
|
157
|
+
|
|
158
|
+
- stack_trace: Traditional function call stack showing the path to the error
|
|
159
|
+
- counterexample: Program state trace showing variable values and execution
|
|
160
|
+
states that lead to the bug. This is specific to model checkers and formal
|
|
161
|
+
verification tools like ESBMC.
|
|
162
|
+
|
|
163
|
+
Note: Not all verifiers support counterexamples (e.g., pytest only provides
|
|
164
|
+
stack traces). Use this class only when counterexample data is available.
|
|
165
|
+
"""
|
|
166
|
+
|
|
167
|
+
counterexample: list[CounterexampleProgramTrace] = Field(
|
|
168
|
+
description="Counterexample demonstrating bug."
|
|
169
|
+
)
|
|
170
|
+
"""Counterexample demonstrating bug."""
|
|
171
|
+
counterexample_hint: str = Field(default="", exclude=True)
|
|
172
|
+
"""Hint shown inline when counterexample is empty (e.g. missing verifier flag)."""
|
|
173
|
+
|
|
174
|
+
@property
|
|
175
|
+
def counterexample_formatted(self) -> str:
|
|
176
|
+
"""Returns a formatted string representation of the counterexample trace.
|
|
177
|
+
|
|
178
|
+
Format: Each trace on a new line showing function name, location, and
|
|
179
|
+
assignment (if available).
|
|
180
|
+
Example:
|
|
181
|
+
State 0: at main in file.c:15
|
|
182
|
+
dist = { 0, 0, 0, 0, 0 }
|
|
183
|
+
State 1: at helper in file.c:42
|
|
184
|
+
dist[0] = 2147483647 (01111111 11111111 11111111 11111111)
|
|
185
|
+
"""
|
|
186
|
+
if not self.counterexample:
|
|
187
|
+
hint = f" ({self.counterexample_hint})" if self.counterexample_hint else ""
|
|
188
|
+
return f"Not available{hint}"
|
|
189
|
+
lines = []
|
|
190
|
+
for trace in self.counterexample:
|
|
191
|
+
func_name = trace.name if trace.name else "<unknown>"
|
|
192
|
+
line_num = trace.line_idx + 1 # Convert to 1-based
|
|
193
|
+
lines.append(
|
|
194
|
+
f"\tState {trace.trace_index}: at {func_name} in {trace.path}:{line_num}"
|
|
195
|
+
)
|
|
196
|
+
# Add assignment information if available
|
|
197
|
+
if trace.assignment:
|
|
198
|
+
lines.append("\t\t" + trace.assignment.replace("\n", "\n\t\t"))
|
|
199
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
# Author: Yiannis Charalambous
|
|
2
|
+
|
|
3
|
+
"""Regex-based parser for extracting structured issues from verifier output."""
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import cast, get_args
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from formal_lib.program_trace import ProgramTrace, CounterexampleProgramTrace
|
|
10
|
+
from formal_lib.verifier_output import VerifierOutput
|
|
11
|
+
from formal_lib.issue import ErrorLocation, Issue, IssueSeverities, VerifierIssue
|
|
12
|
+
from formal_lib.regex import ANSI_ESCAPE_PATTERN
|
|
13
|
+
from formal_lib.specs.base import (
|
|
14
|
+
AnnotatedPattern,
|
|
15
|
+
CounterexampleRegexSpec,
|
|
16
|
+
DeepestFirstPattern,
|
|
17
|
+
ErrorLocationRegexSpec,
|
|
18
|
+
FormattedPattern,
|
|
19
|
+
IssueRegexSpec,
|
|
20
|
+
MultiPattern,
|
|
21
|
+
StackTraceRegexSpec,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class IssueSpecOutputParser:
|
|
26
|
+
"""Parses raw verifier output into structured issues using an IssueRegexSpec."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, regex_spec: IssueRegexSpec) -> None:
|
|
29
|
+
self.regex_spec: IssueRegexSpec = regex_spec
|
|
30
|
+
|
|
31
|
+
def parse_output(
|
|
32
|
+
self, output: str, duration: float = 0.0
|
|
33
|
+
) -> VerifierOutput:
|
|
34
|
+
# Strip ANSI escape codes in case the tool emits colored output.
|
|
35
|
+
output = ANSI_ESCAPE_PATTERN.sub("", output)
|
|
36
|
+
|
|
37
|
+
# Determine success from the spec's success pattern.
|
|
38
|
+
spec = self.regex_spec
|
|
39
|
+
if spec.success:
|
|
40
|
+
matched = bool(re.search(spec.success, output, re.MULTILINE))
|
|
41
|
+
successful = not matched if spec.negate_success else matched
|
|
42
|
+
else:
|
|
43
|
+
successful = True
|
|
44
|
+
|
|
45
|
+
# Extract all issue blocks from the output
|
|
46
|
+
issue_blocks: list[str] = []
|
|
47
|
+
for match in re.finditer(spec.block, output, re.DOTALL | re.MULTILINE):
|
|
48
|
+
issue_blocks.append(match.group(0))
|
|
49
|
+
|
|
50
|
+
# Parse each issue block to extract individual issues
|
|
51
|
+
issues: list[Issue] = [self._parse_issue(block) for block in issue_blocks]
|
|
52
|
+
|
|
53
|
+
# Collect hints from annotated blocks that failed to match.
|
|
54
|
+
hints: list[str] = []
|
|
55
|
+
if not successful and not issues:
|
|
56
|
+
hint = self._get_hint(spec.block)
|
|
57
|
+
if hint:
|
|
58
|
+
hints.append(hint)
|
|
59
|
+
|
|
60
|
+
return VerifierOutput(
|
|
61
|
+
successful=successful,
|
|
62
|
+
issues=issues,
|
|
63
|
+
output=output,
|
|
64
|
+
duration=duration,
|
|
65
|
+
hints=hints,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
@staticmethod
|
|
69
|
+
def _get_hint(pattern: str) -> str:
|
|
70
|
+
return pattern.hint if isinstance(pattern, AnnotatedPattern) else ""
|
|
71
|
+
|
|
72
|
+
@staticmethod
|
|
73
|
+
def _apply_format(pattern: str | None, value: str) -> str:
|
|
74
|
+
return pattern.formatter(value) if isinstance(pattern, FormattedPattern) else value
|
|
75
|
+
|
|
76
|
+
@staticmethod
|
|
77
|
+
def _search_field(
|
|
78
|
+
pattern: str, text: str
|
|
79
|
+
) -> tuple[re.Match[str] | None, str | None]:
|
|
80
|
+
"""Try each alternative in a ``MultiPattern`` until one matches; for a
|
|
81
|
+
plain str pattern, behave like a single ``re.search``.
|
|
82
|
+
|
|
83
|
+
Returns ``(None, None)`` when nothing matched; otherwise the match
|
|
84
|
+
and the specific alternative that produced it (so per-branch
|
|
85
|
+
``FormattedPattern.formatter`` dispatch works inside a MultiPattern).
|
|
86
|
+
"""
|
|
87
|
+
candidates: tuple[str, ...] = (
|
|
88
|
+
pattern.patterns if isinstance(pattern, MultiPattern) else (pattern,)
|
|
89
|
+
)
|
|
90
|
+
for p in candidates:
|
|
91
|
+
m = re.search(p, text, re.MULTILINE)
|
|
92
|
+
if m is not None:
|
|
93
|
+
return m, p
|
|
94
|
+
return None, None
|
|
95
|
+
|
|
96
|
+
@staticmethod
|
|
97
|
+
def _parse_traces(
|
|
98
|
+
text: str,
|
|
99
|
+
spec: StackTraceRegexSpec,
|
|
100
|
+
*,
|
|
101
|
+
as_counterexample: bool = False,
|
|
102
|
+
) -> list[ProgramTrace]:
|
|
103
|
+
"""Parse trace entries from text using a StackTraceRegexSpec.
|
|
104
|
+
|
|
105
|
+
When as_counterexample is True and spec is a CounterexampleRegexSpec,
|
|
106
|
+
produces CounterexampleProgramTrace with assignment data.
|
|
107
|
+
"""
|
|
108
|
+
flags = re.DOTALL | re.MULTILINE if as_counterexample else re.MULTILINE
|
|
109
|
+
block_match = re.search(spec.block, text, flags)
|
|
110
|
+
if not block_match:
|
|
111
|
+
return []
|
|
112
|
+
|
|
113
|
+
block_text = block_match.group(0)
|
|
114
|
+
traces: list[ProgramTrace] = []
|
|
115
|
+
|
|
116
|
+
for trace_index, entry_match in enumerate(
|
|
117
|
+
re.finditer(spec.trace_entry, block_text, flags)
|
|
118
|
+
):
|
|
119
|
+
entry_text = entry_match.group(0)
|
|
120
|
+
|
|
121
|
+
path_match = re.search(spec.path, entry_text)
|
|
122
|
+
line_idx_match = re.search(spec.line_index, entry_text)
|
|
123
|
+
if not (path_match and line_idx_match):
|
|
124
|
+
continue
|
|
125
|
+
|
|
126
|
+
name_match = re.search(spec.name, entry_text)
|
|
127
|
+
path = Path(path_match.group(1))
|
|
128
|
+
name = name_match.group(1) if name_match and name_match.lastindex else None
|
|
129
|
+
line_idx = int(line_idx_match.group(1)) - 1 # Convert to 0-based
|
|
130
|
+
|
|
131
|
+
if (
|
|
132
|
+
as_counterexample
|
|
133
|
+
and isinstance(spec, CounterexampleRegexSpec)
|
|
134
|
+
and spec.assignment
|
|
135
|
+
):
|
|
136
|
+
assignment_match = re.search(
|
|
137
|
+
spec.assignment,
|
|
138
|
+
entry_text,
|
|
139
|
+
re.DOTALL,
|
|
140
|
+
)
|
|
141
|
+
assignment = (
|
|
142
|
+
assignment_match.group(1).strip() if assignment_match else None
|
|
143
|
+
)
|
|
144
|
+
traces.append(
|
|
145
|
+
CounterexampleProgramTrace(
|
|
146
|
+
trace_index=trace_index,
|
|
147
|
+
path=path,
|
|
148
|
+
name=name,
|
|
149
|
+
line_idx=line_idx,
|
|
150
|
+
assignment=assignment,
|
|
151
|
+
)
|
|
152
|
+
)
|
|
153
|
+
else:
|
|
154
|
+
traces.append(
|
|
155
|
+
ProgramTrace(
|
|
156
|
+
trace_index=trace_index,
|
|
157
|
+
path=path,
|
|
158
|
+
name=name,
|
|
159
|
+
line_idx=line_idx,
|
|
160
|
+
)
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
# Some verifiers (ESBMC, CBMC, GDB-style) print frames deepest-first.
|
|
164
|
+
# The deepest_first wrapper on trace_entry signals "reverse the
|
|
165
|
+
# captured list" so consumers always see stack_trace[-1] as the
|
|
166
|
+
# failure frame regardless of source-format direction. Re-index
|
|
167
|
+
# after reversal so trace_index reflects post-reverse position.
|
|
168
|
+
if isinstance(spec.trace_entry, DeepestFirstPattern):
|
|
169
|
+
traces.reverse()
|
|
170
|
+
for new_index, trace in enumerate(traces):
|
|
171
|
+
trace.trace_index = new_index
|
|
172
|
+
|
|
173
|
+
return traces
|
|
174
|
+
|
|
175
|
+
@staticmethod
|
|
176
|
+
def _parse_error_location(
|
|
177
|
+
text: str, spec: ErrorLocationRegexSpec
|
|
178
|
+
) -> ErrorLocation | None:
|
|
179
|
+
"""Apply an ErrorLocationRegexSpec; return None when no match.
|
|
180
|
+
|
|
181
|
+
Scopes path/line/column extraction to ``spec.block`` when the
|
|
182
|
+
block regex is non-empty, else searches the whole issue text.
|
|
183
|
+
Both ``path`` and ``line_index`` must capture for an
|
|
184
|
+
``ErrorLocation`` to be produced — a half-match returns None
|
|
185
|
+
and the caller falls back to the stack trace.
|
|
186
|
+
"""
|
|
187
|
+
scope = text
|
|
188
|
+
if spec.block:
|
|
189
|
+
block_match = re.search(spec.block, text, re.MULTILINE)
|
|
190
|
+
if not block_match:
|
|
191
|
+
return None
|
|
192
|
+
scope = block_match.group(0)
|
|
193
|
+
|
|
194
|
+
path_match = re.search(spec.path, scope) if spec.path else None
|
|
195
|
+
line_match = re.search(spec.line_index, scope) if spec.line_index else None
|
|
196
|
+
if not (path_match and line_match):
|
|
197
|
+
return None
|
|
198
|
+
|
|
199
|
+
column_idx: int | None = None
|
|
200
|
+
if spec.column_index:
|
|
201
|
+
col_match = re.search(spec.column_index, scope)
|
|
202
|
+
if col_match:
|
|
203
|
+
column_idx = int(col_match.group(1)) - 1
|
|
204
|
+
|
|
205
|
+
return ErrorLocation(
|
|
206
|
+
path=Path(path_match.group(1)),
|
|
207
|
+
line_idx=int(line_match.group(1)) - 1,
|
|
208
|
+
column_idx=column_idx,
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
def _parse_issue(self, issue_text: str) -> Issue:
|
|
212
|
+
"""Function that parses a single issue and returns it."""
|
|
213
|
+
|
|
214
|
+
# Extract error type. The formatter is dispatched on the *matched*
|
|
215
|
+
# alternative so MultiPattern branches can each carry their own
|
|
216
|
+
# format_match (or none). _apply_format is a no-op when nothing matched.
|
|
217
|
+
error_type_match, matched_et_pattern = self._search_field(
|
|
218
|
+
self.regex_spec.error_type, issue_text
|
|
219
|
+
)
|
|
220
|
+
error_type = error_type_match.group(1) if error_type_match else "Unknown"
|
|
221
|
+
error_type = self._apply_format(matched_et_pattern, error_type)
|
|
222
|
+
|
|
223
|
+
# Extract message — same matched-pattern dispatch as error_type.
|
|
224
|
+
message_match, matched_msg_pattern = self._search_field(
|
|
225
|
+
self.regex_spec.message, issue_text
|
|
226
|
+
)
|
|
227
|
+
message = message_match.group(1) if message_match else ""
|
|
228
|
+
message = self._apply_format(matched_msg_pattern, message)
|
|
229
|
+
message = re.sub(r"\s*\n\s*", " ", message)
|
|
230
|
+
|
|
231
|
+
# Extract severity
|
|
232
|
+
severity_match = re.search(self.regex_spec.severity, issue_text, re.MULTILINE)
|
|
233
|
+
severity_str = severity_match.group(1).lower() if severity_match else "error"
|
|
234
|
+
# Convert to valid severity literal
|
|
235
|
+
if severity_str not in get_args(IssueSeverities):
|
|
236
|
+
severity_str = "error"
|
|
237
|
+
# Type cast after validation
|
|
238
|
+
severity: IssueSeverities = cast(IssueSeverities, severity_str)
|
|
239
|
+
|
|
240
|
+
# Extract stack trace
|
|
241
|
+
st_spec = self.regex_spec.stack_trace_spec
|
|
242
|
+
stack_trace: list[ProgramTrace] = self._parse_traces(issue_text, st_spec)
|
|
243
|
+
stack_trace_hint = self._get_hint(st_spec.block) if not stack_trace else ""
|
|
244
|
+
|
|
245
|
+
# Extract explicit error-location header when the spec defines one.
|
|
246
|
+
# When None on the spec or no match in the text, error_location stays
|
|
247
|
+
# None and Issue.file_path falls back to stack_trace[-1].
|
|
248
|
+
el_spec = self.regex_spec.error_location
|
|
249
|
+
error_location: ErrorLocation | None = (
|
|
250
|
+
self._parse_error_location(issue_text, el_spec) if el_spec else None
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
# Parse counterexample if spec provides one
|
|
254
|
+
ce_spec = self.regex_spec.counterexample_spec
|
|
255
|
+
if ce_spec:
|
|
256
|
+
counterexample = self._parse_traces(
|
|
257
|
+
issue_text,
|
|
258
|
+
ce_spec,
|
|
259
|
+
as_counterexample=True,
|
|
260
|
+
)
|
|
261
|
+
counterexample_hint = (
|
|
262
|
+
self._get_hint(ce_spec.block) if not counterexample else ""
|
|
263
|
+
)
|
|
264
|
+
return VerifierIssue(
|
|
265
|
+
error_type=error_type,
|
|
266
|
+
message=message,
|
|
267
|
+
stack_trace=stack_trace,
|
|
268
|
+
stack_trace_hint=stack_trace_hint,
|
|
269
|
+
counterexample=cast(
|
|
270
|
+
list[CounterexampleProgramTrace],
|
|
271
|
+
counterexample,
|
|
272
|
+
),
|
|
273
|
+
counterexample_hint=counterexample_hint,
|
|
274
|
+
severity=severity,
|
|
275
|
+
error_location=error_location,
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
return Issue(
|
|
279
|
+
error_type=error_type,
|
|
280
|
+
message=message,
|
|
281
|
+
stack_trace=stack_trace,
|
|
282
|
+
stack_trace_hint=stack_trace_hint,
|
|
283
|
+
severity=severity,
|
|
284
|
+
error_location=error_location,
|
|
285
|
+
)
|
formal_lib/logging.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Author: Yiannis Charalambous
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from pydantic import BaseModel, Field
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class ProgramTrace(BaseModel):
|
|
8
|
+
"""Contains information about traces in source code."""
|
|
9
|
+
|
|
10
|
+
trace_index: int = Field()
|
|
11
|
+
"""The index position of this trace point in the trace stack."""
|
|
12
|
+
path: Path = Field()
|
|
13
|
+
"""The source file of this trace. May not exist for compilation errors. May
|
|
14
|
+
not be relative as it may be a system file."""
|
|
15
|
+
name: str | None = Field(default=None)
|
|
16
|
+
"""The name of the symbol pointed to by the trace, if applicable."""
|
|
17
|
+
line_idx: int = Field()
|
|
18
|
+
"""The location of the trace (0-based)."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class CounterexampleProgramTrace(ProgramTrace):
|
|
22
|
+
"""Program trace with assignment information from counterexample states.
|
|
23
|
+
|
|
24
|
+
This class extends ProgramTrace to capture the variable assignments that
|
|
25
|
+
led to a verification failure. Used by verifiers like ESBMC that provide
|
|
26
|
+
counterexample traces showing the state of variables at each step.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
assignment: str | None = Field(default=None)
|
|
30
|
+
"""The assignment statement(s) for this trace state. Contains the variable
|
|
31
|
+
assignments from the counterexample, e.g., 'dist = { 0, 0, 0, 0, 0 }' or
|
|
32
|
+
'dist[0] = 2147483647 (01111111 11111111 11111111 11111111)'. May be None
|
|
33
|
+
if the state has no assignment information."""
|
formal_lib/py.typed
ADDED
|
File without changes
|