vhdl-style-guide/vsg/diagnostic_runtime.py

111 lines
3.5 KiB
Python

# -*- coding: utf-8 -*-
"""Keeps the machine-readable diagnostic stream valid on every exit path."""
import contextlib
import io
import json
import re
import sys
from vsg.report import diagnostics_json
def run(fMain):
"""Runs VSG normally, guarding stdout only for diagnostic JSON requests."""
if "--diagnostics_json" not in sys.argv[1:]:
return fMain()
oStdout = io.StringIO()
oStderr = io.StringIO()
iExitStatus = 0
oFailure = None
try:
with contextlib.redirect_stdout(oStdout), contextlib.redirect_stderr(oStderr):
fMain()
except SystemExit as oError:
iExitStatus = _exit_status(oError.code)
except Exception as oError: # pragma: no branch - the boundary is intentionally broad
iExitStatus = 1
oFailure = oError
sStdout = oStdout.getvalue().strip()
sStderr = oStderr.getvalue()
if sStderr:
print(sStderr, file=sys.stderr, end="" if sStderr.endswith("\n") else "\n")
if _is_diagnostic_document(sStdout):
print(sStdout)
raise SystemExit(iExitStatus)
if sStdout:
print(sStdout, file=sys.stderr)
sKind, sMessage, dLocation = _failure_details(oFailure, sStdout, sStderr)
dDocument = diagnostics_json.build_incomplete_document(sKind, sMessage, dLocation)
print(diagnostics_json.render(dDocument))
raise SystemExit(iExitStatus or 1)
def _is_diagnostic_document(sOutput):
if not sOutput:
return False
try:
dDocument = json.loads(sOutput)
except (TypeError, ValueError):
return False
return isinstance(dDocument, dict) and dDocument.get("schema") == "vsg.diagnostics"
def _failure_details(oFailure, sStdout, sStderr):
if oFailure is not None:
sDetail = str(oFailure).strip()
if sDetail:
return "internal", "Diagnostic analysis raised " + oFailure.__class__.__name__ + ": " + sDetail, None
return "internal", "Diagnostic analysis raised " + oFailure.__class__.__name__, None
if sStdout:
return "protocol", "VSG did not produce a diagnostic document", None
oUnexpected = re.search(
r"Error: Unexpected token detected while parsing (?P<context>\S+) @ Line (?P<line>\d+), Column (?P<column>\d+)",
sStderr,
)
if oUnexpected is not None:
sExpected = _label_value(sStderr, "Expecting")
sFound = _label_value(sStderr, "Found")
sMessage = "Unexpected token while parsing " + oUnexpected.group("context")
if sExpected:
sMessage += "; expected `" + sExpected + "`"
if sFound:
sMessage += "; found `" + sFound + "`"
return (
"syntax",
sMessage,
{"line": int(oUnexpected.group("line")), "column": int(oUnexpected.group("column"))},
)
oMissing = re.search(r"Error: Closing token not found while parsing Line (?P<line>\d+)", sStderr)
if oMissing is not None:
return "syntax", "Closing token not found", {"line": int(oMissing.group("line")), "column": 1}
lLines = [sLine.strip() for sLine in sStderr.splitlines() if sLine.strip()]
if lLines:
return "analysis", lLines[-1], None
return "analysis", "VSG did not produce a complete diagnostic document", None
def _label_value(sError, sLabel):
oMatch = re.search(r"^\s*" + re.escape(sLabel) + r"\s*:\s*(.*)$", sError, re.MULTILINE)
if oMatch is None:
return ""
return oMatch.group(1).strip()
def _exit_status(oCode):
if oCode is None:
return 0
if isinstance(oCode, int):
return oCode
return 1