python-delphi-lsp 2.0.0__py3-none-any.whl → 2.0.1__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.
delphi_lsp/__init__.py CHANGED
@@ -59,6 +59,17 @@ from .project_indexer import (
59
59
  UnitInfo,
60
60
  UnitParsedHook,
61
61
  )
62
+ from .metrics import (
63
+ CyclomaticMetrics,
64
+ HalsteadMetrics,
65
+ LineMetrics,
66
+ MetricProblem,
67
+ ProjectMetrics,
68
+ RoutineComplexity,
69
+ UnitMetrics,
70
+ analyze_project,
71
+ analyze_unit,
72
+ )
62
73
 
63
74
  __all__ = [
64
75
  '__version__',
@@ -134,6 +145,15 @@ __all__ = [
134
145
  'IncludeFileInfo',
135
146
  'GetUnitSyntaxHook',
136
147
  'UnitParsedHook',
148
+ 'MetricProblem',
149
+ 'LineMetrics',
150
+ 'HalsteadMetrics',
151
+ 'RoutineComplexity',
152
+ 'CyclomaticMetrics',
153
+ 'UnitMetrics',
154
+ 'ProjectMetrics',
155
+ 'analyze_unit',
156
+ 'analyze_project',
137
157
  'dumps',
138
158
  'loads',
139
159
  ]
delphi_lsp/_version.py CHANGED
@@ -1 +1 @@
1
- __version__ = "2.0.0"
1
+ __version__ = "2.0.1"
delphi_lsp/agent_cli.py CHANGED
@@ -44,6 +44,7 @@ def build_parser() -> argparse.ArgumentParser:
44
44
  "implementation",
45
45
  "references",
46
46
  "problems",
47
+ "metrics",
47
48
  ],
48
49
  )
49
50
  view.add_argument("--query", default="")
@@ -18,14 +18,16 @@ from .agent_protocol import (
18
18
  make_target_id,
19
19
  paginate_items,
20
20
  )
21
+ from .agent_metrics import build_workspace_metrics, project_metric_item, unit_metric_item
21
22
  from .agent_relations import ProjectRelationIndex, RelationTarget
22
- from .agent_workspace import AgentUnit, AgentWorkspace
23
+ from .agent_workspace import AgentWorkspace, unit_display_path, unit_source_path, unit_target_id
23
24
  from .consts import AttributeName, SyntaxNodeType
24
25
  from .lsp_server import build_outline_semantic_model, multiline_string_block_end
25
26
  from .nodes import CompoundSyntaxNode, SyntaxNode
26
27
  from .parser import DelphiParser
27
28
  from .semantic import Scope, ScopeKind, Symbol, SymbolKind
28
29
  from .source_reader import read_source_text
30
+ from .metrics import ProjectMetrics
29
31
 
30
32
 
