GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — python-sdk/cldk/core.py at main · codellm-devkit/python-sdk

Expand file tree

/

core.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
437 lines (385 loc) · 19.9 KB
/

core.py

Copy path

File metadata and controls

437 lines (385 loc) · 19.9 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
################################################################################
# Copyright IBM Corporation 2024
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
################################################################################
"""Core CLDK module.
This module provides the top-level entry point for the Code Language Development
Kit (CLDK), a unified framework for performing static analysis across multiple
programming languages. The primary interface is the :class:`CLDK` class, which
serves as a factory for creating language-specific analysis objects, tree-sitter
parsers, and sanitization utilities.
The CLDK supports the following languages:
- **Java**: Full static analysis via CodeAnalyzer backend, including symbol
tables, call graphs, and code metrics.
- **Python**: Static analysis via codeanalyzer-python backend (Jedi plus
PyCG call-graph construction).
Typical usage involves instantiating :class:`CLDK` with a target language, then
calling :meth:`CLDK.analysis` to obtain a language-specific analysis facade.
Note:
This module requires language-specific backends to be available:
- Java: ``codeanalyzer-java`` (the ``cldk[java]`` extra; carries the jar and its JVM)
- Python: ``codeanalyzer-python`` (auto-installed in virtualenv)
"""
from pathlib import Path
import logging
import warnings
from typing import List
from cldk.analysis import AnalysisLevel
from cldk.analysis.java import JavaAnalysis
from cldk.analysis.commons.backend_config import (
CodeAnalyzerConfig,
GoBackend,
JavaBackend,
Neo4jConnectionConfig,
PyBackend,
PyCodeAnalyzerConfig,
TSBackend,
TSCodeAnalyzerConfig,
)
from cldk.analysis.commons.treesitter import TreesitterJava
from cldk.analysis.go import GoAnalysis
from cldk.analysis.python.python_analysis import PythonAnalysis
from cldk.analysis.typescript import TypeScriptAnalysis
from cldk.utils.exceptions import CldkInitializationException
from cldk.utils.sanitization.java import TreesitterSanitizer
logger = logging.getLogger(__name__)
def _normalize_project_path(project_path: str | Path | None) -> Path | None:
"""Expand, resolve, and validate a project path.
Validation is keyed off the *path*, not the backend: any non-``None`` path is resolved and
must exist and be a directory, otherwise :class:`CldkInitializationException` is raised — this
holds on every backend, including Neo4j. ``None`` is returned unchanged and skips validation
entirely, because the Neo4j backends read their graph out of band (over Bolt), so a project
directory is optional there.
"""
if project_path is None:
return None
resolved = Path(project_path).expanduser().resolve()
if not resolved.is_dir():
raise CldkInitializationException(f"project_path does not exist or is not a directory: {resolved}")
return resolved
class CLDK:
"""Core class for the Code Language Development Kit (CLDK).
The CLDK class serves as the primary entry point and factory for all code
analysis operations. It provides a unified interface for initializing
language-specific analysis facades, tree-sitter parsers, and code
sanitization utilities.
This class follows the factory pattern, where the ``language`` parameter
determines which concrete analysis implementation is returned by the
:meth:`analysis`, :meth:`treesitter_parser`, and :meth:`tree_sitter_utils`
methods.
Args:
language: The target programming language for analysis. Supported values
are ``"java"``, ``"python"``, and ``"typescript"`` (case-sensitive).
Attributes:
language (str): The programming language specified during initialization.
This determines which analysis backend and utilities are used.
Raises:
NotImplementedError: Raised by factory methods when the specified
language is not yet supported.
See Also:
- :class:`~cldk.analysis.java.JavaAnalysis`: Java-specific analysis facade.
- :class:`~cldk.analysis.python.PythonAnalysis`: Python-specific analysis facade.
"""
def __init__(self, language: str) -> None:
"""Initialize the CLDK instance with a target programming language.
Args:
language: The programming language to use for analysis. Must be one
of the supported languages: ``"java"``, ``"python"``, or
``"typescript"``. The language string is case-sensitive.
"""
self.language: str = language
# -----[ per-language factory methods (preferred entry points) ]-----
@staticmethod
def java(
project_path: str | Path | None = None,
*,
analysis_level: str = AnalysisLevel.symbol_table,
target_files: List[str] | None = None,
eager: bool = False,
backend: JavaBackend | None = None,
) -> JavaAnalysis:
"""Create a Java analysis facade.
Args:
project_path: Path to the Java project directory. Optional only when ``backend`` is a
:class:`Neo4jConnectionConfig` (the graph is read out of band over Bolt). When
provided, the path is validated — it must exist and be a directory — regardless of
backend.
analysis_level: Analysis depth (see :class:`~cldk.analysis.AnalysisLevel`).
target_files: Restrict analysis to these files.
eager: Force regeneration of cached analysis.
backend: Backend configuration. Defaults to :class:`CodeAnalyzerConfig`; pass a
:class:`Neo4jConnectionConfig` to use the read-only Neo4j backend.
Both configurations accept raw ``namespace`` and ``application_name`` selections.
Raises:
CldkInitializationException: If ``project_path`` is missing and the backend is not
Neo4j. (The 1.x ``source_code`` single-file mode was removed in 2.0.)
"""
# The read-only Neo4j backend reads a graph populated out of band, so it needs no project_path.
if project_path is None and not isinstance(backend, Neo4jConnectionConfig):
raise CldkInitializationException("project_path must be provided.")
return JavaAnalysis(
project_dir=_normalize_project_path(project_path),
analysis_level=analysis_level,
target_files=target_files,
eager_analysis=eager,
backend=backend,
)
@staticmethod
def python(
project_path: str | Path | None = None,
*,
analysis_level: str = AnalysisLevel.symbol_table,
target_files: List[str] | None = None,
eager: bool = False,
backend: PyBackend | None = None,
) -> PythonAnalysis:
"""Create a Python analysis facade.
Args:
project_path: Path to the Python project directory. Optional only when ``backend`` is a
:class:`Neo4jConnectionConfig` (the graph is populated out of band over Bolt). When
provided, the path is validated — it must exist and be a directory — regardless of
backend.
analysis_level: Analysis depth (see :class:`~cldk.analysis.AnalysisLevel`).
target_files: Restrict analysis to these files.
eager: Force regeneration of cached analysis.
backend: Backend configuration. Defaults to :class:`PyCodeAnalyzerConfig`;
pass a :class:`Neo4jConnectionConfig` to use the read-only Neo4j backend.
Set raw ``namespace`` and ``application_name`` on that configuration to select ownership.
"""
return PythonAnalysis(
project_dir=_normalize_project_path(project_path),
analysis_level=analysis_level,
target_files=target_files,
eager_analysis=eager,
backend=backend,
)
@staticmethod
def typescript(
project_path: str | Path | None = None,
*,
analysis_level: str = AnalysisLevel.symbol_table,
target_files: List[str] | None = None,
eager: bool = False,
backend: TSBackend | None = None,
) -> TypeScriptAnalysis:
"""Create a TypeScript analysis facade.
Args:
project_path: Path to the TypeScript project directory. Optional only when ``backend``
is a :class:`Neo4jConnectionConfig` (the graph is populated out of band over Bolt).
When provided, the path is validated — it must exist and be a directory — regardless
of backend.
analysis_level: Analysis depth (see :class:`~cldk.analysis.AnalysisLevel`).
target_files: Restrict analysis to these files.
eager: Force regeneration of cached analysis.
backend: Backend configuration. Defaults to :class:`CodeAnalyzerConfig`; pass a
:class:`TSCodeAnalyzerConfig` (its ``tsc_only`` is a deprecated no-op —
codeanalyzer-typescript removed ``--tsc-only`` in 1.0.0), or a
:class:`Neo4jConnectionConfig` to use the read-only Neo4j backend.
"""
return TypeScriptAnalysis(
project_dir=_normalize_project_path(project_path),
analysis_level=analysis_level,
target_files=target_files,
eager_analysis=eager,
backend=backend,
)
@staticmethod
def go(
project_path: str | Path | None = None,
*,
analysis_level: str = AnalysisLevel.symbol_table,
target_files: List[str] | None = None,
eager: bool = False,
backend: GoBackend | None = None,
) -> GoAnalysis:
"""Create a Go analysis facade.
Go is the SDK's first class-less, type-centric facade: the surface is
``get_types`` / ``get_functions`` / ``get_methods_of``, never ``get_classes``.
Args:
project_path: Path to the Go module directory (needs a ``go.mod``). Optional only when
``backend`` is a :class:`Neo4jConnectionConfig` (the graph is populated out of band
over Bolt). When provided, the path is validated — it must exist and be a directory.
analysis_level: Analysis depth (see :class:`~cldk.analysis.AnalysisLevel`). ``cango``
produces all four: 1 (symbol table), 2 (+ resolver call graph), 3 (+ the
per-callable ``cfg``/``cdg``/``ddg``) and 4 (+ the interprocedural SDG the
dataflow and ``taint`` accessors need).
target_files: Restrict analysis to these files.
eager: Force regeneration of cached analysis.
backend: Backend configuration. Defaults to :class:`CodeAnalyzerConfig` (runs ``cango``);
pass a :class:`Neo4jConnectionConfig` to use the read-only Neo4j backend.
"""
return GoAnalysis(
project_dir=_normalize_project_path(project_path),
analysis_level=analysis_level,
target_files=target_files,
eager_analysis=eager,
backend=backend,
)
def analysis(
self,
project_path: str | Path | None = None,
source_code: str | None = None,
eager: bool = False,
analysis_level: str = AnalysisLevel.symbol_table,
target_files: List[str] | None = None,
analysis_backend_path: str | None = None,
analysis_json_path: str | Path | None = None,
cache_dir: str | Path | None = None,
use_ray: bool = False,
neo4j_config: "Neo4jConnectionConfig | None" = None,
) -> JavaAnalysis | PythonAnalysis | TypeScriptAnalysis | GoAnalysis:
"""Deprecated entry point. Use the per-language factory methods instead.
``CLDK(language).analysis(...)`` is retained as a thin compatibility shim that forwards to
:meth:`java` / :meth:`python` / :meth:`typescript` / :meth:`go` with an appropriate
``backend=`` configuration object.
The former ``analysis_json_path`` is folded into the unified ``cache_dir`` (it is used as
the cache root when ``cache_dir`` is not given). ``analysis_backend_path`` is no longer
supported: the backend binary ships with the packaged dependency, and passing it is ignored.
.. deprecated::
Use :meth:`CLDK.java`, :meth:`CLDK.python`, or :meth:`CLDK.typescript`
with a ``backend=<config>`` object.
"""
warnings.warn(
"CLDK(language).analysis(...) is deprecated; use the per-language factory methods "
"CLDK.java()/CLDK.python()/CLDK.typescript()/CLDK.go() with a backend=<config> object.",
DeprecationWarning,
stacklevel=2,
)
if analysis_backend_path is not None:
warnings.warn(
"analysis_backend_path is no longer supported and is ignored; the backend binary "
"ships with the packaged codeanalyzer-* dependency.",
DeprecationWarning,
stacklevel=2,
)
if project_path is None and source_code is None and neo4j_config is None:
raise CldkInitializationException("Either project_path or source_code must be provided.")
# The former analysis_json_path now folds into the unified cache_dir.
cache_root = cache_dir if cache_dir is not None else analysis_json_path
if self.language == "java":
if source_code is not None:
raise CldkInitializationException("source_code mode was removed in 2.0; pass project_path")
return CLDK.java(
project_path=project_path,
analysis_level=analysis_level,
target_files=target_files,
eager=eager,
backend=CodeAnalyzerConfig(cache_dir=cache_root),
)
elif self.language == "python":
if source_code is not None:
raise CldkInitializationException("source_code mode is not supported for Python; please pass project_path.")
backend = neo4j_config if neo4j_config is not None else PyCodeAnalyzerConfig(cache_dir=cache_root, use_ray=use_ray)
return CLDK.python(
project_path=project_path,
analysis_level=analysis_level,
target_files=target_files,
eager=eager,
backend=backend,
)
elif self.language == "typescript":
if source_code is not None:
raise CldkInitializationException("source_code mode is not supported for TypeScript; please pass project_path.")
backend = neo4j_config if neo4j_config is not None else CodeAnalyzerConfig(cache_dir=cache_root)
return CLDK.typescript(
project_path=project_path,
analysis_level=analysis_level,
target_files=target_files,
eager=eager,
backend=backend,
)
elif self.language == "go":
if source_code is not None:
raise CldkInitializationException("source_code mode is not supported for Go; please pass project_path.")
backend = neo4j_config if neo4j_config is not None else CodeAnalyzerConfig(cache_dir=cache_root)
return CLDK.go(
project_path=project_path,
analysis_level=analysis_level,
target_files=target_files,
eager=eager,
backend=backend,
)
else:
raise NotImplementedError(f"Analysis support for {self.language} is not implemented yet.")
def treesitter_parser(self) -> TreesitterJava:
"""Return a Tree-sitter parser for the selected language.
Creates and returns a language-specific Tree-sitter parser instance
that can be used for syntactic analysis, AST traversal, and code
querying operations. Tree-sitter provides incremental parsing with
excellent performance characteristics for real-time code analysis.
The returned parser provides methods for:
- Parsing source code into an AST
- Running Tree-sitter queries to extract code patterns
- Extracting syntactic elements (methods, classes, imports, etc.)
- Performing lexical analysis
Returns:
TreesitterJava: A Tree-sitter parser wrapper for Java source code.
The parser provides methods such as :meth:`is_parsable`,
:meth:`get_raw_ast`, :meth:`get_all_imports`, and various
code extraction utilities.
Raises:
NotImplementedError: If the language specified during CLDK
initialization does not have a Tree-sitter parser implementation.
Currently, only Java is supported.
Note:
The Tree-sitter parser operates at the syntactic level only and
does not perform semantic analysis. For semantic information like
resolved types or call graphs, use :meth:`analysis` instead.
See Also:
- :class:`~cldk.analysis.commons.treesitter.TreesitterJava`:
Java Tree-sitter parser implementation.
"""
if self.language == "java":
return TreesitterJava()
else:
raise NotImplementedError(f"Treesitter parser for {self.language} is not implemented yet.")
def tree_sitter_utils(self, source_code: str) -> TreesitterSanitizer:
"""Return Tree-sitter-based code sanitization utilities for the selected language.
Creates and returns a utility class that provides code transformation
and sanitization operations using Tree-sitter for parsing. These utilities
are particularly useful for preparing code for LLM consumption, test
generation, and code analysis tasks.
The sanitization utilities provide operations such as:
- Removing unused imports from source code
- Keeping only focal methods and their callees for context reduction
- Extracting and manipulating test assertions
- Identifying and removing dead code
Args:
source_code: The source code string to initialize the utilities with.
This code will be parsed and made available for transformation
operations. Must be valid syntax for the target language.
Returns:
TreesitterSanitizer: A utility wrapper that provides sanitization
and transformation methods for Java source code, including:
- :meth:`~TreesitterSanitizer.keep_only_focal_method_and_its_callees`
- :meth:`~TreesitterSanitizer.remove_unused_imports`
Raises:
NotImplementedError: If the language specified during CLDK
initialization does not have sanitization utilities implemented.
Currently, only Java is supported.
Note:
The sanitization utilities modify code at the syntactic level using
Tree-sitter patterns. For complex refactoring that requires semantic
understanding, consider using the full analysis capabilities via
:meth:`analysis`.
See Also:
- :class:`~cldk.utils.sanitization.java.TreesitterSanitizer`:
Java sanitization utility implementation.
- :meth:`treesitter_parser`: For raw Tree-sitter parsing without
sanitization utilities.
"""
if self.language == "java":
return TreesitterSanitizer(source_code=source_code)
else:
raise NotImplementedError(f"Treesitter parser for {self.language} is not implemented yet.")
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.