codeclone 1.1.0__py3-none-any.whl → 1.2.0__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.
codeclone/baseline.py CHANGED
@@ -10,22 +10,24 @@ from __future__ import annotations
10
10
 
11
11
  import json
12
12
  from pathlib import Path
13
- from typing import Set
14
13
 
15
14
 
16
15
  class Baseline:
17
- def __init__(self, path: str):
16
+ def __init__(self, path: str | Path):
18
17
  self.path = Path(path)
19
- self.functions: Set[str] = set()
20
- self.blocks: Set[str] = set()
18
+ self.functions: set[str] = set()
19
+ self.blocks: set[str] = set()
21
20
 
22
21
  def load(self) -> None:
23
22
  if not self.path.exists():
24
23
  return
25
24
 
26
- data = json.loads(self.path.read_text("utf-8"))
27
- self.functions = set(data.get("functions", []))
28
- self.blocks = set(data.get("blocks", []))
25
+ try:
26
+ data = json.loads(self.path.read_text("utf-8"))
27
+ self.functions = set(data.get("functions", []))
28
+ self.blocks = set(data.get("blocks", []))
29
+ except json.JSONDecodeError as e:
30
+ raise ValueError(f"Corrupted baseline file at {self.path}: {e}") from e
29
31
 
30
32
  def save(self) -> None:
31
33
  self.path.parent.mkdir(parents=True, exist_ok=True)
@@ -42,8 +44,10 @@ class Baseline:
42
44
  )
43
45
 
44
46
  @staticmethod
45
- def from_groups(func_groups: dict, block_groups: dict) -> "Baseline":
46
- bl = Baseline("")
47
+ def from_groups(
48
+ func_groups: dict, block_groups: dict, path: str | Path = ""
49
+ ) -> "Baseline":
50
+ bl = Baseline(path)
47
51
  bl.functions = set(func_groups.keys())
48
52
  bl.blocks = set(block_groups.keys())
49
53
  return bl
codeclone/cache.py CHANGED
@@ -12,17 +12,21 @@ import json
12
12
  import os
13
13
  from dataclasses import asdict
14
14
  from pathlib import Path
15
- from typing import Optional
15
+ from typing import Any, Optional
16
16
 
17
17
 
18
18
  class Cache:
19
- def __init__(self, path: str):
19
+ def __init__(self, path: str | Path):
20
20
  self.path = Path(path)
21
- self.data: dict = {"files": {}}
21
+ self.data: dict[str, Any] = {"files": {}}
22
22
 
23
23
  def load(self) -> None:
24
24
  if self.path.exists():
25
- self.data = json.loads(self.path.read_text("utf-8"))
25
+ try:
26
+ self.data = json.loads(self.path.read_text("utf-8"))
27
+ except json.JSONDecodeError:
28
+ # If cache is corrupted, start fresh
29
+ self.data = {"files": {}}
26
30
 
27
31
  def save(self) -> None:
28
32
  self.path.parent.mkdir(parents=True, exist_ok=True)
@@ -31,10 +35,12 @@ class Cache:
31
35
  "utf-8",
32
36
  )
33
37
 
34
- def get_file_entry(self, filepath: str) -> Optional[dict]:
38
+ def get_file_entry(self, filepath: str) -> Optional[dict[str, Any]]:
35
39
  return self.data.get("files", {}).get(filepath)
36
40
 
