454 lines
28 KiB
Swift
454 lines
28 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
||
import Foundation
|
||
|
||
/// Editor assistance only. The core's ROM-aware tokenizer remains authoritative.
|
||
enum BASICLanguage {
|
||
enum Kind { case keyword, number, string, comment, data }
|
||
struct Span { let range: NSRange; let kind: Kind; let word: String }
|
||
struct Completion: Equatable { let range: NSRange; let words: [String] }
|
||
static let maximumSourceBytes = 1_048_576
|
||
static let sample = DevelopmentStarterSource.planet(withExtension: "bas")
|
||
?? "10 REM EARTH OR MARS EXAMPLE MISSING - REINSTALL VCC PLUS\n"
|
||
// Verified command/function names for the bundled CoCo 3 + Disk BASIC
|
||
// dictionaries. GOTO/GOSUB are conveniences for the GO + TO/SUB tokens.
|
||
static let words: [String] = {
|
||
let names = "FOR GOTO GOSUB GO REM IF DATA PRINT ON INPUT END NEXT DIM READ RUN RESTORE RETURN STOP POKE CONT LIST CLEAR NEW CLOAD CSAVE OPEN CLOSE LLIST SET RESET CLS MOTOR SOUND AUDIO EXEC SKIPF DEL EDIT TRON TROFF DEF LET LINE PCLS PSET PRESET SCREEN PCLEAR COLOR CIRCLE PAINT GET PUT DRAW PCOPY PMODE PLAY DLOAD RENUM TAB TO SUB THEN NOT STEP OFF ELSE USING DIR DRIVE FIELD FILES KILL LOAD LSET MERGE RENAME RSET SAVE WRITE VERIFY UNLOAD DSKINI BACKUP COPY DSKI$ DSKO$ DOS WIDTH PALETTE HSCREEN LPOKE HCLS HCOLOR HPAINT HCIRCLE HLINE HGET HPUT HBUFF HPRINT ERR BRK LOCATE HSTAT HSET HRESET HDRAW CMP RGB ATTR LPEEK BUTTON HPOINT ERNO ERLIN SIN COS TAN ATN LOG EXP SQR SGN ABS INT RND USR PEEK LEN STR$ VAL ASC CHR$ EOF JOYSTK LEFT$ RIGHT$ MID$ POINT INKEY$ MEM INSTR TIMER PPOINT STRING$ CVN FREE LOC LOF MKN$ AS AND OR FN FIX POS HEX$ VARPTR"
|
||
let unique = Set(names.split(separator: " ").map { String($0) })
|
||
return unique.sorted { left, right in
|
||
if left.count == right.count { return left < right }
|
||
return left.count > right.count
|
||
}
|
||
}()
|
||
|
||
// Command descriptions and editor hints share the offline reference.
|
||
// The ROM-aware tokenizer remains authoritative for executable syntax.
|
||
static let signatures: [String: String] = {
|
||
guard let catalog = try? BASICReferenceCatalog.bundled.get() else { return [:] }
|
||
var result: [String: String] = [:]
|
||
for dialect in [BASICReferenceDialect.common, .disk] {
|
||
for entry in catalog.entries where entry.dialect == dialect && result[entry.keyword] == nil {
|
||
result[entry.keyword] = entry.syntax.first
|
||
}
|
||
}
|
||
return result
|
||
}()
|
||
/// Quoted strings, comments and DATA values are opaque to completion.
|
||
static func spans(_ source: String) -> [Span] {
|
||
guard source.utf8.count <= maximumSourceBytes else { return [] }
|
||
let u = Array(source.utf16), upper = Array(source.uppercased().utf16)
|
||
// Case folding can change non-ASCII length. Such text is invalid for the
|
||
// guest tokenizer but must remain harmless while being edited.
|
||
guard upper.count == u.count else { return [] }
|
||
let tokens = words.map { ($0, Array($0.utf16)) }
|
||
var result: [Span] = [], i = 0
|
||
func append(_ start: Int, _ end: Int, _ kind: Kind, _ word: String = "") {
|
||
result.append(Span(range: NSRange(location: start, length: end-start), kind: kind, word: word))
|
||
}
|
||
while i < u.count {
|
||
let start = i
|
||
if u[i] == 34 {
|
||
i += 1; while i < u.count && u[i] != 34 && u[i] != 10 && u[i] != 13 { i += 1 }
|
||
if i < u.count && u[i] == 34 { i += 1 }; append(start,i,.string); continue
|
||
}
|
||
if u[i] == 39 {
|
||
while i < u.count && u[i] != 10 && u[i] != 13 { i += 1 }; append(start,i,.comment); continue
|
||
}
|
||
if let token = tokens.first(where: { i+$0.1.count <= upper.count && upper[i..<i+$0.1.count].elementsEqual($0.1) }) {
|
||
i += token.1.count; append(start,i,.keyword,token.0)
|
||
if token.0 == "REM" {
|
||
let from = i; while i < u.count && u[i] != 10 && u[i] != 13 { i += 1 }; append(from,i,.comment)
|
||
} else if token.0 == "DATA" {
|
||
let from = i; var quoted = false
|
||
while i < u.count && u[i] != 10 && u[i] != 13 {
|
||
if u[i] == 34 { quoted.toggle() }
|
||
if u[i] == 58 && !quoted { break }; i += 1
|
||
}; append(from,i,.data)
|
||
}; continue
|
||
}
|
||
if (48...57).contains(u[i]) {
|
||
i += 1; while i < u.count && ((48...57).contains(u[i]) || u[i] == 46) { i += 1 }
|
||
append(start,i,.number); continue
|
||
}
|
||
i += 1
|
||
}
|
||
return result
|
||
}
|
||
static func completion(_ source: String, at caret: Int) -> Completion? {
|
||
let u = Array(source.utf16)
|
||
guard source.utf8.count <= maximumSourceBytes, caret >= 0, caret <= u.count else { return nil }
|
||
let tokens = spans(source)
|
||
guard !tokens.contains(where: { span in
|
||
switch span.kind {
|
||
case .string, .comment, .data: return caret > span.range.location && caret <= NSMaxRange(span.range)
|
||
default: return false
|
||
}
|
||
}) else { return nil }
|
||
func word(_ c: UInt16) -> Bool { (65...90).contains(c) || (97...122).contains(c) || c == 36 }
|
||
var start = caret, end = caret
|
||
while start > 0 && word(u[start-1]) { start -= 1 }
|
||
while end < u.count && word(u[end]) { end += 1 }
|
||
guard start < caret else { return nil }
|
||
let prefix = String(decoding: u[start..<caret], as: UTF16.self).uppercased()
|
||
let matches = words.filter { $0.hasPrefix(prefix) }.sorted()
|
||
guard !matches.isEmpty else { return nil }
|
||
return Completion(range: NSRange(location:start,length:end-start),words:matches)
|
||
}
|
||
struct InlineCompletion: Equatable {
|
||
let range: NSRange
|
||
let word: String
|
||
let suffix: String
|
||
}
|
||
/// Inline previews only occupy empty space at the end of a physical line.
|
||
/// Ambiguous prefixes continue to use the explicit completion list.
|
||
static func inlineCompletion(_ source: String, at caret: Int) -> InlineCompletion? {
|
||
let text = source as NSString
|
||
guard caret > 0, caret <= text.length,
|
||
caret == text.length || [10, 13].contains(text.character(at: caret)),
|
||
let completion = completion(source, at: caret), completion.words.count == 1,
|
||
NSMaxRange(completion.range) == caret, completion.range.length >= 2,
|
||
let word = completion.words.first, word.utf16.count > completion.range.length else { return nil }
|
||
// Avoid offering a keyword for the alphabetic tail of a variable (A1PRI).
|
||
if completion.range.location > 0 {
|
||
let prior = text.character(at: completion.range.location - 1)
|
||
if (48...57).contains(prior) {
|
||
let line = text.lineRange(for: completion.range)
|
||
let before = text.substring(with: NSRange(location: line.location, length: completion.range.location - line.location))
|
||
guard before.allSatisfy({ $0.isNumber || $0 == " " || $0 == "\t" }) else { return nil }
|
||
}
|
||
}
|
||
return InlineCompletion(range: completion.range, word: word,
|
||
suffix: String(word.dropFirst(completion.range.length)))
|
||
}
|
||
|
||
/// Return at a completed numbered line follows its preceding increment,
|
||
/// or uses ten. Inserting between lines fits into the available numeric gap.
|
||
static func nextLineInsertion(_ source: String, at caret: Int) -> String? {
|
||
let text = source as NSString
|
||
guard source.utf8.count <= maximumSourceBytes, caret > 0, caret <= text.length else { return nil }
|
||
let range = text.lineRange(for: NSRange(location: caret, length: 0))
|
||
var end = NSMaxRange(range)
|
||
while end > range.location && [10, 13].contains(text.character(at: end - 1)) { end -= 1 }
|
||
guard caret == end else { return nil }
|
||
let analysis = analyze(source)
|
||
guard let current = analysis.lines.first(where: { $0.range.location == range.location }),
|
||
current.number < 63999 else { return nil }
|
||
let bodyStart = NSMaxRange(current.labelRange)
|
||
guard bodyStart < end,
|
||
!text.substring(with: NSRange(location: bodyStart, length: end - bodyStart))
|
||
.trimmingCharacters(in: .whitespaces).isEmpty else { return nil }
|
||
let used = Set(analysis.lines.map(\.number))
|
||
let previous = analysis.lines.last(where: { $0.range.location < range.location })
|
||
let increment = previous.map { current.number - $0.number }.flatMap { $0 > 0 ? $0 : nil } ?? 10
|
||
let following = analysis.lines.first(where: { $0.range.location > range.location })
|
||
if let following, following.number <= current.number { return nil }
|
||
let limit = min(63999, following.map { $0.number - 1 } ?? 63999)
|
||
guard limit > current.number else { return nil }
|
||
let gap = limit - current.number + 1
|
||
let step = following != nil && increment >= gap ? max(1, gap / 2) : increment
|
||
var candidate = min(current.number + step, limit)
|
||
while candidate <= limit && used.contains(candidate) { candidate += 1 }
|
||
if candidate > limit {
|
||
candidate = current.number + 1
|
||
while candidate <= limit && used.contains(candidate) { candidate += 1 }
|
||
}
|
||
guard candidate <= limit else { return nil }
|
||
let newline = source.contains("\r\n") ? "\r\n" : source.contains("\r") && !source.contains("\n") ? "\r" : "\n"
|
||
return newline + String(candidate) + " "
|
||
}
|
||
static func hint(_ source: String, at caret: Int) -> String? {
|
||
let text = source as NSString
|
||
guard caret >= 0, caret <= text.length, source.utf8.count <= maximumSourceBytes else { return nil }
|
||
let line = text.lineRange(for: NSRange(location:caret,length:0))
|
||
let prior = spans(source).filter { $0.range.location >= line.location && NSMaxRange($0.range) <= caret && $0.kind == .keyword }
|
||
// These tokens continue the enclosing statement rather than introducing
|
||
// a new signature. They still have independently browsable help entries.
|
||
let fragments: Set<String> = ["TO", "STEP", "THEN", "ELSE", "AS", "AND", "OR", "NOT"]
|
||
return prior.reversed().filter { !fragments.contains($0.word) }.compactMap { signatures[$0.word] }.first
|
||
}
|
||
}
|
||
|
||
extension BASICLanguage {
|
||
enum Severity { case error, warning }
|
||
struct Diagnostic: Identifiable, Equatable {
|
||
let row: Int
|
||
let range: NSRange
|
||
let message: String
|
||
let severity: Severity
|
||
var id: String { "\(row):\(range.location):\(message)" }
|
||
}
|
||
struct NumberedLine {
|
||
let row: Int, number: Int
|
||
let range: NSRange, labelRange: NSRange
|
||
}
|
||
struct Analysis {
|
||
let lines: [NumberedLine]
|
||
let diagnostics: [Diagnostic]
|
||
var hasErrors: Bool { diagnostics.contains { $0.severity == .error } }
|
||
}
|
||
struct RenumberResult { let source: String; let lineCount: Int; let changedReferences: Int }
|
||
struct AssistanceError: LocalizedError {
|
||
let message: String
|
||
var errorDescription: String? { message }
|
||
}
|
||
private struct Reference { let range: NSRange; let target: Int }
|
||
private struct Inspection { var lines: [NumberedLine] = []; var diagnostics: [Diagnostic] = []; var references: [Reference] = [] }
|
||
private struct Atom {
|
||
let text: String, range: NSRange
|
||
let numeric: Bool
|
||
}
|
||
// Exact command-before-function ordering from CoCo 3/Disk BASIC. This is
|
||
// deliberately separate from completion's longest-spelling-first list.
|
||
// An unmatched identifier consumes its alphanumeric tail, so XGOTO is a
|
||
// variable, while FORI=1TO5 contains FOR and TO. Function names stay atomic.
|
||
private static let scanWords = ("FOR GO REM ' ELSE IF DATA PRINT ON INPUT END NEXT DIM READ RUN RESTORE RETURN STOP POKE CONT LIST CLEAR NEW CLOAD CSAVE OPEN CLOSE LLIST SET RESET CLS MOTOR SOUND AUDIO EXEC SKIPF TAB( TO SUB THEN NOT STEP OFF + - * / ^ AND OR > = < DEL EDIT TRON TROFF DEF LET LINE PCLS PSET PRESET SCREEN PCLEAR COLOR CIRCLE PAINT GET PUT DRAW PCOPY PMODE PLAY DLOAD RENUM FN USING DIR DRIVE FIELD FILES KILL LOAD LSET MERGE RENAME RSET SAVE WRITE VERIFY UNLOAD DSKINI BACKUP COPY DSKI$ DSKO$ DOS WIDTH PALETTE HSCREEN LPOKE HCLS HCOLOR HPAINT HCIRCLE HLINE HGET HPUT HBUFF HPRINT ERR BRK LOCATE HSTAT HSET HRESET HDRAW CMP RGB ATTR SGN INT ABS USR RND SIN PEEK LEN STR$ VAL ASC CHR$ EOF JOYSTK LEFT$ RIGHT$ MID$ POINT INKEY$ MEM ATN COS TAN EXP FIX LOG POS SQR HEX$ VARPTR INSTR TIMER PPOINT STRING$ CVN FREE LOC LOF MKN$ AS LPEEK BUTTON HPOINT ERNO ERLIN").split(separator: " ").map { (String($0), Array($0.utf16)) }
|
||
private static let scanWordsByFirst = Dictionary(grouping: scanWords, by: { $0.1[0] })
|
||
private static func isDigit(_ c: UInt16) -> Bool { (48...57).contains(c) }
|
||
private static func isAlpha(_ c: UInt16) -> Bool { (65...90).contains(c) || (97...122).contains(c) }
|
||
private static func scan(_ units: [UInt16], from: Int, to: Int) -> [Atom] {
|
||
var result: [Atom] = [], i = from
|
||
func add(_ text: String, _ start: Int, _ end: Int, numeric: Bool = false) {
|
||
result.append(.init(text: text, range: NSRange(location:start,length:end-start), numeric:numeric))
|
||
}
|
||
while i < to {
|
||
let begin = i, c = units[i]
|
||
if c == 32 || c == 9 { i += 1; continue }
|
||
if c == 34 {
|
||
i += 1; while i < to && units[i] != 34 { i += 1 }
|
||
if i < to { i += 1 }; add("<string>",begin,i); continue
|
||
}
|
||
if c == 39 { break }
|
||
if isDigit(c) {
|
||
i += 1; while i < to && isDigit(units[i]) { i += 1 }
|
||
add(String(decoding:units[begin..<i],as:UTF16.self),begin,i,numeric:true); continue
|
||
}
|
||
if let word = scanWordsByFirst[c >= 97 && c <= 122 ? c-32 : c]?.first(where: { word in
|
||
i+word.1.count <= to && zip(units[i..<i+word.1.count],word.1).allSatisfy { raw, target in
|
||
(raw >= 97 && raw <= 122 ? raw-32 : raw) == target
|
||
}
|
||
}) {
|
||
i += word.1.count
|
||
if word.0 == "REM" { break }
|
||
add(word.0,begin,i)
|
||
if word.0 == "DATA" {
|
||
var quoted = false
|
||
while i < to {
|
||
if units[i] == 34 { quoted.toggle() }
|
||
if units[i] == 58 && !quoted { break }; i += 1
|
||
}
|
||
}
|
||
continue
|
||
}
|
||
i += 1
|
||
if isAlpha(c) {
|
||
while i < to && (isAlpha(units[i]) || isDigit(units[i])) { i += 1 }
|
||
// $ belongs to the variable name, never a reference operand.
|
||
if i < to && units[i] == 36 { i += 1 }
|
||
}
|
||
add(String(decoding:units[begin..<i],as:UTF16.self).uppercased(),begin,i)
|
||
}
|
||
return result
|
||
}
|
||
private static func inspect(_ source: String) -> Inspection {
|
||
var output = Inspection()
|
||
let units = Array(source.utf16)
|
||
func report(_ row: Int, _ range: NSRange, _ text: String, _ severity: Severity = .error) {
|
||
output.diagnostics.append(.init(row:row,range:range,message:text,severity:severity))
|
||
}
|
||
guard source.utf8.count <= maximumSourceBytes else {
|
||
report(1,NSRange(location:0,length:0),"The source exceeds the 1 MiB editor limit."); return output
|
||
}
|
||
var at = 0, row = 0, bodies: [(NumberedLine,Int,Int)] = [], seen: Set<Int> = []
|
||
while at < units.count {
|
||
row += 1; let begin = at
|
||
while at < units.count && units[at] != 10 && units[at] != 13 { at += 1 }
|
||
let end = at
|
||
if at < units.count { let newline = units[at]; at += 1; if newline == 13 && at < units.count && units[at] == 10 { at += 1 } }
|
||
var first = begin
|
||
while first < end && (units[first] == 32 || units[first] == 9) { first += 1 }
|
||
if first == end { continue }
|
||
if let invalid = (begin..<end).first(where: { units[$0] != 9 && (units[$0] < 32 || units[$0] > 126) }) {
|
||
report(row,(source as NSString).rangeOfComposedCharacterSequence(at:invalid),"Use printable ASCII characters (tabs are allowed).")
|
||
}
|
||
if end-first > 249 { report(row,NSRange(location:first,length:end-first),"BASIC input lines may contain at most 249 characters.") }
|
||
guard isDigit(units[first]) else { report(row,NSRange(location:first,length:end-first),"Begin this line with a BASIC line number."); continue }
|
||
var after = first; while after < end && isDigit(units[after]) { after += 1 }
|
||
let label = NSRange(location:first,length:after-first)
|
||
guard let number = Int(String(decoding:units[first..<after],as:UTF16.self)), number <= 63999 else {
|
||
report(row,label,"Line numbers must be between 0 and 63999."); continue
|
||
}
|
||
let line = NumberedLine(row:row,number:number,range:NSRange(location:begin,length:end-begin),labelRange:label)
|
||
output.lines.append(line)
|
||
if !seen.insert(number).inserted { report(row,label,"Line \(number) is defined more than once.") }
|
||
while after < end && (units[after] == 32 || units[after] == 9) { after += 1 }
|
||
if after == end { report(row,label,"A bare number deletes a BASIC line; add a statement or remove this row before renumbering.",.warning) }
|
||
else { bodies.append((line,after,end)) }
|
||
}
|
||
let defined = Set(bodies.map { $0.0.number }), sorted = defined.sorted()
|
||
func lowerBound(_ value: Int) -> Int {
|
||
var lo=0, hi=sorted.count
|
||
while lo<hi { let mid=(lo+hi)/2; if sorted[mid]<value { lo=mid+1 } else { hi=mid } }
|
||
return lo
|
||
}
|
||
for (line,begin,end) in bodies {
|
||
let atoms = scan(units,from:begin,to:end)
|
||
var i = 0, on = false, trap = false
|
||
func boundary(_ index: Int) -> Bool { index >= atoms.count || [":","ELSE"].contains(atoms[index].text) }
|
||
func unsupported(_ atom: Atom) { report(line.row,atom.range,"Renumber cannot safely interpret this line-number operand; use a literal line number.",.warning) }
|
||
func reference(_ index: Int, disableZero: Bool = false) {
|
||
let atom = atoms[index]
|
||
guard let target = Int(atom.text), target <= 63999 else { report(line.row,atom.range,"Referenced line number is outside 0–63999."); return }
|
||
if disableZero && target == 0 { return } // ON ERR/BRK GOTO 0 disables the trap.
|
||
if !defined.contains(target) { report(line.row,atom.range,"Referenced line \(target) is not present in this program.",.warning) }
|
||
output.references.append(.init(range:atom.range,target:target))
|
||
}
|
||
while i < atoms.count {
|
||
let atom = atoms[i], word = atom.text
|
||
if word == ":" || word == "THEN" || word == "ELSE" { on = false; trap = false }
|
||
if word == "ON" { on = true; trap = i+1 < atoms.count && ["ERR","BRK"].contains(atoms[i+1].text) }
|
||
if word == "RENUM" { report(line.row,atom.range,"This program renumbers itself with RENUM; automatic editor renumbering is unsafe.",.warning) }
|
||
if word == "GO" {
|
||
var operand = i+1
|
||
guard operand < atoms.count && ["TO","SUB"].contains(atoms[operand].text) else { unsupported(atom); i += 1; continue }
|
||
operand += 1
|
||
var count = 0
|
||
while operand < atoms.count && atoms[operand].numeric {
|
||
reference(operand,disableZero:trap); count += 1; operand += 1
|
||
if on && !trap && operand < atoms.count && atoms[operand].text == "," { operand += 1; continue }
|
||
break
|
||
}
|
||
if count == 0 || !boundary(operand) || (operand > 0 && atoms[operand-1].text == ",") { unsupported(atom) }
|
||
on = false; trap = false; i = max(i+1,operand); continue
|
||
}
|
||
if ["THEN","ELSE","RUN","EDIT"].contains(word) {
|
||
let operand = i+1
|
||
if operand < atoms.count && atoms[operand].numeric {
|
||
reference(operand)
|
||
if !boundary(operand+1) { unsupported(atom) }
|
||
i = operand+1; continue
|
||
} else if word == "EDIT" || (word == "RUN" && !boundary(operand) && atoms[operand].text != "<string>") { unsupported(atom) }
|
||
}
|
||
if ["LIST","LLIST","DEL"].contains(word) {
|
||
var p = i+1, lowerIndex: Int?, upperIndex: Int?, ranged = false
|
||
if p < atoms.count && atoms[p].numeric { lowerIndex=p; p += 1 }
|
||
if p < atoms.count && atoms[p].text == "-" {
|
||
ranged=true; p += 1
|
||
if p < atoms.count && atoms[p].numeric { upperIndex=p; p += 1 }
|
||
}
|
||
if !boundary(p) { unsupported(atom) }
|
||
else if lowerIndex != nil || upperIndex != nil {
|
||
let low = lowerIndex.map { Int(atoms[$0].text) ?? 64000 } ?? 0
|
||
let high = upperIndex.map { Int(atoms[$0].text) ?? 64000 } ?? (ranged ? 63999 : low)
|
||
if low > 63999 || high > 63999 { report(line.row,atom.range,"Line range is outside 0–63999.") }
|
||
else {
|
||
// Bounds need not name a real line. Preserve the set
|
||
// of included lines, not just exact endpoint matches.
|
||
let firstIndex=lowerBound(low), afterLast=lowerBound(high+1)
|
||
if firstIndex < afterLast {
|
||
let first=sorted[firstIndex], last=sorted[afterLast-1]
|
||
if let index=lowerIndex { output.references.append(.init(range:atoms[index].range,target:first)) }
|
||
if let index=upperIndex { output.references.append(.init(range:atoms[index].range,target:last)) }
|
||
} else { report(line.row,atom.range,"This line range selects no program lines; review it before renumbering.",.warning) }
|
||
}
|
||
}
|
||
i = max(i+1,p); continue
|
||
}
|
||
i += 1
|
||
}
|
||
}
|
||
return output
|
||
}
|
||
static func analyze(_ source: String) -> Analysis {
|
||
let result = inspect(source)
|
||
return Analysis(lines:result.lines,diagnostics:result.diagnostics)
|
||
}
|
||
static func lineRange(for number: Int, in source: String) -> NSRange? {
|
||
let matches = analyze(source).lines.filter { $0.number == number }
|
||
return matches.count == 1 ? matches.first?.range : nil
|
||
}
|
||
/// Numeric program order determines numbering; physical rows, blank lines,
|
||
/// comments, string/data literals and newline style remain unchanged.
|
||
static func renumber(_ source: String, start: Int = 10, step: Int = 10) throws -> RenumberResult {
|
||
guard (0...63999).contains(start), (1...63999).contains(step) else {
|
||
throw AssistanceError(message:"Choose a start from 0 to 63999 and a positive increment up to 63999.")
|
||
}
|
||
let result = inspect(source)
|
||
if let issue = result.diagnostics.first { throw AssistanceError(message:"Row \(issue.row): \(issue.message)") }
|
||
let ordered = result.lines.sorted { $0.number < $1.number }
|
||
guard ordered.count <= 1 || ordered.count-1 <= (63999-start)/step else { throw AssistanceError(message:"The new line numbers would exceed 63999.") }
|
||
let mapping = Dictionary(uniqueKeysWithValues:ordered.enumerated().map { ($0.element.number,start+$0.offset*step) })
|
||
var edits = result.lines.map { ($0.labelRange,String(mapping[$0.number]!)) }
|
||
var changed = 0
|
||
for ref in result.references {
|
||
guard let target = mapping[ref.target] else { throw AssistanceError(message:"Referenced line \(ref.target) is missing.") }
|
||
if (source as NSString).substring(with:ref.range) != String(target) { changed += 1 }
|
||
edits.append((ref.range,String(target)))
|
||
}
|
||
let updated = NSMutableString(string:source)
|
||
for (range,text) in edits.sorted(by: { $0.0.location > $1.0.location }) { updated.replaceCharacters(in:range,with:text) }
|
||
let newSource = updated as String
|
||
// Wider line numbers can make a previously valid line too long.
|
||
if let issue=analyze(newSource).diagnostics.first(where: { $0.severity == .error }) { throw AssistanceError(message:"Renumbering would make row \(issue.row) invalid: \(issue.message)") }
|
||
return .init(source:newSource,lineCount:ordered.count,changedReferences:changed)
|
||
}
|
||
}
|
||
|
||
// Values are copied from a stopped interpreter. Watches never call BASIC.
|
||
struct BASICVariable: Identifiable, Equatable, Sendable {
|
||
let name: String
|
||
let kind: String
|
||
let value: String
|
||
let address: Int
|
||
let dimensions: [Int]
|
||
let elements: [String]
|
||
var id: String { name + (dimensions.isEmpty ? "" : "()") }
|
||
var title: String { dimensions.isEmpty ? name : name + "(" + dimensions.map { String($0 - 1) }.joined(separator: ",") + ")" }
|
||
init?(_ row: [String: Any]) {
|
||
guard let name = row["name"] as? String, let kind = row["kind"] as? String,
|
||
let value = row["value"] as? String, let address = row["address"] as? Int,
|
||
let dimensions = row["dimensions"] as? [Int], let elements = row["elements"] as? [String] else { return nil }
|
||
self.name = name; self.kind = kind; self.value = value; self.address = address
|
||
self.dimensions = dimensions; self.elements = elements
|
||
}
|
||
func elementName(_ offset: Int) -> String {
|
||
var remainder = offset
|
||
let indices = dimensions.map { length -> String in
|
||
defer { remainder /= length }; return String(remainder % length)
|
||
}
|
||
return name + "(" + indices.joined(separator: ",") + ")"
|
||
}
|
||
}
|
||
struct BASICWatch: Equatable, Sendable {
|
||
let name: String
|
||
let indices: [Int]?
|
||
var canonical: String { name + (indices.map { "(" + $0.map(String.init).joined(separator: ",") + ")" } ?? "") }
|
||
init?(_ text: String) {
|
||
// Deliberately no expressions, functions, assignments or device access.
|
||
let compact = text.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
|
||
guard compact.count <= 256, let match = compact.range(of: #"^[A-Z][A-Z0-9]*\$?(\( *[0-9]+ *(, *[0-9]+ *)*\))?$"#, options: .regularExpression) else { return nil }
|
||
guard match == compact.startIndex..<compact.endIndex else { return nil }
|
||
let parts = compact.split(separator: "(", maxSplits: 1)
|
||
let identifier = String(parts[0]), string = identifier.hasSuffix("$")
|
||
guard !BASICLanguage.words.contains(where: { identifier.hasPrefix($0) }) else { return nil }
|
||
name = String((string ? String(identifier.dropLast()) : identifier).prefix(2)) + (string ? "$" : "")
|
||
if parts.count == 2 {
|
||
let values = parts[1].dropLast().split(separator: ",").map { Int($0.trimmingCharacters(in: .whitespaces)) }
|
||
guard !values.isEmpty, values.allSatisfy({ $0 != nil && $0! <= 32767 }) else { return nil }
|
||
indices = values.compactMap { $0 }
|
||
} else { indices = nil }
|
||
}
|
||
func value(in variables: [BASICVariable]) -> String {
|
||
guard let variable = variables.first(where: { $0.name == name && $0.dimensions.isEmpty == (indices == nil) }) else {
|
||
return indices == nil ? "Not assigned" : "Not dimensioned"
|
||
}
|
||
guard let indices else { return variable.value }
|
||
guard indices.count == variable.dimensions.count else { return "Wrong number of subscripts" }
|
||
var offset = 0, stride = 1
|
||
for (index, length) in zip(indices, variable.dimensions) {
|
||
guard index >= 0, index < length else { return "Subscript out of range" }
|
||
offset += index * stride; stride *= length
|
||
}
|
||
guard offset < variable.elements.count else { return "Unavailable" }
|
||
return variable.elements[offset]
|
||
}
|
||
}
|