File size: 39,345 Bytes
3637f8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
"""

module_loader.py

================

Cargador de librerΓ­as Tesseract desde la instalaciΓ³n global.



Estructura esperada en disco:

    libs/

    └── <module>/

        β”œβ”€β”€ main.tbc              ← orquestador (MAGIC "TSORCH")

        └── versions/

            └── <version>/

                β”œβ”€β”€ linker.tbc    ← bytecode del cΓ³digo fuente (MAGIC "TSSLK")

                β”œβ”€β”€ <module>.tmc  ← interfaz pΓΊblica (MAGIC "TSMC")

                └── deps/         ← dependencias externas



Rutas de bΓΊsqueda (en orden):

    Windows:  %LOCALAPPDATA%\\Tesseract\\libs\\

              %APPDATA%\\Tesseract\\libs\\

    Linux:    ~/.local/share/tesseract/libs/

    macOS:    ~/Library/Application Support/tesseract/libs/



ResoluciΓ³n de linker_id β†’ nombre en el linker:

    linker_id = "mathlib_sqrt"

    pure_name = "sqrt"         ← todo lo que estΓ‘ despuΓ©s del primer '_'

    Busca en el linker: "tess_sqrt" primero, luego "sqrt" como fallback.

    El prefijo "tess_" lo aΓ±ade el tsslk_compiler a todos los sΓ­mbolos.

"""

import os
import struct
from pathlib import Path


# ════════════════════════════════════════════════════════════════════════
#  EXCEPCIONES
# ════════════════════════════════════════════════════════════════════════

class ModuleError(Exception):
    pass


# ════════════════════════════════════════════════════════════════════════
#  ModuleInstance  β€” acceso a miembros de un mΓ³dulo via dot notation
# ════════════════════════════════════════════════════════════════════════

class ModuleInstance:
    """

    Instancia de mΓ³dulo. Permite acceso a variables y llamadas a mΓ©todos

    mediante dot notation desde el intΓ©rprete.

    """
    def __init__(self, module_name: str, loader: 'ModuleLoader'):
        self._name   = module_name
        self._loader = loader

    def get_member(self, member_name: str):
        return self._loader.get_export_value(self._name, member_name)

    def call_method(self, method_name: str, args: list, interpreter):
        fn = self._loader.get_function(self._name, method_name)
        return fn.call(args, interpreter)

    def __repr__(self):
        return f"<ModuleInstance '{self._name}'>"


# ════════════════════════════════════════════════════════════════════════
#  Wrapper de funciΓ³n enlazada desde linker.tbc
# ════════════════════════════════════════════════════════════════════════

class _LinkedFunctionWrapper:
    """

    Expone una funciΓ³n del linker.tbc con la misma interfaz

    .call(args, caller_interpreter) que los mΓ³dulos nativos.

    """
    def __init__(self, func_name: str, isolated_interp, debug: bool = False):
        self._func_name = func_name
        self._iso       = isolated_interp
        self._debug     = debug

    def call(self, args: list, caller_interpreter):
        # Lazy import para evitar circular dependency (interpre importa module_loader)
        from interpre import FunctionContext
        if self._debug:
            print(f"  [LinkedFunc] Llamando '{self._func_name}' args={args}")
        ctx = FunctionContext(self._iso, self._func_name, args)
        return ctx.execute_function()


# ════════════════════════════════════════════════════════════════════════
#  MΓ³dulo cargado desde .tbc
# ════════════════════════════════════════════════════════════════════════

class _TbcModule:
    """

    MΓ³dulo completamente cargado: mapa pΓΊblico (.tmc) + intΓ©rprete aislado

    con el linker.tbc ya ejecutado.

    """
    def __init__(self, module_name: str, version: str,

                 tmc_map: dict, isolated_interp, debug: bool = False):
        self.module_name   = module_name
        self.version       = version
        self.tmc_map       = tmc_map
        self._iso          = isolated_interp
        self._debug        = debug
        self._func_cache   = {}
        self._member_aliases: dict = {}   # alias β†’ original_name

    # ── Funciones ───────────────────────────────────────────────────────

    def get_function(self, func_name: str) -> _LinkedFunctionWrapper:
        if func_name in self._func_cache:
            return self._func_cache[func_name]

        funcs = self.tmc_map.get("functions", {})
        if func_name not in funcs:
            raise ModuleError(
                f"La funciΓ³n '{func_name}' no estΓ‘ en el mΓ³dulo '{self.module_name}'."
            )

        func_info  = funcs[func_name]
        linker_id  = func_info.get("linker_id", "")
        real_name  = self._resolve_name(linker_id or func_name)

        wrapper = _LinkedFunctionWrapper(real_name, self._iso, self._debug)
        self._func_cache[func_name] = wrapper
        return wrapper

    # ── Exports (variables / constantes) ────────────────────────────────

    def get_export(self, var_name: str):
        exports = self.tmc_map.get("exports", {})
        if var_name not in exports:
            raise ModuleError(
                f"El export '{var_name}' no existe en el mΓ³dulo '{self.module_name}'."
            )

        exp_info  = exports[var_name]
        linker_id = exp_info.get("linker_id", "")
        real_name = self._resolve_name(linker_id or var_name)

        # Intentar obtener de la tabla de sΓ­mbolos del intΓ©rprete aislado
        iso = self._iso
        for candidate in (real_name, f"tess_{var_name}", var_name):
            try:
                return iso.symbol_table.get_value(candidate)
            except Exception:
                continue

        raise ModuleError(
            f"No se pudo obtener el valor de '{var_name}' del mΓ³dulo '{self.module_name}'."
        )

    # ── Clases ──────────────────────────────────────────────────────────

    def get_classes(self) -> dict:
        """Retorna las ClassDefinition cargadas en el intΓ©rprete aislado."""
        if hasattr(self._iso, 'object_table'):
            return self._iso.object_table.class_definitions
        return {}

    # ── ResoluciΓ³n de nombre: linker_id β†’ nombre real en el linker ───────

    def _resolve_name(self, linker_id: str) -> str:
        """

        Extrae el nombre puro del linker_id y busca el sΓ­mbolo real

        en el intΓ©rprete aislado (tabla de funciones + tabla de sΓ­mbolos).



        ConvenciΓ³n:

          linker_id = "mathlib_sqrt"

          pure_name = "sqrt"              (todo despuΓ©s del primer '_')

          Busca en linker: "tess_sqrt" β†’ "sqrt" β†’ linker_id completo

        """
        if "_" in linker_id:
            pure_name = linker_id.split("_", 1)[1]
        else:
            pure_name = linker_id

        tess_name = f"tess_{pure_name}"

        iso = self._iso

        # Buscar en la tabla de funciones
        for candidate in (tess_name, pure_name, linker_id):
            try:
                iso.symbol_table.get_function(candidate)
                return candidate
            except Exception:
                pass

        # Buscar en la tabla de variables
        for candidate in (tess_name, pure_name, linker_id):
            try:
                iso.symbol_table.get_value(candidate)
                return candidate
            except Exception:
                pass

        # Fallback: devolver el nombre puro aunque no exista (el error llegarΓ‘ al llamar)
        if self._debug:
            print(f"  [ModuleLoader] WARN: no se encontrΓ³ '{linker_id}' β†’ usando '{pure_name}'")
        return pure_name


# ════════════════════════════════════════════════════════════════════════
#  MΓ³dulo nativo Python  (sin .tbc β€” implementado en Python puro)
# ════════════════════════════════════════════════════════════════════════

class _NativeFunctionWrapper:
    """

    Wrapper de funciΓ³n nativa Python con la misma interfaz .call() que

    _LinkedFunctionWrapper. La funciΓ³n viene del NATIVE_MODULE["functions"].

    """
    def __init__(self, fn, func_name: str):
        self._fn        = fn
        self._func_name = func_name

    def call(self, args: list, interpreter):
        return self._fn(args, interpreter)


class _NativePythonModule:
    """

    MΓ³dulo implementado en Python puro (linker_bridge.py y similares).

    Cargado desde un archivo native.py que expone NATIVE_MODULE.



    Comparte la misma interfaz que _TbcModule para que ModuleLoader

    los trate de forma idΓ©ntica.

    """
    def __init__(self, desc: dict):
        self.module_name     = desc["module"]
        self.version         = desc.get("version", "native")
        self.tmc_map         = {
            "functions": {k: {"linker_id": k} for k in desc.get("functions", {})},
            "exports":   {k: {"type": "any", "const": True, "linker_id": k}
                          for k in desc.get("exports", {})},
            "classes":   {},
        }
        self._funcs          = desc.get("functions", {})   # {name: callable(args, interp)}
        self._exports_vals   = desc.get("exports", {})     # {name: callable() β†’ value}
        self._member_aliases: dict = {}
        self._func_cache:    dict = {}

    def get_function(self, func_name: str) -> _NativeFunctionWrapper:
        if func_name in self._func_cache:
            return self._func_cache[func_name]
        real = self._member_aliases.get(func_name, func_name)
        if real not in self._funcs:
            raise ModuleError(
                f"La funciΓ³n '{real}' no existe en el mΓ³dulo nativo '{self.module_name}'."
            )
        w = _NativeFunctionWrapper(self._funcs[real], real)
        self._func_cache[func_name] = w
        return w

    def get_export(self, var_name: str):
        real = self._member_aliases.get(var_name, var_name)
        if real not in self._exports_vals:
            raise ModuleError(
                f"El export '{real}' no existe en el mΓ³dulo nativo '{self.module_name}'."
            )
        return self._exports_vals[real]()

    def get_classes(self) -> dict:
        return {}

    def _resolve_name(self, linker_id: str) -> str:
        return linker_id




class _BinReader:
    def __init__(self, data: bytes):
        self.data = data
        self.pos  = 0

    def read(self, n: int) -> bytes:
        c = self.data[self.pos:self.pos+n]; self.pos += n; return c

    def ru8(self)  -> int:  return struct.unpack(">B", self.read(1))[0]
    def ru16(self) -> int:  return struct.unpack(">H", self.read(2))[0]
    def ri64(self) -> int:  return struct.unpack(">q", self.read(8))[0]
    def rf64(self) -> float: return struct.unpack(">d", self.read(8))[0]

    def rpstr(self) -> str:
        n = self.ru8()
        return self.read(n).decode("utf-8", errors="replace")

    def rwstr(self) -> str:
        n = self.ru16()
        return self.read(n).decode("utf-8", errors="replace")

    def eof(self) -> bool:
        return self.pos >= len(self.data)

    def rtype(self) -> str:
        """Lee un type code con payload y devuelve el nombre del tipo."""
        from tss_bytemap import (TYPE_NAMES, TYPE_ARRAY, TYPE_TUPLE,
                                  TYPE_DICT, TYPE_STRUCT)
        tc   = self.ru8()
        name = TYPE_NAMES.get(tc, "any")
        if tc == TYPE_ARRAY:
            self.ru8(); return "array"
        if tc == TYPE_TUPLE:
            cnt = self.ru8()
            for _ in range(cnt): self.ru8()
            return "tuple"
        if tc == TYPE_DICT:
            self.ru8(); self.ru8(); return "dict"
        if tc == TYPE_STRUCT:
            sname = self.rpstr(); return sname
        return name


# ════════════════════════════════════════════════════════════════════════
#  Vista pΓΊblica de mΓ³dulo para _inject_native_module_symbols
# ════════════════════════════════════════════════════════════════════════

class _ExportView:
    """Objeto de export compatible con la interfaz que usa interpre.py."""
    def __init__(self, value, export_type: str, is_const: bool):
        self.value       = value
        self.export_type = export_type
        self.is_const    = is_const


class _FunctionView:
    """Objeto de funciΓ³n compatible con la interfaz que usa interpre.py."""
    def __init__(self, wrapper: '_LinkedFunctionWrapper', params: dict):
        self._wrapper = wrapper
        self.params   = params
        self.block    = []       # vacΓ­o β€” es una funciΓ³n enlazada, no en script
        self.kind     = 'native'

    def call(self, args, interpreter):
        return self._wrapper.call(args, interpreter)


class _ModulePublicView:
    """

    Adaptador que expone un _TbcModule con la interfaz que espera

    _inject_native_module_symbols en interpre.py:

      mod.get_function(name) β†’ objeto con .params, .block, .kind

      mod.get_export(name)   β†’ objeto con .value, .export_type, .is_const

    """
    def __init__(self, tbc_module: '_TbcModule'):
        self._mod = tbc_module

    def get_function(self, func_name: str) -> _FunctionView:
        real  = self._mod._member_aliases.get(func_name, func_name)
        funcs = self._mod.tmc_map.get("functions", {})
        if real not in funcs:
            raise ModuleError(
                f"FunciΓ³n '{real}' no existe en mΓ³dulo '{self._mod.module_name}'."
            )
        info    = funcs[real]
        wrapper = self._mod.get_function(real)
        return _FunctionView(wrapper, info.get("params", {}))

    def get_export(self, var_name: str) -> _ExportView:
        real    = self._mod._member_aliases.get(var_name, var_name)
        exports = self._mod.tmc_map.get("exports", {})
        if real not in exports:
            raise ModuleError(
                f"Export '{real}' no existe en mΓ³dulo '{self._mod.module_name}'."
            )
        info  = exports[real]
        value = self._mod.get_export(real)
        return _ExportView(value, info.get("type", "any"), info.get("const", False))


# ════════════════════════════════════════════════════════════════════════
#  ModuleLoader  β€” cargador principal
# ════════════════════════════════════════════════════════════════════════

class ModuleLoader:
    """

    Carga librerΓ­as Tesseract desde la instalaciΓ³n global (libs/).



    Interfaz que usa interpre.py:

        is_loaded(name)               β†’ bool

        get_function(mod, func)       β†’ wrapper con .call(args, interp)

        get_export_value(mod, var)    β†’ valor Python

        get_classes(mod)              β†’ dict {name: ClassDefinition}

    """

    def __init__(self, debug: bool = False):
        self._debug   = debug
        self._modules: dict = {}    # module_name β†’ _TbcModule
        self._aliases: dict = {}    # alias β†’ real_module_name
        self._libs_path: Path | None = None
        self._libs_path_resolved = False

    def _resolve_alias(self, name: str) -> str:
        return self._aliases.get(name, name)

    # ════════════════════════════════════════════════════════════════════
    #  Interfaz pΓΊblica (usada por interpre.py)
    # ════════════════════════════════════════════════════════════════════

    def is_loaded(self, name: str) -> bool:
        if name in self._modules or name in self._aliases:
            return True
        self._try_load(name)
        return name in self._modules

    def load(self, module_name: str):
        """Carga el mΓ³dulo completo. Llamado por handle_LIB_CALL."""
        if module_name not in self._modules:
            self._ensure_loaded(module_name)

    def load_selective(self, module_name: str, functions: list):
        """

        Carga el mΓ³dulo y marca quΓ© miembros se importaron selectivamente.

        Llamado por 'from <mod> use f1, f2'.

        La carga completa es la misma β€” la selectividad la gestiona interpre.py.

        """
        self.load(module_name)

    def get_function(self, mod_name: str, func_name: str) -> '_LinkedFunctionWrapper':
        mod_name = self._resolve_alias(mod_name)
        self._ensure_loaded(mod_name)
        mod = self._modules[mod_name]
        # Aplicar alias de miembro si existe
        real_func = mod._member_aliases.get(func_name, func_name)
        return mod.get_function(real_func)

    def get_export_value(self, mod_name: str, var_name: str):
        mod_name = self._resolve_alias(mod_name)
        self._ensure_loaded(mod_name)
        mod = self._modules[mod_name]
        real_name = mod._member_aliases.get(var_name, var_name)
        return mod.get_export(real_name)

    def get_module(self, module_name: str) -> '_ModulePublicView':
        """

        Retorna una vista pΓΊblica del mΓ³dulo compatible con la interfaz que

        usa _inject_native_module_symbols en interpre.py.

        """
        module_name = self._resolve_alias(module_name)
        self._ensure_loaded(module_name)
        return _ModulePublicView(self._modules[module_name])

    def get_classes(self, mod_name: str) -> dict:
        mod_name = self._resolve_alias(mod_name)
        if mod_name not in self._modules:
            return {}
        return self._modules[mod_name].get_classes()

    # ── OOP ──────────────────────────────────────────────────────────────

    def has_class(self, class_name: str) -> bool:
        """Devuelve True si algΓΊn mΓ³dulo cargado tiene esta clase."""
        for mod in self._modules.values():
            if class_name in mod.tmc_map.get("classes", {}):
                return True
            if class_name in mod.get_classes():
                return True
        return False

    def get_class_info(self, class_name: str):
        """

        Retorna (mod_name, class_definition) para una clase nativa.

        Llamado por _instantiate_native_class en interpre.py.

        """
        for mod_name, mod in self._modules.items():
            classes = mod.get_classes()
            if class_name in classes:
                return mod_name, classes[class_name]
        raise ModuleError(f"Clase '{class_name}' no encontrada en ningΓΊn mΓ³dulo cargado.")

    def instantiate(self, mod_name: str, class_name: str,

                    args: list, interpreter) -> 'ModuleInstance':
        """

        Instancia una clase nativa del mΓ³dulo.

        Ejecuta el constructor con los args dados.

        """
        mod_name = self._resolve_alias(mod_name)
        self._ensure_loaded(mod_name)
        mod = self._modules[mod_name]

        # Buscar el constructor en el tmc_map
        cls_info = mod.tmc_map.get("classes", {}).get(class_name, {})
        ctor     = cls_info.get("constructor")

        instance = ModuleInstance(class_name, self)
        instance._mod_name = mod_name

        if ctor:
            ctor_id   = ctor.get("linker_id", "")
            real_name = mod._resolve_name(ctor_id or f"{mod_name}_{class_name}_new")
            try:
                fn = _LinkedFunctionWrapper(real_name, mod._iso, self._debug)
                fn.call(args, interpreter)
            except Exception as e:
                if self._debug:
                    print(f"  [ModuleLoader] WARN: constructor '{class_name}' error: {e}")

        return instance

    # ── Aliases ───────────────────────────────────────────────────────────

    def apply_alias(self, module_name: str, alias: str):
        """library math al m  β†’ m es alias de math"""
        if alias:
            self._aliases[alias] = module_name

    def apply_member_alias_inline(self, module_name: str,

                                   orig_name: str, alias: str):
        """from math use sqrt al sqr  β†’ sqr es alias de sqrt en math"""
        module_name = self._resolve_alias(module_name)
        if module_name in self._modules and alias:
            self._modules[module_name]._member_aliases[alias] = orig_name

    def apply_member_aliases_positional(self, module_name: str,

                                         members: list, aliases: list):
        """from math use sqrt, abs al [sqr, absolute]"""
        module_name = self._resolve_alias(module_name)
        if module_name in self._modules:
            for orig, alias in zip(members, aliases):
                if alias:
                    self._modules[module_name]._member_aliases[alias] = orig

    def apply_on_aliases(self, module_name: str,

                          on_names: list, on_aliases: list):
        """Clause 'on' para mapeo de eventos/callbacks."""
        module_name = self._resolve_alias(module_name)
        if module_name in self._modules:
            for orig, alias in zip(on_names, on_aliases or []):
                if alias:
                    self._modules[module_name]._member_aliases[alias] = orig

    # ════════════════════════════════════════════════════════════════════
    #  Carga de mΓ³dulo
    # ════════════════════════════════════════════════════════════════════

    def _ensure_loaded(self, module_name: str):
        if module_name not in self._modules:
            self._try_load(module_name)
        if module_name not in self._modules:
            raise ModuleError(
                f"El mΓ³dulo '{module_name}' no estΓ‘ instalado o no pudo cargarse. "
                f"Verifica que estΓ‘ en {self._libs_path or 'libs/'}"
            )

    def _try_load(self, module_name: str):
        """Intenta cargar un mΓ³dulo desde la ruta global. No lanza excepciones."""
        try:
            libs = self._get_libs_path()
            if libs is None:
                if self._debug:
                    print(f"[ModuleLoader] No se encontrΓ³ directorio libs/")
                return
            module_dir = libs / module_name
            if not module_dir.exists():
                if self._debug:
                    print(f"[ModuleLoader] MΓ³dulo '{module_name}' no encontrado en {libs}")
                return
            self._load_module(module_name, module_dir)
        except ModuleError as e:
            if self._debug:
                print(f"[ModuleLoader] Error cargando '{module_name}': {e}")
        except Exception as e:
            if self._debug:
                import traceback
                print(f"[ModuleLoader] Error inesperado cargando '{module_name}': {e}")
                traceback.print_exc()

    def _load_module(self, module_name: str, module_dir: Path):
        """

        Pipeline de carga. Detecta automΓ‘ticamente si el mΓ³dulo es:

          A) Nativo Python  β†’ version_dir/native.py  (NATIVE_MODULE descriptor)

          B) Compilado .tbc β†’ version_dir/linker.tbc + version_dir/<mod>.tmc

        """
        main_tbc = module_dir / "main.tbc"
        if not main_tbc.exists():
            raise ModuleError(f"main.tbc no encontrado en {module_dir}")

        version = self._read_main_tbc(main_tbc)
        if self._debug:
            print(f"[ModuleLoader] '{module_name}' versiΓ³n: {version}")

        version_dir = module_dir / "versions" / version
        if not version_dir.exists():
            raise ModuleError(f"Directorio de versiΓ³n no encontrado: {version_dir}")

        # ── A) MΓ³dulo nativo Python (native.py) ───────────────────────────
        native_py = version_dir / "native.py"
        if native_py.exists():
            self._load_native_python(module_name, version, native_py)
            return

        # ── B) MΓ³dulo compilado (.tmc + linker.tbc) ───────────────────────
        tmc_file = version_dir / f"{module_name}.tmc"
        if not tmc_file.exists():
            raise ModuleError(f"{module_name}.tmc no encontrado en {version_dir}")

        tmc_map = self._read_tmc(tmc_file, module_name)
        if self._debug:
            print(f"[ModuleLoader] TMC: "
                  f"{len(tmc_map['functions'])} funcs, "
                  f"{len(tmc_map['exports'])} exports")

        linker_file = version_dir / "linker.tbc"
        if not linker_file.exists():
            raise ModuleError(f"linker.tbc no encontrado en {version_dir}")

        from tsslk_decoder import decode_tbc
        linker_ast = decode_tbc(str(linker_file))

        iso = self._make_isolated_interpreter(linker_ast, module_name)
        self._modules[module_name] = _TbcModule(
            module_name, version, tmc_map, iso, debug=self._debug
        )
        if self._debug:
            print(f"[ModuleLoader] '{module_name}' v{version} (.tbc) cargado OK")

    def _load_native_python(self, module_name: str, version: str, native_py: Path):
        """

        Carga un mΓ³dulo nativo Python desde native.py.

        El archivo debe exponer NATIVE_MODULE = {"module":..., "functions":..., "exports":...}

        """
        import importlib.util
        spec = importlib.util.spec_from_file_location(
            f"_tess_native_{module_name}", str(native_py)
        )
        mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(mod)

        if not hasattr(mod, "NATIVE_MODULE"):
            raise ModuleError(
                f"{native_py} no expone NATIVE_MODULE. "
                f"Agrega NATIVE_MODULE = {{...}} al archivo."
            )

        self._modules[module_name] = _NativePythonModule(mod.NATIVE_MODULE)
        if self._debug:
            desc    = mod.NATIVE_MODULE
            print(f"[ModuleLoader] '{module_name}' v{version} (native.py) cargado OK")
            print(f"  funciones: {list(desc.get('functions', {}).keys())}")
            print(f"  exports:   {list(desc.get('exports', {}).keys())}")

    # ════════════════════════════════════════════════════════════════════
    #  Parseo de main.tbc
    # ════════════════════════════════════════════════════════════════════

    def _read_main_tbc(self, path: Path) -> str:
        """

        Lee el main.tbc y retorna la versiΓ³n seleccionada.



        Formato:

          MAGIC(6) + VER(1) + pstr(module_name) + pstr(version) + pstr(v_count) + ...

        """
        from tss_bytemap import MAGIC_ORCH
        data = path.read_bytes()
        r    = _BinReader(data)

        magic = r.read(6)
        if magic != MAGIC_ORCH:
            raise ModuleError(
                f"main.tbc invΓ‘lido en {path}: magic {magic!r} "
                f"(esperado {MAGIC_ORCH!r})"
            )

        r.ru8()                 # VER
        _module_name = r.rpstr()  # module_name (skip)
        version      = r.rpstr()  # version seleccionada ← esto es lo que nos importa
        # v_count y el resto no se necesitan aquΓ­

        return version

    # ════════════════════════════════════════════════════════════════════
    #  Parseo de .tmc
    # ════════════════════════════════════════════════════════════════════

    def _read_tmc(self, path: Path, module_name: str) -> dict:
        """

        Lee el .tmc y retorna el mapa pΓΊblico:

          {

            "functions": {fname: {linker_id, params, return_type, native}},

            "exports":   {ename: {type, const, linker_id}},

            "classes":   {cname: {constructor: {...}, methods: {...}}}

          }



        El linker_id para exports y funciones se reconstruye como

        f"{module_name}_{name}" si no estΓ‘ explΓ­cito en el binario.

        """
        from tss_bytemap import (MAGIC_TMC, FLAG_NATIVE, FLAG_HAS_ID,
                                  FLAG_HAS_RETURN, TMC_CLASS_HAS_CTOR,
                                  TMC_CLASS_HAS_METHODS,
                                  TYPE_FLOAT, TYPE_INT, TYPE_STRING, TYPE_BOOL,
                                  parse_type_code)

        data = path.read_bytes()
        r    = _BinReader(data)

        magic = r.read(4)
        if magic != MAGIC_TMC:
            raise ModuleError(
                f".tmc invΓ‘lido en {path}: magic {magic!r} "
                f"(esperado {MAGIC_TMC!r})"
            )
        r.ru8()              # FORMAT_VER
        _mod  = r.rpstr()   # module_name
        _ver  = r.rpstr()   # version
        _desc = r.rwstr()   # description

        result = {"functions": {}, "exports": {}, "classes": {}}

        # ── Exports ──────────────────────────────────────────────────────
        ecount = r.ru16()
        for _ in range(ecount):
            ename    = r.rpstr()
            etype    = r.rtype()
            eflags   = r.ru8()
            is_const = bool(eflags & 0x01)

            # Leer y descartar el valor almacenado (no lo usamos en librerΓ­as)
            tc = parse_type_code(etype.split("<")[0].split(":")[0])
            if   tc == TYPE_FLOAT:  r.rf64()
            elif tc == TYPE_INT:    r.ri64()
            elif tc == TYPE_STRING: r.rwstr()
            elif tc == TYPE_BOOL:   r.ru8()
            else:                   r.rwstr()   # fallback wstr

            result["exports"][ename] = {
                "type":      etype,
                "const":     is_const,
                # Linker_id reconstruido por convenciΓ³n: module_name + _ + export_name
                "linker_id": f"{module_name}_{ename}",
            }

        # ── Functions ─────────────────────────────────────────────────────
        fcount = r.ru16()
        for _ in range(fcount):
            fname  = r.rpstr()
            pcount = r.ru8()
            params = {}
            for _ in range(pcount):
                pname = r.rpstr(); ptype = r.rtype()
                params[pname] = ptype
            flags     = r.ru8()
            is_native = bool(flags & FLAG_NATIVE)
            has_id    = bool(flags & FLAG_HAS_ID)
            has_ret   = bool(flags & FLAG_HAS_RETURN)
            fid  = r.rpstr() if has_id  else f"{module_name}_{fname}"
            ret  = r.rtype() if has_ret else ""

            result["functions"][fname] = {
                "linker_id":   fid,
                "params":      params,
                "return_type": ret,
                "native":      is_native,
            }

        # ── Classes (secciΓ³n opcional) ─────────────────────────────────────
        if not r.eof():
            try:
                ccount = r.ru16()
                for _ in range(ccount):
                    cname  = r.rpstr()
                    cflags = r.ru8()
                    cls    = {"constructor": None, "methods": {}}

                    if cflags & TMC_CLASS_HAS_CTOR:
                        pcount = r.ru8()
                        cparams = {}
                        for _ in range(pcount):
                            pname = r.rpstr(); ptype = r.rtype()
                            cparams[pname] = ptype
                        cf  = r.ru8()
                        cid = r.rpstr() if cf & FLAG_HAS_ID     else f"{module_name}_{cname}_new"
                        crt = r.rtype() if cf & FLAG_HAS_RETURN else ""
                        cls["constructor"] = {
                            "linker_id": cid, "params": cparams, "return_type": crt
                        }

                    if cflags & TMC_CLASS_HAS_METHODS:
                        mcount = r.ru16()
                        for _ in range(mcount):
                            mname   = r.rpstr()
                            pcount  = r.ru8()
                            mparams = {}
                            for _ in range(pcount):
                                pname = r.rpstr(); ptype = r.rtype()
                                mparams[pname] = ptype
                            mf  = r.ru8()
                            mid = r.rpstr() if mf & FLAG_HAS_ID     else f"{module_name}_{cname}_{mname}"
                            mrt = r.rtype() if mf & FLAG_HAS_RETURN else ""
                            cls["methods"][mname] = {
                                "linker_id": mid, "params": mparams, "return_type": mrt
                            }

                    result["classes"][cname] = cls
            except Exception:
                # SecciΓ³n de clases corrupta o ausente β€” no es fatal
                pass

        return result

    # ════════════════════════════════════════════════════════════════════
    #  IntΓ©rprete aislado para ejecutar el linker
    # ════════════════════════════════════════════════════════════════════

    def _make_isolated_interpreter(self, linker_ast: dict, module_name: str):
        """

        Crea un Interpreter aislado, ejecuta el linker AST en Γ©l y lo retorna.

        Lazy import de interpre.Interpreter para evitar import circular.

        """
        from interpre import Interpreter
        iso = Interpreter(debug_mode=self._debug)
        iso.interpret(linker_ast, source_path=f"<linker:{module_name}>")
        return iso

    # ════════════════════════════════════════════════════════════════════
    #  LocalizaciΓ³n del directorio libs/
    # ════════════════════════════════════════════════════════════════════

    def _get_libs_path(self) -> Path | None:
        """

        Localiza el directorio global de libs de Tesseract.



        Orden de bΓΊsqueda:

          Windows:  %LOCALAPPDATA%\\Tesseract\\libs

                    %APPDATA%\\Tesseract\\libs

          Linux:    ~/.local/share/tesseract/libs

          macOS:    ~/Library/Application Support/tesseract/libs



        Cachea el resultado para no re-buscar en cada llamada.

        """
        if self._libs_path_resolved:
            return self._libs_path

        self._libs_path_resolved = True
        candidates: list[Path] = []

        if os.name == "nt":   # Windows
            local   = os.environ.get("LOCALAPPDATA", "")
            roaming = os.environ.get("APPDATA", "")
            if local:   candidates.append(Path(local)   / "Tesseract" / "libs")
            if roaming: candidates.append(Path(roaming) / "Tesseract" / "libs")
        else:                  # Linux / macOS
            home = Path.home()
            candidates.append(home / ".local" / "share" / "tesseract" / "libs")
            candidates.append(home / "Library" / "Application Support" / "tesseract" / "libs")

        for p in candidates:
            if p.exists():
                self._libs_path = p
                if self._debug:
                    print(f"[ModuleLoader] libs/ encontrado en: {p}")
                return p

        if self._debug:
            print(f"[ModuleLoader] libs/ no encontrado. Buscado en:")
            for p in candidates:
                print(f"  {p}")

        self._libs_path = None
        return None