31
33
  _ROUTINE_KINDS = frozenset(
@@ -238,6 +240,8 @@ class AgentContext:
238
240
  self._last_revision = workspace.workspace_revision
239
241
  self._registry: _Registry | None = None
240
242
  self._relation_index: ProjectRelationIndex | None = None
243
+ self._metrics: ProjectMetrics | None = None
244
+ self._metrics_revision = ""
241
245
 
242
246
  @classmethod
243
247
  def open(
@@ -270,6 +274,8 @@ class AgentContext:
270
274
  self._require_selected_project()
271
275
  items = self._problem_items()
272
276
  return self._response(parsed, revision, items)
277
+ if parsed.action == "metrics":
278
+ return self._handle_metrics(parsed, revision)
273
279
  if parsed.action == "focus":
274
280
  return self._handle_focus(parsed, revision)
275
281
  if parsed.action == "find":
@@ -294,10 +300,14 @@ class AgentContext:
294
300
  if current_project_id != previous_project_id:
295
301
  self._registry = None
296
302
  self._relation_index = None
303
+ self._metrics = None
304
+ self._metrics_revision = ""
297
305
  self._focus = Focus(project_id=current_project_id) if current_project_id else Focus()
298
306
  elif revision != self._last_revision:
299
307
  self._registry = None
300
308
  self._relation_index = None
309
+ self._metrics = None
310
+ self._metrics_revision = ""
301
311
  elif self._focus.project_id != current_project_id:
302
312
  self._focus = Focus(project_id=current_project_id) if current_project_id else Focus()
303
313
  self._last_revision = revision
@@ -323,12 +333,11 @@ class AgentContext:
323
333
  return items
324
334
 
325
335
  for unit in self._workspace.units:
326
- source_path = _unit_source_path(self._workspace.root, unit)
327
- display_path = _stable_source_display_path(self._workspace.root, unit, source_path)
336
+ display_path = unit_display_path(self._workspace.root, unit)
328
337
  items.append(
329
338
  {
330
339
  "item_type": "unit",
331
- "unit_id": make_target_id("unit", display_path, unit.name),
340
+ "unit_id": unit_target_id(self._workspace.root, unit),
332
341
  "name": unit.name,
333
342
  "path": display_path,
334
343
  "has_error": unit.has_error,
@@ -407,6 +416,55 @@ class AgentContext:
407
416
  self._focus = Focus(project_id=self._workspace.active_project_id)
408
417
  return self._response(request, revision, [self._focus.to_mapping()])
409
418
 
419
+ def _handle_metrics(self, request: AgentRequest, revision: str) -> AgentResponse:
420
+ if request.detail not in {"summary", "members"}:
421
+ raise AgentProtocolError(
422
+ "invalid_detail",
423
+ "Metrics supports only summary or members detail.",
424
+ )
425
+ metrics = self._require_metrics(revision)
426
+ detail = request.detail == "members"
427
+ if request.target_id:
428
+ unit = next(
429
+ (candidate for candidate in metrics.units if candidate.unit_id == request.target_id),
430
+ None,
431
+ )
432
+ if unit is None:
433
+ raise AgentProtocolError(
434
+ "target_not_found",
435
+ f"Target not found: {request.target_id}.",
436
+ )
437
+ return self._response(
438
+ request,
439
+ revision,
440
+ [unit_metric_item(unit, detail=detail)],
441
+ target_id=unit.unit_id,
442
+ )
443
+
444
+ units = metrics.units
445
+ if request.query:
446
+ query = request.query.casefold()
447
+ units = tuple(
448
+ unit
449
+ for unit in units
450
+ if query in unit.name.casefold() or query in unit.path.casefold()
451
+ )
452
+ items = [unit_metric_item(unit, detail=detail) for unit in units]
453
+ else:
454
+ items = [
455
+ project_metric_item(metrics),
456
+ *(unit_metric_item(unit, detail=detail) for unit in units),
457
+ ]
458
+ return self._response(request, revision, items)
459
+
460
+ def _require_metrics(self, revision: str) -> ProjectMetrics:
461
+ self._require_selected_project()
462
+ if self._metrics is not None and self._metrics_revision == revision:
463
+ return self._metrics
464
+ self._metrics = build_workspace_metrics(self._workspace)
465
+ self._metrics_revision = revision
466
+ return self._metrics
467
+
410
468
  def _require_registry(self, revision: str) -> _Registry:
411
469
  project_id = self._require_selected_project()
412
470
  if (
@@ -608,8 +666,8 @@ def _build_registry(workspace: AgentWorkspace, project_id: str, revision: str) -
608
666
  raw_symbols: list[_RawSymbol] = []
609
667
  sources: dict[Path, _SourceDocument] = {}
610
668
  for unit in workspace.units:
611
- source_path = _unit_source_path(workspace.root, unit)
612
- display_path = _stable_source_display_path(workspace.root, unit, source_path)
669
+ source_path = unit_source_path(workspace.root, unit)
670
+ display_path = unit_display_path(workspace.root, unit)
613
671
  try:
614
672
  text = read_source_text(source_path)
615
673
  except OSError as exc:
@@ -727,22 +785,6 @@ def _build_registry(workspace: AgentWorkspace, project_id: str, revision: str) -
727
785
  )
728
786
 
729
787
 
730
- def _unit_source_path(root: Path, unit: AgentUnit) -> Path:
731
- path = Path(unit.path)
732
- if not path.is_absolute():
733
- path = root / path
734
- return path.expanduser().resolve()
735
-
736
-
737
- def _stable_source_display_path(root: Path, unit: AgentUnit, source_path: Path) -> str:
738
- try:
739
- return source_path.relative_to(root).as_posix()
740
- except ValueError:
741
- unit_component = _stable_path_component(unit.name or source_path.stem)
742
- file_component = _stable_path_component(source_path.name)
743
- return f"@external/{unit_component}/{file_component}"
744
-
745
-
746
788
  def _stable_path_component(value: str) -> str:
747
789
  normalized = unicodedata.normalize("NFC", value).replace("\\", "_").replace("/", "_")
748
790
  return normalized or "unknown"
@@ -6,6 +6,7 @@ from typing import Any, Iterable
6
6
  import json
7
7
 
8
8
  from .lsp_server import build_outline_semantic_model, outline_source
9
+ from .metrics import analyze_project
9
10
  from .project_discovery import DelphiProjectDiscovery, discover_delphi_project
10
11
  from .project_indexer import ProjectIndexResult, ProjectIndexer
11
12
  from .semantic import Scope, SourceRange, Symbol, SymbolIndex, SymbolKind
@@ -98,6 +99,8 @@ def layer_payload(index: CodebaseIndex, layer: str, *, query: str = "") -> dict[
98
99
  return _references_payload(index, query=query)
99
100
  if normalized_layer == "problems":
100
101
  return _problems_payload(index)
102
+ if normalized_layer == "metrics":
103
+ return _metrics_payload(index, query=query)
101
104
  raise ValueError(f"Unknown layer: {layer}")
102
105
 
103
106
 
@@ -369,6 +372,44 @@ def _problems_payload(index: CodebaseIndex) -> dict[str, Any]:
369
372
  return {"layer": "problems", "root": index.root, "items": items}
370
373
 
371
374
 
375
+ def _metrics_payload(index: CodebaseIndex, *, query: str) -> dict[str, Any]:
376
+ sources: dict[str, str] = {}
377
+ include_sources: dict[str, str] = {}
378
+ for value in index.discovery.source_files:
379
+ path = Path(value)
380
+ try:
381
+ text = read_source_text(path)
382
+ except (OSError, UnicodeError):
383
+ continue
384
+ if path.suffix.casefold() == ".inc":
385
+ include_sources[str(path)] = text
386
+ elif path.suffix.casefold() in {".pas", ".dpr", ".dpk"}:
387
+ sources[str(path)] = text
388
+
389
+ project_name = "Workspace"
390
+ if len(index.discovery.project_files) == 1:
391
+ project_name = Path(index.discovery.project_files[0]).stem
392
+ metrics = analyze_project(
393
+ sources,
394
+ include_sources=include_sources,
395
+ defines=index.discovery.defines,
396
+ include_paths=index.discovery.include_paths,
397
+ project_name=project_name,
398
+ )
399
+ needle = query.casefold().strip()
400
+ units = [
401
+ unit.to_mapping(detail=True)
402
+ for unit in metrics.units
403
+ if not needle or needle in unit.name.casefold() or needle in unit.path.casefold()
404
+ ]
405
+ return {
406
+ "layer": "metrics",
407
+ "root": index.root,
408
+ "project": metrics.to_mapping(),
409
+ "items": units,
410
+ }
411
+
412
+
372
413
  def _all_symbols(index: CodebaseIndex) -> Iterable[Symbol]:
373
414
  for model in index.models.values():
374
415
  yield from _iter_symbols(model.unit_scope)
@@ -486,6 +527,30 @@ def _render_markdown(payload: dict[str, Any]) -> str:
486
527
  elif payload["layer"] == "problems":
487
528
  for item in payload["items"]:
488
529
  lines.append(f"- {item['kind']}: {item['message']} (`{item.get('origin', '')}`)")
530
+ elif payload["layer"] == "metrics":
531
+ project = payload["project"]
532
+ lines.extend(
533
+ [
534
+ f"- Project LOC: {project['total_loc']}",
535
+ f"- Project LOC with includes: {project['total_loc_with_includes']}",
536
+ f"- Units: {project['unit_count']}",
537
+ f"- Maintainability index: {project['maintainability_index']:.2f}",
538
+ ]
539
+ )
540
+ for item in payload["items"]:
541
+ lines.extend(
542
+ [
543
+ "",
544
+ f"## {item['name']}",
545
+ f"- Path: `{item['path']}`",
546
+ f"- LOC: {item['lines']['total_lines']}",
547
+ f"- Cyclomatic maximum: {item['cyclomatic']['maximum']}",
548
+ f"- Maintainability index: {item['maintainability_index']:.2f}",
549
+ f"- Instability: {item['instability']:.3f}",
550
+ f"- Abstractness: {item['abstractness']:.3f}",
551
+ f"- Distance: {item['distance']:.3f}",
552
+ ]
553
+ )
489
554
  return "\n".join(lines).rstrip() + "\n"
490
555
 
491
556
 
@@ -0,0 +1,82 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import replace
4
+ from pathlib import Path
5
+
6
+ from .agent_workspace import (
7
+ AgentWorkspace,
8
+ unit_display_path,
9
+ unit_source_path,
10
+ unit_target_id,
11
+ )
12
+ from .metrics import MetricProblem, ProjectMetrics, UnitMetrics, analyze_project
13
+ from .source_reader import read_source_text
14
+
15
+
16
+ def build_workspace_metrics(workspace: AgentWorkspace) -> ProjectMetrics:
17
+ sources: dict[str, str] = {}
18
+ include_sources: dict[str, str] = {}
19
+ unit_ids: dict[str, str] = {}
20
+ problems: list[MetricProblem] = []
21
+
22
+ for unit in workspace.units:
23
+ display_path = unit_display_path(workspace.root, unit)
24
+ source_path = unit_source_path(workspace.root, unit)
25
+ try:
26
+ sources[display_path] = read_source_text(source_path)
27
+ except OSError:
28
+ problems.append(
29
+ MetricProblem(
30
+ kind="source_unavailable",
31
+ path=display_path,
32
+ message="Could not read source.",
33
+ )
34
+ )
35
+ continue
36
+ unit_ids[display_path] = unit_target_id(workspace.root, unit)
37
+
38
+ for include_file in workspace.include_files:
39
+ display_path = include_file["path"]
40
+ source_path = _workspace_path(workspace.root, display_path)
41
+ try:
42
+ include_sources[display_path] = read_source_text(source_path)
43
+ except OSError:
44
+ problems.append(
45
+ MetricProblem(
46
+ kind="include_unavailable",
47
+ path=display_path,
48
+ message="Could not read include file.",
49
+ )
50
+ )
51
+
52
+ project = workspace.active_project
53
+ metrics = analyze_project(
54
+ sources,
55
+ include_sources=include_sources,
56
+ defines=workspace.defines,
57
+ include_paths=workspace.include_paths,
58
+ project_id=workspace.active_project_id,
59
+ project_name=project.name if project is not None else "",
60
+ unit_ids=unit_ids,
61
+ )
62
+ if problems:
63
+ metrics = replace(metrics, problems=(*metrics.problems, *problems))
64
+ return metrics
65
+
66
+
67
+ def project_metric_item(metrics: ProjectMetrics) -> dict[str, object]:
68
+ return {"item_type": "project_metrics", **metrics.to_mapping()}
69
+
70
+
71
+ def unit_metric_item(metrics: UnitMetrics, *, detail: bool = False) -> dict[str, object]:
72
+ return {"item_type": "unit_metrics", **metrics.to_mapping(detail=detail)}
73
+
74
+
75
+ def _workspace_path(root: Path, value: str) -> Path:
76
+ path = Path(value).expanduser()
77
+ if not path.is_absolute():
78
+ path = root / path
79
+ return path.resolve()
80
+
81
+
82
+ __all__ = ["build_workspace_metrics", "project_metric_item", "unit_metric_item"]
@@ -19,6 +19,7 @@ SUPPORTED_ACTIONS = (
19
19
  'trace',
20
20
  'focus',
21
21
  'problems',
22
+ 'metrics',
22
23
  )
23
24
 
24
25
  SUPPORTED_DETAILS = (
@@ -181,13 +181,14 @@ Inspect Delphi/Object Pascal only through `delphi_codebase`; never raw bash/read
181
181
  3. Inspect focused details in this order as needed: `summary`, `declaration`, `members`, `context`, `body`, `implementations`.
182
182
  4. Trace relations with `references`, `callers`, `callees`, `uses`, `used_by`, `inherits`, or `implements`.
183
183
  5. Call `problems` before declaring evidence missing. Explain any `sound_partial` relation metadata rather than treating partial results as complete.
184
- 6. Follow `page.next_cursor` with `cursor` until the needed evidence is available.
184
+ 6. Call `metrics` for project LOC and architecture metrics. Use `query` for unit summaries or a unit `target_id` with `detail=members` for full Halstead, complexity, coupling, abstractness, instability, and distance details.
185
+ 7. Follow `page.next_cursor` with `cursor` until the needed evidence is available.
185
186
 
186
187
  Prefer `summary` and `declaration`, narrow `max_items` and `max_chars`, and request `body` only when it is necessary. Keep the focused target stable while collecting evidence.
187
188
 
188
189
  ## Tool calls
189
190
 
190
- `delphi_codebase` accepts `action` (`open`, `find`, `inspect`, `trace`, `focus`, `problems`), optional `query`, `target_id`, `project_id`, `detail`, `relation`, `cursor`, `max_items` (1-50), and `max_chars` (256-40000). It has no root or path argument; the active OpenCode worktree is used.
191
+ `delphi_codebase` accepts `action` (`open`, `find`, `inspect`, `trace`, `focus`, `problems`, `metrics`), optional `query`, `target_id`, `project_id`, `detail`, `relation`, `cursor`, `max_items` (1-50), and `max_chars` (256-40000). It has no root or path argument; the active OpenCode worktree is used.
191
192
  """
192
193
 
193
194
 
@@ -199,7 +200,7 @@ const PYTHON = __PYTHON_EXECUTABLE__
199
200
  const DEFAULT_REQUEST_TIMEOUT_MS = 120_000
200
201
 
201
202
  type AgentRequest = {
202
- action: "open" | "find" | "inspect" | "trace" | "focus" | "problems"
203
+ action: "open" | "find" | "inspect" | "trace" | "focus" | "problems" | "metrics"
203
204
  query?: string
204
205
  target_id?: string
205
206
  project_id?: string
@@ -464,7 +465,7 @@ export const DelphiCodebasePlugin: Plugin = async (_input) => {
464
465
  delphi_codebase: tool({
465
466
  description: "Protocol v2 semantic Delphi/Object Pascal codebase navigation.",
466
467
  args: {
467
- action: tool.schema.enum(["open", "find", "inspect", "trace", "focus", "problems"]),
468
+ action: tool.schema.enum(["open", "find", "inspect", "trace", "focus", "problems", "metrics"]),
468
469
  query: tool.schema.string().optional(),
469
470
  target_id: tool.schema.string().optional(),
470
471
  project_id: tool.schema.string().optional(),
@@ -4,6 +4,7 @@ from dataclasses import dataclass
4
4
  import hashlib
5
5
  import json
6
6
  from pathlib import Path
7
+ import unicodedata
7
8
 
8
9
  from .agent_protocol import AgentProtocolError, Focus, make_target_id
9
10
  from .consts import AttributeName, SyntaxNodeType
@@ -369,6 +370,32 @@ def _display_path(path: Path, root: Path) -> str:
369
370
  return resolved.as_posix()
370
371
 
371
372
 
373
+ def unit_source_path(root: Path, unit: AgentUnit) -> Path:
374
+ path = Path(unit.path)
375
+ if not path.is_absolute():
376
+ path = root / path
377
+ return path.expanduser().resolve()
378
+
379
+
380
+ def unit_display_path(root: Path, unit: AgentUnit) -> str:
381
+ source_path = unit_source_path(root, unit)
382
+ try:
383
+ return source_path.relative_to(root).as_posix()
384
+ except ValueError:
385
+ unit_component = _stable_path_component(unit.name or source_path.stem)
386
+ file_component = _stable_path_component(source_path.name)
387
+ return f"@external/{unit_component}/{file_component}"
388
+
389
+
390
+ def unit_target_id(root: Path, unit: AgentUnit) -> str:
391
+ return make_target_id("unit", unit_display_path(root, unit), unit.name)
392
+
393
+
394
+ def _stable_path_component(value: str) -> str:
395
+ normalized = unicodedata.normalize("NFC", value).replace("\\", "_").replace("/", "_")
396
+ return normalized or "unknown"
397
+
398
+
372
399
  def _outline_agent_source(text: str) -> str:
373
400
  return _compact_outline_whitespace(outline_source(text))
374
401
 
@@ -658,4 +685,11 @@ def _file_records(
658
685
  return records
659
686
 
660
687
 
661
- __all__ = ["AgentProject", "AgentUnit", "AgentWorkspace"]
688
+ __all__ = [
689
+ "AgentProject",
690
+ "AgentUnit",
691
+ "AgentWorkspace",
692
+ "unit_display_path",
693
+ "unit_source_path",
694
+ "unit_target_id",
695
+ ]
@@ -654,7 +654,19 @@ def build_syntax_tree(
654
654
  for item in child:
655
655
  if isinstance(item, SyntaxNode):
656
656
  node.add_child(item)
657
- return node
657
+ elif isinstance(child, set):
658
+ if 'abstract' in child:
659
+ node.set_attribute(AttributeName.anAbstract, 'true')
660
+ if 'sealed' in child:
661
+ node.set_attribute(AttributeName.anSealed, 'true')
662
+ return node
663
+
664
+ def class_modifiers(self, meta: Any, *children: Any) -> set[str]:
665
+ return {
666
+ token_value(child).casefold()
667
+ for child in children
668
+ if self._is_text(child) or is_token(child)
669
+ }
658
670
 
659
671
  def forward_class_decl(self, meta: Any, *children: Any) -> SyntaxNode:
660
672
  node = self._make_node(SyntaxNodeType.ntType, meta)
@@ -1957,7 +1969,7 @@ def build_syntax_tree(
1957
1969
 
1958
1970
  def case_statement(self, meta: Any, *children: Any) -> SyntaxNode:
1959
1971
  node = self._make_node(SyntaxNodeType.ntCase, meta)
1960
- for child in children:
1972
+ for child in self._flatten(children):
1961
1973
  if isinstance(child, SyntaxNode):
1962
1974
  node.add_child(child)
1963
1975
  return node