AutoCython-zhang 2.3.9__tar.gz → 2.3.11__tar.gz

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.
Files changed (19) hide show
  1. {autocython_zhang-2.3.9 → autocython_zhang-2.3.11}/AutoCython/AutoCython.py +7 -3
  2. {autocython_zhang-2.3.9 → autocython_zhang-2.3.11}/AutoCython/_version.py +1 -1
  3. {autocython_zhang-2.3.9 → autocython_zhang-2.3.11}/AutoCython/compile.py +313 -54
  4. {autocython_zhang-2.3.9 → autocython_zhang-2.3.11}/AutoCython/obfuscate.py +571 -123
  5. {autocython_zhang-2.3.9 → autocython_zhang-2.3.11}/AutoCython/run_tasks.py +35 -11
  6. {autocython_zhang-2.3.9 → autocython_zhang-2.3.11}/AutoCython/tools.py +100 -72
  7. {autocython_zhang-2.3.9 → autocython_zhang-2.3.11}/AutoCython_zhang.egg-info/PKG-INFO +2 -2
  8. {autocython_zhang-2.3.9 → autocython_zhang-2.3.11}/AutoCython_zhang.egg-info/top_level.txt +0 -1
  9. {autocython_zhang-2.3.9 → autocython_zhang-2.3.11}/PKG-INFO +2 -2
  10. {autocython_zhang-2.3.9 → autocython_zhang-2.3.11}/README.md +1 -1
  11. {autocython_zhang-2.3.9 → autocython_zhang-2.3.11}/AutoCython/__init__.py +0 -0
  12. {autocython_zhang-2.3.9 → autocython_zhang-2.3.11}/AutoCython_zhang.egg-info/SOURCES.txt +0 -0
  13. {autocython_zhang-2.3.9 → autocython_zhang-2.3.11}/AutoCython_zhang.egg-info/dependency_links.txt +0 -0
  14. {autocython_zhang-2.3.9 → autocython_zhang-2.3.11}/AutoCython_zhang.egg-info/entry_points.txt +0 -0
  15. {autocython_zhang-2.3.9 → autocython_zhang-2.3.11}/AutoCython_zhang.egg-info/requires.txt +1 -1
  16. {autocython_zhang-2.3.9 → autocython_zhang-2.3.11}/LICENSE +0 -0
  17. {autocython_zhang-2.3.9 → autocython_zhang-2.3.11}/MANIFEST.in +0 -0
  18. {autocython_zhang-2.3.9 → autocython_zhang-2.3.11}/pyproject.toml +0 -0
  19. {autocython_zhang-2.3.9 → autocython_zhang-2.3.11}/setup.cfg +0 -0
@@ -1,7 +1,7 @@
1
1
  import os
2
2
  import sys
3
3
  from .run_tasks import run_tasks
4
- from .compile import compile_to_binary
4
+ from .compile import check_output_collisions, compile_to_binary
5
5
  from .tools import parse_arguments, find_python_files
6
6
  from .tools import show_no_compilable_files, show_file_not_found, show_path_not_found
7
7
 
@@ -13,23 +13,26 @@ def compile():
13
13
  if args.file:
14
14
  if os.path.isfile(args.file):
15
15
  compile_file = args.file
16
+ check_output_collisions([compile_file])
16
17
  del_source = args.del_source
17
18
  tasks = [
18
- # 函数, 位置参数, 关键字参数
19
+ # 函数, 显示名称, 位置参数, 关键字参数
19
20
  (compile_to_binary, compile_file, (compile_file, del_source, True, obfuscate_seed), {}),
20
21
  ]
21
22
  run_tasks(tasks, max_workers=1, raise_on_failure=True) # 执行编译
22
23
  else:
23
24
  show_file_not_found(args.file)
25
+ sys.exit(1)
24
26
  elif args.path:
25
27
  if os.path.exists(args.path) and not os.path.isfile(args.path):
26
28
  compile_file_list = find_python_files(args.path)
27
29
  if compile_file_list:
30
+ check_output_collisions(compile_file_list)
28
31
  del_source = args.del_source
