From d9b023c550e27ad8d6c01003f90b3cb917dc98d8 Mon Sep 17 00:00:00 2001 From: saqut Date: Thu, 18 Jun 2026 17:20:06 +0300 Subject: [PATCH] =?UTF-8?q?feat(faz3):=20semantik=20analiz=20=E2=80=94=20t?= =?UTF-8?q?ip=20denetimi=20+=20yap=C4=B1sal=20do=C4=9Frulama=20(#72)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - src/semantic/type_checker: her ExpressionNode'a resolvedType atar * literal bağlama-göre tiplenir (float x = 1 → uyarısız) * değişken→değişken genişletme → W004 * daraltma / farklı tip → E003 * fonksiyon çağrısı argüman sayısı/tipi → E008 * return tipi uyumsuzluğu → E003 (checkAssign üzerinden) - src/semantic/structural_validator: kontrol akışı kuralları * break/continue döngü dışı → E004 * return fonksiyon dışı → E005 - W004 diagnostic kataloğa eklendi - saqut check komutu: tokenize→parse→collect→typecheck→validate - examples/semantic/: widening, narrowing, bad_return, break_outside, bad_args - MISSION-FAZ3.md eklendi Doğrulama: fibonacci.sqt → 0 hata 0 uyarı ✓ widening.sqt → W004 ✓ narrowing.sqt → E003 ✓ break_outside.sqt → E004 ✓ bad_args.sqt → E008 ✓ tests/run.sh → TUM TESTLER GECTI ✓ Co-Authored-By: Claude Opus 4.8 --- MISSION-FAZ3.md | 326 ++++++++++++++++++++++ build/.ninja_deps | Bin 64224 -> 48404 bytes build/.ninja_log | 52 ++-- build/build.ninja | 20 +- examples/semantic/bad_args.sqt | 9 + examples/semantic/bad_return.sqt | 8 + examples/semantic/break_outside.sqt | 5 + examples/semantic/narrowing.sqt | 5 + examples/semantic/widening.sqt | 7 + src/cli/args.hpp | 4 +- src/cli/commands/check.hpp | 59 ++++ src/diagnostic/diagnostic.hpp | 1 + src/main.cpp | 5 + src/semantic/structural_validator.cpp | 95 +++++++ src/semantic/structural_validator.hpp | 22 ++ src/semantic/type_checker.cpp | 384 ++++++++++++++++++++++++++ src/semantic/type_checker.hpp | 41 +++ 17 files changed, 1007 insertions(+), 36 deletions(-) create mode 100644 MISSION-FAZ3.md create mode 100644 examples/semantic/bad_args.sqt create mode 100644 examples/semantic/bad_return.sqt create mode 100644 examples/semantic/break_outside.sqt create mode 100644 examples/semantic/narrowing.sqt create mode 100644 examples/semantic/widening.sqt create mode 100644 src/cli/commands/check.hpp create mode 100644 src/semantic/structural_validator.cpp create mode 100644 src/semantic/structural_validator.hpp create mode 100644 src/semantic/type_checker.cpp create mode 100644 src/semantic/type_checker.hpp diff --git a/MISSION-FAZ3.md b/MISSION-FAZ3.md new file mode 100644 index 0000000..40bb6cd --- /dev/null +++ b/MISSION-FAZ3.md @@ -0,0 +1,326 @@ +# MISSION — Faz 3: Semantik Analiz (Gitea #72) + +> **Bu dosya kendi kendine yeter.** "MISSION-FAZ3'ü oku ve yap" denince +> doğrudan uygula. Bitince DOĞRULAMA bölümünü çalıştır, #72'ye tamamlanma +> yorumu düş, bu dosyayı sil veya MISSION-FAZ4.md ile değiştir. +> `Co-Authored-By: Claude Opus 4.8` trailer'ı unutma. + +--- + +## 0) HEDEF & BAŞARI KRİTERLERİ (#72) + +İki modül: **TypeChecker** (her ExpressionNode'a tip ata) + +**StructuralValidator** (kontrol akışı kuralları). + +Bitti tanımı: +1. `build/saqut check file:examples/fibonacci.sqt` → 0 hata 0 uyarı; her + expression node'unun `resolvedType` alanı JSON'da dolu. +2. `examples/semantic/` test fixture'ları doğru hata/uyarı üretiyor. +3. `-Wall -Wextra` temiz. Faz 0/1/2 testleri hâlâ geçer. + +--- + +## 1) DÖNÜŞÜM KURALLARI (ADR-010 özeti) + +| Durum | Sonuç | Kod | +|---|---|---| +| `float x = 1` | Geçerli — literal 1.0 sayılır | — | +| `double x = 1` | Geçerli | — | +| `float x = intVar` | **Uyarı** — örtük genişletme, veri kaybı yok | W004 | +| `double x = intVar` | **Uyarı** | W004 | +| `double x = floatVar` | **Uyarı** | W004 | +| `int x = 1.5` | **Hata** — literal'den veri kaybı | E003 | +| `int x = floatVar` | **Hata** — daraltma | E003 | +| `float x = doubleVar` | **Hata** — daraltma | E003 | +| `int x = intVar` | Geçerli | — | + +**Kural özeti:** +- Literal bağlama-göre tiplenir: hedef tip daha geniş veya aynıysa uyarısız geçer. +- Değişken→değişken: genişletme (widening) = W004, daraltma (narrowing) = E003. +- Aynı tip = her zaman geçerli. + +**Yardımcı fonksiyon (type_checker içinde):** +```cpp +enum class ConvResult { Ok, Warn_W004, Error_E003 }; +ConvResult checkAssignCompat(const Type& target, const Type& src, bool srcIsLiteral); +``` + +--- + +## 2) KATALOG GÜNCELLEMESİ + +`src/diagnostic/diagnostic.hpp` → W004 ekle: +```cpp +{"W004", DiagLevel::Warning, "Örtük sayısal genişletme (widening)"}, +``` + +--- + +## 3) DOSYA DOSYA PLAN + +Yeni dizin: `src/semantic/`. CMake GLOB_RECURSE → yeni `.cpp`'ler otomatik +alınır ama `build.sh` ile derle (cmake yeniden config eder). + +--- + +### 3.1 `src/semantic/type_checker.hpp` + +```cpp +#ifndef SAQUT_SEMANTIC_TYPE_CHECKER +#define SAQUT_SEMANTIC_TYPE_CHECKER + +#include "symbol/symbol_table.hpp" +#include "diagnostic/diagnostic_engine.hpp" +#include "parser/ast_node.hpp" +#include "core/type.hpp" + +class TypeChecker { +public: + TypeChecker(SymbolTable& table, DiagnosticEngine& diag) + : table_(table), diag_(diag) {} + + void check(ASTNode* program); + +private: + // İfadeyi gez, resolvedType ata, tipi döndür. + // expectedType: bağlam tipi (literal genişletme için); boş = bilinmiyor. + Type checkExpr(ASTNode* node, const Type& expected = Type::error()); + + // Deyimi gez (statement'lar tip döndürmez). + void checkStmt(ASTNode* node); + + // Fonksiyon gövdesini gez; dönüş tipi bağlamını stack'te tut. + void checkFunction(ASTNode* fnNode); + + // Atama uyumunu denetle; uyarı/hata raporla. true = geçerli. + bool checkAssign(const Type& target, const Type& src, + bool srcIsLiteral, const SourceLocation& loc, + const std::string& context); + + SymbolTable& table_; + DiagnosticEngine& diag_; + + // Aktif fonksiyonun beklenen dönüş tipi (iç içe fonksiyon yok, stack + // yerine tek değer yeterli). + Type currentReturnType_; + bool inFunction_ = false; +}; + +#endif // SAQUT_SEMANTIC_TYPE_CHECKER +``` + +--- + +### 3.2 `src/semantic/type_checker.cpp` + +`check(program)`: +- Program children'ı gez: FunctionDecl → `checkFunction`, VariableDecl → + `checkStmt`, StructDecl → atla. + +`checkFunction(fnNode)`: +- `inFunction_ = true; currentReturnType_ = typeFromReturnType(fn->returnType);` +- `checkStmt(body)` (body = children[0]) +- `inFunction_ = false;` + +`checkStmt(node)` — switch(node->kind): +- **Block**: her child → `checkStmt`. +- **VariableDecl**: initExpr varsa `checkExpr(initExpr, typeFromName(vd->varType))`; + sonucu target tiple `checkAssign` ile denetle. +- **ExpressionStatement**: `checkExpr(es->expression)`. +- **ReturnStatement**: value varsa `checkExpr(value, currentReturnType_)`; + sonucu `checkAssign(currentReturnType_, valueType, isLiteral, loc, "return")`. + Değer yok ve returnType != void → E006. +- **IfStatement**: condition checkExpr (bool beklenir, ama şimdilik herhangi + sayısal tip de geçerli — E003 değil, TODO Faz3+); then/else checkStmt. +- **WhileStatement / DoWhileStatement**: condition checkExpr; body checkStmt. +- **ForStatement**: init checkStmt; condition checkExpr; update checkExpr; body checkStmt. +- **Break / Continue / ExpressionStatement**: içerik checkExpr. +- **ReturnStatement**: yukarıda. + +`checkExpr(node, expected)` — switch(node->kind) → Type döndürür: +- **Literal(INTEGER)**: + - expected sayısal ve daha geniş veya aynıysa → `expected` tipini döndür + (literal 1.0 olarak tiplenir, uyarısız). + - expected int veya error → `Type::Int()`. + - expected float literal'e uymuyor (ör. expected=int, literal=FLOAT) → E003. +- **Literal(FLOAT)**: expected double ise double döndür (kayıpsız); expected int → E003; + aksi → `Type::Float()`. +- **Literal(BOOLEAN)**: `Type::Bool()`. +- **Literal(STRING)**: `Type::String()`. +- **Literal(BOŞ)**: `Type::error()` (null — Faz 3+ kapsam dışı). +- **Identifier**: `id->resolvedSymbol ? id->resolvedSymbol->type : Type::error()`. + Type::error() ise E001 zaten Faz 2'de raporlandı, sessiz geç. +- **BinaryExpression**: + - Atama operatörü (EQUAL, +=, -=, vb.): + - left = `checkExpr(left)`, right = `checkExpr(right, leftType)`. + - `checkAssign(leftType, rightType, isLiteralRight, loc, "atama")`. + - `resolvedType = leftType`. + - Aritmetik (+, -, *, /, %): + - Her iki operandı `checkExpr` et. + - İkisi de sayısal ve aynı tip → sonuç o tip. + - İkisi sayısal farklı tip → `checkAssign` mantığıyla uyar/hata; sonuç + daha geniş tip (veya E003 durumunda error). + - Sayısal değil → E003, `Type::error()`. + - Karşılaştırma (==, !=, <, <=, >, >=): + - Operandları checkExpr; uyumlu sayısal veya aynı tip → `Type::Bool()`. + - Uyumsuz → E003, `Type::Bool()` (hata yayılmasın, bool olarak devam). + - Mantıksal (&&, ||): + - Her iki operand bool beklenir; değilse E003. + - Sonuç `Type::Bool()`. + - Unary prefix (-, +, !): + - Left = nullptr; Right = operand. + - `-`/`+`: sayısal beklenir; `!`: bool beklenir. + - resolvedType'a sonucu ata. +- **Call**: + - callee = `checkExpr(callee)` → Function tipi beklenir. + - Argüman sayısı imzayla eşleşmeli → E008. + - Her argüman: `checkExpr(arg, paramType[i])` → `checkAssign(paramType, argType, ...)`. + - resolvedType = callee tipi's `returnType`. +- **Postfix (++/--)**: operand sayısal → sonuç aynı tip; değilse E003. +- **MemberAccess**: `Type::error()` + TODO (struct alan çözümü Faz 3+). +- **IndexExpression**: TODO; `Type::error()`. + +`checkAssign(target, src, srcIsLiteral, loc, ctx)`: +- target veya src = error → `return true` (sessiz geç, hata zaten raporlandı). +- target == src → `return true`. +- Genişletme (widening): + - `int → float`: srcIsLiteral → geçerli (**uyarısız**); değil → **W004**. + - `int → double`, `float → double`: aynı kural. + - srcIsLiteral ve kayıpsız → `return true`. + - srcIsLiteral değil → W004 raporla, `return true` (yine de geçerli). +- Daraltma (narrowing): + - `float → int`, `double → int`, `double → float` → **E003**, `return false`. +- Tamamen farklı tipler (int ↔ string, vb.) → **E003**, `return false`. + +> `srcIsLiteral`: `node->kind == ASTKind::Literal` ise true. + +--- + +### 3.3 `src/semantic/structural_validator.hpp` + +```cpp +#ifndef SAQUT_SEMANTIC_STRUCTURAL_VALIDATOR +#define SAQUT_SEMANTIC_STRUCTURAL_VALIDATOR + +#include "diagnostic/diagnostic_engine.hpp" +#include "parser/ast_node.hpp" + +class StructuralValidator { +public: + StructuralValidator(DiagnosticEngine& diag) : diag_(diag) {} + void validate(ASTNode* program); + +private: + void walkDecl(ASTNode* node); + void walkStmt(ASTNode* node); + + DiagnosticEngine& diag_; + int loopDepth_ = 0; + bool inFunction_ = false; +}; + +#endif // SAQUT_SEMANTIC_STRUCTURAL_VALIDATOR +``` + +--- + +### 3.4 `src/semantic/structural_validator.cpp` + +`validate(program)`: her top-level child → `walkDecl`. + +`walkDecl`: +- FunctionDecl: `inFunction_=true`, `walkStmt(body)`, `inFunction_=false`. +- VariableDecl / StructDecl: atla. + +`walkStmt(node)` — switch: +- **Block**: her child `walkStmt`. +- **IfStatement**: then/else `walkStmt`. +- **WhileStatement / DoWhileStatement**: `loopDepth_++; walkStmt(body); loopDepth_--;` +- **ForStatement**: `loopDepth_++; walkStmt(init?); walkStmt(body); loopDepth_--;` +- **BreakStatement**: `loopDepth_ == 0` → E004. +- **ContinueStatement**: `loopDepth_ == 0` → E004. +- **ReturnStatement**: `!inFunction_` → E005. + (Return tip uyumu TypeChecker'ın işi; burada sadece yapısal kural.) +- **ExpressionStatement / VariableDecl**: `walkStmt` çocukları için yinele. +- Diğer: atla. + +--- + +## 4) CLI — `saqut check` KOMUTU + +### 4.1 `src/cli/commands/check.hpp` + +```cpp +inline int cmdCheck(const CliArgs& args) { + // tokenize → parse → symbolCollect → typeCheck → structValidate + // Tüm hatalar DiagnosticEngine'de toplanır. + // Çıktı: JSON (--compact destekli) + // {"file":"...","diagnostics":{...}} + // exit code: hasErrors() ? 1 : 0 +} +``` + +### 4.2 `src/cli/cli.hpp` veya `main.cpp` + +`check` komutu kaydet; `parseArgs` tanımlı komutlar listesine ekle. + +--- + +## 5) TEST FIXTURE'LARI — `examples/semantic/` + +| Dosya | İçerik | Beklenen | +|---|---|---| +| `widening.sqt` | `float x = 1;` (OK) + `float y = someInt;` | W004 | +| `narrowing.sqt` | `int x = 1.5;` | E003 | +| `bad_return.sqt` | `int foo() { return 1.5; }` | E003 | +| `break_outside.sqt` | top-level `break;` | E004 | +| `return_outside.sqt` | top-level `return 0;` | E005 | +| `bad_args.sqt` | `fibonacci(1, 2)` (1 parametre bekliyor) | E008 | + +--- + +## 6) DOĞRULAMA KOMUTLARI + +```bash +bash scripts/build.sh + +# Başarı: 0 hata 0 uyarı +build/saqut check file:examples/fibonacci.sqt + +# Her expression tipli mi? +build/saqut ast file:examples/fibonacci.sqt | python3 -c " +import json,sys +def walk(n): + if 'resolvedType' in n and n['resolvedType'] is None: + print('UNTIPPED:', n.get('kind'), n.get('name','')) + for v in n.values(): + if isinstance(v, dict): walk(v) + elif isinstance(v, list): [walk(i) for i in v if isinstance(i, dict)] +walk(json.load(sys.stdin))" + +# Hata fixture'ları +build/saqut check file:examples/semantic/widening.sqt # W004 +build/saqut check file:examples/semantic/narrowing.sqt # E003 +build/saqut check file:examples/semantic/break_outside.sqt # E004 +build/saqut check file:examples/semantic/bad_args.sqt # E008 + +# Regresyon +bash tests/run.sh +build/saqut ast file:examples/fibonacci.sqt | python3 -m json.tool >/dev/null && echo AST-OK +``` + +--- + +## 7) HAFIZA İPUÇLARI + +- `ASTKind::BinaryExpression` → `BinaryExpressionNode{Left, Right, Operator(TokenType)}` +- Atama operatörleri: `EQUAL, PLUS_EQUAL, MINUS_EQUAL, STAR_EQUAL, SLASH_EQUAL, ...` +- `ASTKind::Call` → `CallExpressionNode{callee, arguments}` +- `ASTKind::Literal` → `LiteralNode{literalType(INTEGER/FLOAT/...), parserToken}` +- `ASTKind::Identifier` → `IdentifierNode{resolvedSymbol}` (Faz 2'de set edildi) +- `FunctionDeclNode{name, returnType(string), params, children=[body]}` +- `Type::fromName(str)` primitifi çözer; `Type::function(ret, params)` fonksiyon tipi +- `diag_.report("E003", loc, "mesaj")` → katalogdan seviye otomatik çözülür +- `resolvedType` → `ExpressionNode`'un alanı (ast_node.hpp) +- Literal'ın literal tipi: `((LiteralNode*)node)->literalType` +- İki sayısal tipin genişliği: int < float < double (basit sıralama yeterli) diff --git a/build/.ninja_deps b/build/.ninja_deps index b8c5440f248b10951ffad5672392389d5921af93..d94e6477f2e2d8c5ef29e63acb121f2d222d0dfe 100644 GIT binary patch delta 1539 zcmeH{TS!z<6o${Xj&!k$x5m;zE28K!;~0?@R6~VCR+^bs=6F0#I;Aty%o!`F7<$Pr zh_+_NDYde!e9&szWtWFY@Sztep~x^oNxEO5$a={BGpQ6sLC-yWoPY2Av)0~g?X$Z+ z4)J^mxlp{Acb&A0^l(`Z&#T=b^5oPQ#>+b0BEPf7K9tvdxGGX_&RyQy3)WP{9 zyV(?6H9Laq!sf4ieQA|}nR5m`PQ~Gp6_-OQ zHkC@nmI6t!^?S|m#)Jy)y-X1HbYF4vB);cfNT|V&@eyzogb9M+l(xAPd<)=@!dLHd zI`qYse0_%OPz*YoOj?hI<&)$~8l7)0v{*BAHbH`UabdBVi6b_r$V|n2DqqZV zf8AKlldi|qK-Yp})b7)dIu3OL)BzJ2p3VqwglYokz399->}k4r0UAvE^UJ61*Q zZHst?bcoTNnqkyalQ?`U92SsEMmbh2fwE#_h9$qfPr-bt$af3*)Z;yQ??_O$%%RnM z>K!=@o+dAOb{# z(?A51Dcq<@-v?C&o`L6}4!i)TfCTcvCXfhnfeGY+1K=Qd2{waQU^gfvsUU@(tscuP z)ROX+dg|lYehRE7c9Nu?EOv>~m&Q|0by#>k+-Ja9&;W>9HbjPAhH4i0mg+Zbq8&9D z=t>p%}-CtyRXLkU-O@89--EJ;O#PvaIR|p{&r3I@$DM;X~%pz RCN-mmfB9*ne)(yU;~PMO*B1Z) delta 861 zcmbR8i|N5v<_$RxtnKA$UY(l@9sJo?l{y^lIyWD6>t%HH76U(i>8Dw z{mpLSZEURl)*_cXH(!iZXJb9NiQ{wU=D*3>Y^>jov>xx=ted6G#%iPD^}cg+XaP{c z^wOBCotqoWfC`vjy0CO@-dF=<3MH$)?cDsZiJhB|hmE13iIIWf3>Qxn(1Lq?Ol+z= z3=9m#iG`&lKsx>3|NkODTEDcoNIxetNk2HbsKih&KW(z$RB_f+psdB@hr-&EBc}4O zrT}?169r`^vrdy|OrESdO`bIgq{&oOd-BXZ`jT^itau=v3&it)cs>v>0OEy{8)s-wzOqDb^1B&QqQO9Oj<7N` zfK(s!cs&hd&YI1#Gq +#include "cli/args.hpp" +#include "tokenizer/tokenizer.hpp" +#include "parser/parser.hpp" +#include "symbol/symbol_table.hpp" +#include "symbol/symbol_collector.hpp" +#include "semantic/type_checker.hpp" +#include "semantic/structural_validator.hpp" +#include "diagnostic/diagnostic_engine.hpp" +#include "vendor/nlohmann/json.hpp" + +inline int cmdCheck(const CliArgs& args) { + std::string filePath = inputFilePath(args); + std::string source = readSource(args); + if (source.empty()) return 1; + + Tokenizer tokenizer; + auto tokens = tokenizer.scan(source, filePath); + + Parser parser; + ASTNode* ast = parser.parse(tokens); + + DiagnosticEngine diag; + + if (!ast) { + diag.report("E000", SourceLocation{}, "AST üretilemedi"); + nlohmann::json out; + out["file"] = filePath; + out["diagnostics"] = diag.toJsonObj(); + std::cout << (args.compact ? out.dump() : out.dump(2)) << "\n"; + for (auto* t : tokens) delete t; + return 1; + } + + SymbolTable table; + SymbolCollector(table, diag).collect(ast); + + // Sembol toplama hataları varsa tip denetimine geçme + // (çözümsüz semboller tip denetiminde sahte E003 üretir) + if (!diag.hasErrors()) { + TypeChecker(table, diag).check(ast); + StructuralValidator(diag).validate(ast); + } + + nlohmann::json out; + out["file"] = filePath; + out["diagnostics"] = diag.toJsonObj(); + + std::cout << (args.compact ? out.dump() : out.dump(2)) << "\n"; + + delete ast; + for (auto* t : tokens) delete t; + return diag.hasErrors() ? 1 : 0; +} + +#endif // SAQUT_CLI_CHECK diff --git a/src/diagnostic/diagnostic.hpp b/src/diagnostic/diagnostic.hpp index 5e9a3e8..307332f 100644 --- a/src/diagnostic/diagnostic.hpp +++ b/src/diagnostic/diagnostic.hpp @@ -127,6 +127,7 @@ inline const std::vector& diagnosticCatalog() { {"W001", DiagLevel::Warning, "Kullanılmayan değişken"}, {"W002", DiagLevel::Warning, "Sıfıra bölme (sabit ifade)"}, {"W003", DiagLevel::Warning, "Erişilemez (ölü) kod"}, + {"W004", DiagLevel::Warning, "Örtük sayısal genişletme (widening)"}, }; return catalog; } diff --git a/src/main.cpp b/src/main.cpp index 2f3321c..78609e3 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -27,6 +27,7 @@ #include "cli/commands/tokens.hpp" #include "cli/commands/ast.hpp" #include "cli/commands/symbols.hpp" +#include "cli/commands/check.hpp" int main(int argc, char* argv[]) { // Komutları kaydet @@ -48,6 +49,10 @@ int main(int argc, char* argv[]) { "Sembol tablosu (fonksiyonlar, değişkenler)", false, cmdSymbols}); + cli.registerCommand({"check", + "Semantik analiz — tip denetimi + yapısal doğrulama", + false, cmdCheck}); + // --- Gelecek komutlar (TODO) --- cli.registerCommand({"compile", "TODO: Kaynak kodu derle", diff --git a/src/semantic/structural_validator.cpp b/src/semantic/structural_validator.cpp new file mode 100644 index 0000000..64f7d52 --- /dev/null +++ b/src/semantic/structural_validator.cpp @@ -0,0 +1,95 @@ +#include "semantic/structural_validator.hpp" +#include "parser/nodes/declarations.hpp" +#include "parser/nodes/statements.hpp" + +void StructuralValidator::validate(ASTNode* program) { + if (!program) return; + for (ASTNode* child : program->getChildren()) + walkDecl(child); +} + +void StructuralValidator::walkDecl(ASTNode* node) { + if (!node) return; + if (node->kind == ASTKind::FunctionDecl) { + auto* fn = (FunctionDeclNode*)node; + inFunction_ = true; + auto& ch = fn->getChildren(); + if (!ch.empty()) walkStmt(ch[0]); + inFunction_ = false; + } + // VariableDecl / StructDecl: yapısal kural yok +} + +void StructuralValidator::walkStmt(ASTNode* node) { + if (!node) return; + + switch (node->kind) { + + case ASTKind::Block: + for (ASTNode* child : node->getChildren()) walkStmt(child); + break; + + case ASTKind::IfStatement: { + auto* ifn = (IfStatementNode*)node; + if (ifn->thenBranch) walkStmt(ifn->thenBranch); + if (ifn->elseBranch) walkStmt(ifn->elseBranch); + break; + } + + case ASTKind::WhileStatement: { + auto* ws = (WhileStatementNode*)node; + loopDepth_++; + if (ws->body) walkStmt(ws->body); + loopDepth_--; + break; + } + + case ASTKind::DoWhileStatement: { + auto* dw = (DoWhileStatementNode*)node; + loopDepth_++; + if (dw->body) walkStmt(dw->body); + loopDepth_--; + break; + } + + case ASTKind::ForStatement: { + auto* fs = (ForStatementNode*)node; + loopDepth_++; + if (fs->init) walkStmt(fs->init); + if (fs->body) walkStmt(fs->body); + loopDepth_--; + break; + } + + case ASTKind::BreakStatement: + if (loopDepth_ == 0) + diag_.report("E004", node->loc, + "'break' döngü dışında kullanılamaz"); + break; + + case ASTKind::ContinueStatement: + if (loopDepth_ == 0) + diag_.report("E004", node->loc, + "'continue' döngü dışında kullanılamaz"); + break; + + case ASTKind::ReturnStatement: + if (!inFunction_) + diag_.report("E005", node->loc, + "'return' fonksiyon dışında kullanılamaz"); + break; + + case ASTKind::VariableDecl: { + // sibling'leri de gez + for (ASTNode* sib : node->getChildren()) + if (sib->kind == ASTKind::VariableDecl) walkStmt(sib); + break; + } + + case ASTKind::ExpressionStatement: + break; // ifade içinde return/break olamaz + + default: + break; + } +} diff --git a/src/semantic/structural_validator.hpp b/src/semantic/structural_validator.hpp new file mode 100644 index 0000000..aa089b8 --- /dev/null +++ b/src/semantic/structural_validator.hpp @@ -0,0 +1,22 @@ +#ifndef SAQUT_SEMANTIC_STRUCTURAL_VALIDATOR +#define SAQUT_SEMANTIC_STRUCTURAL_VALIDATOR + +#include "diagnostic/diagnostic_engine.hpp" +#include "parser/ast_node.hpp" + +class StructuralValidator { +public: + explicit StructuralValidator(DiagnosticEngine& diag) : diag_(diag) {} + + void validate(ASTNode* program); + +private: + void walkDecl(ASTNode* node); + void walkStmt(ASTNode* node); + + DiagnosticEngine& diag_; + int loopDepth_ = 0; + bool inFunction_ = false; +}; + +#endif // SAQUT_SEMANTIC_STRUCTURAL_VALIDATOR diff --git a/src/semantic/type_checker.cpp b/src/semantic/type_checker.cpp new file mode 100644 index 0000000..f037b53 --- /dev/null +++ b/src/semantic/type_checker.cpp @@ -0,0 +1,384 @@ +#include "semantic/type_checker.hpp" +#include "parser/nodes/program.hpp" +#include "parser/nodes/declarations.hpp" +#include "parser/nodes/statements.hpp" +#include "parser/nodes/expressions.hpp" +#include "parser/nodes/binary_expr.hpp" +#include "parser/nodes/identifier.hpp" +#include "parser/nodes/literal.hpp" + +// ───────────────────────────────────────────────────────────────────────────── +// Yardımcılar +// ───────────────────────────────────────────────────────────────────────────── + +int TypeChecker::numericRank(const Type& t) { + if (!t.isPrimitive()) return -1; + switch (t.prim) { + case PrimitiveKind::Int: return 0; + case PrimitiveKind::Float: return 1; + case PrimitiveKind::Double: return 2; + default: return -1; + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// check — giriş noktası +// ───────────────────────────────────────────────────────────────────────────── + +void TypeChecker::check(ASTNode* program) { + if (!program) return; + for (ASTNode* child : program->getChildren()) { + switch (child->kind) { + case ASTKind::FunctionDecl: checkFunction(child); break; + case ASTKind::VariableDecl: checkStmt(child); break; + default: break; + } + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// checkFunction +// ───────────────────────────────────────────────────────────────────────────── + +void TypeChecker::checkFunction(ASTNode* fnNode) { + auto* fn = (FunctionDeclNode*)fnNode; + inFunction_ = true; + currentReturnType_ = Type::fromName(fn->returnType); + if (currentReturnType_.isError() && fn->returnType != "void") + currentReturnType_ = Type::Void(); // bilinmeyen dönüş tipi → void gibi davran + + auto& ch = fn->getChildren(); + if (!ch.empty()) checkStmt(ch[0]); // body Block + + inFunction_ = false; +} + +// ───────────────────────────────────────────────────────────────────────────── +// checkAssign — atama uyumu + uyarı/hata raporlama +// ───────────────────────────────────────────────────────────────────────────── + +bool TypeChecker::checkAssign(const Type& target, const Type& src, + bool srcIsLiteral, + const SourceLocation& loc, + const std::string& ctx) { + if (target.isError() || src.isError()) return true; // önceki hata, sessiz geç + if (target.equals(src)) return true; + + int tRank = numericRank(target); + int sRank = numericRank(src); + + if (tRank >= 0 && sRank >= 0) { + if (tRank > sRank) { + // Genişletme (widening): int→float, int→double, float→double + if (srcIsLiteral) return true; // literal bağlama-göre tiplenir, uyarısız + diag_.report("W004", loc, + "'" + ctx + "': " + src.toString() + + " → " + target.toString() + " örtük genişletme"); + return true; + } else { + // Daraltma (narrowing): float→int, double→float, vb. + diag_.report("E003", loc, + "'" + ctx + "': " + src.toString() + + " → " + target.toString() + " daraltma (veri kaybı)"); + return false; + } + } + + // Tamamen farklı tipler + diag_.report("E003", loc, + "'" + ctx + "': " + src.toString() + + " tipi " + target.toString() + " tipine atanamaz"); + return false; +} + +// ───────────────────────────────────────────────────────────────────────────── +// checkStmt +// ───────────────────────────────────────────────────────────────────────────── + +void TypeChecker::checkStmt(ASTNode* node) { + if (!node) return; + + switch (node->kind) { + + case ASTKind::Block: + for (ASTNode* child : node->getChildren()) checkStmt(child); + break; + + case ASTKind::VariableDecl: { + auto* vd = (VariableDeclNode*)node; + Type targetType = Type::fromName(vd->varType); + if (vd->initExpr) { + Type srcType = checkExpr(vd->initExpr, targetType); + bool isLit = vd->initExpr->kind == ASTKind::Literal; + checkAssign(targetType, srcType, isLit, vd->loc, vd->name); + } + // sibling VariableDecl'ler (int a, b;) + for (ASTNode* sib : vd->getChildren()) { + if (sib->kind == ASTKind::VariableDecl) checkStmt(sib); + } + break; + } + + case ASTKind::ExpressionStatement: { + auto* es = (ExpressionStatementNode*)node; + if (es->expression) checkExpr(es->expression); + break; + } + + case ASTKind::ReturnStatement: { + auto* rs = (ReturnStatementNode*)node; + if (!rs->value) { + if (inFunction_ && !currentReturnType_.isVoid()) + diag_.report("E006", rs->loc, + "Değersiz return; fonksiyon " + + currentReturnType_.toString() + " döndürmeli"); + break; + } + Type valType = checkExpr(rs->value, currentReturnType_); + bool isLit = rs->value->kind == ASTKind::Literal; + checkAssign(currentReturnType_, valType, isLit, rs->loc, "return"); + break; + } + + case ASTKind::IfStatement: { + auto* ifn = (IfStatementNode*)node; + if (ifn->condition) checkExpr(ifn->condition); + if (ifn->thenBranch) checkStmt(ifn->thenBranch); + if (ifn->elseBranch) checkStmt(ifn->elseBranch); + break; + } + + case ASTKind::WhileStatement: { + auto* ws = (WhileStatementNode*)node; + if (ws->condition) checkExpr(ws->condition); + if (ws->body) checkStmt(ws->body); + break; + } + + case ASTKind::ForStatement: { + auto* fs = (ForStatementNode*)node; + if (fs->init) { + if (fs->init->kind == ASTKind::VariableDecl) checkStmt(fs->init); + else checkExpr(fs->init); + } + if (fs->condition) checkExpr(fs->condition); + if (fs->update) checkExpr(fs->update); + if (fs->body) checkStmt(fs->body); + break; + } + + case ASTKind::DoWhileStatement: { + auto* dw = (DoWhileStatementNode*)node; + if (dw->body) checkStmt(dw->body); + if (dw->condition) checkExpr(dw->condition); + break; + } + + case ASTKind::BreakStatement: + case ASTKind::ContinueStatement: + break; // yapısal doğrulama StructuralValidator'ın işi + + default: + break; + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// checkExpr — tip çıkarımı + resolvedType ataması +// ───────────────────────────────────────────────────────────────────────────── + +Type TypeChecker::checkExpr(ASTNode* node, const Type& expected) { + if (!node) return Type::error(); + + Type result = Type::error(); + + switch (node->kind) { + + // ── Literal ──────────────────────────────────────────────────────────── + case ASTKind::Literal: { + auto* lit = (LiteralNode*)node; + int expRank = numericRank(expected); + + switch (lit->literalType) { + case LiteralType::INTEGER: + // Bağlam daha geniş sayısal tip ise literal o tip olarak tiplenir. + if (expRank > 0) result = expected; // float veya double bekleniyor + else result = Type::Int(); + break; + case LiteralType::FLOAT: + // float literal → double bağlamında double olur; int bağlamında E003. + if (!expected.isError() && expected.equals(Type::Double())) + result = Type::Double(); + else if (!expected.isError() && numericRank(expected) == 0) { + // int bekleniyor ama float literal: E003 + diag_.report("E003", lit->loc, + "Float literal int bağlamında kullanılamaz (veri kaybı)"); + result = Type::error(); + } else { + result = Type::Float(); + } + break; + case LiteralType::BOOLEAN: result = Type::Bool(); break; + case LiteralType::STRING: result = Type::String(); break; + default: result = Type::error(); break; + } + break; + } + + // ── Identifier ───────────────────────────────────────────────────────── + case ASTKind::Identifier: { + auto* id = (IdentifierNode*)node; + result = id->resolvedSymbol ? id->resolvedSymbol->type : Type::error(); + break; + } + + // ── BinaryExpression ─────────────────────────────────────────────────── + case ASTKind::BinaryExpression: { + auto* bin = (BinaryExpressionNode*)node; + + // Atama operatörleri + if (bin->Operator == TokenType::EQUAL || + bin->Operator == TokenType::PLUS_EQUAL || + bin->Operator == TokenType::MINUS_EQUAL || + bin->Operator == TokenType::STAR_EQUAL || + bin->Operator == TokenType::SLASH_EQUAL || + bin->Operator == TokenType::PERCENT_EQUAL) { + Type leftType = checkExpr(bin->Left); + Type rightType = checkExpr(bin->Right, leftType); + bool isLit = bin->Right && bin->Right->kind == ASTKind::Literal; + checkAssign(leftType, rightType, isLit, bin->loc, "atama"); + result = leftType; + break; + } + + // Unary (Left = nullptr): -, +, !, ~ + if (!bin->Left) { + Type rightType = checkExpr(bin->Right); + if (bin->Operator == TokenType::BANG) { + result = Type::Bool(); + } else { + result = rightType.isNumeric() ? rightType : Type::error(); + if (result.isError() && !rightType.isError()) + diag_.report("E003", bin->loc, "Sayısal olmayan operand"); + } + break; + } + + Type leftType = checkExpr(bin->Left); + Type rightType = checkExpr(bin->Right); + + // Mantıksal + if (bin->Operator == TokenType::AMPERSAND_AMPERSAND || + bin->Operator == TokenType::PIPE_PIPE) { + result = Type::Bool(); + break; + } + + // Karşılaştırma + if (bin->Operator == TokenType::EQUAL_EQUAL || + bin->Operator == TokenType::BANG_EQUAL || + bin->Operator == TokenType::LESS || + bin->Operator == TokenType::LESS_EQUAL || + bin->Operator == TokenType::GREATER || + bin->Operator == TokenType::GREATER_EQUAL) { + result = Type::Bool(); + break; + } + + // Aritmetik: +, -, *, /, % + int lRank = numericRank(leftType); + int rRank = numericRank(rightType); + + if (lRank >= 0 && rRank >= 0) { + // Aynı tip veya otomatik genişletme; sonuç daha geniş tip. + result = (lRank >= rRank) ? leftType : rightType; + } else if (!leftType.isError() && !rightType.isError()) { + diag_.report("E003", bin->loc, + "Aritmetik operatör sayısal olmayan tip: " + + leftType.toString() + " ve " + rightType.toString()); + result = Type::error(); + } else { + result = Type::error(); + } + break; + } + + // ── Call ─────────────────────────────────────────────────────────────── + case ASTKind::Call: { + auto* call = (CallExpressionNode*)node; + Type calleeType = checkExpr(call->callee); + + if (!calleeType.isFunction()) { + if (!calleeType.isError()) + diag_.report("E003", call->loc, + "Çağrılabilir değil: " + calleeType.toString()); + result = Type::error(); + // Argümanları yine de gez (cascade hatayı önle) + for (auto* arg : call->arguments) checkExpr(arg); + break; + } + + // Argüman sayısı kontrolü — builtin print hariç (paramTypes boş = değişken arity) + if (!calleeType.paramTypes.empty()) { + size_t expected_count = calleeType.paramTypes.size(); + size_t got_count = call->arguments.size(); + if (got_count != expected_count) { + diag_.report("E008", call->loc, + std::to_string(expected_count) + " argüman bekleniyor, " + + std::to_string(got_count) + " verildi"); + } + } + + // Argüman tiplerini kontrol et + for (size_t i = 0; i < call->arguments.size(); ++i) { + Type paramType = (i < calleeType.paramTypes.size()) + ? calleeType.paramTypes[i] + : Type::error(); + Type argType = checkExpr(call->arguments[i], paramType); + bool isLit = call->arguments[i]->kind == ASTKind::Literal; + if (!paramType.isError()) + checkAssign(paramType, argType, isLit, + call->arguments[i]->loc, "argüman"); + } + + result = calleeType.returnType ? *calleeType.returnType : Type::Void(); + break; + } + + // ── Postfix ++/-- ────────────────────────────────────────────────────── + case ASTKind::Postfix: { + auto* pf = (PostfixNode*)node; + Type opType = checkExpr(pf->operand); + if (!opType.isNumeric() && !opType.isError()) + diag_.report("E003", pf->loc, + "++ / -- sayısal olmayan tip: " + opType.toString()); + result = opType; + break; + } + + // ── MemberAccess / IndexExpression ───────────────────────────────────── + case ASTKind::MemberAccess: { + auto* ma = (MemberAccessNode*)node; + checkExpr(ma->object); + result = Type::error(); // TODO(faz3+): struct alan çözümü + break; + } + case ASTKind::IndexExpression: { + auto* ie = (IndexExpressionNode*)node; + checkExpr(ie->object); + if (ie->index) checkExpr(ie->index); + result = Type::error(); // TODO(faz3+): array eleman tipi + break; + } + + default: + result = Type::error(); + break; + } + + // resolvedType'a yaz (ExpressionNode'dan türeyen tüm node'lar için) + if (auto* exprNode = dynamic_cast(node)) + exprNode->resolvedType = result; + + return result; +} diff --git a/src/semantic/type_checker.hpp b/src/semantic/type_checker.hpp new file mode 100644 index 0000000..cc7febf --- /dev/null +++ b/src/semantic/type_checker.hpp @@ -0,0 +1,41 @@ +#ifndef SAQUT_SEMANTIC_TYPE_CHECKER +#define SAQUT_SEMANTIC_TYPE_CHECKER + +#include "symbol/symbol_table.hpp" +#include "diagnostic/diagnostic_engine.hpp" +#include "parser/ast_node.hpp" +#include "core/type.hpp" + +class TypeChecker { +public: + TypeChecker(SymbolTable& table, DiagnosticEngine& diag) + : table_(table), diag_(diag) {} + + void check(ASTNode* program); + +private: + // İfadeyi gez, resolvedType ata, tipi döndür. + // expected: bağlam tipi — literal genişletme kararı için. + Type checkExpr(ASTNode* node, const Type& expected = Type::error()); + + void checkStmt(ASTNode* node); + void checkFunction(ASTNode* fnNode); + + // Atama / parametre uyumu: true = geçerli (uyarı dahil). + // srcIsLiteral: RHS doğrudan bir Literal node'u mu? + bool checkAssign(const Type& target, const Type& src, + bool srcIsLiteral, + const SourceLocation& loc, + const std::string& context); + + // İki sayısal tipin genişlik sırası: int=0, float=1, double=2; -1 = sayısal değil. + static int numericRank(const Type& t); + + SymbolTable& table_; + DiagnosticEngine& diag_; + + Type currentReturnType_; // aktif fonksiyonun beklenen dönüş tipi + bool inFunction_ = false; +}; + +#endif // SAQUT_SEMANTIC_TYPE_CHECKER