cpyte 4.7.1__tar.gz → 4.7.3__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 (55) hide show
  1. {cpyte-4.7.1 → cpyte-4.7.3}/PKG-INFO +10 -2
  2. cpyte-4.7.1/source/cpyte.egg-info/PKG-INFO → cpyte-4.7.3/readme.md +9 -13
  3. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/__init__.py +1 -1
  4. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/astparse.py +19 -7
  5. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/bytecoding.py +88 -1
  6. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/formatter.py +15 -9
  7. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/semantic_analasis.py +147 -55
  8. cpyte-4.7.1/readme.md → cpyte-4.7.3/source/cpyte.egg-info/PKG-INFO +21 -1
  9. {cpyte-4.7.1 → cpyte-4.7.3}/test/test_compiler_regressions.py +6 -6
  10. {cpyte-4.7.1 → cpyte-4.7.3}/MANIFEST.in +0 -0
  11. {cpyte-4.7.1 → cpyte-4.7.3}/pyproject.toml +0 -0
  12. {cpyte-4.7.1 → cpyte-4.7.3}/setup.cfg +0 -0
  13. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/__main__.py +0 -0
  14. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/_bignum_bc.py +0 -0
  15. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/_runtime_bc.py +0 -0
  16. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/bignum.c +0 -0
  17. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/bignum_protos.h +0 -0
  18. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/clib.py +0 -0
  19. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/compiling.py +0 -0
  20. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/elf2sef.py +0 -0
  21. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/extension_hooks.py +0 -0
  22. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/floats_runtime.c +0 -0
  23. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/gc_runtime.c +0 -0
  24. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/gc_runtime_addition.c +0 -0
  25. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/generate_bc.py +0 -0
  26. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/lexar.py +0 -0
  27. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/linker.py +0 -0
  28. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/lsp_server.py +0 -0
  29. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/mainpie.py +0 -0
  30. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/mksef.py +0 -0
  31. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/opreof_opt.py +0 -0
  32. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/opreof_pipeline.py +0 -0
  33. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/optimizations.py +0 -0
  34. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/package_manifest.py +0 -0
  35. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/runpy_runtime.c +0 -0
  36. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/runtime.c +0 -0
  37. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/runtime_scorpion.c +0 -0
  38. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/scorpion_abi.py +0 -0
  39. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/sef.py +0 -0
  40. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/ugc.h +0 -0
  41. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/ui.py +0 -0
  42. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/update_check.py +0 -0
  43. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/winjit_patch.py +0 -0
  44. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte/winjit_stubs.c +0 -0
  45. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte.egg-info/SOURCES.txt +0 -0
  46. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte.egg-info/dependency_links.txt +0 -0
  47. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte.egg-info/entry_points.txt +0 -0
  48. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte.egg-info/requires.txt +0 -0
  49. {cpyte-4.7.1 → cpyte-4.7.3}/source/cpyte.egg-info/top_level.txt +0 -0
  50. {cpyte-4.7.1 → cpyte-4.7.3}/test/test_bignum_jit.py +0 -0
  51. {cpyte-4.7.1 → cpyte-4.7.3}/test/test_fuzz_del_has.py +0 -0
  52. {cpyte-4.7.1 → cpyte-4.7.3}/test/test_opreof_proofs.py +0 -0
  53. {cpyte-4.7.1 → cpyte-4.7.3}/test/test_scorpion_abi.py +0 -0
  54. {cpyte-4.7.1 → cpyte-4.7.3}/test/test_scorpion_dl.py +0 -0
  55. {cpyte-4.7.1 → cpyte-4.7.3}/test/test_sef_tools.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cpyte
3
- Version: 4.7.1
3
+ Version: 4.7.3
4
4
  Summary: The Cpyte programming language compiler
5
5
  Author: Hoang Duy Tung
6
6
  License: MIT
@@ -44,8 +44,16 @@ See `examples/example_package/` for a complete example package with:
44
44
 
45
45
  ### Using Extension Packages
46
46
 