29
32
  tasks = []
30
33
  for compile_file in compile_file_list:
31
34
  tasks.append(
32
- # 函数, 位置参数, 关键字参数
35
+ # 函数, 显示名称, 位置参数, 关键字参数
33
36
  (compile_to_binary, compile_file, (compile_file, del_source, True, obfuscate_seed), {}),
34
37
  )
35
38
  run_tasks(tasks, max_workers=args.conc, raise_on_failure=True) # 执行编译
@@ -37,6 +40,7 @@ def compile():
37
40
  show_no_compilable_files(args.path)
38
41
  else:
39
42
  show_path_not_found(args.path)
43
+ sys.exit(1)
40
44
  except KeyboardInterrupt:
41
45
  sys.exit(130)
42
46
  except Exception as e:
@@ -2,4 +2,4 @@
2
2
  # -*- coding: utf-8 -*-
3
3
  """版本号模块 - 单一版本号来源"""
4
4
 
5
- __version__ = "2.3.9"
5
+ __version__ = "2.3.11"
@@ -9,7 +9,7 @@ import sys
9
9
  import tempfile
10
10
  import tokenize
11
11
 
12
- from .obfuscate import obfuscate_source
12
+ from .obfuscate import _collect_identifier_names, _fresh_name, obfuscate_source
13
13
 
14
14
  _SUPPORTED_CYTHON_MAJOR = 3
15
15
 
@@ -58,6 +58,12 @@ def _safe_relative_path(rel_path: str) -> str:
58
58
  _SCOPE_TYPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)
59
59
 
60
60
 
61
+ def _unwrap_subscript(node):
62
+ while isinstance(node, ast.Subscript):
63
+ node = node.value
64
+ return node
65
+
66
+
61
67
  def _dotted_name(node):
62
68
  parts = []
63
69
  while isinstance(node, ast.Attribute):
@@ -91,7 +97,12 @@ def _collect_scope_bindings(nodes, scope_node):
91
97
  bound.add(args.vararg.arg)
92
98
  if args.kwarg:
93
99
  bound.add(args.kwarg.arg)
94
- match_capture = getattr(ast, "MatchAs", None)
100
+ match_capture_types = tuple(
101
+ node_type for node_type in (
102
+ getattr(ast, "MatchAs", None),
103
+ getattr(ast, "MatchStar", None),
104
+ ) if node_type is not None
105
+ )
95
106
  match_mapping = getattr(ast, "MatchMapping", None)
96
107
  for node in nodes:
97
108
  if isinstance(node, ast.Name) and isinstance(node.ctx, (ast.Store, ast.Del)):
@@ -104,7 +115,7 @@ def _collect_scope_bindings(nodes, scope_node):
104
115
  for alias in node.names:
105
116
  if alias.name != "*":
106
117
  bound.add(alias.asname or alias.name.split(".", 1)[0])
107
- elif match_capture is not None and isinstance(node, match_capture) and node.name:
118
+ elif match_capture_types and isinstance(node, match_capture_types) and node.name:
108
119
  bound.add(node.name)
109
120
  elif match_mapping is not None and isinstance(node, match_mapping) and node.rest:
110
121
  bound.add(node.rest)
@@ -191,7 +202,7 @@ def _find_pydantic_model_classes(tree):
191
202
  if isinstance(node, ast.ClassDef):
192
203
  is_model = False
193
204
  for base in node.bases:
194
- dotted = _dotted_name(base)
205
+ dotted = _dotted_name(_unwrap_subscript(base))
195
206
  if dotted in base_names or dotted in known_models:
196
207
  is_model = True
197
208
  break
@@ -216,9 +227,15 @@ def _find_pydantic_model_classes(tree):
216
227
  elif match_mapping_type is not None and isinstance(node, match_mapping_type) and node.rest:
217
228
  shadow({node.rest})
218
229
 
