# Kotlin/Java/C Language Server — 完整分析

## 一、專案概覽與定位

這是一個極度輕量級的 VSCode Extension + LSP Server，用 TypeScript 實作。核心能力全部依賴 regex 字串比對，**沒有 AST parser**。支援 Kotlin (.kt/.kts)、Java (.java)、C (.c/.h) 三種語言。

---

## 二、現有功能清單

| 功能 | 說明 |
|------|------|
| **Document Symbol (`@`)** | 目前開啟文件的符號列表（含巢狀 hierarchy） |
| **Go to Definition (`F12`)** | 先在已開啟文件找，再 fallback 到全專案 scan |
| **Workspace Symbol (`#`)** | 跨檔案搜尋符號，有 relevance scoring |
| **Breadcrumbs** | 顯示當前 type → method/function 路徑 |
| **ViewBinding F12** | `ActivityMainBinding` ↔ `activity_main.xml` 雙向映射 |
| **XML id 導航** | `binding.fieldName` → snake_case → XML layout 中的 `android:id` |
| **Quick Symbol Search** | 右鍵選單搜尋整個 workspace |

---

## 三、Goto Definition (F12) — 無法判斷為 symbol 的 case

以下是目前 regex-based parser 必定會失敗的案例：

### A. Kotlin 部分

```kotlin
// ❌ 1. 多行宣告（換行後才出現名字）
val
    myVariable: String = "hello"

// ❌ 2. init block 內的變數
class Foo {
    init {
        val bar = 42
    }
}

// ❌ 3. when expression 的分支變數
when (x) {
    is String -> println(x.length)  // x 不會被識別
}

// ❌ 4. lambda 參數
list.map { item -> item.toUpperCase() }  // "item" 不會被識別

// ❌ 5. for-loop 變數
for ((key, value) in map) {}  // key/value 不會被識別

// ❌ 6. destructuring declarations
val (a, b, c) = pair  // a, b, c 不會被識別

// ❌ 7. class body initializer / secondary constructor
class Foo(val x: Int) {
    val y: String
        get() = "computed"  // 如果 get() 換行，可能漏掉
}

// ❌ 8. annotation with complex arguments spanning multiple lines
@Config(
    name = "test",
    value = 42
)
class MyClass {}  // @ 被 strip 後 regex 才匹配到 class — 但如果有 nested () 會 break

// ❌ 9. inline class delegation / by keyword
class Wrapper private constructor(val inner: Int) : Comparable<Wrapper> {
    override fun compareTo(other: Wrapper): Int = inner - other.inner
}

// ❌ 10. @JvmField, @Volatile, @Transient 等 field-level annotation
@JvmField val myValue: String = ""  // stripLeadingAnnotations 只處理行首的 @

// ❌ 11. Kotlin extension property on nullable receiver
fun StringBuilder.appendText(text: String): StringBuilder { ... }

// ❌ 12. crossinline / noinline lambda parameters
fun foo(callback: (crossinline x: Int) -> Unit) {}

// ❌ 13. reified type parameter usage inside function body
inline fun <reified T> bar() { val t: T = TODO() }  // "t" 不會被識別

// ❌ 14. object expression (anonymous object)
val obj = object : Runnable { override fun run() {} }  // "obj" 可能漏掉

// ❌ 15. const val inside interface / companion
interface Consts {
    @JvmField const val MAX = 100  // 不會被識別為 property
}
```

### B. Java 部分

```java
// ❌ 1. try-with-resources
try (var conn = DriverManager.getConnection(url)) { ... }  // "conn" 不會被識別

// ❌ 2. lambda expressions
list.forEach(item -> System.out.println(item));  // "item" 不會被識別

// ❌ 3. enhanced for-loop variables
for (Entry<String, Integer> entry : map.entrySet()) {}  // "entry" 不會被識別

// ❌ 4. switch expression (Java 14+)
var result = switch (x) { case 1 -> "one"; default -> "other"; };
// "result" 可以，但分支內的不會

// ❌ 5. record component hidden fields
record Point(int x, int y) {}  // x, y 作為 field 不會被識別（只有 record 本身會被識別）

// ❌ 6. varargs parameter inside method body
void foo(String... args) { for (String s : args) {} }  // "s" 不會被識別

// ❌ 7. assert statement variable
assert condition : myMessage;  // "myMessage" 不會被識別

// ❌ 8. multi-catch
catch (IOException | SQLException e) {}  // "e" 不會被識別

// ❌ 9. @Deprecated with cross-line annotation
@Deprecated(
    message = "Use something else",
    since = "1.0"
)
public void oldMethod() {}  // stripLeadingAnnotations 可能 break on nested ()

// ❌ 10. method reference — no variable to identify but still a gap in coverage
```

### C. C 部分

```c
// ❌ 1. pointer declarations with complex types
char **argv;           // 可以識別 "argv"，但 *argc, *argv 並列時只認第一個
int * const ptr;       // const pointer — 可能漏掉

// ❌ 2. function-like macro definitions
#define MAX(a, b) ((a) > (b) ? (a) : (b))  // "MAX", "a", "b" 全部不會被識別

// ❌ 3. struct/union/enum forward declarations without body
struct node *next;     // 如果前面沒有完整的 struct node { ... }，無法跳過去

// ❌ 4. typedef with function pointer
typedef void (*callback_t)(int, int);  // "callback_t" 可能不會被正確識別為 typealias

// ❌ 5. union member access in declaration
union { int a; float b; } data;  // "data" 可以識別，但 a/b 不會

// ❌ 6. preprocessor conditionals containing declarations
#if DEBUG
    int debug_var = 1;  // 可以識別，但不會考慮 #if context
#endif

// ❌ 7. designated initializer in C99+
struct Point p = { .x = 1, .y = 2 };  // "p" 可以識別，但 field names 不會被處理

// ❌ 8. inline assembly / volatile declarations
volatile uint32_t *reg = (uint32_t *)0x1234;  // 可能漏掉

// ❌ 9. __attribute__ declarations
void foo() __attribute__((noreturn));  // attribute 後綴可能讓 regex fail

// ❌ 10. C++ style class/namespace if .cpp files are included
class MyClass { public: void method(); };  // "MyClass" 可以識別，但 "method" 不會（C rules）
```

