# アーキテクチャ構成図

## システム全体構成図

```mermaid
graph TB
    subgraph Editor["エディタ / IDE（VSCode等）"]
        EditorUI["エディタUI"]
    end

    subgraph ServeD["serve-d プロセス"]
        subgraph Transport["Transport層"]
            FileReader["FileReader<br/>(stdin読み取りスレッド)"]
            RPCProcessor["RPCProcessor<br/>(JSON-RPC Fiber)"]
            StdoutWriter["stdout Writer<br/>(RPC応答書き込み)"]
        end

        subgraph ServerBase["Server Base層"]
            LSRouter["LanguageServerRouter<br/>(mixin template)"]
            EventProc["EventProcessor<br/>(UDAベースディスパッチ)"]
            FiberMgr["FiberManager<br/>(協調マルチタスク)"]
            GCCollector["GC Collector<br/>(定期メモリ回収)"]
        end

        subgraph Extension["Extension / Commands層"]
            ExtModule["served.extension<br/>(初期化・設定管理)"]
            subgraph Commands["LSPコマンドハンドラ"]
                Complete["complete<br/>(自動補完)"]
                Definition["definition<br/>(定義ジャンプ)"]
                References["references<br/>(参照検索)"]
                Rename["rename<br/>(リネーム)"]
                Format["format<br/>(フォーマット)"]
                CodeActions["code_actions<br/>(コードアクション)"]
                CodeLens["code_lens<br/>(コードレンズ)"]
                Hover["calltips<br/>(ホバー/シグネチャ)"]
                Symbols["symbol_search<br/>(シンボル検索)"]
                OtherCmds["その他コマンド"]
            end
            subgraph Linters["リンター"]
                DScannerLint["dscanner lint<br/>(slot 0)"]
                DubLint["dub lint<br/>(slot 1)"]
                DfmtLint["dfmt lint<br/>(slot 2)"]
                DiagMgr["DiagnosticManager<br/>(診断統合)"]
            end
            subgraph DocMgr["ドキュメント管理"]
                TextDocMgr["TextDocumentManager<br/>(インメモリ同期)"]
            end
        end

        subgraph BackendAdapter["Backend Adapter層"]
            LazyWSD["LazyWorkspaceD<br/>(遅延ロード付きバックエンド)"]
        end

        subgraph Backend["workspace-d Backend層"]
            WSD["WorkspaceD<br/>(コンポーネントレジストリ)"]
            subgraph Components["コンポーネント群"]
                DCDComp["DCDComponent<br/>(コード補完)"]
                DCDExtComp["DCDExtComponent<br/>(DCD拡張)"]
                DScannerComp["DscannerComponent<br/>(静的解析)"]
                DfmtComp["DfmtComponent<br/>(フォーマット)"]
                DubComp["DubComponent<br/>(プロジェクト管理)"]
                DMDComp["DMDComponent<br/>(コンパイラ)"]
                FSWorkspace["FSWorkspaceComponent<br/>(FS管理)"]
                ImporterComp["ImporterComponent<br/>(自動インポート)"]
                IndexComp["IndexComponent<br/>(インデックス)"]
                SnippetsComp["SnippetsComponent<br/>(スニペット)"]
                OtherComps["その他コンポーネント"]
            end
        end
    end

    subgraph ExternalTools["外部D言語ツール（ライブラリ統合）"]
        DCD["DCD 0.16.2"]
        DScanner["DScanner 0.16.0"]
        Dfmt["dfmt 0.15.2"]
        DUB["DUB 1.40.0"]
        LibDParse["libdparse 0.25.1"]
        LibDDoc["libddoc 0.8.0"]
    end

    EditorUI -- "JSON-RPC over stdin" --> FileReader
    StdoutWriter -- "JSON-RPC over stdout" --> EditorUI

    FileReader --> RPCProcessor
    RPCProcessor --> LSRouter
    LSRouter --> EventProc
    LSRouter --> FiberMgr
    LSRouter --> GCCollector

    EventProc --> ExtModule
    EventProc --> Commands
    EventProc --> Linters
    RPCProcessor --> TextDocMgr

    ExtModule --> LazyWSD
    Commands --> LazyWSD
    Linters --> LazyWSD
    DScannerLint --> DiagMgr
    DubLint --> DiagMgr
    DfmtLint --> DiagMgr
    DiagMgr -- "publishDiagnostics" --> RPCProcessor

    LazyWSD --> WSD
    WSD --> Components

    DCDComp --> DCD
    DScannerComp --> DScanner
    DfmtComp --> Dfmt
    DubComp --> DUB
    DScannerComp --> LibDParse
    DCDExtComp --> LibDParse
    IndexComp --> LibDParse

    RPCProcessor --> StdoutWriter
```