219
- child_bases = tuple(base_names)
220
- child_models = tuple(known_models)
221
- child_modules = tuple(module_prefixes)
230
+ if isinstance(scope_node, ast.ClassDef):
231
+ # Python 的 class 命名空间不构成内部方法或嵌套类体的外层词法作用域。
232
+ child_bases = tuple(inherited_bases)
233
+ child_models = tuple(inherited_models)
234
+ child_modules = tuple(inherited_modules)
235
+ else:
236
+ child_bases = tuple(base_names)
237
+ child_models = tuple(known_models)
238
+ child_modules = tuple(module_prefixes)
222
239
  for node in nodes:
223
240
  if isinstance(node, _SCOPE_TYPES) and node is not scope_node:
224
241
  visit_scope(node, child_bases, child_models, child_modules)
@@ -227,6 +244,129 @@ def _find_pydantic_model_classes(tree):
227
244
  return model_classes
228
245
 
229
246
 
247
+ def _base_class_exprs(node, shadowed_names):
248
+ """提取类定义中无副作用且未被类体遮蔽的基类表达式源码。"""
249
+ exprs = []
250
+ for base in node.bases:
251
+ dotted = _dotted_name(_unwrap_subscript(base))
252
+ if dotted and dotted.split(".", 1)[0] not in shadowed_names:
253
+ exprs.append(dotted)
254
+ return exprs
255
+
256
+
257
+ def _build_pydantic_shim_source(node, forbidden_names):
258
+ """为单个 Pydantic BaseModel 子类生成保留继承与既有配置的兼容代码。"""
259
+ legacy_config = next(
260
+ (
261
+ item for item in node.body
262
+ if isinstance(item, ast.ClassDef) and item.name == "Config"
263
+ ),
264
+ None,
265
+ )
266
+ cls_var = _fresh_name("_ac_c", forbidden_names)
267
+ scope_nodes = list(_walk_scope_nodes(node.body))
268
+ bound_names = _collect_scope_bindings(scope_nodes, node)
269
+ base_var = _fresh_name("_ac_b", forbidden_names)
270
+ type_var = _fresh_name("_ac_t", forbidden_names)
271
+ base_exprs = _base_class_exprs(node, bound_names)
272
+ if base_exprs:
273
+ bases_tuple = "(" + ", ".join(base_exprs) + ",)"
274
+ inherited_ignored = (
275
+ f'*({type_var} for {base_var} in {bases_tuple} '
276
+ f'for {cls_var} in {base_var}.__mro__ '
277
+ f'if "model_config" in {cls_var}.__dict__ '
278
+ f'and {cls_var}.__dict__["model_config"].__class__ is {{}}.__class__ '
279
+ f'for {type_var} in {cls_var}.__dict__["model_config"].get("ignored_types", ())), '
280
+ f'*({type_var} for {base_var} in {bases_tuple} '
281
+ f'for {cls_var} in {base_var}.__mro__ '
282
+ f'if "Config" in {cls_var}.__dict__ '
283
+ f'and "".__class__.__class__ in {cls_var}.__dict__["Config"].__class__.__mro__ '
284
+ f'and "ignored_types" in {cls_var}.__dict__["Config"].__dict__ '
285
+ f'for {type_var} in {cls_var}.__dict__["Config"].__dict__["ignored_types"]), '
286
+ )
287
+ else:
288
+ inherited_ignored = ""
289
+
290
+ if legacy_config is not None:
291
+ return (
292
+ f'Config.ignored_types = ({inherited_ignored}'
293
+ f'*([{cls_var}.__dict__["ignored_types"] for {cls_var} in Config.__mro__ '
294
+ f'if "ignored_types" in {cls_var}.__dict__] or [()])[0], '
295
+ f'(lambda: None).__class__)'
296
+ )
297
+
298
+ has_star_import = any(
299
+ isinstance(item, ast.ImportFrom) and any(alias.name == "*" for alias in item.names)
300
+ for item in scope_nodes
301
+ )
302
+
303
+ has_model_config = "model_config" in bound_names or has_star_import
304
+ locals_shadowed = "locals" in bound_names or has_star_import
305
+
306
+ if not has_model_config:
307
+ return (
308
+ f'model_config = {{"ignored_types": ({inherited_ignored}'
309
+ f'(lambda: None).__class__)}}'
310
+ )
311
+
312
+ if not locals_shadowed:
313
+ own_expr = '(model_config if "model_config" in locals() else {})'
314
+ return (
315
+ f'model_config = {{**{own_expr}, '
316
+ f'"ignored_types": ({inherited_ignored}*{own_expr}.get("ignored_types", ()), '
317
+ f'(lambda: None).__class__)}}'
318
+ )
319
+
320
+ return (
321
+ 'try:\n'
322
+ ' model_config = {**model_config, '
323
+ f'"ignored_types": ({inherited_ignored}*model_config.get("ignored_types", ()), '
324
+ '(lambda: None).__class__)}\n'
325
+ 'except NameError:\n'
326
+ f' model_config = {{"ignored_types": ({inherited_ignored}'
327
+ '(lambda: None).__class__)}'
328
+ )
329
+
330
+
331
+ def _is_computed_field_decorator(dec) -> bool:
332
+ target = dec.func if isinstance(dec, ast.Call) else dec
333
+ dotted = _dotted_name(target)
334
+ return bool(dotted and (dotted == "computed_field" or dotted.endswith(".computed_field")))
335
+
336
+
337
+ def _has_property_decorator(decorator_list) -> bool:
338
+ for dec in decorator_list:
339
+ dotted = _dotted_name(dec)
340
+ if dotted in {"property", "builtins.property", "cached_property", "functools.cached_property"}:
341
+ return True
342
+ return False
343
+
344
+
345
+ def _class_has_cython_callable(node: ast.ClassDef) -> bool:
346
+ return any(
347
+ isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda))
348
+ for item in _walk_scope_nodes(node.body)
349
+ )
350
+
351
+
352
+ def _collect_all_bound_names(tree: ast.AST):
353
+ bound = set()
354
+ for child in ast.walk(tree):
355
+ if isinstance(child, ast.Name) and isinstance(child.ctx, (ast.Store, ast.Del)):
356
+ bound.add(child.id)
357
+ elif isinstance(child, ast.arg):
358
+ bound.add(child.arg)
359
+ elif isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
360
+ bound.add(child.name)
361
+ elif isinstance(child, ast.ExceptHandler) and child.name:
362
+ bound.add(child.name)
363
+ elif isinstance(child, (ast.Import, ast.ImportFrom)):
364
+ for alias in child.names:
365
+ if alias.name != "*":
366
+ bound.add(alias.asname or alias.name.split(".", 1)[0])
367
+ return bound
368
+
369
+
230
370
  def _add_pydantic_ignored_types(source_code: str) -> str:
231
371
  """Make Pydantic v2 models tolerate Cython's bound method type.
232
372
 
@@ -243,42 +383,105 @@ def _add_pydantic_ignored_types(source_code: str) -> str:
243
383
 
244
384
  class_nodes = [
245
385
  node for node in _find_pydantic_model_classes(tree)
246
- if any(isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)) for item in node.body)
386
+ if _class_has_cython_callable(node)
247
387
  ]
248
388
 
249
389
  if not class_nodes:
250
390
  return source_code
251
391
 
252
- # Inject only at the end of the affected class body. Re-unparsing the
392
+ # Inject only at the affected class/decorator lines. Re-unparsing the
253
393
  # entire module would discard comments/formatting and can change unrelated
254
394
  # plain source even though only one model needs the compatibility shim.
255
395
  lines = source_code.splitlines(keepends=True)
256
396
  newline = "\r\n" if "\r\n" in source_code else "\n"
397
+ forbidden_names = _collect_identifier_names(tree)
398
+ all_bound_names = _collect_all_bound_names(tree)
399
+ has_future_annotations = any(
400
+ isinstance(stmt, ast.ImportFrom)
401
+ and stmt.module == "__future__"
402
+ and any(alias.name == "annotations" for alias in stmt.names)
403
+ for stmt in tree.body
404
+ )
405
+ prop_decorator = (
406
+ '@property'
407
+ if 'property' not in all_bound_names
408
+ else '@(__builtins__["property"] if isinstance(__builtins__, dict) else __builtins__.property)'
409
+ )
257
410
  insertions = []
411
+ inline_modified = False
258
412
  for node in class_nodes:
259
- if not node.body or node.lineno == node.end_lineno:
413
+ if not node.body:
260
414
  continue
261
- legacy_config = next(
262
- (
263
- item for item in node.body
264
- if isinstance(item, ast.ClassDef) and item.name == "Config"
265
- ),
266
- None,
267
- )
268
- if legacy_config is not None:
269
- config_source = (
270
- 'Config.ignored_types = (*Config.__dict__.get("ignored_types", ()), '
271
- '(lambda: None).__class__)'
272
- )
273
- else:
274
- config_source = (
275
- 'model_config = {**(model_config if "model_config" in locals() else {}), '
276
- '"ignored_types": (*(model_config if "model_config" in locals() else {})'
277
- '.get("ignored_types", ()), (lambda: None).__class__)}'
278
- )
415
+ config_source = _build_pydantic_shim_source(node, forbidden_names)
416
+ if node.lineno == node.end_lineno:
417
+ if "\n" not in config_source:
418
+ last_stmt = node.body[-1]
419
+ end_col = getattr(last_stmt, "end_col_offset", None)
420
+ if isinstance(end_col, int):
421
+ raw_line = lines[node.lineno - 1].encode("utf-8")
422
+ lines[node.lineno - 1] = (
423
+ raw_line[:end_col]
424
+ + f"; {config_source}".encode("utf-8")
425
+ + raw_line[end_col:]
426
+ ).decode("utf-8")
427
+ inline_modified = True
428
+ continue
429
+
430
+ for item in _walk_scope_nodes(node.body):
431
+ if not isinstance(item, ast.FunctionDef):
432
+ continue
433
+ cf_decorators = [d for d in item.decorator_list if _is_computed_field_decorator(d)]
434
+ if not cf_decorators:
435
+ continue
436
+ if item.returns is not None:
437
+ ret_unparsed = ast.unparse(item.returns)
438
+ ret_expr = repr(ret_unparsed) if has_future_annotations else ret_unparsed
439
+ for dec in cf_decorators:
440
+ if isinstance(dec, ast.Call) and any(
441
+ kw.arg == "return_type" for kw in dec.keywords
442
+ ):
443
+ continue
444
+ dec_end_line = getattr(dec, "end_lineno", None)
445
+ dec_end_col = getattr(dec, "end_col_offset", None)
446
+ if not isinstance(dec_end_line, int) or not isinstance(dec_end_col, int):
447
+ continue
448
+ raw_dec_line = lines[dec_end_line - 1].encode("utf-8")
449
+ if isinstance(dec, ast.Call):
450
+ if dec_end_col > 0 and raw_dec_line[dec_end_col - 1 : dec_end_col] == b")":
451
+ prefix = raw_dec_line[: dec_end_col - 1]
452
+ if not (dec.args or dec.keywords):
453
+ patch_bytes = f"return_type={ret_expr}".encode("utf-8")
454
+ elif prefix.rstrip().endswith(b","):
455
+ patch_bytes = f" return_type={ret_expr}".encode("utf-8")
456
+ else:
457
+ patch_bytes = f", return_type={ret_expr}".encode("utf-8")
458
+ lines[dec_end_line - 1] = (
459
+ prefix + patch_bytes + raw_dec_line[dec_end_col - 1 :]
460
+ ).decode("utf-8")
461
+ inline_modified = True
462
+ else:
463
+ lines[dec_end_line - 1] = (
464
+ raw_dec_line[:dec_end_col]
465
+ + f"(return_type={ret_expr})".encode("utf-8")
466
+ + raw_dec_line[dec_end_col:]
467
+ ).decode("utf-8")
468
+ inline_modified = True
469
+
470
+ if not _has_property_decorator(item.decorator_list):
471
+ outermost_cf = cf_decorators[-1]
472
+ cf_line = lines[outermost_cf.lineno - 1]
473
+ prop_indent = cf_line[: len(cf_line) - len(cf_line.lstrip())]
474
+ insertions.append(
475
+ (outermost_cf.end_lineno, 0, f"{prop_indent}{prop_decorator}{newline}")
476
+ )
477
+
279
478
  class_line = lines[node.lineno - 1]
280
479
  class_indent = class_line[: len(class_line) - len(class_line.lstrip())]
281
- body_line = lines[node.body[0].lineno - 1]
480
+ body_stmt = next(
481
+ (item for item in node.body if item.lineno > node.lineno),
482
+ node.body[0],
483
+ )
484
+ body_line = lines[body_stmt.lineno - 1]
282
485
  body_indent = body_line[: len(body_line) - len(body_line.lstrip())]
283
486
  if not body_indent or len(body_indent) <= len(class_indent):
284
487
  body_indent = class_indent + " "
@@ -287,14 +490,19 @@ def _add_pydantic_ignored_types(source_code: str) -> str:
287
490
  indented_config = newline.join(
288
491
  body_indent + line for line in config_source.splitlines()
289
492
  ) + newline
290
- insertions.append((insert_at, len(body_indent), indented_config))
493
+ insertions.append((insert_at, -len(body_indent), indented_config))
494
+
495
+ if not insertions and not inline_modified:
496
+ return source_code
497
+
498
+ if insertions and lines and not lines[-1].endswith(("\n", "\r")):
499
+ lines[-1] = lines[-1] + newline
291
500
 
292
501
  for line_number, _, text in sorted(
293
502
  insertions,
294
- key=lambda item: (item[0], -item[1]),
503
+ key=lambda item: (item[0], item[1]),
295
504
  reverse=True,
296
505
  ):
297
- offset = line_number
298
506
  offset = min(line_number, len(lines))
299
507
  lines.insert(offset, text)
300
508
  return "".join(lines)
@@ -325,7 +533,10 @@ def _strip_binary(path):
325
533
  after_header = binary_file.read(4)
326
534
  binary_file.seek(0, os.SEEK_END)
327
535
  after_size = binary_file.tell()
328
- minimum_size = max(64, before_size // 4) if before_size is not None else 0
536
+ # DWARF5 debug sections often exceed 75% of an unstripped shared
537
+ # object's size; use a conservative floor that rejects truncated headers
538
+ # without silently rolling back legitimate strip output.
539
+ minimum_size = max(64, before_size // 32) if before_size is not None else 0
329
540
  return (
330
541
  bool(after_header)
331
542
  and after_header == before_header
@@ -415,9 +626,12 @@ def _validate_cython_syntax(source_code: str, file_path: str) -> None:
415
626
  if not unsupported:
416
627
  return
417
628
  feature, node = unsupported[0]
629
+ lineno = getattr(node, 'lineno', '?')
630
+ col_offset = getattr(node, 'col_offset', None)
631
+ column = col_offset + 1 if isinstance(col_offset, int) else '?'
418
632
  raise UnsupportedSyntaxError(
419
633
  f'Cython 3.x does not support {feature} in {file_path} '
420
- f'(line {getattr(node, "lineno", "?")}, column {getattr(node, "col_offset", "?") + 1}).'
634
+ f'(line {lineno}, column {column}).'
421
635
  )
422
636
 
423
637
 
@@ -541,7 +755,7 @@ def _copy_package_inits(
541
755
  rel_init_path = _safe_relative_path(rel_init_path)
542
756
  temp_init_path = os.path.join(temp_dir, rel_init_path)
543
757
  os.makedirs(os.path.dirname(temp_init_path), exist_ok=True)
544
- shutil.copy2(init_path, temp_init_path)
758
+ shutil.copyfile(init_path, temp_init_path)
545
759
 
546
760
  if current_dir == compile_root:
547
761
  break
@@ -552,6 +766,39 @@ def _copy_package_inits(
552
766
  current_dir = parent_dir
553
767
 
554
768
 
769
+ def check_output_collisions(file_paths) -> None:
770
+ """检测同一目录下规范化模块名冲突(含遮蔽同目录既有同名 .py 文件),避免覆盖或误删。"""
771
+ seen = {}
772
+ for file_path in file_paths:
773
+ abs_path = os.path.abspath(file_path)
774
+ source_dir = os.path.dirname(abs_path)
775
+ stem, _ = os.path.splitext(os.path.basename(abs_path))
776
+ safe_stem = _safe_module_component(stem)
777
+ key = (source_dir, safe_stem)
778
+ previous = seen.get(key)
779
+ if previous is not None and previous != abs_path:
780
+ raise ValueError(
781
+ f"Output module name collision ({safe_stem!r}) between "
782
+ f"{previous} and {abs_path}"
783
+ )
784
+ if safe_stem != stem:
785
+ existing_peer = os.path.abspath(os.path.join(source_dir, f"{safe_stem}.py"))
786
+ if existing_peer != abs_path and os.path.isfile(existing_peer):
787
+ raise ValueError(
788
+ f"Output module name collision ({safe_stem!r}) between "
789
+ f"{abs_path} and existing {existing_peer}"
790
+ )
791
+ existing_pkg_init = os.path.abspath(
792
+ os.path.join(source_dir, safe_stem, "__init__.py")
793
+ )
794
+ if os.path.isfile(existing_pkg_init):
795
+ raise ValueError(
796
+ f"Output module name collision ({safe_stem!r}) between "
797
+ f"{abs_path} and existing package {os.path.dirname(existing_pkg_init)}"
798
+ )
799
+ seen[key] = abs_path
800
+
801
+
555
802
  def compile_to_binary(file_path: str, del_source=False, obfuscate=True, obfuscate_seed=None):
556
803
  """
