Sources/OrgCore/Syntax/SyntaxNode.swift

design-themes-widgets
orgstar/Sources/OrgCore/Syntax/SyntaxNode.swift history · blame · raw

161 lines · 5368 bytes

  1import Foundation
  2
  3/// A view of a green node at an absolute offset, with a parent link. Created on demand.
  4public final class SyntaxNode: Sendable {
  5    public let green: GreenNode
  6    public let offset: Int
  7    public let parent: SyntaxNode?
  8
  9    init(green: GreenNode, offset: Int, parent: SyntaxNode?) {
 10        self.green = green
 11        self.offset = offset
 12        self.parent = parent
 13    }
 14
 15    public var kind: SyntaxKind { green.kind }
 16    public var range: Range<Int> { offset..<(offset + green.length) }
 17    public var text: String { green.text }
 18
 19    public var children: [SyntaxNode] {
 20        var result: [SyntaxNode] = []
 21        var at = offset
 22        for child in green.children {
 23            if case .node(let node) = child {
 24                result.append(SyntaxNode(green: node, offset: at, parent: self))
 25            }
 26            at += child.length
 27        }
 28        return result
 29    }
 30
 31    public var tokens: [SyntaxToken] {
 32        var result: [SyntaxToken] = []
 33        var at = offset
 34        for child in green.children {
 35            if case .token(let token) = child {
 36                result.append(SyntaxToken(kind: token.kind, text: token.text, range: at..<(at + token.length)))
 37            }
 38            at += child.length
 39        }
 40        return result
 41    }
 42
 43    /// Child nodes overlapping `range`. Only those are created, so a section with thousands of
 44    /// children costs little when the range is small.
 45    public func children(overlapping range: Range<Int>) -> [SyntaxNode] {
 46        var result: [SyntaxNode] = []
 47        var at = offset
 48        for child in green.children {
 49            let childRange = at..<(at + child.length)
 50            if childRange.lowerBound >= range.upperBound, !range.isEmpty { break }
 51            if case .node(let node) = child, childRange.overlaps(range) {
 52                result.append(SyntaxNode(green: node, offset: at, parent: self))
 53            }
 54            at = childRange.upperBound
 55        }
 56        return result
 57    }
 58
 59    /// The child node whose range contains `position`.
 60    public func child(containing position: Int) -> SyntaxNode? {
 61        var at = offset
 62        for child in green.children {
 63            let end = at + child.length
 64            if position < end {
 65                if case .node(let node) = child, position >= at { return SyntaxNode(green: node, offset: at, parent: self) }
 66                return nil
 67            }
 68            at = end
 69        }
 70        return nil
 71    }
 72
 73    /// The first child node of `kind`.
 74    public func firstChild(_ kind: SyntaxKind) -> SyntaxNode? {
 75        var at = offset
 76        for child in green.children {
 77            if case .node(let node) = child, node.kind == kind { return SyntaxNode(green: node, offset: at, parent: self) }
 78            at += child.length
 79        }
 80        return nil
 81    }
 82
 83    public enum Element {
 84        case node(SyntaxNode)
 85        case token(SyntaxToken)
 86    }
 87
 88    /// Child nodes and tokens in document order.
 89    public var elements: [Element] {
 90        var result: [Element] = []
 91        var at = offset
 92        for child in green.children {
 93            switch child {
 94            case .node(let node): result.append(.node(SyntaxNode(green: node, offset: at, parent: self)))
 95            case .token(let token): result.append(.token(SyntaxToken(kind: token.kind, text: token.text, range: at..<(at + child.length))))
 96            }
 97            at += child.length
 98        }
 99        return result
100    }
101
102    /// This node and every node below it, in document order.
103    public func descendants() -> [SyntaxNode] {
104        [self] + children.flatMap { $0.descendants() }
105    }
106
107    /// A bracket link's path as `org-element-link-parser` reads it: each run of blanks
108    /// holding a newline made one space.
109    var linkPath: String? {
110        tokens.first { $0.kind == .linkPath }.map { $0.text.replacing(/[ \t]*\r?\n[ \t]*/.matchingSemantics(.unicodeScalar), with: " ") }
111    }
112}
113
114public struct SyntaxToken: Sendable, Equatable {
115    public let kind: SyntaxKind
116    public let text: String
117    public let range: Range<Int>
118}
119
120public struct OrgTree: Sendable {
121    public let green: GreenNode
122    public let settings: OrgSettings
123    private let textCache: TextCache
124
125    public init(green: GreenNode, settings: OrgSettings) {
126        self.green = green
127        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)
136    }
137
138    public var root: SyntaxNode { SyntaxNode(green: green, offset: 0, parent: nil) }
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.
141    public var text: String { textCache.text(of: green) }
142}
143
144/// An `OrgTree`'s text, built once.
145private final class TextCache: @unchecked Sendable {
146    private let lock = NSLock()
147    private var text: String?
148
149    init(_ text: String? = nil) {
150        self.text = text
151    }
152
153    func text(of green: GreenNode) -> String {
154        lock.withLock {
155            if let text { return text }
156            let built = green.text
157            text = built
158            return built
159        }
160    }
161}