### D. 通用問題（跨語言）

```kotlin
// ❌ 11. 所有在 comment 中的 symbol
// val hiddenVar = 42   ← 這行不會被識別（目前 stripLeadingAnnotations 不處理 // 內的內容）
/* val alsoHidden = 42 */  ← block comment 同樣問題

// ❌ 12. string literal 中的 symbol
val s = "val myString = 'test'";  // "myString" 不會被識別（目前 regex 只看行首，不判斷是否在字串內）

// ❌ 13. macro / preprocessor (C only) — entire category missing
#define SYMBOL_NAME 42
#define DECLARE_VAR(type, name) type name;

// ❌ 14. Kotlin's @file: annotations / package-level metadata
@file:JvmName("MyUtils")
package com.example

// ❌ 15. Multi-module / cross-project references — purely local, no import resolution
```

---

## 四、可以幫助開發者的改進方案

### 🔴 高優先級（影響日常使用）

#### 1. 支援 Kotlin/Java lambda 參數識別

**問題：** 目前 `fun { item -> ... }` 中的 `item` 完全不會被索引。

**方案：** 在 `parseKotlinLine` / `parseJavaLine` 中新增 lambda parameter regex：

```regex
/\{\s*(\w+)\s*->/        // single param
/\{\s*(\w+),\s*(\w+)\s*->/  // multi params
```

#### 2. 支援 Kotlin destructuring declarations

**問題：** `val (key, value) in map`、`fun foo((a, b): Pair<Int,Int>)` 無法識別。

**方案：** 在 `parseKotlinLine` 新增 pattern：

```regex
/val\s*\(([^)]+)\)/        // val (a, b, c) = ...
/\(\s*(\w+),\s*(\w+)\s*\)/  // function param destructuring
```

#### 3. C 的 `#define` macro symbol 索引

**方案：** 新增 `cMacroRules`：

```regex
/^\s*#\s*define\s+(\w+)\s*\(/    → kind: "macro" (帶參數)
/^\s*#\s*define\s+(\w+)/         → kind: "macro" (常數)z`
```

#### 4. C function pointer typedef 識別

**問題：** `typedef void (*callback_t)(int);` — regex 會誤判為 variable。

**方案：** 在 `extractCVariableSymbols` 中增加 function pointer 排除邏輯。

---

### 🟡 中優先級（改善導航體驗）

#### 5. Go to Definition 支援 import/require-based resolution

**問題：** 目前只靠 name match，不知道 `import com.example.UserService` 的關係。

**方案：** 掃描 `import` / `require` / `#include` 語句建立 alias map。

#### 6. ViewBinding 支援 data binding (layout/*.xml → `<data>` section)

**問題：** 目前只處理 `@+id/`，不處理 `<variable name="user">` 這種 data binding。

**方案：** 在 `parseXmlIds` 旁新增 `parseDataBindingVars`。

#### 7. C header/impl 檔案關聯導航

**問題：** 在 `.h` 中 F12 跳 function，應該能自動找到對應的 `.c` 實作。

**方案：** 建立 name → file 映射表，支援跨檔案 jump。

---

### 🟢 低優先級（進階功能）

#### 8. Kotlin when / Java switch branch variable tracking

讓 `when (x) { is Foo -> x.method() }` 中的 `x` 可以被導航。

#### 9. C++ partial support (.cpp, .hpp)

目前只支援純 C，class/method/namespace 全部缺失。

#### 10. Workspace symbol caching + incremental update

每次 workspace symbol 都全量 scan（MAX_SCAN_FILES=5000），大專案很慢。

**方案：** 檔案變更時增量更新 symbol index，而非每次都 re-parse。

---

## 五、總結評估

| 維度 | 評分 | 說明 |
|------|------|------|
| **開源文件** | ⭐⭐⭐ | README 清楚但缺少 API doc |
| **測試覆蓋率** | ⭐⭐⭐⭐ | `symbols.test.ts` 涵蓋主要 case，但 edge cases 不足 |
| **Goto Definition 準確度** | ⭐⭐ | regex-only 本質限制，lambda/local/宏等大量 case 無法處理 |
| **擴充性** | ⭐⭐⭐ | 架構清晰（symbols.ts 獨立），新增 regex rule 容易 |
| **C 語言支援深度** | ⭐⭐ | macro/struct field/function pointer typedef 全部缺失 |

---

## 核心結論

這個專案作為一個「快速原型 / 輕量級導航工具」是有價值的，但若要達到 production-grade 的 goto definition 體驗，需要引入真正的 **AST parser**（例如 Kotlin 用 kotlinx-compiler 或 Java 用 Eclipse JDT/Language Server），或是至少大幅加強 regex rule coverage。

目前最大的盲區就是：
- 所有函式體內的局部變數（除了 C）
- Lambda / destructuring 參數
- Macro / preprocessor 指令
