Speed up parsing and opening files !461

merged merged by cmc on 2026-11-22 18:49 UTC · krz/orgstar:issue-228-parser-speed into main

12 files changed, +90 −39

Layout: unified · split

Sources/OrgCore/Parser/Lines.swift +23 −9
@@ -84,7 +84,9 @@ func classifyLine(_ line: Substring, alphabetical: Bool = false) -> ClassifiedLi
8484let inlineTaskLevel = 15
8585
8686private func lineClass(_ rest: Substring, columnZero: Bool, alphabetical: Bool) -> LineClass {
87 let trimmed = rest.trimmingTrailingWhitespace
87 lazy var trimmed = rest.trimmingTrailingWhitespace
88 // Every test below needs a particular first character; the first byte rules most out.
89 let first = rest.utf8.first
8890
8991 // As org's `org-outline-regexp`: stars and then a space. A lone `*`, or stars before a tab,
9092 // is not a heading.
@@ -96,7 +98,7 @@ private func lineClass(_ rest: Substring, columnZero: Bool, alphabetical: Bool)
9698 }
9799 }
98100
99 if rest.hasPrefix("#+") {
101 if first == UInt8(ascii: "#"), rest.hasPrefix("#+") {
100102 let lower = trimmed.lowercased()
101103 if lower.hasPrefix("#+begin_") {
102104 let name = lower.dropFirst(8).prefix { !$0.isWhitespace }
@@ -114,9 +116,9 @@ private func lineClass(_ rest: Substring, columnZero: Bool, alphabetical: Bool)
114116 }
115117 }
116118
117 if trimmed == "#" || rest.hasPrefix("# ") || rest.hasPrefix("#\t") { return .comment }
119 if first == UInt8(ascii: "#"), trimmed == "#" || rest.hasPrefix("# ") || rest.hasPrefix("#\t") { return .comment }
118120
119 if rest.hasPrefix("\\begin{") || rest.hasPrefix("\\end{") {
121 if first == UInt8(ascii: "\\"), rest.hasPrefix("\\begin{") || rest.hasPrefix("\\end{") {
120122 let begin = rest.hasPrefix("\\begin{")
121123 let after = rest.dropFirst(begin ? 7 : 5)
122124 let name = after.prefix { $0.isLetter || $0.isNumber || $0 == "*" }
@@ -141,16 +143,17 @@ private func lineClass(_ rest: Substring, columnZero: Bool, alphabetical: Bool)
141143
142144 if rest.first == "|" { return .tableRow }
143145 if rest.first == "+", trimmed.wholeMatch(of: /\+(?:-+\+)+/) != nil { return .tableElRule }
144 if columnZero, rest.hasPrefix("%%(") { return .diarySexp }
145 if trimmed.count >= 5, trimmed.allSatisfy({ $0 == "-" }) { return .horizontalRule }
146 if columnZero, first == UInt8(ascii: "%"), rest.hasPrefix("%%(") { return .diarySexp }
147 if rest.first == "-", trimmed.count >= 5, trimmed.allSatisfy({ $0 == "-" }) { return .horizontalRule }
146148
147 if columnZero, rest.hasPrefix("[fn:"), let close = rest.firstIndex(of: "]"),
149 if columnZero, first == UInt8(ascii: "["), rest.hasPrefix("[fn:"), let close = rest.firstIndex(of: "]"),
148150 close > rest.index(rest.startIndex, offsetBy: 4) {
149151 return .footnoteDefinition
150152 }
151153
152 if rest.hasPrefix("CLOCK:") { return .clock }
153 if rest.hasPrefix("SCHEDULED:") || rest.hasPrefix("DEADLINE:") || rest.hasPrefix("CLOSED:") { return .planning }
154 if first == UInt8(ascii: "C"), rest.hasPrefix("CLOCK:") { return .clock }
155 if first == UInt8(ascii: "S") || first == UInt8(ascii: "D") || first == UInt8(ascii: "C"),
156 rest.hasPrefix("SCHEDULED:") || rest.hasPrefix("DEADLINE:") || rest.hasPrefix("CLOSED:") { return .planning }
154157 if isListBullet(rest, indented: !columnZero, alphabetical: alphabetical) { return .listItem }
155158 return .plain
156159}
@@ -175,6 +178,17 @@ private func isListBullet(_ rest: Substring, indented: Bool, alphabetical: Bool)
175178 return afterBullet.isEmpty || afterBullet.first == " " || afterBullet.first == "\t"
176179}
177180
181/// Whether `bytes` holds a run of `count` copies of `byte`. A cheap test before a search by
182/// Character.
183func containsBytes(_ bytes: Substring.UTF8View, _ byte: UInt8, count: Int) -> Bool {
184 var run = 0
185 for b in bytes {
186 run = b == byte ? run + 1 : 0
187 if run == count { return true }
188 }
189 return false
190}
191
178192extension Substring {
179193 var trimmingTrailingWhitespace: Substring {
180194 var s = self
Sources/OrgCore/Parser/Parser.swift +11 −6
@@ -1,7 +1,8 @@
11public enum OrgParser {
22 public static func parse(_ text: String, defaults: OrgSettings = .default) -> OrgTree {
33 var parser = Parser(text: text, defaults: defaults)
4 return parser.run()
4 let tree = parser.run()
5 return OrgTree(green: tree.green, settings: tree.settings, text: text)
56 }
67}
78
@@ -330,15 +331,18 @@ struct Parser {
330331 if rest.hasPrefix("|-") {
331332 builder.token(.text, rest)
332333 } else {
334 // Pipes are found by byte; one counts only where the Character there is a lone `|`,
335 // as a walk by Character would find it.
333336 var cellStart = rest.startIndex
334 var index = rest.startIndex
335 while index < rest.endIndex {
336 if rest[index] == "|" {
337 let bytes = rest.utf8
338 var index = bytes.startIndex
339 while index < bytes.endIndex {
340 if bytes[index] == UInt8(ascii: "|"), rest[index] == "|" {
337341 if index > rest.startIndex { tableCell(rest[cellStart..<index]) }
338342 builder.token(.marker, "|")
339 cellStart = rest.index(after: index)
343 cellStart = bytes.index(after: index)
340344 }
341 index = rest.index(after: index)
345 index = bytes.index(after: index)
342346 }
343347 if cellStart < rest.endIndex { tableCell(rest[cellStart...]) }
344348 }
@@ -451,6 +455,7 @@ struct Parser {
451455 /// A description item's tag and separator: the text before the last ` ::` on the line
452456 /// that ends it or has blanks after it, and that blank with the `::`.
453457 static func descriptionTag(_ s: Substring) -> (tag: Substring, separator: Substring)? {
458 guard containsBytes(s.utf8, UInt8(ascii: ":"), count: 2) else { return nil }
454459 let line = s.prefix { $0 != "\n" && $0 != "\r" }
455460 var k = line.endIndex
456461 while k > line.startIndex {
Sources/OrgCore/Parser/Settings.swift +1 −1
@@ -140,7 +140,7 @@ enum SettingsScanner {
140140 }
141141 let sequences = types + todos + seqs
142142 var radio: [String] = []
143 for line in lines where line.content.utf8.contains(UInt8(ascii: "<")) && line.content.contains("<<<") {
143 for line in lines where containsBytes(line.content.utf8, UInt8(ascii: "<"), count: 3) {
144144 for m in String(line.content).matches(of: /<<<([^<>\n\r \t](?:[^<>\n\r]*[^<>\n\r \t])?)>>>/) where !radio.contains(String(m.1)) {
145145 radio.append(String(m.1))
146146 }
Sources/OrgCore/Syntax/SyntaxNode.swift +15 −2
@@ -120,15 +120,24 @@ public struct SyntaxToken: Sendable, Equatable {
120120public struct OrgTree: Sendable {
121121 public let green: GreenNode
122122 public let settings: OrgSettings
123 private let textCache = TextCache()
123 private let textCache: TextCache
124124
125125 public init(green: GreenNode, settings: OrgSettings) {
126126 self.green = green
127127 self.settings = settings
128 textCache = TextCache()
129 }
130
131 /// A tree parsed from `text`, which its tokens spell out exactly.
132 init(green: GreenNode, settings: OrgSettings, text: String) {
133 self.green = green
134 self.settings = settings
135 textCache = TextCache(text)
128136 }
129137
130138 public var root: SyntaxNode { SyntaxNode(green: green, offset: 0, parent: nil) }
131 /// Built from the tree on first use, then kept: views read it once per heading.
139 /// The text the tree was parsed from, or for a tree made another way, built from it on
140 /// first use and kept: views read it once per heading.
132141 public var text: String { textCache.text(of: green) }
133142}
134143
@@ -137,6 +146,10 @@ private final class TextCache: @unchecked Sendable {
137146 private let lock = NSLock()
138147 private var text: String?
139148
149 init(_ text: String? = nil) {
150 self.text = text
151 }
152
140153 func text(of green: GreenNode) -> String {
141154 lock.withLock {
142155 if let text { return text }
Sources/OrgCore/Syntax/Wrappers.swift +6 −1
@@ -45,8 +45,13 @@ public enum Wrappers {
4545 public static func all(_ tree: OrgTree) -> [Wrapper] {
4646 var result: [Wrapper] = []
4747 let text = tree.text as NSString
48 // Nodes are made only for drawers, blocks and containers, not for every paragraph.
4849 func walk(_ node: SyntaxNode) {
49 for child in node.children {
50 var at = node.offset
51 for element in node.green.children {
52 defer { at += element.length }
53 guard case .node(let green) = element, kind(green.kind) != nil || containers.contains(green.kind) else { continue }
54 let child = SyntaxNode(green: green, offset: at, parent: node)
5055 if let wrapper = wrapper(child, in: text) { result.append(wrapper) }
5156 if containers.contains(child.kind) { walk(child) }
5257 }
Sources/OrgEditorAppKit/LineIndex.swift +6 −4
@@ -14,13 +14,15 @@ final class LineIndex {
1414 appendStarts(in: text, from: 0, to: text.length)
1515 }
1616
17 /// Reads the text in blocks: a search per line costs more than reading every character.
1718 private func appendStarts(in text: NSString, from: Int, to end: Int) {
19 var buffer = [unichar](repeating: 0, count: 4096)
1820 var location = from
1921 while location < end {
20 let found = text.range(of: "\n", options: .literal, range: NSRange(location: location, length: end - location))
21 guard found.location != NSNotFound else { break }
22 starts.append(found.location + 1)
23 location = found.location + 1
22 let count = min(buffer.count, end - location)
23 text.getCharacters(&buffer, range: NSRange(location: location, length: count))
24 for i in 0..<count where buffer[i] == 10 { starts.append(location + i + 1) }
25 location += count
2426 }
2527 }
2628
Sources/OrgEditorAppKit/OrgEditor+Folding.swift +4 −3
@@ -15,8 +15,9 @@ extension OrgEditor {
1515 setFolds(state, wrappers: nil)
1616 }
1717
18 /// `wrappers`, when given, holds every folded drawer and block.
19 func setFolds(_ state: FoldState, wrappers: [Wrapper]?) {
18 /// `wrappers`, when given, holds every folded drawer and block. `layout` is false when
19 /// nothing has been laid out since the text loaded, so there is no layout to invalidate.
20 func setFolds(_ state: FoldState, wrappers: [Wrapper]?, layout: Bool = true) {
2021 sparseHidden = nil
2122 view.folds = state.folds
2223 view.bodyFolds = state.bodyFolds
@@ -27,7 +28,7 @@ extension OrgEditor {
2728 : state.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: document.tree) })
2829 wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a }
2930 view.wrapperFolds = Set(wrapperHidden.keys)
30 updateHiddenAndLayout()
31 if layout { updateHiddenAndLayout() } else { updateHidden() }
3132 redrawViews()
3233 caretsOutOfHiddenText()
3334 }
Sources/OrgEditorAppKit/OrgEditor.swift +3 −2
@@ -125,10 +125,11 @@ public final class OrgEditor: NSObject {
125125 // Files open at their start, as in Emacs; replacing the storage leaves it at the end.
126126 textView.setSelectedRange(NSRange(location: 0, length: 0))
127127 if let startup {
128 if startup.folds != FoldState() { setFolds(startup.folds, wrappers: startup.wrappers) }
128 if startup.folds != FoldState() { setFolds(startup.folds, wrappers: startup.wrappers, layout: false) }
129129 if startup.alignTables { _ = perform(AlignAllTables()) }
130130 }
131 spellChecking = options.spellCheck
131 // Turning it off clears spelling marks from the whole text; a new view has none.
132 if spellChecking != options.spellCheck { spellChecking = options.spellCheck }
132133 truncatesLines = options.startupTruncated
133134 }
134135
Sources/OrgPresentation/Presentation.swift +9 −5
@@ -223,20 +223,24 @@ public enum Presentation {
223223
224224 private static func computeShadedBlocks(_ tree: OrgTree) -> [Range<Int>] {
225225 var ranges: [Range<Int>] = []
226 func walk(_ node: SyntaxNode) {
227 for child in node.children {
226 // Over green nodes, so no node object is made for each paragraph.
227 func walk(_ node: GreenNode, at offset: Int) {
228 var at = offset
229 for element in node.children {
230 defer { at += element.length }
231 guard case .node(let child) = element else { continue }
228232 switch child.kind {
229233 case .block, .dynamicBlock, .fixedWidth:
230234 // Without the blank lines org counts as part of the element.
231235 let text = child.text
232236 let trimmed = text.utf16.count - String(text.reversed().prefix { $0.isWhitespace }).utf16.count
233 ranges.append(child.range.lowerBound..<(child.range.lowerBound + trimmed))
237 ranges.append(at..<(at + trimmed))
234238 case .paragraph, .table, .heading, .planning, .propertyDrawer, .drawer, .keyword, .comment: continue
235 default: walk(child)
239 default: walk(child, at: at)
236240 }
237241 }
238242 }
239 walk(tree.root)
243 walk(tree.green, at: 0)
240244 return ranges
241245 }
242246
Tests/OrgCoreTests/ParserElementTests.swift +6
@@ -52,6 +52,12 @@ struct ParserElementTests {
5252 #expect(table.children.map(\.kind) == [.tableRow, .tableRow, .tableRow, .tableFormula, .tableFormula])
5353 }
5454
55 @Test func pipeWithACombiningMarkIsCellText() {
56 let row = OrgParser.parse("| a |\u{301} b | ü |\n").root.children[0].children[0].children[0]
57 #expect(row.tokens.filter { $0.kind == .marker }.count == 3)
58 #expect(row.children.filter { $0.kind == .tableCell }.map(\.text) == [" a |\u{301} b ", " ü "])
59 }
60
5561 @Test func footnoteDefinition() {
5662 #expect(childKinds("[fn:1] note\ncontinued\n\nafter\n") == [.footnoteDefinition, .paragraph])
5763 }
Tests/OrgCoreTests/ParserSectionTests.swift +3 −3
@@ -12,7 +12,7 @@ func tokens(of kind: SyntaxKind, in text: String) -> [SyntaxToken] {
1212struct ParserSectionTests {
1313 @Test func emptyDocument() {
1414 let tree = OrgParser.parse("")
15 #expect(tree.text == "")
15 #expect(tree.root.text == "")
1616 #expect(nodeKinds("") == [.document])
1717 }
1818
@@ -63,11 +63,11 @@ struct ParserSectionTests {
6363 }
6464
6565 @Test func headingWithoutNewlineAtEnd() {
66 #expect(OrgParser.parse("* a").text == "* a")
66 #expect(OrgParser.parse("* a").root.text == "* a")
6767 }
6868
6969 @Test(arguments: ["* a\n", "*\n", "* TODO\n", "text\r\n* a\r\n** b\r\n", "\n\n* a\n\n"])
7070 func roundTrip(text: String) {
71 #expect(OrgParser.parse(text).text == text)
71 #expect(OrgParser.parse(text).root.text == text)
7272 }
7373}
Tests/OrgCoreTests/RoundTripTests.swift +3 −3
@@ -50,7 +50,7 @@ struct RoundTripTests {
5050 for n in 0..<2_000 {
5151 let text = randomDocument(&rng)
5252 let tree = OrgParser.parse(text)
53 #expect(tree.text == text, "document \(n)")
53 #expect(tree.root.text == text, "document \(n)")
5454 #expect(checkLengths(tree.root), "document \(n)")
5555 _ = DocumentModel(tree: tree)
5656 }
@@ -66,7 +66,7 @@ struct RoundTripTests {
6666 func encodingFixturesRoundTrip(bytes: [UInt8]) {
6767 let source = SourceText(bytes: bytes)
6868 let tree = OrgParser.parse(source.text)
69 #expect(source.encode(tree.text) == bytes)
69 #expect(source.encode(tree.root.text) == bytes)
7070 }
7171
7272 /// Private corpus: `ORGSTAR_CORPUS=/path/to/org swift test --filter corpus`.
@@ -81,7 +81,7 @@ struct RoundTripTests {
8181 let bytes = try [UInt8](Data(contentsOf: file))
8282 let source = SourceText(bytes: bytes)
8383 let tree = OrgParser.parse(source.text)
84 #expect(source.encode(tree.text) == bytes, "\(file.path)")
84 #expect(source.encode(tree.root.text) == bytes, "\(file.path)")
8585 _ = DocumentModel(tree: tree)
8686 }
8787 }