L3.diagnostics

  1from __future__ import annotations
  2
  3import re
  4from collections.abc import Sequence
  5from pathlib import Path
  6from typing import Literal
  7
  8from lark import UnexpectedInput
  9from pydantic import BaseModel
 10
 11from .check import check_program
 12from .parse import parse_program
 13
 14type DiagnosticStage = Literal["syntax", "semantic", "internal"]
 15type DiagnosticSeverity = Literal["error", "warning", "information"]
 16
 17
 18class Diagnostic(BaseModel, frozen=True):
 19    stage: DiagnosticStage
 20    severity: DiagnosticSeverity = "error"
 21    code: str
 22    message: str
 23    line: int | None = None
 24    column: int | None = None
 25    end_line: int | None = None
 26    end_column: int | None = None
 27    snippet: str | None = None
 28
 29
 30class DiagnosticsReport(BaseModel, frozen=True):
 31    ok: bool
 32    diagnostics: Sequence[Diagnostic]
 33
 34
 35def _line_snippet(source: str, line: int | None) -> str | None:
 36    if line is None:
 37        return None
 38
 39    lines = source.splitlines()
 40    if line < 1 or line > len(lines):
 41        return None
 42
 43    return lines[line - 1]
 44
 45
 46def _position_for_identifier(source: str, identifier: str) -> tuple[int, int] | None:
 47    pattern = re.compile(rf"\b{re.escape(identifier)}\b")
 48    match = pattern.search(source)
 49    if match is None:
 50        return None
 51
 52    before = source[: match.start()]
 53    line = before.count("\n") + 1
 54    if "\n" in before:
 55        column = len(before.rsplit("\n", maxsplit=1)[-1]) + 1
 56    else:
 57        column = len(before) + 1
 58
 59    return line, column
 60
 61
 62def _identifier_from_message(message: str) -> str | None:
 63    unbound = re.search(r"Unbound variable:\s*([A-Za-z_][A-Za-z0-9_]*)", message)
 64    if unbound:
 65        return unbound.group(1)
 66
 67    duplicate = re.search(r"Duplicate (?:bindings|parameters):\s*(.+)$", message)
 68    if duplicate is None:
 69        return None
 70
 71    names = re.findall(r"[A-Za-z_][A-Za-z0-9_]*", duplicate.group(1))
 72    if not names:
 73        return None
 74
 75    return names[0]
 76
 77
 78def _normalize_error_position(source: str, line: int | None, column: int | None) -> tuple[int, int]:
 79    if isinstance(line, int) and isinstance(column, int) and line > 0 and column > 0:
 80        return line, column
 81
 82    lines = source.splitlines()
 83    if not lines:
 84        return 1, 1
 85
 86    last_line_number = len(lines)
 87    last_column = len(lines[-1]) + 1
 88    return last_line_number, last_column
 89
 90
 91def _syntax_diagnostic(source: str, error: UnexpectedInput) -> Diagnostic:
 92    expected = sorted(getattr(error, "expected", []))
 93    expected_message = ""
 94    if expected:
 95        expected_message = f" Expected one of: {', '.join(expected)}."
 96
 97    line, column = _normalize_error_position(
 98        source,
 99        getattr(error, "line", None),
100        getattr(error, "column", None),
101    )
102
103    return Diagnostic(
104        stage="syntax",
105        code="L3_SYNTAX_ERROR",
106        message=f"{str(error).strip()}.{expected_message}",
107        line=line,
108        column=column,
109        end_line=line,
110        end_column=column + 1,
111        snippet=_line_snippet(source, line),
112    )
113
114
115def _semantic_diagnostic(source: str, message: str) -> Diagnostic:
116    identifier = _identifier_from_message(message)
117    position = _position_for_identifier(source, identifier) if identifier else None
118
119    line: int | None = None
120    column: int | None = None
121    end_column: int | None = None
122
123    if position is not None:
124        line, column = position
125        end_column = column + len(identifier) if identifier else None
126
127    code = "L3_SEMANTIC_ERROR"
128    if message.startswith("Unbound variable"):
129        code = "L3_UNBOUND_VARIABLE"
130    elif message.startswith("Duplicate bindings"):
131        code = "L3_DUPLICATE_BINDINGS"
132    elif message.startswith("Duplicate parameters"):
133        code = "L3_DUPLICATE_PARAMETERS"
134
135    return Diagnostic(
136        stage="semantic",
137        code=code,
138        message=message,
139        line=line,
140        column=column,
141        end_line=line,
142        end_column=end_column,
143        snippet=_line_snippet(source, line),
144    )
145
146
147def analyze_source(source: str) -> DiagnosticsReport:
148    try:
149        program = parse_program(source)
150        check_program(program)
151        return DiagnosticsReport(ok=True, diagnostics=[])
152    except UnexpectedInput as error:
153        return DiagnosticsReport(ok=False, diagnostics=[_syntax_diagnostic(source, error)])
154    except ValueError as error:
155        return DiagnosticsReport(ok=False, diagnostics=[_semantic_diagnostic(source, str(error))])
156    except Exception as error:  # pragma: no cover
157        return DiagnosticsReport(
158            ok=False,
159            diagnostics=[
160                Diagnostic(
161                    stage="internal",
162                    code="L3_INTERNAL_ERROR",
163                    message=str(error),
164                )
165            ],
166        )
167
168
169def analyze_file(path: Path) -> DiagnosticsReport:
170    return analyze_source(path.read_text())
type DiagnosticStage = Literal['syntax', 'semantic', 'internal']
type DiagnosticSeverity = Literal['error', 'warning', 'information']
class Diagnostic(pydantic.main.BaseModel):
19class Diagnostic(BaseModel, frozen=True):
20    stage: DiagnosticStage
21    severity: DiagnosticSeverity = "error"
22    code: str
23    message: str
24    line: int | None = None
25    column: int | None = None
26    end_line: int | None = None
27    end_column: int | None = None
28    snippet: str | None = None

