Skip to content

Commit e93b7ed

Browse files
authored
Merge pull request #1849 from kateinoigakukun/katei/json-schema
2 parents 17c0634 + 6803d8c commit e93b7ed

17 files changed

+1226
-52
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
.DS_Store
22
default.profraw
33
Package.resolved
4-
/.build
4+
.build
55
/.*-build
66
/Packages
77
/*.xcodeproj

CONTRIBUTING.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,14 @@ swift package format-source-code
115115
116116
If you are developing SourceKit-LSP in VS Code, you can also run the *Run swift-format* task from *Tasks: Run tasks* in the command palette.
117117
118+
## Generate configuration schema
119+
120+
If you modify the configuration options in [`SKOptions`](./Sources/SKOptions), you need to regenerate the configuration the JSON schema and the documentation by running the following command:
121+
122+
```bash
123+
./sourcekit-lsp-dev-utils generate-config-schema
124+
```
125+
118126
## Authoring commits
119127
120128
Prefer to squash the commits of your PR (*pull request*) and avoid adding commits like “Address review comments”. This creates a clearer git history, which doesn’t need to record the history of how the PR evolved.

Documentation/Configuration File.md

Lines changed: 30 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
<!-- DO NOT EDIT THIS FILE. This file is generated by ConfigSchemaGen/OptionDocument.swift. -->
2+
13
# Configuration File
24

35
`.sourcekit-lsp/config.json` configuration files can be used to modify the behavior of SourceKit-LSP in various ways. The following locations are checked. Settings in later configuration files override settings in earlier configuration files
@@ -12,44 +14,45 @@ The structure of the file is currently not guaranteed to be stable. Options may
1214
## Structure
1315

1416
`config.json` is a JSON file with the following structure. All keys are optional and unknown keys are ignored.
15-
16-
- `swiftPM`: Dictionary with the following keys, defining options for SwiftPM workspaces
17+
- `swiftPM`: Options for SwiftPM workspaces.
1718
- `configuration: "debug"|"release"`: The configuration to build the project for during background indexing and the configuration whose build folder should be used for Swift modules if background indexing is disabled. Equivalent to SwiftPM's `--configuration` option.
1819
- `scratchPath: string`: Build artifacts directory path. If nil, the build system may choose a default value. This path can be specified as a relative path, which will be interpreted relative to the project root. Equivalent to SwiftPM's `--scratch-path` option.
19-
- `swiftSDKsDirectory: string`: Equivalent to SwiftPM's `--swift-sdks-path` option
20-
- `swiftSDK: string`: Equivalent to SwiftPM's `--swift-sdk` option
21-
- `triple: string`: Equivalent to SwiftPM's `--triple` option
20+
- `swiftSDKsDirectory: string`: Equivalent to SwiftPM's `--swift-sdks-path` option.
21+
- `swiftSDK: string`: Equivalent to SwiftPM's `--swift-sdk` option.
22+
- `triple: string`: Equivalent to SwiftPM's `--triple` option.
2223
- `cCompilerFlags: string[]`: Extra arguments passed to the compiler for C files. Equivalent to SwiftPM's `-Xcc` option.
2324
- `cxxCompilerFlags: string[]`: Extra arguments passed to the compiler for C++ files. Equivalent to SwiftPM's `-Xcxx` option.
2425
- `swiftCompilerFlags: string[]`: Extra arguments passed to the compiler for Swift files. Equivalent to SwiftPM's `-Xswiftc` option.
2526
- `linkerFlags: string[]`: Extra arguments passed to the linker. Equivalent to SwiftPM's `-Xlinker` option.
26-
- `disableSandbox: bool`: Disables running subprocesses from SwiftPM in a sandbox. Useful when running `sourcekit-lsp` in a sandbox because nested sandboxes are not supported.
27-
- `compilationDatabase`: Dictionary with the following keys, defining options for workspaces with a compilation database
27+
- `disableSandbox: boolean`: Disables running subprocesses from SwiftPM in a sandbox. Equivalent to SwiftPM's `--disable-sandbox` option. Useful when running `sourcekit-lsp` in a sandbox because nested sandboxes are not supported.
28+
- `compilationDatabase`: Dictionary with the following keys, defining options for workspaces with a compilation database.
2829
- `searchPaths: string[]`: Additional paths to search for a compilation database, relative to a workspace root.
29-
- `fallbackBuildSystem`: Dictionary with the following keys, defining options for files that aren't managed by any build system
30-
- `cCompilerFlags: string[]`: Extra arguments passed to the compiler for C files
31-
- `cxxCompilerFlags: string[]`: Extra arguments passed to the compiler for C++ files
32-
- `swiftCompilerFlags: string[]`: Extra arguments passed to the compiler for Swift files
30+
- `fallbackBuildSystem`: Dictionary with the following keys, defining options for files that aren't managed by any build system.
31+
- `cCompilerFlags: string[]`: Extra arguments passed to the compiler for C files.
32+
- `cxxCompilerFlags: string[]`: Extra arguments passed to the compiler for C++ files.
33+
- `swiftCompilerFlags: string[]`: Extra arguments passed to the compiler for Swift files.
3334
- `sdk: string`: The SDK to use for fallback arguments. Default is to infer the SDK using `xcrun`.
34-
- `buildSettingsTimeout: int`: Number of milliseconds to wait for build settings from the build system before using fallback build settings.
35-
- `clangdOptions: string[]`: Extra command line arguments passed to `clangd` when launching it
36-
- `index`: Dictionary with the following keys, defining options related to indexing
35+
- `buildSettingsTimeout: integer`: Number of milliseconds to wait for build settings from the build system before using fallback build settings.
36+
- `clangdOptions: string[]`: Extra command line arguments passed to `clangd` when launching it.
37+
- `index`: Options related to indexing.
3738
- `indexStorePath: string`: Directory in which a separate compilation stores the index store. By default, inferred from the build system.
3839
- `indexDatabasePath: string`: Directory in which the indexstore-db should be stored. By default, inferred from the build system.
3940
- `indexPrefixMap: [string: string]`: Path remappings for remapping index data for local use.
40-
- `maxCoresPercentageToUseForBackgroundIndexing: double`: A hint indicating how many cores background indexing should use at most (value between 0 and 1). Background indexing is not required to honor this setting
41-
- `updateIndexStoreTimeout: int`: Number of seconds to wait for an update index store task to finish before killing it.
42-
- `logging`: Dictionary with the following keys, changing SourceKit-LSP’s logging behavior on non-Apple platforms. On Apple platforms, logging is done through the [system log](Diagnose%20Bundle.md#Enable%20Extended%20Logging). These options can only be set globally and not per workspace.
43-
- `logLevel: "debug"|"info"|"default"|"error"|"fault"`: The level from which one onwards log messages should be written.
41+
- `maxCoresPercentageToUseForBackgroundIndexing: number`: A hint indicating how many cores background indexing should use at most (value between 0 and 1). Background indexing is not required to honor this setting.
42+
- `updateIndexStoreTimeout: integer`: Number of seconds to wait for an update index store task to finish before killing it.
43+
- `logging`: Options related to logging, changing SourceKit-LSP’s logging behavior on non-Apple platforms. On Apple platforms, logging is done through the [system log](Diagnose%20Bundle.md#Enable%20Extended%20Logging). These options can only be set globally and not per workspace.
44+
- `level: "debug"|"info"|"default"|"error"|"fault"`: The level from which one onwards log messages should be written.
4445
- `privacyLevel: "public"|"private"|"sensitive"`: Whether potentially sensitive information should be redacted. Default is `public`, which redacts potentially sensitive information.
4546
- `inputMirrorDirectory: string`: Write all input received by SourceKit-LSP on stdin to a file in this directory. Useful to record and replay an entire SourceKit-LSP session.
46-
- `defaultWorkspaceType: "buildserver"|"compdb"|"swiftpm"`: Overrides workspace type selection logic.
47+
- `defaultWorkspaceType: "buildServer"|"compilationDatabase"|"swiftPM"`: Default workspace type. Overrides workspace type selection logic.
4748
- `generatedFilesPath: string`: Directory in which generated interfaces and macro expansions should be stored.
48-
- `backgroundIndexing: bool`: Explicitly enable or disable background indexing.
49-
- `backgroundPreparationMode: "build"|"noLazy"|"enabled"`: Determines how background indexing should prepare a target. Possible values are:
50-
- `build`: Build a target to prepare it
51-
- `noLazy`: Prepare a target without generating object files but do not do lazy type checking and function body skipping
52-
- `enabled`: Prepare a target without generating object files and the like
53-
- `cancelTextDocumentRequestsOnEditAndClose: bool`: Whether sending a `textDocument/didChange` or `textDocument/didClose` notification for a document should cancel all pending requests for that document.
54-
- `experimentalFeatures: string[]`: Experimental features to enable. Available features: on-type-formatting
55-
- `swiftPublishDiagnosticsDebounceDuration: double`: The time that `SwiftLanguageService` should wait after an edit before starting to compute diagnostics and sending a `PublishDiagnosticsNotification`.
49+
- `backgroundIndexing: boolean`: Whether background indexing is enabled.
50+
- `backgroundPreparationMode: "build"|"noLazy"|"enabled"`: Determines how background indexing should prepare a target.
51+
- `build`: Build a target to prepare it.
52+
- `noLazy`: Prepare a target without generating object files but do not do lazy type checking and function body skipping. This uses SwiftPM's `--experimental-prepare-for-indexing-no-lazy` flag.
53+
- `enabled`: Prepare a target without generating object files.
54+
- `cancelTextDocumentRequestsOnEditAndClose: boolean`: Whether sending a `textDocument/didChange` or `textDocument/didClose` notification for a document should cancel all pending requests for that document.
55+
- `experimentalFeatures: ("on-type-formatting")[]`: Experimental features that are enabled.
56+
- `swiftPublishDiagnosticsDebounceDuration: number`: The time that `SwiftLanguageService` should wait after an edit before starting to compute diagnostics and sending a `PublishDiagnosticsNotification`.
57+
- `workDoneProgressDebounceDuration: number`: When a task is started that should be displayed to the client as a work done progress, how many milliseconds to wait before actually starting the work done progress. This prevents flickering of the work done progress in the client for short-lived index tasks which end within this duration.
58+
- `sourcekitdRequestTimeout: number`: The maximum duration that a sourcekitd request should be allowed to execute before being declared as timed out. In general, editors should cancel requests that they are no longer interested in, but in case editors don't cancel requests, this ensures that a long-running non-cancelled request is not blocking sourcekitd and thus most semantic functionality. In particular, VS Code does not cancel the semantic tokens request, which can cause a long-running AST build that blocks sourcekitd.

SourceKitLSPDevUtils/Package.swift

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// swift-tools-version: 6.0
2+
3+
import PackageDescription
4+
5+
let package = Package(
6+
name: "SourceKitLSPDevUtils",
7+
platforms: [.macOS(.v10_15)],
8+
products: [
9+
.executable(name: "sourcekit-lsp-dev-utils", targets: ["SourceKitLSPDevUtils"])
10+
],
11+
dependencies: [
12+
.package(url: "https://github.com/swiftlang/swift-syntax.git", from: "600.0.1"),
13+
.package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.5.0"),
14+
],
15+
targets: [
16+
.executableTarget(
17+
name: "SourceKitLSPDevUtils",
18+
dependencies: [
19+
"ConfigSchemaGen",
20+
.product(name: "ArgumentParser", package: "swift-argument-parser"),
21+
]
22+
),
23+
.target(
24+
name: "ConfigSchemaGen",
25+
dependencies: [
26+
.product(name: "SwiftSyntax", package: "swift-syntax"),
27+
.product(name: "SwiftParser", package: "swift-syntax"),
28+
]
29+
),
30+
]
31+
)

SourceKitLSPDevUtils/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# sourcekit-lsp-dev-utils
2+
3+
This directory contains utilities for developing SourceKit-LSP. [CONTRIBUTING.md](../CONTRIBUTING.md) covers how to use these utilities.
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors
6+
// Licensed under Apache License v2.0 with Runtime Library Exception
7+
//
8+
// See https://swift.org/LICENSE.txt for license information
9+
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10+
//
11+
//===----------------------------------------------------------------------===//
12+
13+
import Foundation
14+
import SwiftParser
15+
import SwiftSyntax
16+
17+
/// The main entry point for generating a JSON schema and Markdown documentation
18+
/// for the SourceKit-LSP configuration file format
19+
/// (`.sourcekit-lsp/config.json`) from the Swift type definitions in
20+
/// `SKOptions` Swift module.
21+
package struct ConfigSchemaGen {
22+
private struct WritePlan {
23+
fileprivate let category: String
24+
fileprivate let path: URL
25+
fileprivate let contents: () throws -> Data
26+
27+
fileprivate func write() throws {
28+
try contents().write(to: path)
29+
}
30+
}
31+
32+
private static let projectRoot = URL(fileURLWithPath: #filePath)
33+
.deletingLastPathComponent()
34+
.deletingLastPathComponent()
35+
.deletingLastPathComponent()
36+
.deletingLastPathComponent()
37+
private static let sourceDir =
38+
projectRoot
39+
.appendingPathComponent("Sources")
40+
.appendingPathComponent("SKOptions")
41+
private static let configSchemaJSONPath =
42+
projectRoot
43+
.appendingPathComponent("config.schema.json")
44+
private static let configSchemaDocPath =
45+
projectRoot
46+
.appendingPathComponent("Documentation")
47+
.appendingPathComponent("Configuration File.md")
48+
49+
/// Generates and writes the JSON schema and documentation for the SourceKit-LSP configuration file format.
50+
package static func generate() throws {
51+
let plans = try plan()
52+
for plan in plans {
53+
print("Writing \(plan.category) to \"\(plan.path.path)\"")
54+
try plan.write()
55+
}
56+
}
57+
58+
/// Verifies that the generated JSON schema and documentation in the current source tree
59+
/// are up-to-date with the Swift type definitions in `SKOptions`.
60+
/// - Returns: `true` if the generated files are up-to-date, `false` otherwise.
61+
package static func verify() throws -> Bool {
62+
let plans = try plan()
63+
for plan in plans {
64+
print("Verifying \(plan.category) at \"\(plan.path.path)\"")
65+
let expectedContents = try plan.contents()
66+
let actualContents = try Data(contentsOf: plan.path)
67+
guard expectedContents == actualContents else {
68+
print("error: \(plan.category) is out-of-date!")
69+
print("Please run `./sourcekit-lsp-dev-utils generate-config-schema` to update it.")
70+
return false
71+
}
72+
}
73+
return true
74+
}
75+
76+
private static func plan() throws -> [WritePlan] {
77+
let sourceFiles = FileManager.default.enumerator(at: sourceDir, includingPropertiesForKeys: nil)!
78+
let typeNameResolver = TypeDeclResolver()
79+
80+
for case let fileURL as URL in sourceFiles {
81+
guard fileURL.pathExtension == "swift" else {
82+
continue
83+
}
84+
let sourceText = try String(contentsOf: fileURL)
85+
let sourceFile = Parser.parse(source: sourceText)
86+
typeNameResolver.collect(from: sourceFile)
87+
}
88+
let rootTypeDecl = try typeNameResolver.lookupType(fullyQualified: ["SourceKitLSPOptions"])
89+
let context = OptionSchemaContext(typeNameResolver: typeNameResolver)
90+
var schema = try context.buildSchema(from: rootTypeDecl)
91+
92+
// Manually annotate the logging level enum since LogLevel type exists
93+
// outside of the SKOptions module
94+
schema["logging"]?["level"]?.kind = .enum(
95+
OptionTypeSchama.Enum(
96+
name: "LogLevel",
97+
cases: ["debug", "info", "default", "error", "fault"].map {
98+
OptionTypeSchama.Case(name: $0)
99+
}
100+
)
101+
)
102+
schema["logging"]?["privacyLevel"]?.kind = .enum(
103+
OptionTypeSchama.Enum(
104+
name: "PrivacyLevel",
105+
cases: ["public", "private", "sensitive"].map {
106+
OptionTypeSchama.Case(name: $0)
107+
}
108+
)
109+
)
110+
111+
return [
112+
WritePlan(
113+
category: "JSON Schema",
114+
path: configSchemaJSONPath,
115+
contents: { try generateJSONSchema(from: schema, context: context) }
116+
),
117+
WritePlan(
118+
category: "Schema Documentation",
119+
path: configSchemaDocPath,
120+
contents: { try generateDocumentation(from: schema, context: context) }
121+
),
122+
]
123+
}
124+
125+
private static func generateJSONSchema(from schema: OptionTypeSchama, context: OptionSchemaContext) throws -> Data {
126+
let schemaBuilder = JSONSchemaBuilder(context: context)
127+
var jsonSchema = try schemaBuilder.build(from: schema)
128+
jsonSchema.title = "SourceKit-LSP Configuration"
129+
jsonSchema.comment = "DO NOT EDIT THIS FILE. This file is generated by \(#fileID)."
130+
let encoder = JSONEncoder()
131+
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
132+
return try encoder.encode(jsonSchema)
133+
}
134+
135+
private static func generateDocumentation(from schema: OptionTypeSchama, context: OptionSchemaContext) throws -> Data
136+
{
137+
let docBuilder = OptionDocumentBuilder(context: context)
138+
guard let data = try docBuilder.build(from: schema).data(using: .utf8) else {
139+
throw ConfigSchemaGenError("Failed to encode documentation as UTF-8")
140+
}
141+
return data
142+
}
143+
}
144+
145+
struct ConfigSchemaGenError: Error, CustomStringConvertible {
146+
let description: String
147+
148+
init(_ description: String) {
149+
self.description = description
150+
}
151+
}

0 commit comments

Comments
 (0)