47
+ **Canonical import style (preferred):**
47
48
  ```cpy
48
- import @package_name
49
+ import std.collections
50
+ import std.collections.hash_map
51
+ ```
52
+
53
+ Legacy `@...` imports (e.g. `import "@std/collections/hash_map"`) are still accepted for backward compatibility but are deprecated; `cpy format` rewrites them to the canonical dotted form.
54
+
55
+ ```cpy
56
+ import std.your_package
49
57
 
50
58
  # Use custom keywords and syntax from the package
51
59
  async def my_function() -> Promise:
@@ -1,15 +1,3 @@
1
- Metadata-Version: 2.4
2
- Name: cpyte
3
- Version: 4.7.1
4
- Summary: The Cpyte programming language compiler
5
- Author: Hoang Duy Tung
6
- License: MIT
7
- Requires-Python: >=3.11
8
- Description-Content-Type: text/markdown
9
- Requires-Dist: llvmlite>=0.45
10
- Requires-Dist: lsprotocol>=2025.0.0
11
- Requires-Dist: pygls>=1.3.1
12
-
13
1
  NOTICE: It seems cpyte has been going through a lot of changes, including the OOP work which was quite fabulous and python-like. I liked how the syntax changes very interestingly and made the language better. However, after a lot of experimentation and many breaking changes, I've decided that the syntax lock is now settled. The language is being stabilized, and development will slow down as we focus on reliability and polish instead of constant churn. After that, improvements will be delivered through the @std/improvements package with the extension hook framework.
14
2
 
15
3
  Check out the official documentation [here](https://gitea.5gnew.io.vn/Cpyte-Project/Cpyte/src/branch/main/source/cpyte/cpy_language_documentation.md).
@@ -44,8 +32,16 @@ See `examples/example_package/` for a complete example package with:
44
32
 
45
33
  ### Using Extension Packages
46
34
 
35
+ **Canonical import style (preferred):**
36
+ ```cpy
37
+ import std.collections
38
+ import std.collections.hash_map
39
+ ```
40
+
41
+ Legacy `@...` imports (e.g. `import "@std/collections/hash_map"`) are still accepted for backward compatibility but are deprecated; `cpy format` rewrites them to the canonical dotted form.
42
+
47
43
  ```cpy
48
- import @package_name
44
+ import std.your_package
49
45
 
50
46
  # Use custom keywords and syntax from the package
51
47
  async def my_function() -> Promise:
@@ -1,4 +1,4 @@
1
- __version__ = "4.7.1"
1
+ __version__ = "4.7.3"
2
2
 
3
3
  # ---------------------------------------------------------------------------
4
4
  # Public library API.
@@ -478,9 +478,7 @@ def _parse_ternary(tokens: list[Token], pos: int):
478
478
  then, pos = _parse_ternary(tokens, pos)
479
479
  pos = _skip_expr_newlines(tokens, pos)
480
480
  if pos >= len(tokens) or tokens[pos].type != TokenType.COLON:
481
- raise TernaryParseError(
482
- 'Expected ":" in conditional expression', tok
483
- )
481
+ raise TernaryParseError('Expected ":" in conditional expression', tok)
484
482
  pos += 1
485
483
  pos = _skip_expr_newlines(tokens, pos)
486
484
  orelse, pos = _parse_ternary(tokens, pos)
