intentumdiff-python 0.0.1__py3-none-win_arm64.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.
- intentumdiff/__init__.py +134 -0
- intentumdiff/_differ_gate.py +210 -0
- intentumdiff/_differ_presentation.py +786 -0
- intentumdiff/_differ_runtime.py +320 -0
- intentumdiff/analysis/__init__.py +1 -0
- intentumdiff/analysis/compile_commands.py +151 -0
- intentumdiff/analysis/cross_file.py +71 -0
- intentumdiff/analysis/diagnostics.py +309 -0
- intentumdiff/analysis/guardrail_reports.py +254 -0
- intentumdiff/analysis/guardrails.py +318 -0
- intentumdiff/analysis/invariances.py +1207 -0
- intentumdiff/analysis/keyed_profiles.py +25 -0
- intentumdiff/analysis/resource_profiles.py +14 -0
- intentumdiff/analysis/schema_resolver.py +816 -0
- intentumdiff/analysis/text_review.py +46 -0
- intentumdiff/analysis/user_schemas.py +430 -0
- intentumdiff/assets.py +45 -0
- intentumdiff/cache/__init__.py +37 -0
- intentumdiff/cache/duckdb_store.py +98 -0
- intentumdiff/cache/sqlite_store.py +149 -0
- intentumdiff/cache/store.py +190 -0
- intentumdiff/cli/__init__.py +199 -0
- intentumdiff/cli/_commands.py +2141 -0
- intentumdiff/cli/_parser.py +1061 -0
- intentumdiff/cli/_shared.py +644 -0
- intentumdiff/content_type.py +59 -0
- intentumdiff/core/__init__.py +1 -0
- intentumdiff/core/commit_differ.py +599 -0
- intentumdiff/core/config.py +51 -0
- intentumdiff/core/cst_serializer.py +101 -0
- intentumdiff/core/diffignore.py +87 -0
- intentumdiff/core/index.py +189 -0
- intentumdiff/core/indexer.py +792 -0
- intentumdiff/core/models.py +837 -0
- intentumdiff/differ.py +2195 -0
- intentumdiff/github_app.py +287 -0
- intentumdiff/intentumdiff_rust_core/__init__.py +7 -0
- intentumdiff/intentumdiff_rust_core/ffi.py +8 -0
- intentumdiff/intentumdiff_rust_core/intentumdiff_rust_core.dll +0 -0
- intentumdiff/invariances/__init__.py +2 -0
- intentumdiff/invariances/rules.schema.json +283 -0
- intentumdiff/invariances/rules.yaml +349 -0
- intentumdiff/live_server.py +1314 -0
- intentumdiff/lsp/__init__.py +67 -0
- intentumdiff/lsp/client.py +544 -0
- intentumdiff/lsp/config.py +96 -0
- intentumdiff/lsp/enricher.py +227 -0
- intentumdiff/lsp/exceptions.py +27 -0
- intentumdiff/lsp/launcher.py +273 -0
- intentumdiff/lsp/servers.py +356 -0
- intentumdiff/lsp_server/__init__.py +14 -0
- intentumdiff/lsp_server/_codelens.py +67 -0
- intentumdiff/lsp_server/_diagnostics.py +62 -0
- intentumdiff/lsp_server/_handlers.py +175 -0
- intentumdiff/lsp_server/server.py +205 -0
- intentumdiff/plugins/__init__.py +1 -0
- intentumdiff/plugins/adapter.py +397 -0
- intentumdiff/plugins/builtins.py +323 -0
- intentumdiff/plugins/exceptions.py +93 -0
- intentumdiff/plugins/hub.py +1155 -0
- intentumdiff/plugins/language_metadata.py +250 -0
- intentumdiff/plugins/loader.py +1252 -0
- intentumdiff/plugins/registry.py +1079 -0
- intentumdiff/plugins/registry.schema.json +99 -0
- intentumdiff/plugins/registry_schema.py +280 -0
- intentumdiff/plugins/wit/plugin.wit +351 -0
- intentumdiff/rust_core.py +2370 -0
- intentumdiff/serve/__init__.py +19 -0
- intentumdiff/serve/_app.py +485 -0
- intentumdiff/serve/_static/index.html +326 -0
- intentumdiff/serve/_static/playground.js +567 -0
- intentumdiff/sources/__init__.py +1 -0
- intentumdiff/sources/base.py +28 -0
- intentumdiff/sources/file_source.py +48 -0
- intentumdiff/sources/git_source.py +375 -0
- intentumdiff/sources/live_buffer_source.py +113 -0
- intentumdiff/sources/patch_source.py +126 -0
- intentumdiff/sources/string_source.py +44 -0
- intentumdiff/testing.py +165 -0
- intentumdiff/vcs/__init__.py +37 -0
- intentumdiff/vcs/_safe_path.py +50 -0
- intentumdiff/vcs/base.py +136 -0
- intentumdiff/vcs/git_backend.py +97 -0
- intentumdiff/vcs/git_cli.py +100 -0
- intentumdiff/vcs/hg_backend.py +94 -0
- intentumdiff/vcs/perforce_backend.py +109 -0
- intentumdiff/vcs/svn_backend.py +105 -0
- intentumdiff/wasm/.gitkeep +2 -0
- intentumdiff/wasm/abap_parser.wasm +0 -0
- intentumdiff/wasm/adf_parser.wasm +0 -0
- intentumdiff/wasm/asciidoc_parser.wasm +0 -0
- intentumdiff/wasm/asm_parser.wasm +0 -0
- intentumdiff/wasm/assemblyscript_parser.wasm +0 -0
- intentumdiff/wasm/astro_parser.wasm +0 -0
- intentumdiff/wasm/bash_parser.wasm +0 -0
- intentumdiff/wasm/clojure_parser.wasm +0 -0
- intentumdiff/wasm/cmake_parser.wasm +0 -0
- intentumdiff/wasm/cpp_parser.wasm +0 -0
- intentumdiff/wasm/csharp_parser.wasm +0 -0
- intentumdiff/wasm/css_parser.wasm +0 -0
- intentumdiff/wasm/dart_parser.wasm +0 -0
- intentumdiff/wasm/databricks_parser.wasm +0 -0
- intentumdiff/wasm/dax_parser.wasm +0 -0
- intentumdiff/wasm/delphi_parser.wasm +0 -0
- intentumdiff/wasm/dockerfile_parser.wasm +0 -0
- intentumdiff/wasm/elixir_parser.wasm +0 -0
- intentumdiff/wasm/freebasic_parser.wasm +0 -0
- intentumdiff/wasm/generic_parser.wasm +0 -0
- intentumdiff/wasm/gitignore_parser.wasm +0 -0
- intentumdiff/wasm/go_parser.wasm +0 -0
- intentumdiff/wasm/gomod_parser.wasm +0 -0
- intentumdiff/wasm/graphql_parser.wasm +0 -0
- intentumdiff/wasm/groovy_parser.wasm +0 -0
- intentumdiff/wasm/haskell_parser.wasm +0 -0
- intentumdiff/wasm/html_parser.wasm +0 -0
- intentumdiff/wasm/ini_parser.wasm +0 -0
- intentumdiff/wasm/java_parser.wasm +0 -0
- intentumdiff/wasm/js_ts_parser.wasm +0 -0
- intentumdiff/wasm/json_parser.wasm +0 -0
- intentumdiff/wasm/kotlin_parser.wasm +0 -0
- intentumdiff/wasm/latex_parser.wasm +0 -0
- intentumdiff/wasm/lua_parser.wasm +0 -0
- intentumdiff/wasm/make_parser.wasm +0 -0
- intentumdiff/wasm/markdown_parser.wasm +0 -0
- intentumdiff/wasm/mdx_parser.wasm +0 -0
- intentumdiff/wasm/ocaml_parser.wasm +0 -0
- intentumdiff/wasm/odin_parser.wasm +0 -0
- intentumdiff/wasm/parser_manifest.json +590 -0
- intentumdiff/wasm/perl_parser.wasm +0 -0
- intentumdiff/wasm/php_parser.wasm +0 -0
- intentumdiff/wasm/plsql_parser.wasm +0 -0
- intentumdiff/wasm/po_parser.wasm +0 -0
- intentumdiff/wasm/postscript_parser.wasm +0 -0
- intentumdiff/wasm/powershell_parser.wasm +0 -0
- intentumdiff/wasm/proto_parser.wasm +0 -0
- intentumdiff/wasm/puppet_parser.wasm +0 -0
- intentumdiff/wasm/python_parser.wasm +0 -0
- intentumdiff/wasm/qsharp_parser.wasm +0 -0
- intentumdiff/wasm/r_parser.wasm +0 -0
- intentumdiff/wasm/reasonml_parser.wasm +0 -0
- intentumdiff/wasm/ruby_parser.wasm +0 -0
- intentumdiff/wasm/rust_parser.wasm +0 -0
- intentumdiff/wasm/sas_parser.wasm +0 -0
- intentumdiff/wasm/scala_parser.wasm +0 -0
- intentumdiff/wasm/scss_parser.wasm +0 -0
- intentumdiff/wasm/sql_parser.wasm +0 -0
- intentumdiff/wasm/squirrel_parser.wasm +0 -0
- intentumdiff/wasm/svelte_parser.wasm +0 -0
- intentumdiff/wasm/swift_parser.wasm +0 -0
- intentumdiff/wasm/terraform_parser.wasm +0 -0
- intentumdiff/wasm/toml_parser.wasm +0 -0
- intentumdiff/wasm/tsql_parser.wasm +0 -0
- intentumdiff/wasm/vbnet_parser.wasm +0 -0
- intentumdiff/wasm/vue_parser.wasm +0 -0
- intentumdiff/wasm/wat_parser.wasm +0 -0
- intentumdiff/wasm/xml_parser.wasm +0 -0
- intentumdiff/wasm/yaml_parser.wasm +0 -0
- intentumdiff/wasm/zig_parser.wasm +0 -0
- intentumdiff/watcher.py +259 -0
- intentumdiff_python-0.0.1.dist-info/METADATA +112 -0
- intentumdiff_python-0.0.1.dist-info/RECORD +165 -0
- intentumdiff_python-0.0.1.dist-info/WHEEL +4 -0
- intentumdiff_python-0.0.1.dist-info/entry_points.txt +80 -0
- intentumdiff_python-0.0.1.dist-info/licenses/LICENSE +21 -0
- intentumdiff_python-0.0.1.dist-info/sboms/intentumdiff-rust-core.cyclonedx.json +10968 -0
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""
|
|
2
|
+
intentumdiff.lsp.config
|
|
3
|
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
4
|
+
|
|
5
|
+
``LspServerConfig`` — connection parameters for one language's LSP server.
|
|
6
|
+
|
|
7
|
+
Two transport modes are supported, similar to MCP:
|
|
8
|
+
|
|
9
|
+
**TCP** (``transport="tcp"``)
|
|
10
|
+
Connect to an already-running server over a TCP socket.
|
|
11
|
+
|
|
12
|
+
**Stdio** (``transport="stdio"``)
|
|
13
|
+
Spawn the server as a subprocess and communicate via its stdin/stdout.
|
|
14
|
+
The :class:`~intentumdiff.lsp.client.AsyncLspClient` manages the
|
|
15
|
+
subprocess lifecycle when this transport is used.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import re
|
|
21
|
+
from typing import Literal
|
|
22
|
+
|
|
23
|
+
from pydantic import BaseModel, Field, model_validator
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class LspServerConfig(BaseModel, frozen=True):
|
|
27
|
+
"""Connection parameters for one language's LSP server.
|
|
28
|
+
|
|
29
|
+
Use the factory classmethods :meth:`tcp` and :meth:`stdio` for
|
|
30
|
+
construction, or :meth:`from_string` to parse ``"host:port"`` shorthand.
|
|
31
|
+
|
|
32
|
+
TCP example::
|
|
33
|
+
|
|
34
|
+
LspServerConfig.tcp("localhost", port=2087)
|
|
35
|
+
LspServerConfig.from_string("localhost:2087")
|
|
36
|
+
|
|
37
|
+
Stdio example::
|
|
38
|
+
|
|
39
|
+
LspServerConfig.stdio("pylsp")
|
|
40
|
+
LspServerConfig.stdio("typescript-language-server", "--stdio")
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
transport: Literal["tcp", "stdio"] = "tcp"
|
|
44
|
+
|
|
45
|
+
# TCP fields
|
|
46
|
+
host: str = Field(default="localhost", min_length=1)
|
|
47
|
+
port: int | None = None
|
|
48
|
+
|
|
49
|
+
# Stdio fields
|
|
50
|
+
command: tuple[str, ...] = ()
|
|
51
|
+
|
|
52
|
+
@model_validator(mode="after")
|
|
53
|
+
def _validate(self) -> "LspServerConfig":
|
|
54
|
+
if self.transport == "tcp":
|
|
55
|
+
if self.port is None:
|
|
56
|
+
raise ValueError("port is required for tcp transport")
|
|
57
|
+
if not (1 <= self.port <= 65535):
|
|
58
|
+
raise ValueError("port must be between 1 and 65535")
|
|
59
|
+
else: # stdio
|
|
60
|
+
if not self.command:
|
|
61
|
+
raise ValueError("command must not be empty for stdio transport")
|
|
62
|
+
return self
|
|
63
|
+
|
|
64
|
+
# ── Factory classmethods ──────────────────────────────────────────────────
|
|
65
|
+
|
|
66
|
+
@classmethod
|
|
67
|
+
def tcp(cls, host: str = "localhost", *, port: int) -> "LspServerConfig":
|
|
68
|
+
"""Create a TCP transport config."""
|
|
69
|
+
return cls(transport="tcp", host=host, port=port)
|
|
70
|
+
|
|
71
|
+
@classmethod
|
|
72
|
+
def stdio(cls, *command: str) -> "LspServerConfig":
|
|
73
|
+
"""Create a stdio transport config from a command and arguments."""
|
|
74
|
+
return cls(transport="stdio", command=command)
|
|
75
|
+
|
|
76
|
+
@classmethod
|
|
77
|
+
def from_string(cls, value: str) -> "LspServerConfig":
|
|
78
|
+
"""Parse ``"host:port"`` shorthand into a TCP config.
|
|
79
|
+
|
|
80
|
+
Examples::
|
|
81
|
+
|
|
82
|
+
LspServerConfig.from_string("localhost:2087")
|
|
83
|
+
LspServerConfig.from_string("127.0.0.1:9000")
|
|
84
|
+
"""
|
|
85
|
+
m = re.fullmatch(r"([^:]+):(\d+)", value.strip())
|
|
86
|
+
if not m:
|
|
87
|
+
raise ValueError(
|
|
88
|
+
f"Invalid LSP server address {value!r}. "
|
|
89
|
+
"Expected 'host:port', e.g. 'localhost:2087'."
|
|
90
|
+
)
|
|
91
|
+
return cls(transport="tcp", host=m.group(1), port=int(m.group(2)))
|
|
92
|
+
|
|
93
|
+
def __str__(self) -> str:
|
|
94
|
+
if self.transport == "tcp":
|
|
95
|
+
return f"{self.host}:{self.port}"
|
|
96
|
+
return " ".join(self.command)
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""
|
|
2
|
+
intentumdiff.lsp.enricher
|
|
3
|
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
4
|
+
|
|
5
|
+
``TypeEnricher`` — attaches LSP hover type information to ``SemanticNode`` leaves.
|
|
6
|
+
|
|
7
|
+
Usage
|
|
8
|
+
-----
|
|
9
|
+
::
|
|
10
|
+
|
|
11
|
+
async with AsyncLspClient(config) as client:
|
|
12
|
+
enricher = TypeEnricher(client, language="python")
|
|
13
|
+
type_map = await enricher.enrich(uri, source_text, root_node)
|
|
14
|
+
# type_map: dict[node_id, type_string]
|
|
15
|
+
|
|
16
|
+
The enricher only queries leaf nodes whose ``node_type`` is in
|
|
17
|
+
``_NAME_TYPES`` (identifiers, names, symbols …). It uses
|
|
18
|
+
``asyncio.gather`` to parallelise all hover requests for a single file,
|
|
19
|
+
which keeps latency proportional to the server's response time rather than
|
|
20
|
+
the number of nodes.
|
|
21
|
+
|
|
22
|
+
LSP failures are non-fatal:
|
|
23
|
+
- ``LspConnectionError`` — logged as a warning; an empty dict is returned.
|
|
24
|
+
- ``LspTimeoutError`` per node — that node is silently skipped.
|
|
25
|
+
- Any other exception — logged as a debug message; the node is skipped.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import asyncio
|
|
31
|
+
import logging
|
|
32
|
+
import pathlib
|
|
33
|
+
|
|
34
|
+
from intentumdiff.lsp.client import AsyncLspClient
|
|
35
|
+
from intentumdiff.lsp.exceptions import LspConnectionError, LspTimeoutError
|
|
36
|
+
from intentumdiff.core.models import SemanticNode
|
|
37
|
+
|
|
38
|
+
logger = logging.getLogger(__name__)
|
|
39
|
+
|
|
40
|
+
# Node types whose *own* position is hovered and whose *own* id gets the result.
|
|
41
|
+
# Kept narrow: only specific name nodes the refactoring rules sub-classify.
|
|
42
|
+
# Generic ``identifier``/``name``/``symbol`` are excluded — they appear
|
|
43
|
+
# hundreds of times per file but are never directly read for ``type_info`` by
|
|
44
|
+
# any refactoring rule.
|
|
45
|
+
_NAME_TYPES = frozenset(
|
|
46
|
+
{
|
|
47
|
+
"function_name",
|
|
48
|
+
"class_name",
|
|
49
|
+
"variable_name",
|
|
50
|
+
"method_name", # some parsers emit method_name instead of function_name
|
|
51
|
+
}
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
# Declaration/parameter node types whose ``type_info`` is read by refactoring
|
|
55
|
+
# rules (EXTRACT_VARIABLE, INTRODUCE_PARAMETER_OBJECT). The enricher hovers
|
|
56
|
+
# at the *first name-leaf child's* position but stores the result under the
|
|
57
|
+
# *declaration node's* id so it lands on the node the rules inspect.
|
|
58
|
+
_DECL_NODE_TYPES = frozenset(
|
|
59
|
+
{
|
|
60
|
+
"assignment",
|
|
61
|
+
"variable_declaration",
|
|
62
|
+
"let_declaration",
|
|
63
|
+
"const_declaration",
|
|
64
|
+
"local_variable_declaration",
|
|
65
|
+
"variable_declarator",
|
|
66
|
+
}
|
|
67
|
+
)
|
|
68
|
+
_PARAM_NODE_TYPES = frozenset(
|
|
69
|
+
{
|
|
70
|
+
"parameter",
|
|
71
|
+
"typed_parameter",
|
|
72
|
+
"typed_identifier",
|
|
73
|
+
"required_parameter",
|
|
74
|
+
"optional_parameter",
|
|
75
|
+
}
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
# Maximum concurrent hover requests per file. Most servers handle far more,
|
|
79
|
+
# but we cap to avoid overwhelming a slow server.
|
|
80
|
+
_MAX_CONCURRENT = 50
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _path_to_uri(path: str) -> str:
|
|
84
|
+
"""Convert a filesystem path to a ``file://`` URI."""
|
|
85
|
+
return pathlib.Path(path).resolve().as_uri()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class TypeEnricher:
|
|
89
|
+
"""Queries an LSP server for type information for all name-leaf nodes.
|
|
90
|
+
|
|
91
|
+
Parameters
|
|
92
|
+
----------
|
|
93
|
+
client:
|
|
94
|
+
A connected ``AsyncLspClient``.
|
|
95
|
+
language:
|
|
96
|
+
LSP ``languageId`` for ``didOpen`` notifications (e.g. ``"python"``).
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
def __init__(self, client: AsyncLspClient, language: str) -> None:
|
|
100
|
+
self._client = client
|
|
101
|
+
self._language = language
|
|
102
|
+
|
|
103
|
+
async def enrich(
|
|
104
|
+
self,
|
|
105
|
+
file_path: str,
|
|
106
|
+
source_text: str,
|
|
107
|
+
root: SemanticNode,
|
|
108
|
+
) -> dict[str, str]:
|
|
109
|
+
"""Return a ``{node_id: type_string}`` mapping for all name leaves.
|
|
110
|
+
|
|
111
|
+
Sends ``textDocument/didOpen``, fires all hover requests concurrently,
|
|
112
|
+
then sends ``textDocument/didClose``.
|
|
113
|
+
|
|
114
|
+
Returns an empty dict on connection failure so that the caller can
|
|
115
|
+
continue the diff pipeline without type information.
|
|
116
|
+
"""
|
|
117
|
+
uri = _path_to_uri(file_path)
|
|
118
|
+
try:
|
|
119
|
+
await self._client.did_open(uri, self._language, source_text)
|
|
120
|
+
except LspConnectionError as exc:
|
|
121
|
+
logger.warning("LSP type enrichment skipped (%s): %s", file_path, exc)
|
|
122
|
+
return {}
|
|
123
|
+
try:
|
|
124
|
+
result = await self._query_all(uri, root)
|
|
125
|
+
finally:
|
|
126
|
+
try:
|
|
127
|
+
await self._client.did_close(uri)
|
|
128
|
+
except Exception:
|
|
129
|
+
logger.debug("LSP didClose failed for %s", uri, exc_info=True)
|
|
130
|
+
return result
|
|
131
|
+
|
|
132
|
+
# ── Internal ──────────────────────────────────────────────────────────────
|
|
133
|
+
|
|
134
|
+
def _first_name_leaf(self, node: SemanticNode) -> SemanticNode | None:
|
|
135
|
+
"""Return the first leaf descendant whose node_type is a name type."""
|
|
136
|
+
all_name_types = _NAME_TYPES | frozenset({"identifier", "name", "symbol"})
|
|
137
|
+
for child in node.children:
|
|
138
|
+
if child.is_leaf() and child.node_type in all_name_types:
|
|
139
|
+
return child
|
|
140
|
+
found = self._first_name_leaf(child)
|
|
141
|
+
if found is not None:
|
|
142
|
+
return found
|
|
143
|
+
return None
|
|
144
|
+
|
|
145
|
+
def _collect_hover_targets(
|
|
146
|
+
self, root: SemanticNode
|
|
147
|
+
) -> list[tuple[SemanticNode, SemanticNode]]:
|
|
148
|
+
"""Return ``(result_node, position_node)`` pairs to hover.
|
|
149
|
+
|
|
150
|
+
* For **name-type leaves** (:data:`_NAME_TYPES`): hover at the leaf
|
|
151
|
+
position, store result under the leaf's id.
|
|
152
|
+
* For **declaration/parameter nodes** (:data:`_DECL_NODE_TYPES`,
|
|
153
|
+
:data:`_PARAM_NODE_TYPES`): hover at the first name-leaf child's
|
|
154
|
+
position, but store the result under the *declaration node's* id.
|
|
155
|
+
This makes ``type_info`` land on the node that refactoring rules
|
|
156
|
+
actually inspect (e.g. the ``assignment`` node for
|
|
157
|
+
EXTRACT_VARIABLE).
|
|
158
|
+
|
|
159
|
+
Result node ids are deduplicated so each node is queried at most once.
|
|
160
|
+
"""
|
|
161
|
+
seen: set[str] = set()
|
|
162
|
+
targets: list[tuple[SemanticNode, SemanticNode]] = []
|
|
163
|
+
|
|
164
|
+
for node in [root, *root.descendants()]:
|
|
165
|
+
if node.id in seen:
|
|
166
|
+
continue
|
|
167
|
+
if node.node_type in _NAME_TYPES and node.is_leaf():
|
|
168
|
+
seen.add(node.id)
|
|
169
|
+
targets.append((node, node))
|
|
170
|
+
elif node.node_type in (_DECL_NODE_TYPES | _PARAM_NODE_TYPES):
|
|
171
|
+
leaf = self._first_name_leaf(node)
|
|
172
|
+
if leaf is not None:
|
|
173
|
+
seen.add(node.id)
|
|
174
|
+
targets.append((node, leaf))
|
|
175
|
+
|
|
176
|
+
return targets
|
|
177
|
+
|
|
178
|
+
def _hover_triples(self, root: SemanticNode) -> list[tuple[str, int, int]]:
|
|
179
|
+
"""``(result_node_id, line, col)`` hover targets — Rust core first (issue 100 S2),
|
|
180
|
+
with :meth:`_collect_hover_targets` as the Python fallback/oracle."""
|
|
181
|
+
from intentumdiff.rust_core import try_rust_collect_hover_targets
|
|
182
|
+
|
|
183
|
+
rust_triples = try_rust_collect_hover_targets(root)
|
|
184
|
+
if rust_triples is not None:
|
|
185
|
+
return rust_triples
|
|
186
|
+
return [
|
|
187
|
+
(rn.id, pn.position.start_line, pn.position.start_col)
|
|
188
|
+
for rn, pn in self._collect_hover_targets(root)
|
|
189
|
+
]
|
|
190
|
+
|
|
191
|
+
async def _query_node(
|
|
192
|
+
self,
|
|
193
|
+
uri: str,
|
|
194
|
+
node_id: str,
|
|
195
|
+
line: int,
|
|
196
|
+
col: int,
|
|
197
|
+
sem: asyncio.Semaphore,
|
|
198
|
+
) -> tuple[str, str | None]:
|
|
199
|
+
"""Query hover at ``line:col``; return (node_id, type_string|None)."""
|
|
200
|
+
async with sem:
|
|
201
|
+
try:
|
|
202
|
+
type_str = await self._client.hover(uri, line, col)
|
|
203
|
+
return node_id, type_str
|
|
204
|
+
except LspTimeoutError:
|
|
205
|
+
return node_id, None
|
|
206
|
+
except Exception as exc:
|
|
207
|
+
logger.debug(
|
|
208
|
+
"LSP hover failed for node %s at %d:%d — %s",
|
|
209
|
+
node_id, line, col, exc,
|
|
210
|
+
)
|
|
211
|
+
return node_id, None
|
|
212
|
+
|
|
213
|
+
async def _query_all(
|
|
214
|
+
self,
|
|
215
|
+
uri: str,
|
|
216
|
+
root: SemanticNode,
|
|
217
|
+
) -> dict[str, str]:
|
|
218
|
+
"""Fire all hover requests concurrently; collect non-None results."""
|
|
219
|
+
targets = self._hover_triples(root)
|
|
220
|
+
if not targets:
|
|
221
|
+
return {}
|
|
222
|
+
|
|
223
|
+
sem = asyncio.Semaphore(_MAX_CONCURRENT)
|
|
224
|
+
tasks = [self._query_node(uri, nid, line, col, sem) for nid, line, col in targets]
|
|
225
|
+
pairs = await asyncio.gather(*tasks)
|
|
226
|
+
|
|
227
|
+
return {nid: t for nid, t in pairs if t is not None}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""
|
|
2
|
+
intentumdiff.lsp.exceptions
|
|
3
|
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
4
|
+
|
|
5
|
+
Non-fatal LSP warning exceptions.
|
|
6
|
+
|
|
7
|
+
Both subclass ``Exception`` directly rather than a library-wide base so that
|
|
8
|
+
callers can catch them without importing any other IntentumDiff symbol.
|
|
9
|
+
They are treated as warnings in the pipeline — a file whose LSP enrichment
|
|
10
|
+
fails is diffed without type information rather than aborting.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class LspConnectionError(Exception):
|
|
17
|
+
"""Raised when the TCP connection to the LSP server cannot be established.
|
|
18
|
+
|
|
19
|
+
This is non-fatal: the diff pipeline continues without type enrichment.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class LspTimeoutError(Exception):
|
|
24
|
+
"""Raised when an LSP request does not receive a response within the timeout.
|
|
25
|
+
|
|
26
|
+
This is non-fatal: the affected node is left with ``type_info=None``.
|
|
27
|
+
"""
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
"""
|
|
2
|
+
intentumdiff.lsp.launcher
|
|
3
|
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
4
|
+
|
|
5
|
+
``LspServerProcess`` — auto-start a language server and return a ready
|
|
6
|
+
:class:`~intentumdiff.lsp.config.LspServerConfig`.
|
|
7
|
+
|
|
8
|
+
Two strategies mirror the transport modes:
|
|
9
|
+
|
|
10
|
+
**TCP servers** — manual already-running servers may still be used by passing
|
|
11
|
+
a TCP :class:`~intentumdiff.lsp.config.LspServerConfig` directly to the
|
|
12
|
+
client. Auto-started TCP subprocesses are legacy-only and require
|
|
13
|
+
``allow_unverified_tcp_autostart=True`` on the server spec because generic LSP
|
|
14
|
+
servers cannot prove they own the loopback port after reservation release.
|
|
15
|
+
|
|
16
|
+
**Stdio servers** — no external process is spawned here. The launcher
|
|
17
|
+
returns a stdio config whose ``command`` the
|
|
18
|
+
:class:`~intentumdiff.lsp.client.AsyncLspClient` will execute and manage
|
|
19
|
+
when its own ``start()`` is called.
|
|
20
|
+
|
|
21
|
+
Typical usage::
|
|
22
|
+
|
|
23
|
+
from intentumdiff.lsp.launcher import LspServerProcess
|
|
24
|
+
from intentumdiff.lsp.client import AsyncLspClient
|
|
25
|
+
|
|
26
|
+
async with LspServerProcess("python") as cfg:
|
|
27
|
+
async with AsyncLspClient(cfg) as client:
|
|
28
|
+
enricher = TypeEnricher(client, "python")
|
|
29
|
+
type_map = await enricher.enrich(path, source, root)
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import asyncio
|
|
35
|
+
import logging
|
|
36
|
+
import os
|
|
37
|
+
import shutil
|
|
38
|
+
import socket
|
|
39
|
+
import sys
|
|
40
|
+
from contextlib import suppress
|
|
41
|
+
|
|
42
|
+
from intentumdiff.lsp.config import LspServerConfig
|
|
43
|
+
from intentumdiff.lsp.exceptions import LspConnectionError
|
|
44
|
+
from intentumdiff.lsp.servers import KNOWN_SERVER_SPECS, LspServerSpec
|
|
45
|
+
|
|
46
|
+
logger = logging.getLogger(__name__)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _subprocess_env() -> dict[str, str]:
|
|
50
|
+
"""Return os.environ with the current venv's Scripts/bin prepended to PATH."""
|
|
51
|
+
env = dict(os.environ)
|
|
52
|
+
scripts = os.path.join(sys.prefix, "Scripts" if os.name == "nt" else "bin")
|
|
53
|
+
current = env.get("PATH", "")
|
|
54
|
+
if scripts not in current.split(os.pathsep):
|
|
55
|
+
env["PATH"] = scripts + os.pathsep + current
|
|
56
|
+
return env
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _resolve_command(cmd: tuple[str, ...], env: dict[str, str]) -> tuple[str, ...]:
|
|
60
|
+
"""Resolve *cmd[0]* via shutil.which; on Windows wrap .cmd/.bat via cmd.exe."""
|
|
61
|
+
resolved = shutil.which(cmd[0], path=env.get("PATH"))
|
|
62
|
+
if resolved is None:
|
|
63
|
+
return cmd
|
|
64
|
+
if os.name == "nt" and resolved.lower().endswith((".cmd", ".bat")):
|
|
65
|
+
return ("cmd.exe", "/c", resolved) + cmd[1:]
|
|
66
|
+
return (resolved,) + cmd[1:]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# ---------------------------------------------------------------------------
|
|
70
|
+
# Port utilities
|
|
71
|
+
# ---------------------------------------------------------------------------
|
|
72
|
+
|
|
73
|
+
def _reserve_port(host: str = "127.0.0.1") -> tuple[int, socket.socket]:
|
|
74
|
+
"""Bind to port 0, return (port, reservation_socket).
|
|
75
|
+
|
|
76
|
+
Keep the socket open until the subprocess has been spawned. On Windows,
|
|
77
|
+
request exclusive-address ownership so another local process cannot co-bind
|
|
78
|
+
the reserved port with SO_REUSEADDR while the reservation is held.
|
|
79
|
+
|
|
80
|
+
Caller **must** call ``reservation_sock.close()`` after
|
|
81
|
+
``create_subprocess_exec`` returns.
|
|
82
|
+
"""
|
|
83
|
+
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
84
|
+
if os.name == "nt" and hasattr(socket, "SO_EXCLUSIVEADDRUSE"):
|
|
85
|
+
s.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
|
|
86
|
+
s.bind((host, 0))
|
|
87
|
+
port: int = s.getsockname()[1]
|
|
88
|
+
return port, s
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
async def _wait_for_port(host: str, port: int, *, timeout: float) -> None:
|
|
92
|
+
"""Poll until *host:port* accepts connections or *timeout* elapses.
|
|
93
|
+
|
|
94
|
+
Raises :exc:`~intentumdiff.lsp.exceptions.LspConnectionError` if the
|
|
95
|
+
server does not become reachable within the timeout.
|
|
96
|
+
"""
|
|
97
|
+
loop = asyncio.get_event_loop()
|
|
98
|
+
deadline = loop.time() + timeout
|
|
99
|
+
while True:
|
|
100
|
+
try:
|
|
101
|
+
_, writer = await asyncio.wait_for(
|
|
102
|
+
asyncio.open_connection(host, port), timeout=1.0
|
|
103
|
+
)
|
|
104
|
+
writer.close()
|
|
105
|
+
with suppress(Exception):
|
|
106
|
+
await writer.wait_closed()
|
|
107
|
+
return
|
|
108
|
+
except (ConnectionRefusedError, OSError, asyncio.TimeoutError):
|
|
109
|
+
if loop.time() >= deadline:
|
|
110
|
+
raise LspConnectionError(
|
|
111
|
+
f"LSP server did not become reachable on {host}:{port} "
|
|
112
|
+
f"within {timeout:.0f}s"
|
|
113
|
+
)
|
|
114
|
+
await asyncio.sleep(0.25)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
# ---------------------------------------------------------------------------
|
|
118
|
+
# Launcher
|
|
119
|
+
# ---------------------------------------------------------------------------
|
|
120
|
+
|
|
121
|
+
class LspServerProcess:
|
|
122
|
+
"""Manage the lifecycle of a spawned LSP server subprocess.
|
|
123
|
+
|
|
124
|
+
Parameters
|
|
125
|
+
----------
|
|
126
|
+
language:
|
|
127
|
+
Language identifier (e.g. ``"python"``, ``"rust"``).
|
|
128
|
+
spec:
|
|
129
|
+
Optional :class:`~intentumdiff.lsp.servers.LspServerSpec` to use
|
|
130
|
+
instead of the built-in :data:`KNOWN_SERVER_SPECS` entry. Pass this
|
|
131
|
+
when loading a user-defined server from ``lsp_servers.json``.
|
|
132
|
+
host:
|
|
133
|
+
Loopback address to use for TCP servers (default ``"127.0.0.1"``).
|
|
134
|
+
|
|
135
|
+
Usage::
|
|
136
|
+
|
|
137
|
+
async with LspServerProcess("rust") as cfg:
|
|
138
|
+
async with AsyncLspClient(cfg) as client:
|
|
139
|
+
...
|
|
140
|
+
"""
|
|
141
|
+
|
|
142
|
+
def __init__(
|
|
143
|
+
self,
|
|
144
|
+
language: str,
|
|
145
|
+
spec: "LspServerSpec | None" = None,
|
|
146
|
+
host: str = "127.0.0.1",
|
|
147
|
+
) -> None:
|
|
148
|
+
self._language = language
|
|
149
|
+
self._spec = spec # None → look up KNOWN_SERVER_SPECS at start()
|
|
150
|
+
self._host = host
|
|
151
|
+
# Set after start() for TCP servers; None for stdio servers.
|
|
152
|
+
self._proc: asyncio.subprocess.Process | None = None
|
|
153
|
+
self._config: LspServerConfig | None = None
|
|
154
|
+
|
|
155
|
+
@property
|
|
156
|
+
def config(self) -> LspServerConfig:
|
|
157
|
+
"""The connection config — available after :meth:`start` returns."""
|
|
158
|
+
if self._config is None:
|
|
159
|
+
raise RuntimeError(
|
|
160
|
+
"LspServerProcess.start() has not been called yet."
|
|
161
|
+
)
|
|
162
|
+
return self._config
|
|
163
|
+
|
|
164
|
+
async def start(self) -> LspServerConfig:
|
|
165
|
+
"""Spawn (TCP) or prepare (stdio) the server and return its config.
|
|
166
|
+
|
|
167
|
+
Raises
|
|
168
|
+
------
|
|
169
|
+
ValueError
|
|
170
|
+
If *language* has no entry in :data:`KNOWN_SERVER_SPECS`.
|
|
171
|
+
LspConnectionError
|
|
172
|
+
If the server binary is not found or does not start in time.
|
|
173
|
+
"""
|
|
174
|
+
spec = self._spec or KNOWN_SERVER_SPECS.get(self._language)
|
|
175
|
+
if spec is None:
|
|
176
|
+
available = ", ".join(sorted(KNOWN_SERVER_SPECS))
|
|
177
|
+
raise ValueError(
|
|
178
|
+
f"No auto-start spec for language {self._language!r}. "
|
|
179
|
+
f"Available: {available}"
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
if spec.transport == "tcp":
|
|
183
|
+
if not spec.allow_unverified_tcp_autostart:
|
|
184
|
+
raise LspConnectionError(
|
|
185
|
+
"Auto-started TCP LSP servers are disabled by default. "
|
|
186
|
+
"Use a stdio server spec or connect to an already-running "
|
|
187
|
+
"manual TCP endpoint. Set allow_unverified_tcp_autostart "
|
|
188
|
+
"only for trusted legacy commands that accept the local "
|
|
189
|
+
"port-race residual risk."
|
|
190
|
+
)
|
|
191
|
+
logger.warning(
|
|
192
|
+
"Starting %s LSP with unverified TCP auto-start. Prefer stdio "
|
|
193
|
+
"or manual TCP because child port ownership cannot be proven.",
|
|
194
|
+
self._language,
|
|
195
|
+
)
|
|
196
|
+
port, _reservation_sock = _reserve_port(self._host)
|
|
197
|
+
cmd = tuple(
|
|
198
|
+
part.format(host=self._host, port=port)
|
|
199
|
+
for part in spec.command
|
|
200
|
+
)
|
|
201
|
+
env = _subprocess_env()
|
|
202
|
+
resolved_cmd = _resolve_command(cmd, env)
|
|
203
|
+
try:
|
|
204
|
+
self._proc = await asyncio.create_subprocess_exec(
|
|
205
|
+
*resolved_cmd,
|
|
206
|
+
stdout=asyncio.subprocess.DEVNULL,
|
|
207
|
+
stderr=asyncio.subprocess.PIPE,
|
|
208
|
+
env=env,
|
|
209
|
+
)
|
|
210
|
+
except (FileNotFoundError, OSError) as exc:
|
|
211
|
+
hint = f"\nInstall: {spec.install_hint}" if spec.install_hint else ""
|
|
212
|
+
raise LspConnectionError(
|
|
213
|
+
f"Cannot start {self._language} LSP server "
|
|
214
|
+
f"({cmd[0]!r} not found).{hint}"
|
|
215
|
+
) from exc
|
|
216
|
+
finally:
|
|
217
|
+
# Release the reservation socket now that the subprocess has
|
|
218
|
+
# been launched. The reservation was exclusive on Windows, so
|
|
219
|
+
# local co-binding is blocked while we hold it.
|
|
220
|
+
_reservation_sock.close()
|
|
221
|
+
|
|
222
|
+
try:
|
|
223
|
+
await _wait_for_port(
|
|
224
|
+
self._host, port, timeout=spec.startup_timeout
|
|
225
|
+
)
|
|
226
|
+
except LspConnectionError:
|
|
227
|
+
await self.stop() # clean up the zombie process
|
|
228
|
+
raise
|
|
229
|
+
|
|
230
|
+
self._config = LspServerConfig.tcp(self._host, port=port)
|
|
231
|
+
logger.debug(
|
|
232
|
+
"Started %s LSP server (tcp) on %s:%d pid=%d",
|
|
233
|
+
self._language, self._host, port, self._proc.pid,
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
else: # stdio
|
|
237
|
+
cmd = tuple(
|
|
238
|
+
part.format(pid=str(os.getpid()))
|
|
239
|
+
for part in spec.command
|
|
240
|
+
)
|
|
241
|
+
self._config = LspServerConfig.stdio(*cmd)
|
|
242
|
+
logger.debug(
|
|
243
|
+
"Prepared %s LSP server (stdio): %s",
|
|
244
|
+
self._language, " ".join(cmd),
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
return self._config
|
|
248
|
+
|
|
249
|
+
async def stop(self) -> None:
|
|
250
|
+
"""Terminate the server subprocess.
|
|
251
|
+
|
|
252
|
+
For **stdio** servers this is a no-op: the
|
|
253
|
+
:class:`~intentumdiff.lsp.client.AsyncLspClient` owns and
|
|
254
|
+
terminates the process via :meth:`~AsyncLspClient.shutdown`.
|
|
255
|
+
"""
|
|
256
|
+
if self._proc is None:
|
|
257
|
+
return
|
|
258
|
+
try:
|
|
259
|
+
self._proc.terminate()
|
|
260
|
+
await asyncio.wait_for(self._proc.wait(), timeout=5.0)
|
|
261
|
+
except ProcessLookupError:
|
|
262
|
+
pass # already gone
|
|
263
|
+
except (asyncio.TimeoutError, Exception):
|
|
264
|
+
with suppress(Exception):
|
|
265
|
+
self._proc.kill()
|
|
266
|
+
finally:
|
|
267
|
+
self._proc = None
|
|
268
|
+
|
|
269
|
+
async def __aenter__(self) -> LspServerConfig:
|
|
270
|
+
return await self.start()
|
|
271
|
+
|
|
272
|
+
async def __aexit__(self, *_: object) -> None:
|
|
273
|
+
await self.stop()
|