557
804
  将指定的 Python 文件(.py)通过 Cython 编译为二进制扩展文件
@@ -577,52 +824,61 @@ def compile_to_binary(file_path: str, del_source=False, obfuscate=True, obfuscat
577
824
  if ext != '.py':
578
825
  raise ValueError(f"ValueError: The file {file_path} is not a valid Python file (.py)!")
579
826
 
827
+ check_output_collisions([abs_file_path])
828
+
580
829
  module_layout = _resolve_module_layout(abs_file_path)
581
830
  safe_module_name = module_layout['safe_module_name']
582
831
  target_ext = get_platform_extension()
583
832
  temp_dir = tempfile.mkdtemp()
584
833
 
585
834
  try:
586
- # Keep the source tree away from the setup process' import path. A
587
- # module named ``collections.py`` (or another stdlib name) otherwise
588
- # shadows the stdlib while setuptools starts up.
589
- source_root = os.path.join(temp_dir, 'source')
835
+ # Keep the source tree inside a non-package subdirectory of build_root:
836
+ # 1) ``collections.py`` (or another stdlib name) is not in build_root
837
+ # itself, so it cannot shadow stdlib modules on sys.path[0];
838
+ # 2) Extension receives a clean relative subpath free of ``..`` and free
839
+ # of any glob metacharacters (such as ``[py311]``) in TMPDIR.
590
840
  build_root = os.path.join(temp_dir, 'build')
841
+ source_root = os.path.join(build_root, '_src')
591
842
  temp_file_path = os.path.join(source_root, module_layout['safe_rel_path'])
843
+ rel_temp_file_path = os.path.relpath(temp_file_path, build_root).replace(os.sep, '/')
592
844
  os.makedirs(os.path.dirname(temp_file_path), exist_ok=True)
593
- os.makedirs(build_root, exist_ok=True)
594
845
  _copy_package_inits(
595
846
  abs_file_path,
596
847
  module_layout['compile_root'],
597
848
  source_root,
598
849
  sanitize=True,
599
850
  )
600
- shutil.copy2(abs_file_path, temp_file_path)
601
851
  # ``tokenize.open`` honors a PEP 263 coding cookie (and UTF-8 BOM)
602
- # instead of assuming that every input file is UTF-8.
603
- with tokenize.open(temp_file_path) as source_file:
852
+ # instead of assuming that every input file is UTF-8. Read directly
853
+ # from ``abs_file_path`` so read-only (0444) sources do not propagate
854
+ # non-writable mode bits onto ``temp_file_path``.
855
+ with tokenize.open(abs_file_path) as source_file:
604
856
  original_source = source_file.read()
605
857
  source_encoding = source_file.encoding
606
858
 
607
859
  _validate_cython_syntax(original_source, file_path)
608
860
 
609
- def write_source(source):
610
- _write_source(temp_file_path, source, source_encoding)
611
-
612
861
  if obfuscate:
613
862
  try:
614
863
  compatible_source = _add_pydantic_ignored_types(original_source)
615
- obfuscated = obfuscate_source(compatible_source, seed=obfuscate_seed)
616
- write_source(obfuscated)
864
+ transformed_source = obfuscate_source(compatible_source, seed=obfuscate_seed)
617
865
  except Exception as exc:
618
866
  raise RuntimeError(f"Obfuscation failed for {file_path}: {exc}") from exc
619
867
  else:
620
- write_source(_add_pydantic_ignored_types(original_source))
868
+ transformed_source = _add_pydantic_ignored_types(original_source)
869
+
870
+ _write_source(temp_file_path, transformed_source, source_encoding)
621
871
 
622
872
  setup_code = f"""
873
+ import os
623
874
  from setuptools import setup
624
875
  from setuptools import Extension
625
876
  from Cython.Build import cythonize
877
+ from Cython.Compiler import Options as _cython_options
878
+
879
+ # Match standard Python semantics: reading a local in an untaken branch before
880
+ # its assignment raises UnboundLocalError at runtime instead of failing build.
881
+ _cython_options.error_on_uninitialized = False
626
882
 
627
883
  compiler_directives = {{
628
884
  'language_level': '3',
@@ -630,18 +886,20 @@ compiler_directives = {{
630
886
  'always_allow_keywords': True,
631
887
  'binding': True,
632
888
  'embedsignature': False,
633
- 'wraparound': False,
634
889
  }}
890
+ extra_compile_args = ['-g0', '-fvisibility=hidden'] if os.name != 'nt' else []
635
891
 
636
892
  setup(
637
893
  ext_modules=cythonize(
638
894
  [
639
895
  Extension(
640
896
  {repr(module_layout['qualified_module_name'])},
641
- [{repr(temp_file_path)}],
897
+ [{repr(rel_temp_file_path)}],
898
+ extra_compile_args=extra_compile_args,
642
899
  )
643
900
  ],
644
901
  compiler_directives=compiler_directives,
902
+ c_line_in_traceback=False,
645
903
  force=True
646
904
  )
647
905
  )
@@ -650,7 +908,7 @@ setup(
650
908
  with open(setup_path, 'w', encoding='utf-8') as f:
651
909
  f.write(setup_code)
652
910
 
653
- command = [sys.executable, 'setup.py', 'build_ext']
911
+ command = [sys.executable, 'setup.py', '--no-user-cfg', 'build_ext']
654
912
  try:
655
913
  result = subprocess.run(
656
914
  command,
@@ -666,9 +924,10 @@ setup(
666
924
  error_msg = result.stderr.decode('utf-8', errors='replace')
667
925
  raise RuntimeError(f"Compilation failed: {error_msg}")
668
926
 
927
+ escaped_build_dir = glob.escape(os.path.join(build_root, 'build'))
669
928
  patterns = [
670
- os.path.join(build_root, 'build', '**', f"{safe_module_name}*{target_ext}"),
671
- os.path.join(build_root, 'build', '**', f"*{safe_module_name}*{target_ext}"),
929
+ os.path.join(escaped_build_dir, '**', f"{safe_module_name}*{target_ext}"),
930
+ os.path.join(escaped_build_dir, '**', f"*{safe_module_name}*{target_ext}"),
672
931
  ]
673
932
  matches = []
674
933
  for pattern in patterns: