Project 3 - Interpreter and Type-checker for Switch Statement#11
Open
PauloV1 wants to merge 14 commits into
Open
Project 3 - Interpreter and Type-checker for Switch Statement#11PauloV1 wants to merge 14 commits into
PauloV1 wants to merge 14 commits into
Conversation
- Add scripts/minic wrapper script for convenient access to mini_c binary - Add .envrc configuration for automatic direnv activation - Allows using 'minic' command as documented in README
Introduce the variant in to represent switch-case control flow, including a target expression, literal cases with their bodies, and a default branch.
Parse switch statements in statements.rs, including the target expression, one or more case branches (integer and boolean literals), and a mandatory default block. Ensure each case and default contains at least one statement.
Add todo!() stubs for Statement::Switch in both type checking and evaluation phases to satisfy exhaustive pattern matching and keep the project compiling.
Replaced the mutable closures case_parse and default_parse with declarative nom combinators (tuple and map) inside the switch parser. This removes the need for mutable state in sub-parsers and makes the parsing logic more idiomatic and cohesive.
Implement type checker and interpreter for Switch statement
- Implement semantic check to reject duplicate cases in a switch block - fix: make literal pattern matching exhaustive by returning a TypeError for unsupported types
- Implement runtime/evaluation check for duplicate labels in switch cases - fix: import from AST module to resolve scope compilation error
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Descrição Geral
Este PR implementa o suporte completo à estrutura condicional
switchna linguagem MiniC. A implementação abrange desde a validação semântica (Type-Checker), execução de código (Interpreter) e uma ampla suíte de testes de integração.Detalhes das Implementações
1. Type-Checker (
src/semantic/type_checker.rs)Implementação de regras semânticas estritas para o nó
Statement::Switch:target): O tipo da expressão avaliada deve ser estritamenteType::IntouType::Bool.casedeve coincidir ou ser compatível com o tipo dotarget.case) duplicados.casee dodefaulté analisado dentro de um escopo isolado utilizando o mecanismo deenv.snapshot()eenv.restore(). Isso impede:casepara o escopo externo.switch.2. Interpretador (
src/interpreter/exec_stmt.rs)Execução em tempo de execução da instrução
switch:cases(gerandoRuntimeErrorpara duplicados).target) e busca linear pelocasecorrespondente. Se nenhum corresponder, o blocodefaulté selecionado.switchsão isoladas usandoenv.names()no início eenv.remove_new()na saída do bloco.returnantecipado de dentro de umcase, o escopo é limpo corretamente antes de propagar o valor de retorno.Cobertura de Testes
Os testes implementados cobrem todos os cenários de sucesso e caminhos de erro esperados.
Testes do Type-Checker (
tests/type_checker.rs)test_type_check_switch_int_ok: Validação bem-sucedida de chaves inteiras.test_type_check_switch_bool_ok: Validação bem-sucedida de chaves booleanas.test_type_check_switch_mismatched_case_type: Erro ao usar umcase boolem umswitch int.test_type_check_switch_unsupported_target_type: Erro ao tentar usarfloatcomo target.test_type_check_switch_duplicate_case_labels: Detecção decaseduplicado.test_type_check_switch_cross_branch_pollution_err: Garante que variáveis declaradas em um ramo não sejam vistas em outro.test_type_check_switch_independent_branches_ok: Permite redefinição da mesma variável em ramos paralelos distintos.test_type_check_switch_scope_leak_err: Garante que variáveis internas não vazem para o escopo que sucede oswitch.Testes do Interpretador (
tests/interpreter.rs)test_switch_exec_match_case: Desvio de fluxo correto para ocasecorrespondente.test_switch_exec_match_default: Execução dodefaultquando não há correspondência.test_switch_exec_early_return: Retorno de valor a partir de funções contendo umswitch.test_switch_exec_scoping: Validação em tempo de execução de que variáveis declaradas no switch deixam de existir após o bloco.test_switch_exec_duplicate_error: Erro em tempo de execução ao encontrar labels duplicadas.test_switch_exec_bool_cases: Execução com chaves booleanas.test_switch_exec_complex_target: Avaliação dinâmica do target utilizando expressões (ex:switch a + b).