## レイヤー構成図

```mermaid
graph TB
    subgraph L1["Protocol層"]
        direction LR
        Protocol["served.lsp.protocol<br/>(LSP v3.16型定義)"]
        JsonOps["served.lsp.jsonops<br/>(JSON操作)"]
        URI["served.lsp.uri<br/>(URI変換)"]
    end

    subgraph L2["Transport層"]
        direction LR
        JSONRPC["served.lsp.jsonrpc<br/>(RPCProcessor)"]
        FileReader2["served.lsp.filereader<br/>(stdin読み取り)"]
        TextDocMgr2["served.lsp.textdocumentmanager"]
    end

    subgraph L3["Server Base層"]
        direction LR
        ServerBase["served.serverbase<br/>(LanguageServerRouter)"]
        Events["served.utils.events<br/>(EventProcessor)"]
        FiberMgr2["served.utils.fibermanager"]
        Async["served.utils.async"]
    end

    subgraph L4["Extension / Commands層"]
        direction LR
        Extension2["served.extension"]
        CmdGroup["served.commands.*"]
        LintGroup["served.linters.*"]
        WorkerGroup["served.workers.*"]
        Types["served.types"]
    end

    subgraph L5["Backend Adapter層"]
        direction LR
        LazyWSD2["served.backend.lazy_workspaced"]
    end

    subgraph L6["Backend層 (workspace-d)"]
        direction LR
        BackendAPI["workspaced.api"]
        BackendCore["workspaced.backend"]
        ComGroup["workspaced.com.*"]
    end

    L1 --> L2
    L2 --> L3
    L3 --> L4
    L4 --> L5
    L5 --> L6
```

## サブパッケージ依存関係図

```mermaid
graph LR
    subgraph MainPkg["serve-d (メインパッケージ)"]
        Main["source/"]
    end

    subgraph SubPkgs["サブパッケージ"]
        ProtocolPkg["serve-d:protocol"]
        LSPPkg["serve-d:lsp"]
        ServerBasePkg["serve-d:serverbase"]
        HTTPPkg["serve-d:http"]
        DCDPkg["serve-d:dcd"]
        WorkspaceDPkg["serve-d:workspace-d"]
    end

    subgraph ExtDeps["外部依存ライブラリ"]
        MirIon["mir-ion 2.3.5"]
        MirAlgo["mir-algorithm 3.22.4"]
        DCDLib["dcd 0.16.2"]
        DScannerLib["dscanner 0.16.0"]
        DfmtLib["dfmt 0.15.2"]
        DubLib["dub 1.40.0"]
        LibDParseLib["libdparse 0.25.1"]
        LibDDocLib["libddoc 0.8.0"]
        RequestsLib["requests 2.2.0"]
        StandardPaths["standardpaths 0.8.2"]
        Inifiled["inifiled 1.3.3"]
        FuzzyMatch["fuzzymatch 1.0.0"]
        SdlFmt["sdlfmt 0.1.1"]
    end

    Main --> LSPPkg
    Main --> ServerBasePkg
    Main --> HTTPPkg
    Main --> WorkspaceDPkg
    Main --> LibDDocLib
    Main --> FuzzyMatch
    Main --> SdlFmt

    LSPPkg --> ProtocolPkg
    LSPPkg --> MirIon
    LSPPkg --> MirAlgo

    ProtocolPkg --> MirIon
    ProtocolPkg --> MirAlgo

    ServerBasePkg --> LSPPkg

    HTTPPkg --> RequestsLib

    DCDPkg --> DCDLib

    WorkspaceDPkg --> DCDPkg
    WorkspaceDPkg --> DScannerLib
    WorkspaceDPkg --> DfmtLib
    WorkspaceDPkg --> DubLib
    WorkspaceDPkg --> LibDParseLib
    WorkspaceDPkg --> MirAlgo
    WorkspaceDPkg --> StandardPaths
    WorkspaceDPkg --> Inifiled
```

