Compare changes

Choose any two refs to compare.

+2 -2
Package.swift
···
name: "PterodactylBuild",
targets: ["PterodactylBuild"]
),
-
.library(
+
.executable(
name: "PterodactylLanguageServer",
targets: ["PterodactylLanguageServer"]
)
···
.product(name: "llbuild2fx", package: "swift-llbuild2")
]
),
-
.target(
+
.executableTarget(
name: "PterodactylLanguageServer",
dependencies: [
"LanguageServer",
+8 -5
Sources/PterodactylBuild/Keys/Blob/GetLineMap.swift
···
import llbuild2fx
extension Keys.Blob {
-
struct GetLineMap: BuildKey {
-
let blobId: LLBDataID
+
public struct GetLineMap: BuildKey {
+
public let blobId: LLBDataID
+
public init(blobId: LLBDataID) {
+
self.blobId = blobId
+
}
-
typealias ValueType = PterodactylSyntax.LineMap
+
public typealias ValueType = PterodactylSyntax.LineMap
-
static let versionDependencies: [any FXVersioning.Type] = [ReadContents.self]
+
public static let versionDependencies: [any FXVersioning.Type] = [ReadContents.self]
-
func computeValue(_ ctx: BuildContext<Self>) async throws -> ValueType {
+
public func computeValue(_ ctx: BuildContext<Self>) async throws -> ValueType {
let code = try await ctx.request(ReadContents(blobId: blobId))
return PterodactylSyntax.LineMap(source: code)
}
+14 -10
Sources/PterodactylBuild/Keys/Blob/ParseDocument.swift
···
import Foundation
import PterodactylSyntax
import llbuild2fx
+
import Logging
extension Keys.Blob {
-
struct ParseDocument: BuildKey {
-
let blobId: LLBDataID
-
-
struct ValueType: Codable, FXValue {
-
let tree: PterodactylSyntax.SyntaxTree
-
let diagnostics: [Diagnostic]
+
public struct ParseDocument: BuildKey {
+
public let blobId: LLBDataID
+
public init(blobId: LLBDataID) {
+
self.blobId = blobId
}
-
static let versionDependencies: [any FXVersioning.Type] = [ReadContents.self, Tokenise.self]
+
public struct ValueType: Codable, FXValue {
+
public let tree: PterodactylSyntax.SyntaxTree
+
public let diagnostics: [Diagnostic]
+
}
-
func computeValue(_ ctx: BuildContext<Self>) async throws -> ValueType {
+
public static let versionDependencies: [any FXVersioning.Type] = [ReadContents.self, Tokenise.self]
+
+
public func computeValue(_ ctx: BuildContext<Self>) async throws -> ValueType {
let code = try await ctx.request(ReadContents(blobId: blobId))
let tokens = try await ctx.request(Tokenise(blobId: blobId))
var parser = Parser(source: code, tokens: tokens)
-
PterodactylSyntax.Document.parse(&parser)
-
return ValueType(tree: parser.tree, diagnostics: parser.diagnostics)
+
PterodactylSyntax.Document.parse(&parser, recovery: [])
+
return ValueType(tree: parser.builder.tree, diagnostics: parser.diagnostics)
}
}
}
+17
Sources/PterodactylLanguageServer/Archive/LLBDeclFileTree+Singleton.swift
···
+
// SPDX-FileCopyrightText: 2025 The Project Pterodactyl Developers
+
//
+
// SPDX-License-Identifier: MPL-2.0
+
+
import Foundation
+
import TSCBasic
+
import llbuild2fx
+
+
extension LLBDeclFileTree {
+
public static func file(absolutePath: AbsolutePath, contents: String) -> Self {
+
let components = absolutePath.components
+
let leaf = LLBDeclFileTree.file(contents)
+
return components.dropFirst().reversed().reduce(leaf) { tail, name in
+
.directory(files: [name: tail])
+
}
+
}
+
}
+40
Sources/PterodactylLanguageServer/Archive/SourceTreeManager.swift
···
+
// SPDX-FileCopyrightText: 2025 The Project Pterodactyl Developers
+
//
+
// SPDX-License-Identifier: MPL-2.0
+
+
//import LanguageServerProtocol
+
//import PterodactylBuild
+
//import TSCBasic
+
//import llbuild2fx
+
//
+
//actor SourceTreeManager {
+
// private let buildEngine: FXEngine
+
// private let casClient: LLBCASFSClient
+
// private let casContext: TSCUtility.Context
+
// private(set) var sourceTree: LLBCASFileTree
+
//
+
// init(buildEngine: FXEngine, casClient: LLBCASFSClient, casContext: TSCUtility.Context, sourceTree: LLBCASFileTree? = nil) async throws {
+
// self.buildEngine = buildEngine
+
// self.casClient = casClient
+
// self.casContext = casContext
+
// if let sourceTree {
+
// self.sourceTree = sourceTree
+
// } else {
+
// self.sourceTree = try await casClient.storeDir(.dir([:]), casContext).get()
+
// }
+
// }
+
//
+
// func setBufferText(uri: DocumentUri, text: String) async throws -> LLBCASFileTree {
+
// let path = try AbsolutePath.fromDocumentUri(uri)
+
// let singletonDeclTree = LLBDeclFileTree.file(absolutePath: path, contents: text)
+
// let singletonTree: LLBCASFileTree = try await casClient.storeDir(singletonDeclTree, casContext).get()
+
// self.sourceTree = try await sourceTree.merge(with: singletonTree, in: casClient.db, casContext).get()
+
// return sourceTree
+
// }
+
//
+
// func getBufferText(uri: DocumentUri) async throws -> String? {
+
// let path = try AbsolutePath.fromDocumentUri(uri)
+
// guard let (id, _) = try await sourceTree.lookup(path: path, in: casClient.db, casContext).get() else { return nil }
+
// return try await buildEngine.build(key: Keys.Blob.ReadContents(blobId: id), casContext).get()
+
// }
+
//}
+44 -27
Sources/PterodactylLanguageServer/EventHandler.swift
···
import LanguageServerProtocol
import Logging
import PterodactylBuild
+
import PterodactylSyntax
import TSCBasic
import llbuild2fx
···
private let buildEngine: FXEngine
private let casContext: TSCUtility.Context
private let casClient: LLBCASFSClient
-
private let sourceTreeManager: SourceTreeManager
-
init(connection: JSONRPCClientConnection) async throws {
+
var storedBlobs: [DocumentUri: (blobId: LLBDataID, version: Int?)] = [:]
+
+
init(connection: JSONRPCClientConnection) {
self.connection = connection
let group = LLBMakeDefaultDispatchGroup()
···
self.buildEngine = FXEngine(group: group, db: db, functionCache: functionCache, executor: executor)
self.casClient = LLBCASFSClient(db)
self.casContext = Context()
-
-
self.sourceTreeManager = try await SourceTreeManager(buildEngine: buildEngine, casClient: casClient, casContext: casContext)
}
-
func publishDiagnostics(uri: String, version: Int?) async throws {
+
func storeBlob(text: String, uri: DocumentUri, version: Int?) async throws -> LLBDataID {
+
if let stored = storedBlobs[uri], let version, let storedVersion = stored.version, storedVersion >= version {
+
return stored.blobId
+
}
+
let blobId: LLBDataID = try await casClient.store(LLBByteBuffer(string: text), casContext).get()
+
storedBlobs[uri] = (blobId: blobId, version: version)
+
return blobId
+
}
+
+
func publishLiveDiagnostics(blobId: LLBDataID, uri: DocumentUri, version: Int?) async throws {
+
let lineMap = try await buildEngine.build(key: Keys.Blob.GetLineMap(blobId: blobId), casContext).get()
+
let parseResult = try await buildEngine.build(key: Keys.Blob.ParseDocument(blobId: blobId), casContext).get()
+
let diagnostics = parseResult.diagnostics.map { $0.lspDiagnostic(lineMap: lineMap) }
+
let publishParams = PublishDiagnosticsParams(uri: uri, version: version, diagnostics: diagnostics)
+
try await connection.sendNotification(.textDocumentPublishDiagnostics(publishParams))
}
}
···
TextDocumentSyncOptions(
openClose: true,
change: .full,
+
save: .optionA(false)
)
}
···
func textDocumentDidChange(_ params: DidChangeTextDocumentParams) async {
guard let text = params.contentChanges.first?.text else { return }
do {
-
try await sourceTreeManager.setBufferText(uri: params.textDocument.uri, text: text)
-
// FIXME: this needs to be a transaction.
-
// try await publishDiagnostics(uri: params.textDocument.uri, version: params.textDocument.version)
+
let blobId: LLBDataID = try await storeBlob(text: text, uri: params.textDocument.uri, version: params.textDocument.version)
+
try await publishLiveDiagnostics(blobId: blobId, uri: params.textDocument.uri, version: params.textDocument.version)
} catch {}
}
func textDocumentDidOpen(_ params: DidOpenTextDocumentParams) async {
-
// TODO: restore
-
// await bufferManager.setBufferText(key: params.textDocument.uri, text: params.textDocument.text)
+
let text = params.textDocument.text
do {
-
try await publishDiagnostics(uri: params.textDocument.uri, version: params.textDocument.version)
+
let blobId: LLBDataID = try await storeBlob(text: text, uri: params.textDocument.uri, version: params.textDocument.version)
+
try await publishLiveDiagnostics(blobId: blobId, uri: params.textDocument.uri, version: params.textDocument.version)
} catch {}
}
func semanticTokensFull(id: JSONId, params: SemanticTokensParams) async -> Response<SemanticTokensResponse> {
-
// TODO: restore
-
// guard let document = await bufferManager.documentForBuffer(key: params.textDocument.uri) else { return .success(nil) }
+
guard let storedBlob = storedBlobs[params.textDocument.uri] else { return .success(nil) }
-
let tokenSink: [SemanticToken] = []
-
// TODO: restore
-
// document.tree.collectSemanticTokens(&tokenSink)
-
-
let response = SemanticTokensResponse(SemanticTokens(resultId: nil, tokens: tokenSink))
-
return .success(response)
+
do {
+
let lineMap = try await buildEngine.build(key: Keys.Blob.GetLineMap(blobId: storedBlob.blobId), casContext).get()
+
let parseResult = try await buildEngine.build(key: Keys.Blob.ParseDocument(blobId: storedBlob.blobId), casContext).get()
+
let cursor = SyntaxCursor(lineMap: lineMap, node: .tree(parseResult.tree), utf16Offset: 0)
+
return .success(SemanticTokensResponse(SemanticTokens(resultId: nil, tokens: cursor.semanticTokens)))
+
} catch {
+
return .success(nil)
+
}
}
func foldingRange(id: JSONId, params: FoldingRangeParams) async -> Response<FoldingRangeResponse> {
-
// TODO: restore
-
// guard let document = await bufferManager.documentForBuffer(key: params.textDocument.uri) else { return .success(nil) }
-
let rangeSink: [FoldingRange] = []
-
// TODO: restore
-
// document.tree.collectFoldingRanges(&rangeSink)
-
let response = FoldingRangeResponse(rangeSink)
-
Logger.shared.info("Ranges: \(rangeSink)")
-
return .success(response)
+
guard let storedBlob = storedBlobs[params.textDocument.uri] else { return .success(nil) }
+
+
do {
+
let lineMap = try await buildEngine.build(key: Keys.Blob.GetLineMap(blobId: storedBlob.blobId), casContext).get()
+
let parseResult = try await buildEngine.build(key: Keys.Blob.ParseDocument(blobId: storedBlob.blobId), casContext).get()
+
let cursor = SyntaxCursor(lineMap: lineMap, node: .tree(parseResult.tree), utf16Offset: 0)
+
return .success(FoldingRangeResponse(cursor.foldingRanges))
+
} catch {
+
return .success(nil)
+
}
}
-17
Sources/PterodactylLanguageServer/LLBDeclFileTree+Singleton.swift
···
-
// SPDX-FileCopyrightText: 2025 The Project Pterodactyl Developers
-
//
-
// SPDX-License-Identifier: MPL-2.0
-
-
import Foundation
-
import TSCBasic
-
import llbuild2fx
-
-
extension LLBDeclFileTree {
-
public static func file(absolutePath: AbsolutePath, contents: String) -> Self {
-
let components = absolutePath.components
-
let leaf = LLBDeclFileTree.file(contents)
-
return components.dropFirst().reversed().reduce(leaf) { tail, name in
-
.directory(files: [name: tail])
-
}
-
}
-
}
+54
Sources/PterodactylLanguageServer/PterodactylLanguageServer.swift
···
+
// SPDX-FileCopyrightText: 2025 The Project Pterodactyl Developers
+
//
+
// SPDX-License-Identifier: MPL-2.0
+
+
import Foundation
+
import JSONRPC
+
import LanguageServer
+
import LanguageServerProtocol
+
import Logging
+
+
final class Server {
+
private let connection: JSONRPCClientConnection
+
private let eventHandler: EventHandler
+
+
init() {
+
let channel = DataChannel.stdio()
+
connection = JSONRPCClientConnection(channel)
+
eventHandler = EventHandler(connection: connection)
+
}
+
+
func start() async throws {
+
do {
+
Logger.shared.debug("Starting")
+
try await startEventLoop()
+
} catch {
+
Logger.shared.error("Server error: \(error)")
+
throw error
+
}
+
}
+
+
func startEventLoop() async throws {
+
for await event in await connection.eventSequence {
+
try await handle(event: event)
+
}
+
}
+
+
func handle(event: ClientEvent) async throws {
+
switch event {
+
case .request(let id, let request):
+
await eventHandler.handleRequest(id: id, request: request)
+
case .notification(let notification):
+
await eventHandler.handleNotification(notification)
+
case .error(_): ()
+
}
+
}
+
}
+
+
@main
+
struct PterodactylLanguageServer {
+
static func main() async throws {
+
let server = Server()
+
try await server.start()
+
}
+
}
-39
Sources/PterodactylLanguageServer/SourceTreeManager.swift
···
-
// SPDX-FileCopyrightText: 2025 The Project Pterodactyl Developers
-
//
-
// SPDX-License-Identifier: MPL-2.0
-
-
import LanguageServerProtocol
-
import PterodactylBuild
-
import TSCBasic
-
import llbuild2fx
-
-
actor SourceTreeManager {
-
private let buildEngine: FXEngine
-
private let casClient: LLBCASFSClient
-
private let casContext: TSCUtility.Context
-
private(set) var sourceTree: LLBCASFileTree
-
-
init(buildEngine: FXEngine, casClient: LLBCASFSClient, casContext: TSCUtility.Context, sourceTree: LLBCASFileTree? = nil) async throws {
-
self.buildEngine = buildEngine
-
self.casClient = casClient
-
self.casContext = casContext
-
if let sourceTree {
-
self.sourceTree = sourceTree
-
} else {
-
self.sourceTree = try await casClient.storeDir(.dir([:]), casContext).get()
-
}
-
}
-
-
func setBufferText(uri: DocumentUri, text: String) async throws {
-
let path = try AbsolutePath.fromDocumentUri(uri)
-
let singletonDeclTree = LLBDeclFileTree.file(absolutePath: path, contents: text)
-
let singletonTree: LLBCASFileTree = try await casClient.storeDir(singletonDeclTree, casContext).get()
-
self.sourceTree = try await sourceTree.merge(with: singletonTree, in: casClient.db, casContext).get()
-
}
-
-
func getBufferText(uri: DocumentUri) async throws -> String? {
-
let path = try AbsolutePath.fromDocumentUri(uri)
-
guard let (id, _) = try await sourceTree.lookup(path: path, in: casClient.db, casContext).get() else { return nil }
-
return try await buildEngine.build(key: Keys.Blob.ReadContents(blobId: id), casContext).get()
-
}
-
}
+1 -1
Sources/PterodactylSyntax/BlockLayoutProcessor.swift
···
result.append(Token(kind: .blockEnd, text: ""))
}
-
if !firstTokenInBlock && indentStack.count > 1 && locatedToken.location.startColumn == indentStack.last! {
+
if !firstTokenInBlock && indentStack.count > 1 && locatedToken.token.kind.isVisible && locatedToken.location.startColumn == indentStack.last! {
result.append(Token(kind: .blockSep, text: ""))
}
}
+22 -5
Sources/PterodactylSyntax/Diagnostic.swift
···
import LanguageServerProtocol
public struct Diagnostic: Equatable, Codable, Sendable {
-
typealias Severity = LanguageServerProtocol.DiagnosticSeverity
-
-
let message: String
-
let severity: Severity
-
let absoluteUtf16Range: Range<Int>
+
public typealias Severity = LanguageServerProtocol.DiagnosticSeverity
+
+
public let message: String
+
public let severity: Severity
+
public let absoluteUtf16Range: Range<Int>
init(message: String, severity: Severity, absoluteRange: Range<Int>) {
self.message = message
···
init(message: String, absoluteRange: Range<Int>) {
self.init(message: message, severity: Severity.error, absoluteRange: absoluteRange)
+
}
+
+
func lspRange(lineMap: LineMap) -> LanguageServerProtocol.LSPRange {
+
let start = lineMap.location(at: absoluteUtf16Range.lowerBound)
+
let end = lineMap.location(at: absoluteUtf16Range.upperBound)
+
return LSPRange(
+
start: Position(line: start.line, character: start.column),
+
end: Position(line: end.line, character: end.column)
+
)
+
}
+
+
public func lspDiagnostic(lineMap: LineMap) -> LanguageServerProtocol.Diagnostic {
+
LanguageServerProtocol.Diagnostic(
+
range: lspRange(lineMap: lineMap),
+
severity: severity,
+
message: message
+
)
}
}
+7 -7
Sources/PterodactylSyntax/Grammar/Document/Import.swift
···
static let kind = SyntaxTreeKind(name: "import.name")
static let kinds = [kind]
-
static func before(_ parser: inout Parser) -> Bool {
+
static func precondition(_ parser: inout Parser) -> Bool {
parser.isAt(kind: .identifier)
}
-
static func inside(_ parser: inout Parser) -> ParseResult {
-
parser.expect(kind: .identifier, metadata: TokenMetadata(semanticTokenType: .namespace))
+
static func inside(_ parser: inout Parser, recovery: Set<TokenKind>) -> ParseResult {
+
parser.expect(kind: .identifier, metadata: TokenMetadata(semanticTokenType: .namespace), recovery: recovery)
return ParseResult(kind: Self.kind)
}
}
···
static let kind = SyntaxTreeKind(name: "import")
static let kinds = [kind]
-
static func before(_ parser: inout Parser) -> Bool {
+
static func precondition(_ parser: inout Parser) -> Bool {
parser.isAt(kind: .keyword(.import))
}
-
static func inside(_ parser: inout Parser) -> ParseResult {
-
parser.expect(kind: .keyword(.import), metadata: TokenMetadata(semanticTokenType: .keyword))
+
static func inside(_ parser: inout Parser, recovery: Set<TokenKind>) -> ParseResult {
+
parser.expect(kind: .keyword(.import), metadata: TokenMetadata(semanticTokenType: .keyword), recovery: recovery)
parser.eatTrivia()
-
ImportName.parse(&parser)
+
ImportName.parse(&parser, recovery: recovery)
return ParseResult(kind: Self.kind)
}
}
+3 -3
Sources/PterodactylSyntax/Grammar/Document/Theory/Declaration/Lhs.swift
···
static let kind = SyntaxTreeKind(name: "declaration.lhs")
static let kinds = [kind]
-
static func before(_ parser: inout Parser) -> Bool {
+
static func precondition(_ parser: inout Parser) -> Bool {
parser.isAt(kind: .identifier)
}
-
static func inside(_ parser: inout Parser) -> ParseResult {
-
parser.expect(kind: .identifier, metadata: TokenMetadata(semanticTokenType: .method))
+
static func inside(_ parser: inout Parser, recovery: Set<TokenKind>) -> ParseResult {
+
parser.expect(kind: .identifier, metadata: TokenMetadata(semanticTokenType: .method), recovery: recovery)
return ParseResult(kind: Self.kind)
}
}
+3 -3
Sources/PterodactylSyntax/Grammar/Document/Theory/Declaration/Rhs.swift
···
static let kind = SyntaxTreeKind(name: "declaration.lhs")
static let kinds = [kind]
-
static func before(_ parser: inout Parser) -> Bool {
+
static func precondition(_ parser: inout Parser) -> Bool {
parser.isAt(kind: .identifier)
}
-
static func inside(_ parser: inout Parser) -> ParseResult {
-
parser.expect(kind: .identifier, metadata: TokenMetadata(semanticTokenType: .method))
+
static func inside(_ parser: inout Parser, recovery: Set<TokenKind>) -> ParseResult {
+
parser.expect(kind: .identifier, metadata: TokenMetadata(semanticTokenType: .method), recovery: recovery)
return ParseResult(kind: Self.kind)
}
}
+6 -5
Sources/PterodactylSyntax/Grammar/Document/Theory/Declaration.swift
···
static let kinds = [Kinds.claim, Kinds.refine, Kinds.define]
-
static func before(_ parser: inout Parser) -> Bool {
-
Lhs.before(&parser)
+
static func precondition(_ parser: inout Parser) -> Bool {
+
Lhs.precondition(&parser)
}
static let punctuationMap: [Punctuation: SyntaxTreeKind] = [
···
.doubleRightArrow: Kinds.define
]
-
static func inside(_ parser: inout Parser) -> ParseResult {
-
Lhs.parse(&parser)
+
static func inside(_ parser: inout Parser, recovery: Set<TokenKind>) -> ParseResult {
+
let punctuations = punctuationMap.keys.map { TokenKind.punctuation($0) }
+
Lhs.parse(&parser, recovery: recovery.union(punctuations))
parser.eatTrivia()
var kind: SyntaxTreeKind = .error
···
}
parser.eatTrivia()
-
Rhs.parse(&parser)
+
Rhs.parse(&parser, recovery: recovery)
return ParseResult(kind: kind)
}
+5 -13
Sources/PterodactylSyntax/Grammar/Document/Theory/TheoryBlock.swift
···
static let kind = SyntaxTreeKind(name: "theory.block")
static let kinds = [kind]
-
static func before(_ parser: inout Parser) -> Bool {
+
static func precondition(_ parser: inout Parser) -> Bool {
parser.isAt(kind: .keyword(.where))
}
-
static func inside(_ parser: inout Parser) -> ParseResult {
-
parser.expect(kind: .keyword(.where), metadata: TokenMetadata(semanticTokenType: .keyword))
+
static func inside(_ parser: inout Parser, recovery: Set<TokenKind>) -> ParseResult {
+
parser.expect(kind: .keyword(.where), metadata: TokenMetadata(semanticTokenType: .keyword), recovery: recovery.union([.keyword(.theory), .blockComment(terminated: true), .lineComment]))
-
parser.eatTrivia()
if parser.eat(kind: .blockBegin, metadata: nil) {
parser.eatTrivia()
-
-
while Declaration.tryParse(&parser) {
+
while parser.eat(kind: .blockSep, metadata: nil) {
+
Declaration.parse(&parser, recovery: recovery.union([.blockSep, .blockEnd]))
parser.eatTrivia()
-
if parser.eat(kind: .blockSep, metadata: nil) {
-
parser.eatTrivia()
-
continue
-
} else {
-
break
-
}
}
-
_ = parser.eat(kind: .blockEnd, metadata: nil)
}
+2 -2
Sources/PterodactylSyntax/Grammar/Document/Theory/TheoryName.swift
···
static let kind = SyntaxTreeKind(name: "theory.name")
static let kinds = [kind]
-
static func before(_ parser: inout Parser) -> Bool {
+
static func precondition(_ parser: inout Parser) -> Bool {
parser.isAt(kind: .identifier)
}
-
static func inside(_ parser: inout Parser) -> ParseResult {
+
static func inside(_ parser: inout Parser, recovery: Set<TokenKind>) -> ParseResult {
parser.advance(metadata: TokenMetadata(semanticTokenType: .interface))
return ParseResult(kind: Self.kind)
}
+6 -6
Sources/PterodactylSyntax/Grammar/Document/Theory.swift
···
enum Theory: Grammar {
static let kind = SyntaxTreeKind(name: "theory")
static let kinds = [kind]
-
-
static func before(_ parser: inout Parser) -> Bool {
+
+
static func precondition(_ parser: inout Parser) -> Bool {
parser.isAt(kind: .keyword(.theory))
}
-
static func inside(_ parser: inout Parser) -> ParseResult {
-
parser.expect(kind: .keyword(.theory), metadata: TokenMetadata(semanticTokenType: .keyword))
+
static func inside(_ parser: inout Parser, recovery: Set<TokenKind>) -> ParseResult {
+
parser.expect(kind: .keyword(.theory), metadata: TokenMetadata(semanticTokenType: .keyword), recovery: recovery)
parser.eatTrivia()
-
if !TheoryName.tryParse(&parser) {
+
if !TheoryName.tryParse(&parser, recovery: recovery) {
parser.advance(error: "Expected theory name")
}
parser.eatTrivia()
-
TheoryBlock.parse(&parser)
+
TheoryBlock.parse(&parser, recovery: recovery)
return ParseResult(kind: Self.kind)
}
+5 -5
Sources/PterodactylSyntax/Grammar/Document.swift
···
public static let kind = SyntaxTreeKind(name: "document")
public static let kinds = [kind]
-
public static func before(_ parser: inout Parser) -> Bool {
+
public static func precondition(_ parser: inout Parser) -> Bool {
true
}
-
public static func inside(_ parser: inout Parser) -> ParseResult {
+
public static func inside(_ parser: inout Parser, recovery: Set<TokenKind>) -> ParseResult {
parser.eatTrivia()
// Parse imports
while !parser.isAt(kind: .eof) {
parser.eatTrivia()
-
if Theory.before(&parser) { break }
+
if Theory.precondition(&parser) { break }
-
if !Import.tryParse(&parser) {
+
if !Import.tryParse(&parser, recovery: recovery) {
parser.advance(error: "Expected to see either an import or a theory declaration, but instead got \(parser.currentToken.kind): \(parser.currentToken.text)")
}
}
// Theories section
while !parser.isAt(kind: .eof) {
-
if !Theory.tryParse(&parser) {
+
if !Theory.tryParse(&parser, recovery: recovery) {
if parser.isAt(kindSatisfying: \.isVisible) {
let token = parser.currentToken
parser.advance(error: "Unexpected token: \(token.kind)")
+17 -17
Sources/PterodactylSyntax/Grammar.swift
···
static var kinds: [SyntaxTreeKind] { get }
/// Indicates whether the current parser state is consistent with the grammatical production starting here. When a given grammatical element is optional, this can be used to avoid backtracking. This is a *precondition* for parsing.
-
static func before(_ parser: inout Parser) -> Bool
+
static func precondition(_ parser: inout Parser) -> Bool
-
/// Parse the grammatical production, assuming the precondition indicated by ``before(_:)``. This function should not be called outside this module (instead, use ``parse(_:)`` and ``tryParse(_:)``.
-
static func inside(_ parser: inout Parser) -> ParseResult
+
/// Parse the grammatical production, assuming the precondition indicated by ``precondition(_:)``. This function should not be called outside this module (instead, use ``parse(_:recovery:)`` and ``tryParse(_:recovery:)``.
+
static func inside(_ parser: inout Parser, recovery: Set<TokenKind>) -> ParseResult
+
}
+
+
extension Grammar {
+
public static func tryParse(_ parser: inout Parser, recovery: Set<TokenKind>) -> Bool {
+
guard !parser.isEndOfFile && precondition(&parser) else { return false }
+
parse(&parser, recovery: recovery)
+
return true
+
}
+
+
public static func parse(_ parser: inout Parser, recovery: Set<TokenKind>) {
+
let mark = parser.builder.open()
+
let result = inside(&parser, recovery: recovery)
+
parser.builder.close(mark: mark, kind: result.kind, metadata: result.metadata)
+
}
}
public struct ParseResult {
···
}
}
-
-
extension Grammar {
-
public static func tryParse(_ parser: inout Parser) -> Bool {
-
guard !parser.isEndOfFile && before(&parser) else { return false }
-
parse(&parser)
-
return true
-
}
-
-
public static func parse(_ parser: inout Parser) {
-
let mark = parser.open()
-
let result = inside(&parser)
-
parser.close(mark: mark, kind: result.kind, metadata: result.metadata)
-
}
-
}
+1 -1
Sources/PterodactylSyntax/LineMap.swift
···
private let utf16LineOffsets: [Int]
public init(source: String) {
-
var offsets: [Int] = []
+
var offsets: [Int] = [0]
for idx in source.indices {
let c = source[idx]
if c == "\n" || c == "\r\n" || c == "\r" {
+61 -83
Sources/PterodactylSyntax/Parser.swift
···
// SPDX-License-Identifier: MPL-2.0
public struct Parser {
-
enum Event: Equatable {
-
case open(kind: SyntaxTreeKind, metadata: SyntaxTreeMetadata?)
-
case close
-
case advance(metadata: TokenMetadata?)
-
}
-
public struct MarkOpened {
internal let index: Int
}
···
}
public private(set) var diagnostics: [Diagnostic] = []
+
public var builder: SyntaxTreeBuilder = SyntaxTreeBuilder()
-
private var fuel: Int = 0
+
private var inError: Bool = false
private var position: Int = 0
-
private var events: [Event] = []
private var absoluteUtf16Offset: Int = 0
public var absoluteRangeAtCursor: Range<Int> {
return absoluteUtf16Offset..<absoluteUtf16Offset
···
}
-
public mutating func open() -> MarkOpened {
-
let mark = MarkOpened(index: events.count)
-
events.append(.open(kind: .error, metadata: nil))
-
return mark
-
}
-
-
public mutating func close(mark: MarkOpened, kind: SyntaxTreeKind, metadata: SyntaxTreeMetadata?) {
-
events[mark.index] = .open(kind: kind, metadata: metadata)
-
events.append(.close)
-
}
-
public mutating func advance(metadata: TokenMetadata?) {
precondition(!isEndOfFile)
-
events.append(.advance(metadata: metadata))
+
builder.advance(token: currentToken, metadata: metadata)
absoluteUtf16Offset += currentToken.utf16Length
position += 1
-
fuel = 256
}
-
public mutating func advance(error: String?, metadata: TokenMetadata? = nil) {
-
let mark = open()
-
if let error {
-
let diagnostic = Diagnostic(
-
message: error,
-
absoluteRange: absoluteRangeOfCurrentToken
-
)
+
public mutating func advance(error: String, metadata: TokenMetadata? = nil) {
+
let mark = builder.open()
+
let diagnostic = Diagnostic(
+
message: error,
+
absoluteRange: absoluteRangeOfCurrentToken
+
)
-
diagnostics.append(diagnostic)
-
}
+
diagnostics.append(diagnostic)
advance(metadata: metadata)
-
close(mark: mark, kind: .error, metadata: nil)
-
}
-
-
public mutating func lookahead(_ k: Int) -> TokenKind? {
-
precondition(fuel > 0, "Parser is stuck!")
-
fuel -= 1
-
let index = position + k
-
guard tokens.indices.contains(index) else { return nil }
-
return tokens[index].kind
+
builder.close(mark: mark, kind: .error, metadata: nil)
}
-
public mutating func eat(kindSatisfying predicate: (TokenKind) -> Bool, metadata: TokenMetadata?) -> Bool {
-
guard !isEndOfFile && isAt(kindSatisfying: predicate) else { return false }
+
public mutating func eat(kind: TokenKind, metadata: TokenMetadata?) -> Bool {
+
guard !isEndOfFile && isAt(kindSatisfying: { $0 == kind }) else { return false }
advance(metadata: metadata)
return true
}
-
public mutating func eat(kind: TokenKind, metadata: TokenMetadata?) -> Bool {
-
eat(kindSatisfying: { $0 == kind }, metadata: metadata)
+
enum ControlFlow {
+
case `continue`
+
case `break`
}
-
public mutating func expect(kind: TokenKind, metadata: TokenMetadata?, error: String? = nil) {
-
if eat(kind: kind, metadata: metadata) { return }
-
let diagnostic = Diagnostic(
-
message: error ?? "Expected \(kind) but got \(currentToken.kind): `\(currentToken.text)`",
-
absoluteRange: absoluteRangeAtCursor
-
)
-
diagnostics.append(diagnostic)
+
mutating func ate(kind: TokenKind, metadata: TokenMetadata?) -> ControlFlow {
+
guard eat(kind: kind, metadata: metadata) else { return .continue }
+
inError = false
+
eatTrivia()
+
return .break
}
-
public var tree: SyntaxTree {
-
var events = events
-
var stack: [SyntaxTree.Builder] = []
-
var cursor: Int = 0
+
mutating func recoverUntil(_ anchors: Set<TokenKind>, expected: TokenKind, error: String? = nil) {
+
var discardTokens: [Token] = []
+
let startOffset = absoluteUtf16Offset
-
precondition(events.popLast() == .close)
+
while !self.isAt(kindSatisfying: { anchors.contains($0) }) {
+
if isEndOfFile { break }
+
let token = currentToken
+
advance(metadata: nil)
+
discardTokens.append(token)
+
}
-
for event in events {
-
switch event {
-
case .open(let kind, let metadata):
-
stack.append(SyntaxTree.Builder(kind: kind, metadata: metadata, children: []))
-
case .close:
-
let tree = stack.popLast()!
-
stack.modifyLast { last in
-
last.children.append(.tree(tree.tree))
-
}
-
case .advance(let metadata):
-
let token = tokens[cursor]
-
cursor += 1
-
stack.modifyLast { last in
-
last.children.append(.token(token, metadata: metadata))
-
}
+
var endOffset = startOffset
+
+
let error = error ?? "Expected \(expected) but got \(discardTokens)"
+
+
if discardTokens.isEmpty {
+
if !inError {
+
inError = true
+
diagnostics.append(Diagnostic(message: error, absoluteRange: absoluteRangeAtCursor))
+
}
+
return
+
} else {
+
let mark = builder.open()
+
for discardToken in discardTokens {
+
endOffset += discardToken.utf16Length
+
}
+
+
builder.close(mark: mark, kind: .error, metadata: nil)
+
+
if !inError {
+
inError = true
+
diagnostics.append(Diagnostic(message: error, absoluteRange: startOffset..<endOffset))
}
}
+
}
-
assert(stack.count == 1)
-
return stack.popLast()!.tree
+
public mutating func expect(kind: TokenKind, metadata: TokenMetadata?, recovery: Set<TokenKind>, error: String? = nil) {
+
var anchors = recovery
+
if ate(kind: kind, metadata: metadata) == .break { return }
+
anchors.insert(kind)
+
recoverUntil(anchors, expected: kind, error: error)
+
let _ = ate(kind: kind, metadata: metadata)
}
+
}
+
extension Parser {
mutating func eatTrivium() -> Bool {
switch currentToken.kind {
-
case .whitespace:
+
case .whitespace, .newline:
advance(metadata: nil)
return true
case .blockComment(let terminated):
···
mutating func eatTrivia() {
while !isEndOfFile && eatTrivium() {}
-
}
-
-
}
-
-
extension Array {
-
fileprivate mutating func modifyLast(_ modifier: (inout Element) -> Void) {
-
if var last = popLast() {
-
modifier(&last)
-
append(last)
-
}
}
}
+22
Sources/PterodactylSyntax/SemanticToken.swift
···
return result
}
}
+
+
extension SyntaxCursor {
+
public func collectSemanticTokens(_ sink: inout [SemanticToken]) {
+
if let (_, metadata) = node.token, let metadata {
+
for lineRange in singleLineRanges {
+
if let semanticToken = metadata.semanticToken(range: lineRange) {
+
sink.append(semanticToken)
+
}
+
}
+
}
+
+
for child in children {
+
child.collectSemanticTokens(&sink)
+
}
+
}
+
+
public var semanticTokens: [SemanticToken] {
+
var tokens: [SemanticToken] = []
+
collectSemanticTokens(&tokens)
+
return tokens
+
}
+
}
+1 -1
Sources/PterodactylSyntax/SyntaxCursor.swift
···
utf16Offset..<utf16Offset + node.utf16Length
}
-
init(lineMap: LineMap, node: SyntaxTree.Child, utf16Offset: Int) {
+
public init(lineMap: LineMap, node: SyntaxTree.Child, utf16Offset: Int) {
self.lineMap = lineMap
self.node = node
self.utf16Offset = utf16Offset
+1 -1
Sources/PterodactylSyntax/SyntaxTree.swift
···
extension SyntaxTree {
/// A mutable version of ``SyntaxTree`` that does not keep track of textual length, for use when constructing trees.
-
public struct Builder {
+
public struct MutableTree {
public var kind: SyntaxTreeKind
public var metadata: SyntaxTreeMetadata?
public var children: [Child]
+70
Sources/PterodactylSyntax/SyntaxTreeBuilder.swift
···
+
// SPDX-FileCopyrightText: 2025 The Project Pterodactyl Developers
+
//
+
// SPDX-License-Identifier: MPL-2.0
+
+
import Foundation
+
+
public struct SyntaxTreeBuilder {
+
private enum Event: Equatable {
+
case open(kind: SyntaxTreeKind, metadata: SyntaxTreeMetadata?)
+
case close
+
case advance(token: Token, metadata: TokenMetadata?)
+
}
+
+
public struct MarkOpened {
+
internal let index: Int
+
}
+
+
private var events: [Event] = []
+
+
public mutating func advance(token: Token, metadata: TokenMetadata?) {
+
events.append(.advance(token: token, metadata: metadata))
+
}
+
+
public mutating func open() -> MarkOpened {
+
let mark = MarkOpened(index: events.count)
+
events.append(.open(kind: .error, metadata: nil))
+
return mark
+
}
+
+
public mutating func close(mark: MarkOpened, kind: SyntaxTreeKind, metadata: SyntaxTreeMetadata?) {
+
events[mark.index] = .open(kind: kind, metadata: metadata)
+
events.append(.close)
+
}
+
+
public var tree: SyntaxTree {
+
var events = events
+
var stack: [SyntaxTree.MutableTree] = []
+
+
precondition(events.popLast() == .close)
+
+
for event in events {
+
switch event {
+
case .open(let kind, let metadata):
+
stack.append(SyntaxTree.MutableTree(kind: kind, metadata: metadata, children: []))
+
case .close:
+
let tree = stack.popLast()!
+
stack.modifyLast { last in
+
last.children.append(.tree(tree.tree))
+
}
+
case .advance(let token, let metadata):
+
stack.modifyLast { last in
+
last.children.append(.token(token, metadata: metadata))
+
}
+
}
+
}
+
+
assert(stack.count == 1)
+
return stack.popLast()!.tree
+
}
+
}
+
+
+
extension Array {
+
fileprivate mutating func modifyLast(_ modifier: (inout Element) -> Void) {
+
if var last = popLast() {
+
modifier(&last)
+
append(last)
+
}
+
}
+
}
+1 -1
Sources/PterodactylSyntax/Token.swift
···
import Foundation
-
public struct Token: Codable {
+
public struct Token: Codable, Equatable {
public let kind: TokenKind
public let text: String
public let utf16Length: Int
+2 -1
Sources/PterodactylSyntax/Types.swift
···
case equal = "="
}
-
public enum TokenKind: Codable, Equatable, Sendable {
+
public enum TokenKind: Codable, Equatable, Sendable, Hashable {
case eof
case keyword(Keyword)
case punctuation(Punctuation)
···
default: true
}
}
+
public var canDetermineLayoutColumn: Bool {
switch self {
case .whitespace, .eof: false
+37
Tests/PterodactylBuildTests/Test.swift
···
import Testing
@testable import PterodactylBuild
+
@testable import PterodactylSyntax
@testable import llbuild2fx
struct BuildTests {
+
@Test
+
func testBlockLayout() async throws {
+
let code = """
+
theory Foo where
+
foo : bar
+
baz : sdf
+
"""
+
+
var lexer = PterodactylSyntax.Lexer(input: code)
+
let flatTokens = lexer.tokenize()
+
let blockTokens = BlockLayoutProcessor(tokens: flatTokens).layout()
+
+
#expect(
+
blockTokens.map(\.kind) == [
+
.keyword(.theory), .whitespace, .identifier, .whitespace, .keyword(.where), .blockBegin, .newline, .whitespace, .blockSep, .identifier, .whitespace,
+
.punctuation(.colon),
+
.whitespace, .identifier, .newline, .whitespace, .blockSep, .identifier, .whitespace, .punctuation(.colon), .whitespace, .identifier, .blockEnd, .eof
+
])
+
}
+
+
@Test
+
func testParse() async throws {
+
let code = """
+
theory Foo where
+
asdf : asdf
+
"""
+
+
var lexer = PterodactylSyntax.Lexer(input: code)
+
let flatTokens = lexer.tokenize()
+
let blockTokens = BlockLayoutProcessor(tokens: flatTokens).layout()
+
var parser = Parser(source: code, tokens: blockTokens)
+
Document.parse(&parser, recovery: [])
+
+
#expect(parser.diagnostics.isEmpty)
+
}
+
@Test
func testImports() async throws {
let group = LLBMakeDefaultDispatchGroup()
+4 -17
Tests/PterodactylLanguageServerTests/Test.swift
···
+
// SPDX-FileCopyrightText: 2025 The Project Pterodactyl Developers
+
//
+
// SPDX-License-Identifier: MPL-2.0
+
//
// File.swift
// Pterodactyl
···
])
#expect(foo.debugDescription == expected.debugDescription)
-
}
-
-
@Test
-
func testSourceTreeManager() async throws {
-
let group = LLBMakeDefaultDispatchGroup()
-
let db = LLBInMemoryCASDatabase(group: group)
-
let functionCache = FXInMemoryFunctionCache(group: group)
-
let executor = FXLocalExecutor()
-
let engine = FXEngine(group: group, db: db, functionCache: functionCache, executor: executor)
-
let client = LLBCASFSClient(db)
-
let context = Context()
-
-
let manager = try await SourceTreeManager(buildEngine: engine, casClient: client, casContext: context)
-
let uri = "file://foo/bar/wooo.txt"
-
let contents = "hello world"
-
try await manager.setBufferText(uri: uri, text: contents)
-
try await #expect(manager.getBufferText(uri: uri) == contents)
}
}
+6
test.ptero
···
+
theory asdf where
+
foo : asdfs
+
foo : sdf
+
+
/* asdfasdf */
+
// asdf;lkj asdf;klj asdfkjh asdfjlkha sdfljk