@@ -1314,8 +1312,6 @@ def parse_file(tokens: list[Token], pos: int = 0, enable_extensions: bool = True
1314
1312
  if pos >= len(tokens) or tokens[pos].type in (TokenType.EOF, TokenType.DEDENT):
1315
1313
  break
1316
1314
 
1317
- tok = tokens[pos]
1318
-
1319
1315
  all_hooks = _get_all_parser_hooks(enable_extensions)
1320
1316
  if all_hooks:
1321
1317
  ctx = _make_parser_ctx(tokens, pos)
@@ -2036,8 +2032,22 @@ def parse_import(tokens: list[Token], pos: int):
2036
2032
  return node, pos
2037
2033
  elif t.type == TokenType.IDENTIFIER:
2038
2034
  assert t.value is not None
2039
- module = t.value
2035
+ first = t.value
2040
2036
  pos += 1
2037
+ parts = [first]
2038
+ # Allow dotted form: group.pkg.sub or pkg.sub or std.collections.hash_map
2039
+ while pos < len(tokens) and tokens[pos].type == TokenType.DOT:
2040
+ # look ahead: dot followed by identifier
2041
+ if pos + 1 >= len(tokens) or tokens[pos + 1].type != TokenType.IDENTIFIER:
2042
+ break
2043
+ pos += 1 # consume dot
2044
+ part = tokens[pos].value
2045
+ assert part is not None
2046
+ parts.append(part)
2047
+ pos += 1
2048
+ # Also allow slash form in the same token stream? probably not common now
2049
+ module = ".".join(parts)
2050
+ node = Import(module, token=tok)
2041
2051
  else:
2042
2052
  raise ParseError("Expected module name or quoted header path", t)
2043
2053
 
@@ -2916,6 +2926,9 @@ def parse_suite(tokens: list[Token], pos: int):
2916
2926
 
2917
2927
  _TYPE_NAMES = {
2918
2928
  "int",
2929
+ "uint8",
2930
+ "uint16",
2931
+ "uint32",
2919
2932
  "int64",
2920
2933
  "uint64",
2921
2934
  "float",
@@ -3418,7 +3431,6 @@ def parse_switch(tokens: list[Token], pos: int):
3418
3431
  TokenType.EOF,
3419
3432
  ):
3420
3433
  if tokens[pos].type == TokenType.KEYWORD and tokens[pos].value == "case":
3421
- tok2 = tokens[pos]
3422
3434
  pos += 1
3423
3435
  case_val, pos = parse_expression(tokens, pos)
3424
3436
  if pos >= len(tokens) or tokens[pos].type != TokenType.COLON:
@@ -929,6 +929,13 @@ class LLVM:
929
929
  self.global_vars = {}
930
930
  # Constant Variable store here.
931
931
  self.const_vars = {}
932
+ # Top-level constants are evaluated in a private init function BEFORE
933
+ # user function bodies are emitted, so references to them inside those
934
+ # functions resolve (see `emit_program`). `_global_const_init` marks
935
+ # that pre-pass so runtime-valued constants lower to module globals
936
+ # instead of allocas local to the init function.
937
+ self._const_init_fn = None
938
+ self._global_const_init = False
932
939
  self.locals = {}
933
940
  self.local_types = {}
934
941
  self.string_id = 0
@@ -1845,6 +1852,64 @@ class LLVM:
1845
1852
  _collect_ccodes(toplevel)
1846
1853
  _collect_ccodes(funcdefs)
1847
1854
 
1855
+ # ---- Global constants must exist BEFORE function bodies ----
1856
+ # Top-level statements are normally lowered into `main` *after* every
1857
+ # function body has been emitted, so a global `int (X) = 5` used inside
1858
+ # a function used to hit `Undefined variable 'X' at codegen`. Evaluate
1859
+ # top-level constant declarations in a private initializer function
1860
+ # first; simple literal constants become compile-time `ir.Constant`
1861
+ # values (no runtime code at all), while runtime-valued constants are
1862
+ # lowered to module globals by `emit_vardecl`'s `_global_const_init`
1863
+ # branch. The init function is called at the start of `main`.
1864
+ const_decls = [
1865
+ n
1866
+ for n in toplevel
1867
+ if isinstance(n, VarDecl) and getattr(n, "is_const", False)
1868
+ ]
1869
+ if const_decls:
1870
+ # A constant initializer may call a user function; declare those
1871
+ # headers now (normally they are created with their bodies below).
1872
+ # Names already bound (runtime builtins, imported C functions) are
1873
+ # left alone so the existing collision checks still fire.
1874
+ for fn_node in funcdefs:
1875
+ fname = getattr(fn_node, "name", None)
1876
+ if (
1877
+ not fname
1878
+ or fname == "main"
1879
+ or fname in self.functions
1880
+ or getattr(fn_node, "decorators", None)
1881
+ ):
1882
+ continue
1883
+ try:
1884
+ fret = self.llvm_type(fn_node.rettype or "int")
1885
+ fparams = [self.llvm_type(t) for t in fn_node.params.values()]
1886
+ except Exception:
1887
+ continue
1888
+ self.functions[fname] = ir.Function(
1889
+ self.module, ir.FunctionType(fret, fparams), name=fname
1890
+ )
1891
+ init_fn = ir.Function(
1892
+ self.module,
1893
+ ir.FunctionType(ir.VoidType(), []),
1894
+ name="__cpyte_const_init",
1895
+ )
1896
+ init_entry = init_fn.append_basic_block("entry")
1897
+ saved_builder = self.builder
1898
+ saved_global_const_init = self._global_const_init
1899
+ self.builder = ir.IRBuilder(init_entry)
1900
+ self._global_const_init = True
1901
+ try:
1902
+ for node in const_decls:
1903
+ self.emit(node)
1904
+ finally:
1905
+ if init_entry.terminator is None:
1906
+ self.builder.ret_void()
1907
+ self._global_const_init = saved_global_const_init
1908
+ self.builder = saved_builder
1909
+ self._const_init_fn = init_fn
1910
+ const_ids = {id(n) for n in const_decls}
1911
+ toplevel = [n for n in toplevel if id(n) not in const_ids]
1912
+
1848
1913
  user_main = None
1849
1914
  for node in funcdefs:
1850
1915
  if getattr(node, "name", None) == "main":
@@ -1876,6 +1941,8 @@ class LLVM:
1876
1941
  gc_start_fn = self.functions.get("gc_start_thread")
1877
1942
  if gc_start_fn:
1878
1943
  self.builder.call(gc_start_fn, [])
1944
+ if self._const_init_fn is not None:
1945
+ self.builder.call(self._const_init_fn, [])
1879
1946
  for node in toplevel:
1880
1947
  self.emit(node)
1881
1948
  if not self.no_gc:
@@ -3446,6 +3513,12 @@ class LLVM:
3446
3513
  if gc_start_fn:
3447
3514
  self.builder.call(gc_start_fn, [])
3448
3515
 
3516
+ # Runtime-valued top-level constants live in module globals; initialize
3517
+ # them before any user statement (including original top-level code
3518
+ # prepended to main) runs.
3519
+ if node.name == "main" and self._const_init_fn is not None:
3520
+ self.builder.call(self._const_init_fn, [])
3521
+
3449
3522
  old_locals = self.locals
3450
3523
  old_local_types = self.local_types
3451
3524
  old_ssa = self.ssa_values
@@ -8262,7 +8335,21 @@ class LLVM:
8262
8335
  value = self._extend_to_i64(
8263
8336
  value, self._is_unsigned_node(node.init)
8264
8337
  )
8265
- if isinstance(value, ir.Constant):
8338
+ if self._global_const_init and not isinstance(value, ir.Constant):
8339
+ # Top-level constant with a runtime-valued initializer:
8340
+ # an alloca in the private init function would go out of
8341
+ # scope, so use a module-level global. `emit_variable`
8342
+ # loads through the registered const pointer.
8343
+ gv = ir.GlobalVariable(
8344
+ self.module,
8345
+ value.type,
8346
+ name=f"__const_{node.name}",
8347
+ )
8348
+ gv.initializer = ir.Constant(value.type, None)
8349
+ self.builder.store(value, gv)
8350
+ self.global_vars[node.name] = gv
8351
+ self._declare_const(node.name, gv)
8352
+ elif isinstance(value, ir.Constant):
8266
8353
  self._declare_const(node.name, value)
8267
8354
  else:
8268
8355
  ptr = self._alloca(ty, name=node.name)
@@ -1,3 +1,4 @@
1
+ import re as _re
1
2
  from dataclasses import dataclass, field
2
3
 
3
4
  from . import astparse
@@ -80,6 +81,8 @@ def _escape_string(value: str) -> str:
80
81
  return '"' + "".join(_STRING_ESCAPES.get(ch, ch) for ch in value) + '"'
81
82
 
82
83
 
84
+ _IDENT_RE = _re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
85
+
83
86
  def _char_text(code: int) -> str:
84
87
  ch = chr(code & 0xFF)
85
88
  return "'" + _STRING_ESCAPES.get(ch, ch) + "'"
@@ -395,11 +398,19 @@ class _Formatter:
395
398
  def _emit_import(self, node, level: int):
396
399
  module = node.module
397
400
  if module.startswith("@"):
398
- text = f"import @{module[1:].replace('/', '.')}"
399
- elif _IDENT_RE.match(module):
400
- text = f"import {module}"
401
+ # canonical: strip '@' and turn '/' into '.'
402
+ canon = module[1:].replace("/", ".")
403
+ text = f"import {canon}"
401
404
  else:
402
- text = f"import {_escape_string(module)}"
405
+ # already in dotted or other form
406
+ if _IDENT_RE.match(module):
407
+ text = f"import {module}"
408
+ else:
409
+ # could be "a.b.c"
410
+ if all(_IDENT_RE.match(p) for p in module.split(".") if p):
411
+ text = f"import {module}"
412
+ else:
413
+ text = f"import {_escape_string(module)}"
403
414
  if getattr(node, "sdk_path", None):
404
415
  text += f" sdk({_escape_string(node.sdk_path)})"
405
416
  self._emit_simple(node, text, level)
@@ -564,11 +575,6 @@ class _Formatter:
564
575
  self._emit_simple(node, text + ")", level)
565
576
 
566
577
 
567
- import re as _re
568
-
569
- _IDENT_RE = _re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
570
-
571
-
572
578
  def _need_parens(child, parent_op, is_right: bool) -> bool:
573
579
  if not isinstance(child, astparse.BinOp):
574
580
  return False
@@ -773,6 +773,7 @@ class SemanticAnalyzer:
773
773
  self._promoted_vars: set[str] = set()
774
774
  self._forward_names: set[str] = set()
775
775
  self._imported_clibs: set[str] = set()
776
+ self._imported_cpy_files: set[str] = set()
776
777
  self._heap_names: set[str] = set()
777
778
  self._gc_new_names: set[str] = set()
778
779
  if scorpion:
@@ -2584,20 +2585,22 @@ class SemanticAnalyzer:
2584
2585
  self._register_import_symbols(symbols, node)
2585
2586
  return
2586
2587
 
2587
- # `@std.<pkg>.<sub>` is a runtime-resolved deep extension, but
2588
- # `@std.<pkg>` is the dot form of a scoped CPM package and must reach
2589
- # the resolver like `@std/<pkg>` does.
2590
- is_deep_extension = module.startswith("@std.") and module.count(".") >= 2
2588
+ # Deep extension forms: e.g. @std.net.something (runtime-resolved). Heuristic: if third segment looks like a submodule API beyond pkg, but our canonical is group.pkg.subfile for CPM.
2589
+ # For CPM: group.pkg OR group.pkg.file => try CPM import.
2590
+ is_deep_extension = False # keep for future; not the same as group.pkg.file
2591
2591
 
2592
2592
  if not is_file_import:
2593
- if is_deep_extension:
2594
- pass # deep extension
2595
- elif self._try_cpm_import(node, module):
2593
+ if self._try_cpm_import(node, module):
2596
2594
  return
2595
+ # Deep std extension (runtime-resolved by package extensions): e.g. std.pkg.sub or @std/pkg/sub
2596
+ if module.startswith("@") and module[1:].startswith("std") and (module[1:].count("/") >= 2 or module[1:].count(".") >= 2):
2597
+ return
2598
+ if not module.startswith("@") and module.startswith("std."):
2599
+ parts = module.split(".")
2600
+ if len(parts) >= 3:
2601
+ return
2597
2602
 
2598
2603
  if module.startswith("@"):
2599
- if is_deep_extension:
2600
- return # deep extension resolved at runtime
2601
2604
  self.error(f"package `{module}` not installed — run 'cpm install'", node)
2602
2605
  return
2603
2606
 
@@ -2703,9 +2706,7 @@ class SemanticAnalyzer:
2703
2706
  kind = "class" if isinstance(ast_node, ClassDef) else "struct"
2704
2707
  self.globals.define(ast_node.name, Symbol(kind, None, ast_node))
2705
2708
  elif isinstance(ast_node, Import):
2706
- self._register_imported_types(
2707
- getattr(ast_node, "sub_ast", None) or []
2708
- )
2709
+ self._register_imported_types(getattr(ast_node, "sub_ast", None) or [])
2709
2710
 
2710
2711
  def _register_import_symbols(self, symbols, node, var_names=None):
2711
2712
  s = self.globals
@@ -2966,36 +2967,99 @@ class SemanticAnalyzer:
2966
2967
  return None
2967
2968
 
2968
2969
  def _try_cpm_import(self, node: Import, module: str) -> bool:
2969
- # Support both @scope.name and @scope/name import forms.
2970
- import_name = module.removeprefix("@")
2971
- pkg_name = import_name.replace("/", ".").split(".")[-1]
2972
-
2973
2970
  roots = cpm_module_roots(self._workspace_root, self._filedir)
2974
2971
  has_cpm_root = any(os.path.isdir(root) for root in roots)
2975
2972
 
2976
- # A package already loaded purely via its manifest (extension hooks only)
2977
- # has no real symbols; short-circuit only when no CPM directory exists to
2978
- # resolve a real entry from. A package that ships an entry file must still
2979
- # re-export its actual symbols below.
2980
- if pkg_name in self._loaded_packages and not has_cpm_root:
2973
+ submodule_parts = []
2974
+ pkg_name = None
2975
+ scope = None
2976
+ is_legacy = False
2977
+
2978
+ # Canonical: group.pkg[.file...] e.g. std.collections.hash_map
2979
+ # Legacy: @group/pkg/... or @group.pkg... (deprecated)
2980
+ if module.startswith("@"):
2981
+ is_legacy = True
2982
+ raw = module[1:].replace(".", "/")
2983
+ canon = raw.replace("/", ".")
2984
+ self.warning(
2985
+ f"deprecated import style `{module}`; use `{canon}` (canonical: `group.pkg[.file]`)",
2986
+ node,
2987
+ note="formatter will rewrite to the canonical form; please update imports",
2988
+ )
2989
+ pparts = [p for p in raw.split("/") if p != ""]
2990
+ if len(pparts) < 1:
2991
+ return False
2992
+ # Deep extension like @std.math.foo (>=3 parts) is runtime-resolved; do not CPM-resolve.
2993
+ if len(pparts) >= 3 and pparts[0] == "std":
2994
+ return False
2995
+ scope = pparts[0]
2996
+ if len(pparts) == 1:
2997
+ pkg_name = pparts[0]
2998
+ submodule_parts = []
2999
+ else:
3000
+ pkg_name = pparts[1]
3001
+ if len(pparts) > 2:
3002
+ submodule_parts = pparts[2:]
3003
+ else:
3004
+ parts = [p for p in module.split(".") if p != ""]
3005
+ if len(parts) == 0:
3006
+ return False
3007
+ # Canonical deep extension: std.pkg.sub... (>=3 parts) is runtime-resolved by extensions.
3008
+ if len(parts) >= 3 and parts[0] == "std":
3009
+ return False
3010
+ if len(parts) == 1:
3011
+ pkg_name = parts[0]
3012
+ scope = None
3013
+ submodule_parts = []
3014
+ else:
3015
+ # group.pkg(.sub...) — canonical CPM submodule
3016
+ scope = parts[0]
3017
+ pkg_name = parts[1]
3018
+ if len(parts) > 2:
3019
+ submodule_parts = parts[2:]
3020
+
3021
+ if pkg_name is None:
3022
+ return False
3023
+
3024
+ if (
3025
+ pkg_name in self._loaded_packages
3026
+ and not has_cpm_root
3027
+ and len(submodule_parts) == 0
3028
+ and scope is None
3029
+ ):
2981
3030
  self._register_import_symbols({}, node)
2982
3031
  return True
2983
3032
 
2984
- # Remember manifest-only packages, but keep looking: a later root may
2985
- # contain the package's real .cpy entry or prebuilt IR.
2986
3033
  manifest_only = False
2987
3034
  for cpm_root in roots:
2988
3035
  if not os.path.isdir(cpm_root):
2989
3036
  continue
2990
3037
 
2991
- if module.startswith("@"):
2992
- scoped = module[1:].replace("/", ".").replace(".", os.sep)
2993
- parts = scoped.split(os.sep)
2994
- pkg_dir = os.path.join(cpm_root, f"@{parts[0]}", *parts[1:])
3038
+ pkg_dir = None
3039
+ if scope is not None:
3040
+ # look under @scope/pkg_name
3041
+ cand = os.path.join(cpm_root, f"@{scope}", pkg_name)
3042
+ if os.path.isdir(cand):
3043
+ pkg_dir = cand
2995
3044
  else:
2996
- pkg_dir = os.path.join(cpm_root, *module.replace("/", ".").split("."))
3045
+ # no scope: search for a dir named pkg_name under any @group
3046
+ # try common: scan for @*/pkg_name
3047
+ try:
3048
+ for g in os.listdir(cpm_root):
3049
+ if g.startswith("@"):
3050
+ cand = os.path.join(cpm_root, g, pkg_name)
3051
+ if os.path.isdir(cand):
3052
+ pkg_dir = cand
3053
+ break
3054
+ except OSError:
3055
+ pass
3056
+ if pkg_dir is None:
3057
+ # also allow flat pkg_name (non-scoped)
3058
+ cand = os.path.join(cpm_root, pkg_name)
3059
+ if os.path.isdir(cand):
3060
+ pkg_dir = cand
2997
3061
 
2998
- if not os.path.isdir(pkg_dir):
3062
+ if pkg_dir is None or not os.path.isdir(pkg_dir):
2999
3063
  continue
3000
3064
 
3001
3065
  versions = sort_cpm_versions(
@@ -3014,6 +3078,46 @@ class SemanticAnalyzer:
3014
3078
  ):
3015
3079
  manifest_only = True
3016
3080
 
3081
+ # Submodule import: group.pkg.file or legacy forms
3082
+ if len(submodule_parts) > 0:
3083
+ base = submodule_parts[0]
3084
+ tried = []
3085
+ cand_paths = [os.path.join(version_dir, base + ".cpy")]
3086
+ if len(submodule_parts) > 1:
3087
+ cand_paths.append(
3088
+ os.path.join(version_dir, *submodule_parts) + ".cpy"
3089
+ )
3090
+ for fpath in cand_paths:
3091
+ tried.append(fpath)
3092
+ if os.path.isfile(fpath):
3093
+ result = self._import_cpy(fpath, node)
3094
+ if result:
3095
+ self._register_import_symbols(result[0], node)
3096
+ return True
3097
+ found_any = []
3098
+ for rootd, _dirs, files in os.walk(version_dir):
3099
+ if base + ".cpy" in files:
3100
+ found_any.append(os.path.join(rootd, base + ".cpy"))
3101
+ if len(found_any) == 1:
3102
+ result = self._import_cpy(found_any[0], node)
3103
+ if result:
3104
+ self._register_import_symbols(result[0], node)
3105
+ return True
3106
+ if len(found_any) > 1:
3107
+ listed = ", ".join(sorted(found_any))
3108
+ self.error(
3109
+ f"submodule `{base}` is ambiguous in package `@{scope or '?'}{os.sep}{pkg_name}`; found: {listed}",
3110
+ node,
3111
+ )
3112
+ return True
3113
+ tried_str = "; ".join(tried)
3114
+ self.error(
3115
+ f"submodule/file `{base}` not found in package `{scope + '.' + pkg_name if scope else pkg_name}` (looked for: {tried_str})",
3116
+ node,
3117
+ note="canonical form: `group.pkg.file`; no aliases are applied",
3118
+ )
3119
+ return True
3120
+
3017
3121
  cpy_file = self._find_package_entry(version_dir, pkg_name)
3018
3122
  if cpy_file:
3019
3123
  result = self._import_cpy(cpy_file, node)
@@ -3032,6 +3136,17 @@ class SemanticAnalyzer:
3032
3136
  return False
3033
3137
 
3034
3138
  def _import_cpy(self, module: str, node: Import | None = None):
3139
+ try:
3140
+ real = os.path.realpath(module)
3141
+ except OSError:
3142
+ real = os.path.abspath(module)
3143
+ if real in self._imported_cpy_files:
3144
+ if node is not None:
3145
+ node.module_tag = module_tag(real)
3146
+ node.sub_ast = []
3147
+ return {}, "cpy"
3148
+ self._imported_cpy_files.add(real)
3149
+
3035
3150
  try:
3036
3151
  with open(module) as f:
3037
3152
  source = f.read()
@@ -3068,13 +3183,6 @@ class SemanticAnalyzer:
3068
3183
  sub_ast = []
3069
3184
  for ast_node in imported_ast:
3070
3185
  if isinstance(ast_node, (CCode, Llvm)):
3071
- # Propagate embedded `ccode:`/`llvm:` blocks from the imported
3072
- # module so (a) their functions become callable from the
3073
- # importing program and (b) codegen emits and links the C/LLVM
3074
- # body. The sub-analyzer already parsed the block and cached the
3075
- # symbols on the node under its own scope; re-register them on
3076
- # this analyzer's globals and keep the node in sub_ast so
3077
- # `emit_ccode`/`emit_llvm` runs at codegen.
3078
3186
  existing_syms = getattr(ast_node, "symbols", None) or []
3079
3187
  if existing_syms:
3080
3188
  self._register_import_symbols(
@@ -3094,9 +3202,6 @@ class SemanticAnalyzer:
3094
3202
  symbols[ast_node.name] = (ret_type, params, False)
3095
3203
  sub_ast.append(ast_node)
3096
3204
  elif isinstance(ast_node, FuncDef):
3097
- # Module-private functions: not exported as symbols, but kept in
3098
- # sub_ast so codegen still emits their bodies — public functions
3099
- # of the imported module may call them.
3100
3205
  sub_ast.append(ast_node)
3101
3206
  elif isinstance(ast_node, StructDef):
3102
3207
  sub_ast.append(ast_node)
@@ -3106,32 +3211,19 @@ class SemanticAnalyzer:
3106
3211
  elif isinstance(ast_node, ClassDef):
3107
3212
  sub_ast.append(ast_node)
3108
3213
  if not self.globals.lookup_local(ast_node.name):
3109
- self.globals.define(
3110
- ast_node.name, Symbol("class", None, ast_node)
3111
- )
3214
+ self.globals.define(ast_node.name, Symbol("class", None, ast_node))
3112
3215
  elif isinstance(ast_node, Import):
3113
3216
  for fname, (ret_type, params, vararg) in ast_node.symbols:
3114
3217
  if fname not in symbols:
3115
3218
  symbols[fname] = (ret_type, params, vararg)
3116
3219
 
3117
- # Struct/class names travel with their functions: a module that
3118
- # returns (or takes) a type defined by ITS OWN imports must stay
3119
- # usable by consumers that only import the middle module.
3120
- self._register_imported_types(
3121
- getattr(ast_node, "sub_ast", None) or []
3122
- )
3220
+ self._register_imported_types(getattr(ast_node, "sub_ast", None) or [])
3123
3221
 
3124
- # Preserve the sub-AST chain for re-exported imports so codegen
3125
- # can still reach the aggregated module's function definitions
3126
- # (emit_program recurses through Import sub_ast).
3127
3222
  if getattr(ast_node, "sub_ast", None):
3128
3223
  sub_ast.append(ast_node)
3129
3224
 
3130
3225
  if node is not None:
3131
- # Tag the import so codegen knows which module this symbol table
3132
- # came from (used to resolve imported parameter types against the
3133
- # defining module's structs).
3134
- node.module_tag = module_tag(module)
3226
+ node.module_tag = module_tag(real)
3135
3227
  node.sub_ast = sub_ast
3136
3228
  return symbols, "cpy"
3137
3229
 
@@ -1,3 +1,15 @@
1
+ Metadata-Version: 2.4
2
+ Name: cpyte
3
+ Version: 4.7.3
4
+ Summary: The Cpyte programming language compiler
5
+ Author: Hoang Duy Tung
6
+ License: MIT
7
+ Requires-Python: >=3.11
8
+ Description-Content-Type: text/markdown
9
+ Requires-Dist: llvmlite>=0.45
10
+ Requires-Dist: lsprotocol>=2025.0.0
11
+ Requires-Dist: pygls>=1.3.1
12
+
1
13
  NOTICE: It seems cpyte has been going through a lot of changes, including the OOP work which was quite fabulous and python-like. I liked how the syntax changes very interestingly and made the language better. However, after a lot of experimentation and many breaking changes, I've decided that the syntax lock is now settled. The language is being stabilized, and development will slow down as we focus on reliability and polish instead of constant churn. After that, improvements will be delivered through the @std/improvements package with the extension hook framework.
2
14
 
3
15
  Check out the official documentation [here](https://gitea.5gnew.io.vn/Cpyte-Project/Cpyte/src/branch/main/source/cpyte/cpy_language_documentation.md).
@@ -32,8 +44,16 @@ See `examples/example_package/` for a complete example package with:
32
44
 
33
45
  ### Using Extension Packages
34
46
 
47
+ **Canonical import style (preferred):**
48
+ ```cpy
49
+ import std.collections
50
+ import std.collections.hash_map
51
+ ```
52
+
53
+ Legacy `@...` imports (e.g. `import "@std/collections/hash_map"`) are still accepted for backward compatibility but are deprecated; `cpy format` rewrites them to the canonical dotted form.
54
+
35
55
  ```cpy
36
- import @package_name
56
+ import std.your_package
37
57
 
38
58
  # Use custom keywords and syntax from the package
39
59
  async def my_function() -> Promise:
@@ -191,8 +191,8 @@ def test_global_cpm_import_resolves_without_workspace():
191
191
  )
192
192
 
193
193
  source = (
194
- 'import "@std/demo"\n'
195
- 'import "@std/extonly"\n'
194
+ 'import std.demo\n'
195
+ 'import std.extonly\n'
196
196
  'import "plain"\n'
197
197
  "public def main() -> int:\n"
198
198
  " return demo_value() + plain_value()\n"
@@ -225,7 +225,7 @@ def test_workspace_cpm_package_wins_over_global_and_dot_form_imports():
225
225
  )
226
226
 
227
227
  source = (
228
- 'import "@std.demo"\n'
228
+ 'import std.demo\n'
229
229
  "public def main() -> int:\n"
230
230
  " return local_demo()\n"
231
231
  )
@@ -240,10 +240,10 @@ def test_workspace_cpm_package_wins_over_global_and_dot_form_imports():
240
240
 
241
241
 
242
242
  def test_deep_std_extension_import_is_still_skipped():
243
- # `@std.<pkg>.<sub>` is resolved at runtime; it must not be reported as a
244
- # missing CPM package, unlike the two-segment `@std.<pkg>` package form.
243
+ # `std.<pkg>.<sub>` (and legacy `@std.<pkg>.<sub>`) is resolved at runtime;
244
+ # it must not be reported as a missing CPM package.
245
245
  parse_and_analyze(
246
- 'import "@std.math.foo"\npublic def main() -> int:\n return 0\n',
246
+ 'import std.math.foo\npublic def main() -> int:\n return 0\n',
247
247
  enable_extensions=False,
248
248
  )
249
249
 
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes