doppelcode 0.7.0b5.post1__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.
@@ -0,0 +1,124 @@
1
+ """Files that are not UTF-8 (Windows-1255 Hebrew comments, Windows-1252 degree or micro signs).
2
+
3
+ DoppelCode keeps every file's bytes: text is decoded as UTF-8 with ``surrogateescape``, so a byte that is not
4
+ UTF-8 travels as a surrogate and is written back unchanged. The twin therefore has the original's encoding too.
5
+ An AI agent's editor often does not: it opens the twin file as UTF-8 and saves it that way, which turns every
6
+ such byte into U+FFFD, or it guesses the code page and saves real characters as UTF-8. Import would then write
7
+ those bytes into the original on lines the AI never touched.
8
+
9
+ ``repair`` compares the AI's version (after reverse translation) with the base (the original's bytes at the
10
+ last sync). A line whose only difference is that encoding damage gets the base line's bytes back. Lines the AI
11
+ really changed are written in the file's code page when it can be told from the repaired lines, so the
12
+ original does not end up in two encodings.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import re
18
+ from dataclasses import dataclass
19
+
20
+ # Single-byte code pages tried in this order; the one that explains the most lines wins.
21
+ CANDIDATES = ("cp1255", "cp1252", "cp1251", "cp1250", "cp1253", "cp1254", "cp1256", "cp1257", "cp1258")
22
+
23
+ _SURROGATES = re.compile("[\udc80-\udcff]+")
24
+ _FFFD_RUN = re.compile("�+")
25
+
26
+
27
+ @dataclass
28
+ class Repair:
29
+ data: bytes
30
+ lines: int = 0 # lines given back their original bytes
31
+ encoding: str | None = None # the code page the AI's editor used, when it could be told
32
+ reencoded: int = 0 # changed lines written in that code page
33
+ left_utf8: int = 0 # changed lines with characters the code page does not have (left as UTF-8)
34
+
35
+
36
+ def _dec(data: bytes) -> str:
37
+ return data.decode("utf-8", errors="surrogateescape")
38
+
39
+
40
+ def _enc(text: str) -> bytes:
41
+ return text.encode("utf-8", errors="surrogateescape")
42
+
43
+
44
+ def _split(text: str) -> list[tuple[str, str]]:
45
+ """(content, line end) pairs; the line end is '' for a last line without one."""
46
+ out = []
47
+ for line in text.splitlines(keepends=True):
48
+ body = line.rstrip("\r\n")
49
+ out.append((body, line[len(body):]))
50
+ return out
51
+
52
+
53
+ def repair(theirs: bytes, base: bytes | None) -> Repair:
54
+ """``theirs`` with the lines that only lost the base's encoding given back their original bytes."""
55
+ if base is None:
56
+ return Repair(theirs)
57
+ base_text = _dec(base)
58
+ if not _SURROGATES.search(base_text):
59
+ return Repair(theirs) # the original is UTF-8 (or ASCII): nothing to repair
60
+ their_text = _dec(theirs)
61
+ if _SURROGATES.search(their_text) or their_text.isascii():
62
+ return Repair(theirs) # still the original's encoding, or no candidate lines
63
+
64
+ by_fffd: dict[str, str | None] = {}
65
+ by_cp: dict[str, dict[str, str | None]] = {cp: {} for cp in CANDIDATES}
66
+
67
+ def put(table: dict[str, str | None], key: str, body: str) -> None:
68
+ if table.get(key, body) != body:
69
+ table[key] = None # two different base lines look the same: ambiguous
70
+ else:
71
+ table[key] = body
72
+
73
+ for body, _ in _split(base_text):
74
+ if not _SURROGATES.search(body):
75
+ continue
76
+ put(by_fffd, _SURROGATES.sub("�", body), body)
77
+ raw = _enc(body)
78
+ for cp in CANDIDATES:
79
+ try:
80
+ put(by_cp[cp], raw.decode(cp), body)
81
+ except UnicodeDecodeError:
82
+ pass
83
+
84
+ lines = _split(their_text)
85
+ out: list[str] = []
86
+ fixed = 0
87
+ votes: dict[str, int] = {}
88
+ unmatched: list[int] = []
89
+ for i, (body, end) in enumerate(lines):
90
+ if body.isascii():
91
+ out.append(body + end)
92
+ continue
93
+ hit = None
94
+ if "�" in body:
95
+ hit = by_fffd.get(_FFFD_RUN.sub("�", body))
96
+ else:
97
+ for cp in CANDIDATES:
98
+ h = by_cp[cp].get(body)
99
+ if h is not None:
100
+ hit = h
101
+ votes[cp] = votes.get(cp, 0) + 1
102
+ if hit is not None:
103
+ out.append(hit + end)
104
+ fixed += 1
105
+ else:
106
+ out.append(body + end)
107
+ unmatched.append(i)
108
+
109
+ rep = Repair(theirs, lines=fixed)
110
+ if not fixed:
111
+ return rep
112
+ if votes:
113
+ rep.encoding = max(CANDIDATES, key=lambda cp: (votes.get(cp, 0), -CANDIDATES.index(cp)))
114
+ for i in unmatched:
115
+ body, end = lines[i]
116
+ if "�" in body:
117
+ continue
118
+ try:
119
+ out[i] = _dec(body.encode(rep.encoding)) + end
120
+ rep.reencoded += 1
121
+ except UnicodeEncodeError:
122
+ rep.left_utf8 += 1
123
+ rep.data = _enc("".join(out))
124
+ return rep
doppelcode/headers.py ADDED
@@ -0,0 +1,115 @@
1
+ """Compiler discovery and system-header identifier harvesting."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import subprocess
8
+ from pathlib import Path
9
+
10
+ from . import lexer
11
+
12
+ _FALLBACK_COMPILERS = [
13
+ r"C:\msys64\mingw64\bin\gcc.exe",
14
+ r"C:\msys64\ucrt64\bin\gcc.exe",
15
+ r"C:\msys64\clang64\bin\clang.exe",
16
+ r"C:\Program Files\LLVM\bin\clang.exe",
17
+ ]
18
+
19
+
20
+ def find_compiler(configured: str | None = None) -> str | None:
21
+ if configured:
22
+ return configured if Path(configured).exists() or shutil.which(configured) else None
23
+ for name in ("gcc", "clang", "cc"):
24
+ found = shutil.which(name)
25
+ if found:
26
+ return found
27
+ for cand in _FALLBACK_COMPILERS:
28
+ if Path(cand).exists():
29
+ return cand
30
+ return None
31
+
32
+
33
+ def find_cxx_compiler(configured: str | None, c_compiler: str | None) -> str | None:
34
+ """g++ / clang++: configured, next to the C compiler, or on PATH."""
35
+ if configured:
36
+ return find_compiler(configured)
37
+ if c_compiler:
38
+ p = Path(c_compiler)
39
+ for name in ("g++", "clang++", "c++"):
40
+ cand = p.with_name(name + p.suffix)
41
+ if cand.exists():
42
+ return str(cand)
43
+ for name in ("g++", "clang++", "c++"):
44
+ found = shutil.which(name)
45
+ if found:
46
+ return found
47
+ return None
48
+
49
+
50
+ def compiler_env(compiler: str) -> dict:
51
+ """Environment with the compiler's own bin dir first (needed for MSYS2 gcc's DLLs)."""
52
+ env = dict(os.environ)
53
+ bindir = str(Path(compiler).resolve().parent)
54
+ env["PATH"] = bindir + os.pathsep + env.get("PATH", "")
55
+ return env
56
+
57
+
58
+ def system_include_dirs(compiler: str, language: str = "c") -> list[Path]:
59
+ """Ask the compiler for its #include <...> search list (language "c" or "c++")."""
60
+ try:
61
+ proc = subprocess.run(
62
+ [compiler, "-x" + language, "-E", "-v", "-"],
63
+ input="", capture_output=True, text=True, timeout=30, env=compiler_env(compiler),
64
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), # no console flash under pythonw
65
+ )
66
+ except (OSError, subprocess.SubprocessError):
67
+ return []
68
+ dirs: list[Path] = []
69
+ inside = False
70
+ for line in proc.stderr.splitlines():
71
+ if line.startswith("#include <...> search starts here"):
72
+ inside = True
73
+ continue
74
+ if line.startswith("End of search list"):
75
+ break
76
+ if inside:
77
+ p = Path(line.strip().replace(" (framework directory)", ""))
78
+ if p.is_dir():
79
+ dirs.append(p.resolve())
80
+ return dirs
81
+
82
+
83
+ def _read(path: Path) -> str:
84
+ return path.read_bytes().decode("utf-8", errors="replace")
85
+
86
+
87
+ def harvest(header_names: set[str], include_dirs: list[Path], max_files: int = 2000) -> tuple[set[str], set[str]]:
88
+ """Resolve the given <header> names and collect all identifiers, recursively.
89
+
90
+ Returns (identifiers, unresolved header names).
91
+ """
92
+ idents: set[str] = set()
93
+ unresolved: set[str] = set()
94
+ seen: set[Path] = set()
95
+ queue: list[tuple[str, Path | None, bool]] = [(h, None, True) for h in sorted(header_names)]
96
+
97
+ while queue and len(seen) < max_files:
98
+ name, rel_dir, top = queue.pop()
99
+ candidates = ([rel_dir / name] if rel_dir else []) + [d / name for d in include_dirs]
100
+ path = next((c for c in candidates if c.is_file()), None)
101
+ if path is None:
102
+ if top: # nested misses are usually inside #if branches for other platforms
103
+ unresolved.add(name)
104
+ continue
105
+ path = path.resolve()
106
+ if path in seen:
107
+ continue
108
+ seen.add(path)
109
+ for tok in lexer.tokenize(_read(path)):
110
+ if tok.kind == lexer.IDENT:
111
+ idents.add(tok.text)
112
+ elif tok.kind == lexer.HEADER:
113
+ inner = tok.text[1:-1].strip()
114
+ queue.append((inner, path.parent if tok.text[0] == "\"" else None, False))
115
+ return idents, unresolved
doppelcode/keepset.py ADDED
@@ -0,0 +1,84 @@
1
+ """Names that must never be renamed: C keywords, extensions and the standard library.
2
+
3
+ The standard library list is a fallback for machines without a compiler; when
4
+ include dirs are available, ``headers.harvest`` adds every identifier from the
5
+ system headers the project actually includes.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ C_KEYWORDS = set("""
11
+ auto break case char const continue default do double else enum extern float for goto if
12
+ inline int long register restrict return short signed sizeof static struct switch typedef
13
+ union unsigned void volatile while
14
+ _Alignas _Alignof _Atomic _Bool _Complex _Generic _Imaginary _Noreturn _Static_assert
15
+ _Thread_local _BitInt _Decimal32 _Decimal64 _Decimal128
16
+ alignas alignof bool constexpr false nullptr static_assert thread_local true typeof
17
+ typeof_unqual
18
+ asm __asm __asm__ __attribute__ __attribute __declspec __inline __inline__ __restrict
19
+ __restrict__ __volatile__ __extension__ __typeof__ __typeof __int64 __int128 __cdecl
20
+ __stdcall __fastcall __forceinline __builtin_va_list __builtin_offsetof __func__
21
+ __FUNCTION__ __PRETTY_FUNCTION__ __LINE__ __FILE__ __DATE__ __TIME__ __STDC__
22
+ __STDC_VERSION__ __COUNTER__ __has_include __has_attribute __VA_ARGS__ __VA_OPT__
23
+ defined __has_include_next __has_builtin __has_c_attribute
24
+ main
25
+ """.split())
26
+
27
+ C_STDLIB = set("""
28
+ NULL EOF BUFSIZ FILENAME_MAX FOPEN_MAX L_tmpnam SEEK_CUR SEEK_END SEEK_SET TMP_MAX
29
+ stdin stdout stderr FILE fpos_t size_t ssize_t ptrdiff_t wchar_t wint_t wctype_t
30
+ max_align_t nullptr_t offsetof va_list va_start va_end va_arg va_copy
31
+ EXIT_FAILURE EXIT_SUCCESS RAND_MAX MB_CUR_MAX div_t ldiv_t lldiv_t
32
+ int8_t int16_t int32_t int64_t uint8_t uint16_t uint32_t uint64_t
33
+ int_least8_t int_least16_t int_least32_t int_least64_t uint_least8_t uint_least16_t
34
+ uint_least32_t uint_least64_t int_fast8_t int_fast16_t int_fast32_t int_fast64_t
35
+ uint_fast8_t uint_fast16_t uint_fast32_t uint_fast64_t intptr_t uintptr_t intmax_t uintmax_t
36
+ INT8_MIN INT8_MAX INT16_MIN INT16_MAX INT32_MIN INT32_MAX INT64_MIN INT64_MAX UINT8_MAX
37
+ UINT16_MAX UINT32_MAX UINT64_MAX SIZE_MAX PTRDIFF_MIN PTRDIFF_MAX INTPTR_MIN INTPTR_MAX
38
+ UINTPTR_MAX INTMAX_MIN INTMAX_MAX UINTMAX_MAX INT8_C INT16_C INT32_C INT64_C UINT8_C
39
+ UINT16_C UINT32_C UINT64_C INTMAX_C UINTMAX_C
40
+ CHAR_BIT CHAR_MIN CHAR_MAX SCHAR_MIN SCHAR_MAX UCHAR_MAX SHRT_MIN SHRT_MAX USHRT_MAX INT_MIN
41
+ INT_MAX UINT_MAX LONG_MIN LONG_MAX ULONG_MAX LLONG_MIN LLONG_MAX ULLONG_MAX MB_LEN_MAX
42
+ FLT_MAX FLT_MIN FLT_EPSILON DBL_MAX DBL_MIN DBL_EPSILON LDBL_MAX LDBL_MIN LDBL_EPSILON
43
+ FLT_DIG DBL_DIG FLT_MANT_DIG DBL_MANT_DIG
44
+ errno EDOM ERANGE EILSEQ EINVAL ENOMEM ENOENT EACCES EAGAIN EBUSY EEXIST EINTR EIO
45
+ assert static_assert NDEBUG
46
+ true false bool
47
+ clock_t time_t tm tm_sec tm_min tm_hour tm_mday tm_mon tm_year tm_wday tm_yday tm_isdst
48
+ timespec tv_sec tv_nsec CLOCKS_PER_SEC TIME_UTC
49
+ jmp_buf setjmp longjmp sig_atomic_t signal raise SIGABRT SIGFPE SIGILL SIGINT SIGSEGV SIGTERM
50
+ SIG_DFL SIG_ERR SIG_IGN
51
+ lconv setlocale localeconv LC_ALL LC_COLLATE LC_CTYPE LC_MONETARY LC_NUMERIC LC_TIME
52
+ HUGE_VAL HUGE_VALF HUGE_VALL INFINITY NAN FP_INFINITE FP_NAN FP_NORMAL FP_SUBNORMAL FP_ZERO
53
+ M_PI M_E M_SQRT2 M_LN2 M_LN10 M_PI_2 M_PI_4
54
+ fclose fflush fopen freopen setbuf setvbuf fprintf fscanf printf scanf snprintf sprintf
55
+ sscanf vfprintf vfscanf vprintf vscanf vsnprintf vsprintf vsscanf fgetc fgets fputc fputs
56
+ getc getchar gets putc putchar puts ungetc fread fwrite fgetpos fseek fsetpos ftell rewind
57
+ clearerr feof ferror perror remove rename tmpfile tmpnam _IOFBF _IOLBF _IONBF fileno
58
+ atof atoi atol atoll strtod strtof strtold strtol strtoll strtoul strtoull rand srand
59
+ aligned_alloc calloc free malloc realloc abort atexit at_quick_exit exit _Exit getenv
60
+ quick_exit system bsearch qsort abs labs llabs div ldiv lldiv mblen mbtowc wctomb mbstowcs
61
+ wcstombs
62
+ memcpy memmove memset memcmp memchr strcpy strncpy strcat strncat strcmp strncmp strcoll
63
+ strxfrm strchr strrchr strspn strcspn strpbrk strstr strtok strerror strlen strdup strndup
64
+ strnlen strtok_r memccpy
65
+ isalnum isalpha isblank iscntrl isdigit isgraph islower isprint ispunct isspace isupper
66
+ isxdigit tolower toupper
67
+ acos asin atan atan2 cos sin tan acosh asinh atanh cosh sinh tanh exp exp2 expm1 frexp ilogb
68
+ ldexp log log10 log1p log2 logb modf scalbn scalbln cbrt fabs hypot pow sqrt erf erfc lgamma
69
+ tgamma ceil floor nearbyint rint lrint llrint round lround llround trunc fmod remainder
70
+ remquo copysign nan nextafter nexttoward fdim fmax fmin fma isfinite isinf isnan isnormal
71
+ signbit fpclassify sinf cosf tanf sqrtf powf fabsf floorf ceilf roundf expf logf log10f
72
+ atan2f fmodf fminf fmaxf
73
+ clock difftime mktime time asctime ctime gmtime localtime strftime timespec_get
74
+ thrd_t mtx_t cnd_t atomic_int atomic_bool memory_order
75
+ wcslen wcscpy wcscmp wprintf fwprintf swprintf
76
+ """.split())
77
+
78
+ # Words used as generated-name prefixes must never collide with these.
79
+ ALWAYS_KEEP = C_KEYWORDS | C_STDLIB
80
+
81
+
82
+ def is_reserved(name: str) -> bool:
83
+ """Implementation-reserved identifiers: __x and _X."""
84
+ return name.startswith("__") or (len(name) > 1 and name[0] == "_" and name[1].isupper())
@@ -0,0 +1,168 @@
1
+ """Language profiles: file extensions, lexical options, keywords and well-known library names.
2
+
3
+ Two renaming policies (see project.build_mapping):
4
+ "all" C, C++: every identifier is renamed except keywords and names harvested from the
5
+ system headers the project includes (the compiler tells where they are).
6
+ "declared" Python, C#, Java, JavaScript, TypeScript: only names the project declares are renamed
7
+ (classes, functions, methods, fields, variables, parameters), minus the keep names
8
+ below and minus names used as members (x.name) that the project never defines -
9
+ those belong to libraries. Python also harvests names from the imported modules'
10
+ source files (pyharvest.py).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ from dataclasses import dataclass, field
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Language:
21
+ key: str
22
+ title: str
23
+ extensions: tuple[str, ...]
24
+ policy: str # "all" | "declared"
25
+ preprocessor: bool = False # '#' directives at line start (C, C++, C#)
26
+ hash_comments: bool = False # '#' starts a comment (Python)
27
+ char_quote: bool = True # '...' is a char literal (C-like) rather than a string
28
+ keywords: frozenset[str] = field(default_factory=frozenset)
29
+ keep: frozenset[str] = field(default_factory=frozenset) # library / runtime names never renamed
30
+
31
+
32
+ def _w(text: str) -> frozenset[str]:
33
+ return frozenset(text.split())
34
+
35
+
36
+ C_KEYWORDS = _w("""auto break case char const continue default do double else enum extern float for goto if
37
+ inline int long register restrict return short signed sizeof static struct switch typedef union unsigned
38
+ void volatile while _Alignas _Alignof _Atomic _Bool _Complex _Generic _Imaginary _Noreturn _Static_assert
39
+ _Thread_local bool true false NULL main defined asm typeof __attribute__ __declspec""")
40
+
41
+ CPP_KEYWORDS = C_KEYWORDS | _w("""alignas alignof and and_eq bitand bitor catch char8_t char16_t char32_t class
42
+ co_await co_return co_yield compl concept const_cast consteval constexpr constinit decltype delete
43
+ dynamic_cast explicit export final friend import module mutable namespace new noexcept not not_eq nullptr
44
+ operator or or_eq override private protected public reinterpret_cast requires static_assert static_cast
45
+ template this thread_local throw try typeid typename using virtual wchar_t xor xor_eq std""")
46
+
47
+ CSHARP_KEYWORDS = _w("""abstract as base bool break byte case catch char checked class const continue decimal
48
+ default delegate do double else enum event explicit extern false finally fixed float for foreach goto if
49
+ implicit in int interface internal is lock long namespace new null object operator out override params
50
+ private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct
51
+ switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual void volatile while
52
+ add alias and ascending async await by descending dynamic equals from get global group init into join let
53
+ managed nameof nint not notnull nuint on or orderby partial record remove required scoped select set
54
+ unmanaged value var when where with yield file""")
55
+ CSHARP_KEEP = _w("""System Console WriteLine Write ReadLine ReadKey String Object Math Main Program args
56
+ ToString Equals GetHashCode GetType Dispose DisposeAsync IDisposable IAsyncDisposable IEnumerable IEnumerator
57
+ GetEnumerator MoveNext Current Reset Compare CompareTo IComparable Clone ICloneable Finalize Invoke
58
+ List Dictionary HashSet Queue Stack Array Task Action Func EventHandler EventArgs Exception Attribute
59
+ Add Remove Clear Contains ContainsKey TryGetValue Count Length Keys Values Insert IndexOf Sort Reverse
60
+ Select Where First FirstOrDefault Last Any All Sum Max Min Average OrderBy ToList ToArray Linq Collections
61
+ Generic Text Threading Tasks IO File Path Directory Collections Format Parse TryParse Join Split Trim
62
+ Substring Replace StartsWith EndsWith ToUpper ToLower Empty IsNullOrEmpty Now Today Value HasValue
63
+ OnPropertyChanged PropertyChanged INotifyPropertyChanged Configure ConfigureServices Startup""")
64
+
65
+ JAVA_KEYWORDS = _w("""abstract assert boolean break byte case catch char class const continue default do
66
+ double else enum extends final finally float for goto if implements import instanceof int interface long
67
+ native new package private protected public return short static strictfp super switch synchronized this
68
+ throw throws transient try void volatile while true false null var record sealed permits yield non sealed
69
+ exports module open opens provides requires to transitive uses with""")
70
+ JAVA_KEEP = _w("""java javax lang util io System out err in println print printf String Object Math main args
71
+ toString equals hashCode getClass clone finalize compareTo Comparable compare Comparator run Runnable call
72
+ Callable iterator Iterator hasNext next remove Iterable close AutoCloseable List ArrayList Map HashMap Set
73
+ HashSet Arrays Collections Optional Stream stream map filter collect forEach of get put add size isEmpty
74
+ contains length charAt substring Integer Long Double Boolean Character Exception RuntimeException Override
75
+ Deprecated SuppressWarnings FunctionalInterface Thread start apply accept test valueOf parseInt format""")
76
+
77
+ JS_KEYWORDS = _w("""break case catch class const continue debugger default delete do else export extends
78
+ false finally for function if import in instanceof new null return super switch this throw true try typeof
79
+ var void while with yield let static async await of get set undefined NaN Infinity arguments""")
80
+ JS_KEEP = _w("""console log error warn info document window globalThis Math JSON Object Array String Number
81
+ Boolean Symbol Promise Map Set WeakMap Date RegExp Error require module exports default constructor
82
+ prototype length push pop shift unshift map filter reduce forEach find some every includes indexOf slice
83
+ splice join split concat keys values entries then catch finally resolve reject toString valueOf
84
+ addEventListener querySelector getElementById fetch setTimeout setInterval process env argv""")
85
+
86
+ TS_KEYWORDS = JS_KEYWORDS | _w("""abstract any as asserts bigint boolean declare enum implements infer interface
87
+ is keyof module namespace never number object override private protected public readonly string symbol
88
+ type unique unknown satisfies accessor""")
89
+ TS_KEEP = JS_KEEP | _w("""Partial Required Readonly Record Pick Omit Exclude Extract NonNullable ReturnType
90
+ Parameters InstanceType Awaited Promise Array""")
91
+
92
+ PY_KEYWORDS = _w("""False None True and as assert async await break class continue def del elif else except
93
+ finally for from global if import in is lambda nonlocal not or pass raise return try while with yield
94
+ match case type self cls""")
95
+
96
+
97
+ def _py_keep() -> frozenset[str]:
98
+ import builtins
99
+ names = set(dir(builtins))
100
+ for t in (str, bytes, bytearray, list, dict, set, frozenset, tuple, int, float, complex, bool, object,
101
+ type, memoryview, range, slice, BaseException, Exception):
102
+ names.update(dir(t))
103
+ names.update("""__name__ __main__ __file__ __doc__ __all__ __init__ __version__ __slots__ __dict__
104
+ args kwargs main""".split())
105
+ return frozenset(names)
106
+
107
+
108
+ LANGUAGES: dict[str, Language] = {
109
+ "c": Language("c", "C", (".c", ".h"), "all", preprocessor=True, keywords=C_KEYWORDS),
110
+ "cpp": Language("cpp", "C++", (".cpp", ".cc", ".cxx", ".c++", ".hpp", ".hh", ".hxx", ".h++", ".ipp",
111
+ ".inl", ".tpp"), "all", preprocessor=True, keywords=CPP_KEYWORDS),
112
+ "csharp": Language("csharp", "C#", (".cs",), "declared", preprocessor=True, keywords=CSHARP_KEYWORDS,
113
+ keep=CSHARP_KEEP),
114
+ "java": Language("java", "Java", (".java",), "declared", keywords=JAVA_KEYWORDS, keep=JAVA_KEEP),
115
+ "javascript": Language("javascript", "JavaScript", (".js", ".mjs", ".cjs", ".jsx"), "declared",
116
+ char_quote=False, keywords=JS_KEYWORDS, keep=JS_KEEP),
117
+ "typescript": Language("typescript", "TypeScript", (".ts", ".mts", ".cts", ".tsx"), "declared",
118
+ char_quote=False, keywords=TS_KEYWORDS, keep=TS_KEEP),
119
+ "python": Language("python", "Python", (".py", ".pyw", ".pyi"), "declared", hash_comments=True,
120
+ char_quote=False, keywords=PY_KEYWORDS, keep=_py_keep()),
121
+ }
122
+ BY_EXTENSION = {ext: lang.key for lang in LANGUAGES.values() for ext in lang.extensions}
123
+
124
+
125
+ def for_path(rel: str, c_extensions: list[str] | None = None) -> str | None:
126
+ name = rel.rsplit("/", 1)[-1]
127
+ ext = ("." + name.rsplit(".", 1)[-1].lower()) if "." in name else ""
128
+ if c_extensions is not None and ext in c_extensions:
129
+ return "c"
130
+ return BY_EXTENSION.get(ext)
131
+
132
+
133
+ def is_code(mode: str | None) -> bool:
134
+ return mode in LANGUAGES
135
+
136
+
137
+ # -- language detection for pasted text (message tool) --------------------------------------------
138
+ _SIGNS = {
139
+ "python": [r"^\s*def \w+\(.*\)\s*(->.*)?:\s*$", r"^\s*(from \S+ )?import \w", r"^\s*class \w+(\(.*\))?:\s*$",
140
+ r"^\s*(elif|except|finally)\b.*:\s*$", r"\bself\.\w", r"^\s*print\(", r"^\s*@\w+", r'"""',
141
+ r"^\s*#(?!include|define|if|endif|pragma|region)"],
142
+ "csharp": [r"^\s*using System", r"\bnamespace \w+(\.\w+)*\s*[{;]?\s*$", r"\b(public|private|internal) "
143
+ r"(static |override |async |sealed |partial )*(class|void|string|int|Task)\b", r"Console\.Write",
144
+ r"\{ get; (private )?set; \}", r"\bvar \w+ = new\b", r"\$\"", r"@\""],
145
+ "java": [r"^\s*package [\w.]+;", r"^\s*import java\.", r"System\.out\.print", r"\bpublic static void main",
146
+ r"@Override", r"\bextends \w+ implements\b|\bimplements \w+", r"\bnew \w+<.*>\(\)"],
147
+ "typescript": [r":\s*(string|number|boolean|any|void)\b", r"^\s*(export )?interface \w+", r"^\s*type \w+ =",
148
+ r"\bas (string|number|const)\b", r"<\w+>\(", r"^\s*(export )?enum \w+"],
149
+ "javascript": [r"^\s*(const|let|var) \w+ = ", r"\bfunction \w*\(", r"=>", r"console\.log", r"\brequire\(",
150
+ r"^\s*(export|import) ", r"`[^`]*\$\{", r"===|!=="],
151
+ "cpp": [r"^\s*#include <(iostream|vector|string|map|memory|algorithm)>", r"\bstd::", r"\bnamespace \w+\s*\{",
152
+ r"\btemplate\s*<", r"\bclass \w+(\s*:\s*(public|private) \w+)?\s*\{", r"::\w+\(", r"\bcout\b",
153
+ r"\bnullptr\b", r"\bauto \w+ ="],
154
+ "c": [r"^\s*#include <\w+\.h>", r"^\s*#define \w+", r"\btypedef struct\b", r"\bprintf\(", r"\bmalloc\(",
155
+ r"\buint\d+_t\b", r"^\s*(static )?(int|void|char|float|double) \w+\(.*\)\s*\{?\s*$"],
156
+ }
157
+ _SIGN_RE = {k: [re.compile(p, re.M) for p in v] for k, v in _SIGNS.items()}
158
+
159
+
160
+ def detect(text: str) -> str | None:
161
+ """Best-guess language of a pasted snippet, or None for prose / unknown."""
162
+ scores = {k: sum(len(r.findall(text)) for r in rs) for k, rs in _SIGN_RE.items()}
163
+ if scores["typescript"] and scores["javascript"]:
164
+ scores["typescript"] += scores["javascript"] # TS is a superset of JS
165
+ if scores["cpp"]:
166
+ scores["cpp"] += scores["c"] // 2 # C++ files contain C-looking lines
167
+ best = max(scores, key=lambda k: scores[k])
168
+ return best if scores[best] >= 2 else None