File: AbstractBuildServer.py

package info (click to toggle)
swiftlang 6.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,856,264 kB
  • sloc: cpp: 9,995,718; ansic: 2,234,019; asm: 1,092,167; python: 313,940; objc: 82,726; f90: 80,126; lisp: 38,373; pascal: 25,580; sh: 20,378; ml: 5,058; perl: 4,751; makefile: 4,725; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (213 lines) | stat: -rw-r--r-- 7,717 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#!/usr/bin/env python3
##===----------------------------------------------------------------------===##
##
## This source file is part of the Swift.org open source project
##
## Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors
## Licensed under Apache License v2.0 with Runtime Library Exception
##
## See https://swift.org/LICENSE.txt for license information
## See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
##
##===----------------------------------------------------------------------===##

import json
import sys
from typing import Dict, List, Optional


class RequestError(Exception):
    """
    An error that can be thrown from a request handling function in `AbstractBuildServer` to return an error response to
    SourceKit-LSP.
    """

    code: int
    message: str

    def __init__(self, code: int, message: str):
        self.code = code
        self.message = message


class AbstractBuildServer:
    """
    An abstract class to implement a BSP server in Python for SourceKit-LSP testing purposes.
    """

    def run(self):
        """
        Run the build server. This should be called from the top-level code of the build server's Python file.
        """
        while True:
            line = sys.stdin.readline()
            if len(line) == 0:
                break

            assert line.startswith("Content-Length:")
            length = int(line[len("Content-Length:") :])
            sys.stdin.readline()
            message = json.loads(sys.stdin.read(length))

            try:
                result = self.handle_message(message)
                if result is not None:
                    response_message: Dict[str, object] = {
                        "jsonrpc": "2.0",
                        "id": message["id"],
                        "result": result,
                    }
                    self.send_raw_message(response_message)
            except RequestError as e:
                error_response_message: Dict[str, object] = {
                    "jsonrpc": "2.0",
                    "id": message["id"],
                    "error": {
                        "code": e.code,
                        "message": e.message,
                    },
                }
                self.send_raw_message(error_response_message)

    def handle_message(self, message: Dict[str, object]) -> Optional[Dict[str, object]]:
        """
        Dispatch handling of the given method, received from SourceKit-LSP to the message handling function.
        """
        method: str = str(message["method"])
        params: Dict[str, object] = message["params"]  # type: ignore
        if method == "build/exit":
            return self.exit(params)
        elif method == "build/initialize":
            return self.initialize(params)
        elif method == "build/initialized":
            return self.initialized(params)
        elif method == "build/shutdown":
            return self.shutdown(params)
        elif method == "buildTarget/prepare":
            return self.buildtarget_prepare(params)
        elif method == "buildTarget/sources":
            return self.buildtarget_sources(params)
        elif method == "textDocument/registerForChanges":
            return self.register_for_changes(params)
        elif method == "textDocument/sourceKitOptions":
            return self.textdocument_sourcekitoptions(params)
        elif method == "workspace/didChangeWatchedFiles":
            return self.workspace_did_change_watched_files(params)
        elif method == "workspace/buildTargets":
            return self.workspace_build_targets(params)
        elif method == "workspace/waitForBuildSystemUpdates":
            return self.workspace_waitForBuildSystemUpdates(params)

        # ignore other notifications
        if "id" in message:
            raise RequestError(code=-32601, message=f"Method not found: {method}")

    def send_raw_message(self, message: Dict[str, object]):
        """
        Send a raw message to SourceKit-LSP. The message needs to have all JSON-RPC wrapper fields.

        Subclasses should not call this directly
        """
        message_str = json.dumps(message)
        sys.stdout.buffer.write(
            f"Content-Length: {len(message_str)}\r\n\r\n{message_str}".encode("utf-8")
        )
        sys.stdout.flush()

    def send_notification(self, method: str, params: Dict[str, object]):
        """
        Send a notification with the given method and parameters to SourceKit-LSP.
        """
        message: Dict[str, object] = {
            "jsonrpc": "2.0",
            "method": method,
            "params": params,
        }
        self.send_raw_message(message)

    # Message handling functions.
    # Subclasses should override these to provide functionality.

    def exit(self, notification: Dict[str, object]) -> None:
        pass

    def initialize(self, request: Dict[str, object]) -> Dict[str, object]:
        return {
            "displayName": "test server",
            "version": "0.1",
            "bspVersion": "2.0",
            "rootUri": "blah",
            "capabilities": {"languageIds": ["swift", "c", "cpp", "objective-c", "objective-c"]},
            "data": {
                "sourceKitOptionsProvider": True,
            },
        }

    def initialized(self, notification: Dict[str, object]) -> None:
        pass

    def register_for_changes(self, notification: Dict[str, object]):
        pass

    def textdocument_sourcekitoptions(
        self, request: Dict[str, object]
    ) -> Dict[str, object]:
        raise RequestError(
            code=-32601, message=f"'textDocument/sourceKitOptions' not implemented"
        )

    def shutdown(self, request: Dict[str, object]) -> Dict[str, object]:
        return {}

    def buildtarget_prepare(self, request: Dict[str, object]) -> Dict[str, object]:
        raise RequestError(
            code=-32601, message=f"'buildTarget/prepare' not implemented"
        )

    def buildtarget_sources(self, request: Dict[str, object]) -> Dict[str, object]:
        raise RequestError(
            code=-32601, message=f"'buildTarget/sources' not implemented"
        )

    def workspace_did_change_watched_files(self, notification: Dict[str, object]) -> None:
        pass

    def workspace_build_targets(self, request: Dict[str, object]) -> Dict[str, object]:
        raise RequestError(
            code=-32601, message=f"'workspace/buildTargets' not implemented"
        )

    def workspace_waitForBuildSystemUpdates(self, request: Dict[str, object]) -> Dict[str, object]:
        return {}


class LegacyBuildServer(AbstractBuildServer):
    def send_sourcekit_options_changed(self, uri: str, options: List[str]):
        """
        Send a `build/sourceKitOptionsChanged` notification to SourceKit-LSP, informing it about new build settings
        using the old push-based settings model.
        """
        self.send_notification(
            "build/sourceKitOptionsChanged",
            {
                "uri": uri,
                "updatedOptions": {"options": options},
            },
        )

    """
    A build server that doesn't declare the `sourceKitOptionsProvider` and uses the push-based settings model.
    """

    def initialize(self, request: Dict[str, object]) -> Dict[str, object]:
        return {
            "displayName": "test server",
            "version": "0.1",
            "bspVersion": "2.0",
            "rootUri": "blah",
            "capabilities": {"languageIds": ["a", "b"]},
            "data": {
                "indexDatabasePath": "some/index/db/path",
                "indexStorePath": "some/index/store/path",
            },
        }