!!! abstract "Usage Documentation" Models

A base class for creating Pydantic models.

Attributes: __class_vars__: The names of the class variables defined on the model. __private_attributes__: Metadata about the private attributes of the model. __signature__: The synthesized __init__ [Signature][inspect.Signature] of the model.

__pydantic_complete__: Whether model building is completed, or if there are still undefined fields.
__pydantic_core_schema__: The core schema of the model.
__pydantic_custom_init__: Whether the model has a custom `__init__` function.
__pydantic_decorators__: Metadata containing the decorators defined on the model.
    This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1.
__pydantic_generic_metadata__: Metadata for generic models; contains data used for a similar purpose to
    __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.
__pydantic_parent_namespace__: Parent namespace of the model, used for automatic rebuilding of models.
__pydantic_post_init__: The name of the post-init method for the model, if defined.
__pydantic_root_model__: Whether the model is a [`RootModel`][pydantic.root_model.RootModel].
__pydantic_serializer__: The `pydantic-core` `SchemaSerializer` used to dump instances of the model.
__pydantic_validator__: The `pydantic-core` `SchemaValidator` used to validate instances of the model.

__pydantic_fields__: A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects.
__pydantic_computed_fields__: A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_extra__: A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra]
    is set to `'allow'`.
__pydantic_fields_set__: The names of fields explicitly set during instantiation.
__pydantic_private__: Values of private attributes set on the model instance.
stage: DiagnosticStage = PydanticUndefined
severity: DiagnosticSeverity = 'error'
code: str = PydanticUndefined
message: str = PydanticUndefined
line: int | None = None
column: int | None = None
end_line: int | None = None
end_column: int | None = None
snippet: str | None = None
class DiagnosticsReport(pydantic.main.BaseModel):
31class DiagnosticsReport(BaseModel, frozen=True):
32    ok: bool
33    diagnostics: Sequence[Diagnostic]

!!! abstract "Usage Documentation" Models

A base class for creating Pydantic models.

Attributes: __class_vars__: The names of the class variables defined on the model. __private_attributes__: Metadata about the private attributes of the model. __signature__: The synthesized __init__ [Signature][inspect.Signature] of the model.

__pydantic_complete__: Whether model building is completed, or if there are still undefined fields.
__pydantic_core_schema__: The core schema of the model.
__pydantic_custom_init__: Whether the model has a custom `__init__` function.
__pydantic_decorators__: Metadata containing the decorators defined on the model.
    This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1.
__pydantic_generic_metadata__: Metadata for generic models; contains data used for a similar purpose to
    __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.
__pydantic_parent_namespace__: Parent namespace of the model, used for automatic rebuilding of models.
__pydantic_post_init__: The name of the post-init method for the model, if defined.
__pydantic_root_model__: Whether the model is a [`RootModel`][pydantic.root_model.RootModel].
__pydantic_serializer__: The `pydantic-core` `SchemaSerializer` used to dump instances of the model.
__pydantic_validator__: The `pydantic-core` `SchemaValidator` used to validate instances of the model.

__pydantic_fields__: A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects.
__pydantic_computed_fields__: A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_extra__: A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra]
    is set to `'allow'`.
__pydantic_fields_set__: The names of fields explicitly set during instantiation.
__pydantic_private__: Values of private attributes set on the model instance.
ok: bool = PydanticUndefined
diagnostics: Sequence[Diagnostic] = PydanticUndefined
def analyze_source(source: str) -> DiagnosticsReport:
148def analyze_source(source: str) -> DiagnosticsReport:
149    try:
150        program = parse_program(source)
151        check_program(program)
152        return DiagnosticsReport(ok=True, diagnostics=[])
153    except UnexpectedInput as error:
154        return DiagnosticsReport(ok=False, diagnostics=[_syntax_diagnostic(source, error)])
155    except ValueError as error:
156        return DiagnosticsReport(ok=False, diagnostics=[_semantic_diagnostic(source, str(error))])
157    except Exception as error:  # pragma: no cover
158        return DiagnosticsReport(
159            ok=False,
160            diagnostics=[
161                Diagnostic(
162                    stage="internal",
163                    code="L3_INTERNAL_ERROR",
164                    message=str(error),
165                )
166            ],
167        )
def analyze_file(path: pathlib.Path) -> DiagnosticsReport:
170def analyze_file(path: Path) -> DiagnosticsReport:
171    return analyze_source(path.read_text())