Um compilador completo implementado em Python para fins educacionais
Características • Instalação • Uso • Arquitetura • Exemplos • Equipe
Este é um mini-compilador acadêmico desenvolvido para a disciplina de Compiladores. O projeto implementa todas as fases clássicas de um compilador, desde a análise léxica até a geração de código assembly, seguindo a arquitetura pipeline moderna.
Este projeto foi desenvolvido por:
- Lucas Farias (@Kl4uz)
- José Lucas (@lalisalix)
- Ester Arraiz (@esterarraiz)
- Laura Barbosa (@tinywin)
- Henrique Noronha (@henrique-noronha)
- ✅ Implementar um analisador léxico (tokenização)
- ✅ Construir um analisador sintático (parser)
- ✅ Gerar uma Árvore Sintática Abstrata (AST)
- ✅ Realizar análise semântica (tipos e escopos)
- ✅ Gerar código intermediário (TAC - Three-Address Code)
- ✅ Aplicar otimizações (constant folding, dead code elimination)
- ✅ Gerar código assembly final
- ✅ Simular ambientes de execução (runtime stack)
| Recurso | Status | Descrição |
|---|---|---|
| Análise Léxica | ✅ | Tokenização com suporte a funções, operadores e palavras-chave |
| Análise Sintática | ✅ | Parser completo com detecção de erros |
| AST | ✅ | Construção de árvore sintática abstrata |
| Análise Semântica | ✅ | Verificação de tipos e escopos |
| Tabela de Símbolos | ✅ | Gerenciamento de escopos aninhados |
| Código Intermediário | ✅ | Geração de TAC (Three-Address Code) |
| Otimização | ✅ | Constant folding, dead code elimination, peephole |
| Geração de Assembly | ✅ | Código assembly otimizado |
| Runtime Stack | ✅ | Simulação de pilha de ativação |
| Funções | ✅ | Suporte completo a funções com parâmetros |
// Exemplo de código suportado
int soma(int a, int b) {
int resultado = a + b;
return resultado;
}
int main() {
int x = 10;
int y = 20;
int total = soma(x, y);
print(total);
if (total > 25) {
print(1);
} else {
print(0);
}
return 0;
}Suporte a:
- ✅ Tipos:
int - ✅ Variáveis locais e globais
- ✅ Funções com parâmetros e retorno
- ✅ Expressões aritméticas:
+,-,*,/ - ✅ Operadores relacionais:
<,>,==,!=,<=,>= - ✅ Estruturas de controle:
if/else,while - ✅ Impressão:
print()
- Python 3.8+
- pip (gerenciador de pacotes Python)
- Clone o repositório
git clone https://github.com/Kl4uz/compilador-python.git
cd compilador-python- Crie um ambiente virtual (recomendado)
# Linux/Mac
python3 -m venv venv
source venv/bin/activate
# Windows
python -m venv venv
venv\Scripts\activate- Instale as dependências
pip install -r requirements.txt- Verifique a instalação
python run.py --versionO compilador oferece 3 modos de uso diferentes:
Compile código diretamente no terminal usando a flag -e:
python run.py -e "x = 5 + 3; print(x);"Exemplo com saída:
$ python run.py -e "int x = 10 + 5;"
🔍 [1/7] Análise Léxica...
✓ 7 tokens gerados
🌳 [2/7] Análise Sintática...
✓ Árvore de parsing construída
🎯 [3/7] Construção da AST...
✓ AST gerada
🔬 [4/7] Análise Semântica...
✓ Análise semântica concluída
⚙️ [5/7] Geração de Código Intermediário...
✓ 2 instruções TAC geradas
⚡ [6/7] Otimização...
✓ Otimizado: 2 → 1 instruções
🎯 [7/7] Geração de Assembly...
✓ 3 instruções assembly geradas
✅ Compilação bem-sucedida!Compile um arquivo de código usando a flag -f:
python run.py -f examples/hello_world.txtExemplo:
$ python run.py -f examples/functions.txt
📄 Compilando arquivo: examples/functions.txt
🔍 [1/7] Análise Léxica...
✓ 45 tokens gerados
🌳 [2/7] Análise Sintática...
✓ Árvore de parsing construída
...
✅ Compilação bem-sucedida!Execute sem argumentos para entrar no modo interativo:
python run.py╔════════════════════════════════════════════╗
║ MINI-COMPILADOR PYTHON v1.0 ║
║ Modo Interativo (REPL) ║
╚════════════════════════════════════════════╝
Digite seu código (ou 'exit' para sair):
>>> int x = 10;
✓ Compilado com sucesso!
>>> print(x);
✓ Compilado com sucesso!
>>> OUTPUT: 10
>>> exit
Até logo! 👋
| Flag | Descrição | Exemplo |
|---|---|---|
-e, --expr |
Compila expressão inline | python run.py -e "x = 5;" |
-f, --file |
Compila arquivo | python run.py -f code.txt |
-v, --verbose |
Modo verboso (detalhado) | python run.py -f code.txt -v |
-q, --quiet |
Modo silencioso | python run.py -f code.txt -q |
-o, --output |
Salva assembly em arquivo | python run.py -f code.txt -o out.asm |
--no-optimize |
Desativa otimizações | python run.py -e "x=2*3;" --no-optimize |
--show-tokens |
Mostra tokens gerados | python run.py -e "x=5;" --show-tokens |
--show-ast |
Mostra AST gerada | python run.py -e "x=5;" --show-ast |
--show-ir |
Mostra código intermediário | python run.py -e "x=5;" --show-ir |
--version |
Mostra versão | python run.py --version |
--help |
Mostra ajuda | python run.py --help |
Mostra todos os passos da compilação:
python run.py -f examples/hello_world.txt -vSaída:
============================================================
📄 CÓDIGO FONTE
============================================================
int main() {
int x = 10;
print(x);
return 0;
}
============================================================
🔍 FASE 1: ANÁLISE LÉXICA
============================================================
Token 1: INT (type: keyword)
Token 2: MAIN (type: identifier)
Token 3: LPAREN (type: delimiter)
...
============================================================
🌳 FASE 2: ÁRVORE SINTÁTICA
============================================================
program
├── function_def (main)
│ └── block
│ ├── declaration (x)
│ ├── print_stmt
│ └── return_stmt
...
Mostra apenas erros (útil para CI/CD):
python run.py -f examples/hello_world.txt -qSaída apenas se houver erro:
❌ ERRO na linha 5: Variável 'y' não declarada
python run.py -f examples/functions.txt -o output.asmGera arquivo output.asm:
; Código gerado pelo Mini-Compilador v1.0
; Data: 2025-11-28 14:30:00
LOAD R1, 10
STORE x, R1
LOAD R1, x
PRINT R1
HALTVer apenas os tokens:
python run.py -e "x = 5 + 3;" --show-tokensVer apenas a AST:
python run.py -e "x = 5 + 3;" --show-astVer apenas o código intermediário (TAC):
python run.py -e "x = 5 + 3;" --show-irVer tudo:
python run.py -e "x = 5 + 3;" --show-tokens --show-ast --show-ir -vSem otimização:
python run.py -e "x = 2 * 3;" --no-optimize --show-irTAC Gerado:
t1 = 2 * 3
x = t1
Com otimização (padrão):
python run.py -e "x = 2 * 3;" --show-irTAC Otimizado:
x = 6
┌─────────────────┐
│ Código Fonte │
└────────┬────────┘
│
▼
┌─────────────────┐
│ 1. Léxico │ ─────► Tokens
│ (lexer.py) │
└────────┬────────┘
│
▼
┌─────────────────┐
│ 2. Sintático │ ─────► Parse Tree
│ (parser.py) │
└────────┬────────┘
│
▼
┌─────────────────┐
│ 3. AST Builder │ ─────► AST
│ (ast_builder.py)│
└────────┬────────┘
│
▼
┌─────────────────┐
│ 4. Semântico │ ─────► AST Anotada
│ (semantic.py) │ + Tabela Símbolos
└────────┬────────┘
│
▼
┌─────────────────┐
│ 5. Gerador IR │ ─────► TAC
│(ir_generator.py)│
└────────┬────────┘
│
▼
┌─────────────────┐
│ 6. Otimizador │ ─────► TAC Otimizado
│ (optimizer.py) │
└────────┬────────┘
│
▼
┌─────────────────┐
│ 7. Gerador Asm │ ─────► Assembly
│ (codegen.py) │
└────────┬────────┘
│
▼
┌─────────────────┐
│ Assembly Final │
└─────────────────┘
compilador-python/
├── README.md # Este arquivo
├── requirements.txt # Dependências Python
├── .gitignore # Arquivos ignorados
│
├── src/ # 📂 Código fonte
│ ├── __init__.py
│ ├── main.py # 🎯 Ponto de entrada (CLI)
│ ├── compiler.py # 🔧 Pipeline principal
│ ├── lexer.py # 📝 Analisador léxico
│ ├── parser.py # 🌳 Analisador sintático
│ ├── ast_builder.py # 🎯 Construtor de AST
│ ├── semantic.py # 🔬 Análise semântica
│ ├── symbol_table.py # 📊 Tabela de símbolos
│ ├── ir_generator.py # ⚙️ Gerador de código intermediário
│ ├── optimizer.py # ⚡ Otimizador
│ ├── codegen.py # 🎯 Gerador de assembly
│ ├── runtime.py # 🏃 Runtime stack simulation
│ └── interpreter.py # 🎮 Interpretador TAC
│
├── tests/ # 🧪 Testes
│ ├── test_lexer.py
│ ├── test_parser.py
│ ├── test_semantic.py
│ ├── test_ir.py
│ ├── test_optimizer.py
│ ├── test_codegen.py
│ └── test_pipeline.py # Teste de integração
│
├── examples/ # 📚 Exemplos de código
│ ├── hello_world.txt # Exemplo básico
│ ├── functions.txt # Funções
│ ├── control_flow.txt # If/While
│ └── optimization.txt # Demonstração de otimizações
│
└── docs/ # 📖 Documentação
├── grammar.md # Gramática da linguagem
├── pipeline.md # Arquitetura do pipeline
└── ETAPA7_AMBIENTES_EXECUCAO.md
Arquivo: examples/hello_world.txt
int main() {
int x = 42;
print(x);
return 0;
}Execução:
python run.py -f examples/hello_world.txtAssembly Gerado:
LOAD R1, 42
STORE x, R1
LOAD R1, x
PRINT R1
HALTArquivo: examples/functions.txt
int soma(int a, int b) {
return a + b;
}
int main() {
int resultado = soma(10, 20);
print(resultado);
return 0;
}Execução:
python run.py -f examples/functions.txt -vTAC Gerado:
FUNCTION soma
PARAM a
PARAM b
t1 = a + b
RETURN t1
END_FUNCTION
FUNCTION main
t2 = CALL soma, 10, 20
resultado = t2
PRINT resultado
RETURN 0
END_FUNCTION
Código:
int main() {
int x = 2 * 3 + 5;
print(x);
return 0;
}Sem otimização:
python run.py -f examples/optimization.txt --no-optimize --show-irTAC:
t1 = 2 * 3
t2 = t1 + 5
x = t2
PRINT x
Com otimização (padrão):
python run.py -f examples/optimization.txt --show-irTAC Otimizado:
x = 11
PRINT x
Arquivo: examples/control_flow.txt
int main() {
int x = 10;
if (x > 5) {
print(1);
} else {
print(0);
}
int i = 0;
while (i < 3) {
print(i);
i = i + 1;
}
return 0;
}Execução:
python run.py -f examples/control_flow.txtSaída:
>>> OUTPUT: 1
>>> OUTPUT: 0
>>> OUTPUT: 1
>>> OUTPUT: 2
pytest tests/ -v# Testar apenas o lexer
pytest tests/test_lexer.py -v
# Testar apenas o pipeline completo
pytest tests/test_pipeline.py -vpytest tests/ --cov=src --cov-report=htmlAbre o relatório: open htmlcov/index.html
O compilador detecta e reporta diversos tipos de erros:
$ python run.py -e "int x = @;"
❌ ERRO LÉXICO (linha 1, coluna 9):
Caractere inválido: '@'$ python run.py -e "int x = 5"
❌ ERRO SINTÁTICO (linha 1):
Esperado ';' após declaração$ python run.py -e "x = y + 5;"
❌ ERRO SEMÂNTICO (linha 1):
Variável 'y' não declarada$ python run.py -e "int x = 5; x = 10 + 20 + 30;"
❌ ERRO SEMÂNTICO (linha 1):
Variável 'x' já declarada neste escopoVeja a gramática completa em: docs/grammar.md
Resumo:
<program> ::= <stmt_list>
<stmt_list> ::= <stmt> | <stmt> <stmt_list>
<stmt> ::= <assign_stmt> | <if_stmt> | <while_stmt> | <print_stmt>
<expr> ::= <term> (('+' | '-') <term>)*
<term> ::= <factor> (('*' | '/') <factor>)*
<factor> ::= <number> | <id> | '(' <expr> ')'
Documentação detalhada: docs/pipeline.md
Detalhes sobre runtime stack: docs/ETAPA7_AMBIENTES_EXECUCAO.md
Este projeto está sob a licença MIT. Veja o arquivo LICENSE para mais detalhes.
- Aho, A. V., Lam, M. S., Sethi, R., & Ullman, J. D. (2006). Compilers: Principles, Techniques, and Tools (2nd ed.). Pearson.
- Cooper, K. D., & Torczon, L. (2011). Engineering a Compiler (2nd ed.). Morgan Kaufmann.
- Appel, A. W. (2004). Modern Compiler Implementation in Java (2nd ed.). Cambridge University Press.
⭐ Se este projeto foi útil, considere dar uma estrela no repositório! ⭐
Desenvolvido com ❤️ para a disciplina de Compiladores