37
- def put_file_entry(self, filepath: str, stat_sig: dict, units, blocks) -> None:
41
+ def put_file_entry(
42
+ self, filepath: str, stat_sig: dict[str, Any], units: list, blocks: list
43
+ ) -> None:
38
44
  self.data.setdefault("files", {})[filepath] = {
39
45
  "stat": stat_sig,
40
46
  "units": [asdict(u) for u in units],
codeclone/cfg.py CHANGED
@@ -107,6 +107,18 @@ class CFGBuilder:
107
107
  case ast.For():
108
108
  self._visit_for(stmt)
109
109
 
110
+ case ast.AsyncFor():
111
+ self._visit_for(stmt) # Structure is identical to For
112
+
113
+ case ast.Try() | ast.TryStar():
114
+ self._visit_try(stmt)
115
+
116
+ case ast.With() | ast.AsyncWith():
117
+ self._visit_with(stmt)
118
+
119
+ case ast.Match():
120
+ self._visit_match(stmt)
121
+
110
122
  case _:
111
123
  self.current.statements.append(stmt)
112
124
 
@@ -153,7 +165,7 @@ class CFGBuilder:
153
165
 
154
166
  self.current = after_block
155
167
 
156
- def _visit_for(self, stmt: ast.For) -> None:
168
+ def _visit_for(self, stmt: ast.For | ast.AsyncFor) -> None:
157
169
  iter_block = self.cfg.create_block()
158
170
  body_block = self.cfg.create_block()
159
171
  after_block = self.cfg.create_block()
@@ -171,3 +183,156 @@ class CFGBuilder:
171
183
  self.current.add_successor(iter_block)
172
184
 
173
185
  self.current = after_block
186
+
187
+ def _visit_with(self, stmt: ast.With | ast.AsyncWith) -> None:
188
+ # Treat WITH as linear flow (enter -> body -> exit), but preserve block structure
189
+ # We record the context manager expression in the current block
190
+ # Then we enter a new block for the body (to separate it structurally)
191
+ # Then we enter a new block for 'after' (exit)
192
+
193
+ # Why new block? Because 'with' implies a scope/context.
194
+ # It helps matching.
195
+
196
+ body_block = self.cfg.create_block()
197
+ after_block = self.cfg.create_block()
198
+
199
+ # Record the 'items' (context managers)
200
+ # We wrap them in Expr to treat them as statements for hashing
201
+ for item in stmt.items:
202
+ self.current.statements.append(ast.Expr(value=item.context_expr))
203
+
204
+ self.current.add_successor(body_block)
205
+
206
+ self.current = body_block
207
+ self._visit_statements(stmt.body)
208
+ if not self.current.is_terminated:
209
+ self.current.add_successor(after_block)
210
+
211
+ self.current = after_block
212
+
213
+ def _visit_try(self, stmt: ast.Try | ast.TryStar) -> None:
214
+ # Simplified Try CFG:
215
+ # Try Body -> [Handlers...] -> Finally/After
216
+ # Try Body -> Else -> Finally/After
217
+
218
+ try_block = self.cfg.create_block()
219
+ self.current.add_successor(try_block)
220
+
221
+ # We don't know WHERE in the try block exception happens, so we assume
222
+ # any point in try block *could* jump to handlers.
223
+ # But for structural hashing, we just process the body.
224
+ # Ideally, we should link the try_block (or its end) to handlers?
225
+ # A simple approximation:
226
+ # 1. Process body.
227
+ # 2. Link entry (or end of body) to handlers?
228
+ # Let's do: Entry -> BodyBlock.
229
+ # Entry -> HandlerBlocks (to represent potential jump).
230
+
231
+ # Actually, let's keep it linear but branched.
232
+ # Current -> TryBody
233
+ # Current -> Handlers (Abstractly representing the jump)
234
+
235
+ handlers_blocks = [self.cfg.create_block() for _ in stmt.handlers]
236
+ else_block = self.cfg.create_block() if stmt.orelse else None
237
+ final_block = self.cfg.create_block() # This is finally or after
238
+
239
+ # Link current to TryBody
240
+ self.current = try_block
241
+ self._visit_statements(stmt.body)
242
+
243
+ # If try body finishes successfully:
244
+ if not self.current.is_terminated:
245
+ if else_block:
246
+ self.current.add_successor(else_block)
247
+ else:
248
+ self.current.add_successor(final_block)
249
+
250
+ # Handle Else
251
+ if else_block:
252
+ self.current = else_block
253
+ self._visit_statements(stmt.orelse)
254
+ if not self.current.is_terminated:
255
+ self.current.add_successor(final_block)
256
+
257
+ # Handle Handlers
258
+ # We assume control flow *could* jump from start of Try to any handler
259
+ # (Technically from inside try, but we model structural containment)
260
+ # To make fingerprints stable, we just need to ensure handlers are visited
261
+ # and linked.
262
+
263
+ # We link the *original* predecessor (before try) or the try_block start to handlers?
264
+ # Let's link the `try_block` (as a container concept) to handlers.
265
+ # But `try_block` was mutated by `_visit_statements`.
266
+ # Let's use the `try_block` (start of try) to link to handlers.
267
+ for h_block in handlers_blocks:
268
+ try_block.add_successor(h_block)
269
+
270
+ for handler, h_block in zip(stmt.handlers, handlers_blocks):
271
+ self.current = h_block
272
+ # Record exception type
273
+ if handler.type:
274
+ self.current.statements.append(ast.Expr(value=handler.type))
275
+ self._visit_statements(handler.body)
276
+ if not self.current.is_terminated:
277
+ self.current.add_successor(final_block)
278
+
279
+ # Finally logic:
280
+ # If there is a finally block, `final_block` IS the finally block.
281
+ # We visit it. Then we create a new `after_finally` block?
282
+ # Or `final_block` is the start of finally.
283
+
284
+ if stmt.finalbody:
285
+ self.current = final_block
286
+ self._visit_statements(stmt.finalbody)
287
+ # And then continue to next code?
288
+ # Yes, finally flows to next statement.
289
+ # Unless terminated.
290
+
291
+ # If no finally, `final_block` is just the merge point (after).
292
+ self.current = final_block
293
+
294
+ def _visit_match(self, stmt: ast.Match) -> None:
295
+ # Match subject -> Cases -> After
296
+
297
+ self.current.statements.append(ast.Expr(value=stmt.subject))
298
+
299
+ after_block = self.cfg.create_block()
300
+
301
+ for case_ in stmt.cases:
302
+ case_block = self.cfg.create_block()
303
+ self.current.add_successor(case_block)
304
+
305
+ # Save current context to restore for next case branching?
306
+ # No, 'current' is the match subject block. It branches to ALL cases.
307
+
308
+ # Visit Case
309
+ # We must set self.current to case_block for visiting body
310
+ # But we lose reference to 'match subject block' to link next case!
311
+ # So we need a variable `subject_block`.
312
+ pass
313
+
314
+ # Re-implementing loop correctly
315
+ subject_block = self.current
316
+
317
+ for case_ in stmt.cases:
318
+ case_block = self.cfg.create_block()
319
+ subject_block.add_successor(case_block)
320
+
321
+ self.current = case_block
322
+ # We could record the pattern here?
323
+ # patterns are complex AST nodes. For now, let's skip pattern structure hash
324
+ # and just hash the body. Or dump pattern as statement?
325
+ # Pattern is not a statement.
326
+ # Let's ignore pattern details for V1, or try to normalize it.
327
+ # If we ignore pattern, then `case []:` and `case {}:` look same.
328
+ # Ideally: `self.current.statements.append(case_.pattern)` but pattern is not stmt.
329
+ # We can wrap in Expr? `ast.Expr(value=case_.pattern)`?
330
+ # Pattern is NOT an Expr subclass in 3.10. It's `ast.pattern`.
331
+ # So we cannot append it to `statements` list which expects `ast.stmt`.
332
+ # We will ignore pattern structure for now (it's structural flow we care about).
333
+
334
+ self._visit_statements(case_.body)
335
+ if not self.current.is_terminated:
336
+ self.current.add_successor(after_block)
337
+
338
+ self.current = after_block