pyinterfaces 0.2.0__tar.gz → 0.4.0__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.
- {pyinterfaces-0.2.0 → pyinterfaces-0.4.0}/PKG-INFO +1 -1
- pyinterfaces-0.4.0/pyinterfaces/compilador.py +72 -0
- {pyinterfaces-0.2.0 → pyinterfaces-0.4.0}/pyproject.toml +1 -1
- pyinterfaces-0.2.0/pyinterfaces/compilador.py +0 -116
- {pyinterfaces-0.2.0 → pyinterfaces-0.4.0}/README.md +0 -0
- {pyinterfaces-0.2.0 → pyinterfaces-0.4.0}/license.txt +0 -0
- {pyinterfaces-0.2.0 → pyinterfaces-0.4.0}/pyinterfaces/__init__.py +0 -0
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import codecs
|
|
2
|
+
import io
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
def traduzir_sintaxe_java(texto: str) -> str:
|
|
6
|
+
"""
|
|
7
|
+
Substitui 'Interface Nome:' por 'class Nome(ABC):' e adiciona
|
|
8
|
+
@abstractmethod em todos os métodos que começam com 'def'.
|
|
9
|
+
"""
|
|
10
|
+
linhas = texto.split('\n')
|
|
11
|
+
resultado = ["from abc import ABC, abstractmethod\n"]
|
|
12
|
+
dentro_da_interface = False
|
|
13
|
+
|
|
14
|
+
for linha in linhas:
|
|
15
|
+
# 1. Detecta o início da declaração: 'Interface Nome:' (com ou sem espaços)
|
|
16
|
+
inicio_match = re.match(r'\s*Interface\s+(\w+)\s*:', linha)
|
|
17
|
+
if inicio_match:
|
|
18
|
+
nome_interface = inicio_match.group(1)
|
|
19
|
+
resultado.append(f"class {nome_interface}(ABC):")
|
|
20
|
+
dentro_da_interface = True
|
|
21
|
+
continue
|
|
22
|
+
|
|
23
|
+
# Detecta se o bloco da interface acabou (linha sem espaços na esquerda)
|
|
24
|
+
if dentro_da_interface and linha.strip() and not linha.startswith(' '):
|
|
25
|
+
dentro_da_interface = False
|
|
26
|
+
|
|
27
|
+
if dentro_da_interface:
|
|
28
|
+
linha_limpa = linha.strip()
|
|
29
|
+
# 2. Captura métodos que começam com 'def' dentro da interface
|
|
30
|
+
if linha_limpa.startswith('def '):
|
|
31
|
+
# Garante que o método termine com ':' esperado pelo Python
|
|
32
|
+
if not linha_limpa.endswith(':'):
|
|
33
|
+
linha_limpa += ':'
|
|
34
|
+
|
|
35
|
+
# Injeta o 'self' automaticamente caso o usuário não tenha colocado
|
|
36
|
+
if '(self' not in linha_limpa:
|
|
37
|
+
linha_limpa = linha_limpa.replace('(', '(self, ').replace('(self, )', '(self)')
|
|
38
|
+
|
|
39
|
+
resultado.append(f" @abstractmethod")
|
|
40
|
+
resultado.append(f" {linha_limpa}")
|
|
41
|
+
resultado.append(f" pass")
|
|
42
|
+
else:
|
|
43
|
+
resultado.append(linha)
|
|
44
|
+
|
|
45
|
+
return '\n'.join(resultado)
|
|
46
|
+
|
|
47
|
+
# --- INFRAESTRUTURA DE CODEC DO PYTHON ---
|
|
48
|
+
|
|
49
|
+
class JavaInterfaceDecoder(codecs.BufferedIncrementalDecoder):
|
|
50
|
+
def _buffer_decode(self, input, errors, final):
|
|
51
|
+
if final:
|
|
52
|
+
dados_em_bytes = bytes(input)
|
|
53
|
+
texto_traduzido = traduzir_sintaxe_java(dados_em_bytes.decode('utf-8'))
|
|
54
|
+
return (texto_traduzido, len(input))
|
|
55
|
+
return ('', 0)
|
|
56
|
+
|
|
57
|
+
def buscar_codec(nome_codec):
|
|
58
|
+
if nome_codec == 'py_interface':
|
|
59
|
+
return codecs.CodecInfo(
|
|
60
|
+
name='py_interface',
|
|
61
|
+
encode=codecs.utf_8_encode,
|
|
62
|
+
decode=lambda input, errors='strict': (traduzir_sintaxe_java(bytes(input).decode('utf-8')), len(input)),
|
|
63
|
+
incrementalencoder=codecs.utf_8_encode,
|
|
64
|
+
incrementaldecoder=JavaInterfaceDecoder,
|
|
65
|
+
streamreader=lambda stream, errors='strict': io.StringIO(traduzir_sintaxe_java(stream.read().decode('utf-8'))),
|
|
66
|
+
streamwriter=codecs.utf_8_encode
|
|
67
|
+
)
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
def registrar_syntax():
|
|
71
|
+
"""Registra o tradutor de código dentro do núcleo de encodings do Python"""
|
|
72
|
+
codecs.register(buscar_codec)
|
|
@@ -1,116 +0,0 @@
|
|
|
1
|
-
import codecs
|
|
2
|
-
import io
|
|
3
|
-
import re
|
|
4
|
-
|
|
5
|
-
def converter_tipos_java_para_python(argumentos_str: str) -> str:
|
|
6
|
-
"""
|
|
7
|
-
Transforma 'String titular, int idade' em 'titular: str, idade: int'.
|
|
8
|
-
Também garante que o 'self' seja mantido corretamente se o usuário colocar.
|
|
9
|
-
"""
|
|
10
|
-
mapa_tipos = {
|
|
11
|
-
'String': 'str',
|
|
12
|
-
'int': 'int',
|
|
13
|
-
'double': 'float',
|
|
14
|
-
'float': 'float',
|
|
15
|
-
'boolean': 'bool',
|
|
16
|
-
'void': 'None',
|
|
17
|
-
'List': 'list',
|
|
18
|
-
'Map': 'dict'
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
argumentos_limpos = argumentos_str.strip()
|
|
22
|
-
if not argumentos_limpos:
|
|
23
|
-
return "self"
|
|
24
|
-
|
|
25
|
-
partes = [p.strip() for p in argumentos_limpos.split(',')]
|
|
26
|
-
novos_args = []
|
|
27
|
-
|
|
28
|
-
# CORREÇÃO AQUI: Verificamos se 'self' está contido na lista de partes
|
|
29
|
-
if len(partes) > 0 and partes[0] == 'self':
|
|
30
|
-
novos_args.append('self')
|
|
31
|
-
partes = partes[1:]
|
|
32
|
-
else:
|
|
33
|
-
# Injeta o 'self' automaticamente (padrão Java puro)
|
|
34
|
-
novos_args.append('self')
|
|
35
|
-
|
|
36
|
-
for parte in partes:
|
|
37
|
-
if not parte:
|
|
38
|
-
continue
|
|
39
|
-
componentes = re.split(r'\s+', parte)
|
|
40
|
-
if len(componentes) == 2:
|
|
41
|
-
tipo_java, nome_var = componentes
|
|
42
|
-
tipo_python = mapa_tipos.get(tipo_java, tipo_java)
|
|
43
|
-
novos_args.append(f"{nome_var}: {tipo_python}")
|
|
44
|
-
else:
|
|
45
|
-
novos_args.append(parte)
|
|
46
|
-
|
|
47
|
-
return ", ".join(novos_args)
|
|
48
|
-
|
|
49
|
-
def traduzir_sintaxe_java(texto: str) -> str:
|
|
50
|
-
"""
|
|
51
|
-
Varre o arquivo de texto substituindo a sintaxe 'Interface Nome { ... }'
|
|
52
|
-
por classes Python puras usando abc.ABC, tipagem estrita e @abstractmethod.
|
|
53
|
-
"""
|
|
54
|
-
linhas = texto.split('\n')
|
|
55
|
-
resultado = ["from abc import ABC, abstractmethod\n"]
|
|
56
|
-
dentro_da_interface = False
|
|
57
|
-
|
|
58
|
-
for linha in linhas:
|
|
59
|
-
# 1. Detecta o início da declaração: 'Interface Nome {'
|
|
60
|
-
inicio_match = re.match(r'\s*Interface\s+(\w+)\s*\{', linha)
|
|
61
|
-
if inicio_match:
|
|
62
|
-
nome_interface = inicio_match.group(1)
|
|
63
|
-
resultado.append(f"class {nome_interface}(ABC):")
|
|
64
|
-
dentro_da_interface = True
|
|
65
|
-
continue
|
|
66
|
-
|
|
67
|
-
if dentro_da_interface:
|
|
68
|
-
# 2. Detecta o fechamento da interface com a chave '}'
|
|
69
|
-
if '}' in linha:
|
|
70
|
-
dentro_da_interface = False
|
|
71
|
-
continue
|
|
72
|
-
|
|
73
|
-
# 3. Captura o método com padrão Java: TipoRetorno nomeMetodo(Argumentos)
|
|
74
|
-
linha_limpa = linha.strip().replace(';', '')
|
|
75
|
-
if linha_limpa:
|
|
76
|
-
metodo_match = re.match(r'(?:\w+\s+)?(\w+)\s*\((.*?)\)', linha_limpa)
|
|
77
|
-
if metodo_match:
|
|
78
|
-
nome_metodo = metodo_match.group(1)
|
|
79
|
-
args_brutos = metodo_match.group(2)
|
|
80
|
-
|
|
81
|
-
args_traduzidos = converter_tipos_java_para_python(args_brutos)
|
|
82
|
-
|
|
83
|
-
resultado.append(f" @abstractmethod")
|
|
84
|
-
resultado.append(f" def {nome_metodo}({args_traduzidos}):")
|
|
85
|
-
resultado.append(f" pass")
|
|
86
|
-
else:
|
|
87
|
-
resultado.append(linha)
|
|
88
|
-
|
|
89
|
-
return '\n'.join(resultado)
|
|
90
|
-
|
|
91
|
-
# --- INFRAESTRUTURA DE CODEC DO PYTHON ---
|
|
92
|
-
|
|
93
|
-
class JavaInterfaceDecoder(codecs.BufferedIncrementalDecoder):
|
|
94
|
-
def _buffer_decode(self, input, errors, final):
|
|
95
|
-
if final:
|
|
96
|
-
dados_em_bytes = bytes(input)
|
|
97
|
-
texto_traduzido = traduzir_sintaxe_java(dados_em_bytes.decode('utf-8'))
|
|
98
|
-
return (texto_traduzido, len(input))
|
|
99
|
-
return ('', 0)
|
|
100
|
-
|
|
101
|
-
def buscar_codec(nome_codec):
|
|
102
|
-
if nome_codec == 'py_interface':
|
|
103
|
-
return codecs.CodecInfo(
|
|
104
|
-
name='py_interface',
|
|
105
|
-
encode=codecs.utf_8_encode,
|
|
106
|
-
decode=lambda input, errors='strict': (traduzir_sintaxe_java(bytes(input).decode('utf-8')), len(input)),
|
|
107
|
-
incrementalencoder=codecs.utf_8_encode,
|
|
108
|
-
incrementaldecoder=JavaInterfaceDecoder,
|
|
109
|
-
streamreader=lambda stream, errors='strict': io.StringIO(traduzir_sintaxe_java(stream.read().decode('utf-8'))),
|
|
110
|
-
streamwriter=codecs.utf_8_encode
|
|
111
|
-
)
|
|
112
|
-
return None
|
|
113
|
-
|
|
114
|
-
def registrar_syntax():
|
|
115
|
-
"""Registra o tradutor de código dentro do núcleo de encodings do Python"""
|
|
116
|
-
codecs.register(buscar_codec)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|