## リクエスト処理フロー図

```mermaid
sequenceDiagram
    participant Editor as エディタ/IDE
    participant FR as FileReader<br/>(Thread)
    participant RPC as RPCProcessor<br/>(Fiber)
    participant Router as LanguageServerRouter
    participant FM as FiberManager
    participant EP as EventProcessor
    participant Cmd as Command Handler<br/>(served.commands.*)
    participant Backend as LazyWorkspaceD
    participant Comp as workspace-d<br/>Component

    Editor->>FR: JSON-RPC Request<br/>(stdin)
    FR->>RPC: バイトデータ転送
    RPC->>RPC: ヘッダー解析<br/>Content-Length取得
    RPC->>RPC: JSONパース<br/>RequestMessageRaw生成
    RPC->>Router: メッセージキューに格納

    Router->>FM: 新しいFiber生成<br/>(gotRequest)
    FM->>EP: processRequest実行
    EP->>EP: @protocolMethod UDA<br/>でハンドラ検索
    EP->>Cmd: ハンドラ呼び出し<br/>(パラメータ自動デシリアライズ)
    Cmd->>Backend: backend.get!Component()
    Backend->>Backend: 遅延ロードチェック<br/>(LazyInstance)
    Backend->>Comp: コンポーネントAPI呼び出し
    Comp-->>Cmd: 結果返却
    Cmd-->>EP: 結果返却
    EP->>RPC: ResponseMessageRaw<br/>JSON直列化
    RPC->>Editor: JSON-RPC Response<br/>(stdout)
```

## 診断（Linting）処理フロー図

```mermaid
sequenceDiagram
    participant Editor as エディタ/IDE
    participant Router as LanguageServerRouter
    participant Ext as served.extension
    participant Timer as setTimeout
    participant DSLint as dscanner linter<br/>(slot 0)
    participant DubLint as dub linter<br/>(slot 1)
    participant DfmtLint as dfmt linter<br/>(slot 2)
    participant DiagMgr as DiagnosticManager
    participant RPC as RPCProcessor

    Editor->>Router: textDocument/didChange
    Router->>Ext: onDidChangeDocument()
    Ext->>Timer: setTimeout(dscanner, 200ms)
    Ext->>Timer: setTimeout(dfmt, 50ms)

    Timer->>DSLint: lint(document)
    DSLint->>DiagMgr: createDiagnosticsFor!0(uri)
    DSLint->>DiagMgr: updateDiagnostics()

    Timer->>DfmtLint: lint(document)
    DfmtLint->>DiagMgr: createDiagnosticsFor!2(uri)
    DfmtLint->>DiagMgr: updateDiagnostics()

    Editor->>Router: textDocument/didSave
    Router->>Ext: onDidSaveDocument()
    Ext->>DSLint: lint(document)
    Ext->>DubLint: lint(document)
    DubLint->>DiagMgr: createDiagnosticsFor!1(uri)
    DubLint->>DiagMgr: updateDiagnostics()

    DiagMgr->>DiagMgr: combineDiagnostics()<br/>(3スロット統合)
    DiagMgr->>RPC: publishDiagnostics通知
    RPC->>Editor: textDocument/publishDiagnostics
```

## コンポーネントライフサイクル図

```mermaid
stateDiagram-v2
    [*] --> Registered: backend.register!T()
    Registered --> LazyAttached: instance生成時<br/>(attachLazy)
    LazyAttached --> Loading: 初回アクセス時<br/>(onBeforeAccessComponent)
    Loading --> Active: create() + attachComponent()
    Active --> Active: API呼び出し
    Active --> [*]: shutdown / removeInstance

    state LazyAttached {
        [*] --> Pending
        Pending --> Pending: has!T = true<br/>(遅延ロード可能)
    }

    state Active {
        [*] --> Running
        Running --> Crashed: 例外発生
        Crashed --> Running: handleCrash<br/>(自動再起動)
    }
```
