Files

209 lines
13 KiB
Swift

// SPDX-License-Identifier: GPL-3.0-or-later
import Foundation
/// Read-only lexical assistance. Queries never compile, execute Make, evaluate
/// macros, or rebuild the project index. All coordinates are native UTF-16.
enum CMOCCompletion {
struct Candidate: Identifiable, Equatable, Sendable {
var id: String { name }
let name: String
let detail: String
let conditional: Bool
let replacementRange: NSRange
let insertion: String
}
struct ParameterHint: Identifiable, Equatable, Sendable {
var id: String { sourcePath + ":" + signature }
let signature: String
let name: String
let parameters: [String]
let activeParameter: Int
let conditional: Bool
let sourcePath: String
}
private static let keywords = ["asm", "auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "int", "interrupt", "long", "register", "return", "short", "signed", "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "volatile", "while"]
private static let controls: Set<String> = ["if", "for", "while", "switch", "sizeof", "return", "else", "do", "asm", "__asm"]
private static let typeWords: Set<String> = ["void", "char", "short", "int", "long", "float", "double", "unsigned", "signed", "struct", "union", "enum", "typedef"]
static func suggestions(index: CMOCProjectIndex, path: String, text: String, offset: Int, limit: Int = 80) -> [Candidate] {
guard ["c", "h"].contains((path as NSString).pathExtension.lowercased()),
text.utf8.count <= CMOCProjectIndex.maximumFileBytes else { return [] }
let units = Array(text.utf16)
guard offset >= 0, offset <= units.count, let scan = scan(units, to: offset), !scan.suppressed else { return [] }
var start = offset, end = offset
while start > 0 && identifierPart(units[start - 1]) { start -= 1 }
while end < units.count && identifierPart(units[end]) { end += 1 }
if start < end && !identifierStart(units[start]) { return [] }
let prefix = String(decoding: units[start..<offset], as: UTF16.self)
guard prefix.utf16.count <= 256 else { return [] }
let preceding = scan.tokens.last { $0.offset < start }
guard preceding?.text != ".", preceding?.text != "->" else { return [] }
let range = NSRange(location: start, length: end - start)
let revision = Revision(original: index.documents[path], current: units, offset: offset)
let symbols = index.completionSymbols(from: path, offset: revision.offset, prefix: prefix, includeLocals: revision.safeScopes)
.filter { $0.path != path || revision.keeps($0) }
var seen: Set<String> = [], candidates: [Candidate] = []
let maximum = min(max(1, limit), 200)
for symbol in symbols {
guard seen.insert(symbol.name).inserted else { continue }
let uncertain = symbol.conditional || !revision.safeScopes || (symbol.path == path && revision.changed)
candidates.append(.init(name: symbol.name,
detail: symbol.kind.rawValue + " · " + symbol.signature + " · " + symbol.path,
conditional: uncertain, replacementRange: range, insertion: symbol.name))
if candidates.count >= maximum { return candidates }
}
for keyword in keywords where keyword.hasPrefix(prefix) && seen.insert(keyword).inserted {
candidates.append(.init(name: keyword, detail: "C keyword", conditional: false, replacementRange: range, insertion: keyword))
if candidates.count >= maximum { break }
}
return candidates
}
static func parameterHints(index: CMOCProjectIndex, path: String, text: String, offset: Int) -> [ParameterHint] {
guard ["c", "h"].contains((path as NSString).pathExtension.lowercased()),
text.utf8.count <= CMOCProjectIndex.maximumFileBytes else { return [] }
let units = Array(text.utf16)
guard offset >= 0, offset <= units.count, let scanned = scan(units, to: offset), !scanned.suppressed || scanned.literal else { return [] }
struct Frame { let delimiter: String; let name: String?; let tokenIndex: Int; var argument: Int }
let tokens = scanned.tokens
var stack: [Frame] = []
for (i, token) in tokens.enumerated() {
switch token.text {
case "(", "[", "{":
guard stack.count < 128 else { return [] }
let previous = i > 0 ? tokens[i - 1] : nil
let member = i > 1 && [".", "->"].contains(tokens[i - 2].text)
let name = token.text == "(" && previous?.identifier == true && !controls.contains(previous!.text) && !member ? previous!.text : nil
stack.append(.init(delimiter: token.text, name: name, tokenIndex: i, argument: 0))
case ")", "]", "}":
let expected = token.text == ")" ? "(" : token.text == "]" ? "[" : "{"
guard stack.last?.delimiter == expected else { return [] }
stack.removeLast()
case ",":
if stack.last?.name != nil { stack[stack.count - 1].argument += 1 }
default: break
}
}
guard let call = stack.last(where: { $0.name != nil }), let name = call.name else { return [] }
let nameToken = tokens[call.tokenIndex - 1]
let revision = Revision(original: index.documents[path], current: units, offset: nameToken.offset)
// An indexed declaration, or a newly typed obvious declaration, is not
// a call. Function pointers and member calls are deliberately omitted.
if index.symbols.contains(where: { $0.path == path && $0.name == name && $0.offsetUTF16 == revision.offset && $0.kind == .function }) { return [] }
let statementStart = tokens[..<(call.tokenIndex - 1)].lastIndex(where: { [";", "{", "}"].contains($0.text) }).map { $0 + 1 } ?? 0
let prefix = tokens[statementStart..<(call.tokenIndex - 1)].map(\.text)
if !prefix.contains("="), !prefix.contains(where: { controls.contains($0) }), !prefix.contains("(") {
if prefix.contains(where: { typeWords.contains($0) }) || (!prefix.isEmpty && prefix.allSatisfy { $0 == "*" || $0.utf16.first.map(identifierStart) == true }) { return [] }
}
let matches = index.completionSymbols(from: path, offset: revision.offset, prefix: name, includeLocals: revision.safeScopes)
.filter { $0.name == name && ($0.path != path || revision.keeps($0)) }
// A local object shadows a global function even when its type happens
// to be a function pointer. Do not invent its callable signature.
guard !matches.contains(where: { $0.kind != .function && $0.kind != .macro }) else { return [] }
var seen: Set<String> = [], result: [ParameterHint] = []
for symbol in matches where symbol.kind == .function || symbol.kind == .macro {
guard let parameters = parameters(in: symbol.signature, name: name), seen.insert(symbol.signature).inserted else { continue }
result.append(.init(signature: symbol.signature, name: name, parameters: parameters, activeParameter: call.argument,
conditional: symbol.conditional || symbol.kind == .macro || !revision.safeScopes || (symbol.path == path && revision.changed), sourcePath: symbol.path))
if result.count == 8 { break }
}
return result
}
private struct Revision {
let offset: Int, changed: Bool, safeScopes: Bool
let changedRange: Range<Int>
init(original: String?, current: [UInt16], offset: Int) {
guard let original else { self.offset = 0; changed = true; safeScopes = false; changedRange = 0..<Int.max; return }
let old = Array(original.utf16)
var prefix = 0
while prefix < min(old.count, current.count), old[prefix] == current[prefix] { prefix += 1 }
var suffix = 0
while suffix < min(old.count - prefix, current.count - prefix), old[old.count - suffix - 1] == current[current.count - suffix - 1] { suffix += 1 }
changed = prefix != old.count || prefix != current.count
changedRange = prefix..<(old.count - suffix)
if offset <= prefix { self.offset = offset }
else if offset >= current.count - suffix { self.offset = offset + old.count - current.count }
else { self.offset = prefix }
safeScopes = !changed || (old[changedRange].allSatisfy(CMOCCompletion.identifierPart) && current[prefix..<(current.count - suffix)].allSatisfy(CMOCCompletion.identifierPart))
}
func keeps(_ symbol: CMOCProjectIndex.Symbol) -> Bool {
let token = symbol.offsetUTF16..<(symbol.offsetUTF16 + symbol.lengthUTF16)
return !token.overlaps(changedRange) && !(changedRange.isEmpty && token.contains(changedRange.lowerBound))
}
}
private struct Token {
let text: String, offset: Int
var identifier: Bool { text.utf16.first.map(CMOCCompletion.identifierStart) == true }
}
private struct Scan { let tokens: [Token]; let suppressed: Bool; var literal = false }
/// Scans only the prefix before the caret, retaining delimiters but treating
/// literals/comments/directives as opaque. Continued lines remain opaque.
private static func scan(_ units: [UInt16], to end: Int) -> Scan? {
var tokens: [Token] = [], i = 0, lineStart = true
while i < end {
if tokens.count >= CMOCProjectIndex.maximumTokens || (i % 1024 == 0 && Task.isCancelled) { return nil }
let c = units[i], next = i + 1 < end ? units[i + 1] : 0
if c == 10 || c == 13 { lineStart = true; i += 1; continue }
if c == 32 || c == 9 { i += 1; continue }
if (lineStart && c == 35) || (c == 47 && next == 47) {
i += 1
while i < end {
if units[i] == 10 {
let previous = i > 0 && units[i - 1] == 13 ? i - 2 : i - 1
if previous < 0 || units[previous] != 92 { break }
}
i += 1
}
if i == end { return .init(tokens: tokens, suppressed: true) }
continue
}
if c == 47 && next == 42 {
i += 2; var closed = false
while i < end {
if units[i] == 42, i + 1 < end, units[i + 1] == 47 { i += 2; closed = true; break }
if units[i] == 10 { lineStart = true }; i += 1
}
if !closed { return .init(tokens: tokens, suppressed: true) }; continue
}
lineStart = false
if c == 34 || c == 39 {
let quote = c; i += 1; var closed = false
while i < end {
if units[i] == 92 { i += min(2, end - i); continue }
if units[i] == quote { i += 1; closed = true; break }
i += 1
}
if !closed { return .init(tokens: tokens, suppressed: true, literal: true) }; continue
}
let start = i; i += 1
if identifierPart(c) { while i < end && identifierPart(units[i]) { i += 1 } }
else if c == 45 && next == 62 { i += 1 }
tokens.append(.init(text: String(decoding: units[start..<i], as: UTF16.self), offset: start))
}
return .init(tokens: tokens, suppressed: false)
}
private static func identifierStart(_ c: UInt16) -> Bool { c == 95 || (65...90).contains(c) || (97...122).contains(c) }
private static func identifierPart(_ c: UInt16) -> Bool { identifierStart(c) || (48...57).contains(c) }
private static func parameters(in signature: String, name: String) -> [String]? {
if signature.hasPrefix("#define ") && !signature.hasPrefix("#define " + name + "(") { return nil }
let declaration = signature.hasPrefix("#define ") ? String(signature.dropFirst(8)) : signature
let units = Array(declaration.utf16)
guard let scan = scan(units, to: units.count), !scan.suppressed else { return nil }
let tokens = scan.tokens
guard let nameIndex = tokens.indices.first(where: { tokens[$0].text == name && $0 + 1 < tokens.count && tokens[$0 + 1].text == "(" }) else { return nil }
var depth = 0, parts: [[String]] = [[]]
for token in tokens[(nameIndex + 2)...] {
if token.text == ")", depth == 0 {
let parameters = parts.map { $0.joined(separator: " ").replacingOccurrences(of: ". . .", with: "...") }
return parameters == [""] || parameters == ["void"] ? [] : parameters
}
if token.text == ",", depth == 0 { parts.append([]); continue }
if ["(", "[", "{"].contains(token.text) { depth += 1 }
if [")", "]", "}"].contains(token.text) { depth -= 1; if depth < 0 { return nil } }
parts[parts.count - 1].append(token.text)
}
return nil // The index bounds display signatures; never guess truncated parameters.
}
}