Sources/OrgCore/Lint/Linter.swift
209 lines · 8383 bytes
12 symbols in this file
1import Foundation
2
3/// One run of the checkers over a file. The tree is walked once to collect what the checkers
4/// read; checkers that org-lint runs as regexp searches over the buffer search the text and ask
5/// the tree which element each line belongs to.
6struct Linter {
7 let text: String
8 let ns: NSString
9 let tree: OrgTree
10 let path: String?
11 let env: LintEnvironment
12 let model: DocumentModel
13 var findings: [LintFinding] = []
14
15 /// UTF-16 offset of each line's first character.
16 let lineStarts: [Int]
17 /// The innermost element each line belongs to.
18 var lineTags: [Tag]
19 /// Encrypted entry bodies, which aren't linted.
20 var excluded: [Range<Int>] = []
21
22 enum Tag: Equatable {
23 case none, other, heading, paragraph, planning, drawer, propertyDrawer, dynamicBlock
24 /// A block whose contents aren't parsed: comment, example, export, src and verse blocks.
25 case verbatimBlock
26 case block
27 }
28
29 var links: [SyntaxNode] = []
30 var footnoteReferences: [SyntaxNode] = []
31 var footnoteDefinitions: [SyntaxNode] = []
32 var targets: [SyntaxNode] = []
33 var keywords: [SyntaxNode] = []
34 var propertyDrawers: [SyntaxNode] = []
35 var drawers: [SyntaxNode] = []
36 var blocks: [SyntaxNode] = []
37 var plannings: [SyntaxNode] = []
38 var clocks: [SyntaxNode] = []
39 var timestamps: [SyntaxNode] = []
40
41 /// `#+NAME` values of elements, and `#+RESULTS` values, for fuzzy links.
42 var names: [(offset: Int, value: String)] = []
43 var resultNames: [String] = []
44
45 init(text: String, tree: OrgTree, path: String?, environment: LintEnvironment) {
46 self.text = text
47 ns = text as NSString
48 self.tree = tree
49 self.path = path
50 env = environment
51 model = DocumentModel(tree: tree)
52 var starts = [0]
53 var offset = 0
54 for unit in text.utf16 {
55 offset += 1
56 if unit == 10 { starts.append(offset) }
57 }
58 if starts.count > 1, starts.last == ns.length { starts.removeLast() }
59 lineStarts = starts
60 lineTags = Array(repeating: .none, count: starts.count)
61 }
62
63 mutating func run() {
64 excluded = encryptedBodies()
65 walk(tree.root)
66 keywordChecks()
67 linkChecks()
68 attachmentChecks()
69 duplicateChecks()
70 drawerChecks()
71 blockChecks()
72 lineChecks()
73 headingChecks()
74 propertyChecks()
75 timestampChecks()
76 footnoteChecks()
77 }
78
79 // MARK: - Lines
80
81 /// 0-based line of a UTF-16 offset.
82 func lineIndex(_ offset: Int) -> Int {
83 var low = 0, high = lineStarts.count - 1
84 while low < high {
85 let mid = (low + high + 1) / 2
86 if lineStarts[mid] <= offset { low = mid } else { high = mid - 1 }
87 }
88 return low
89 }
90
91 /// Line `index`'s text, without its line ending.
92 func line(_ index: Int) -> String {
93 let start = lineStarts[index]
94 let end = index + 1 < lineStarts.count ? lineStarts[index + 1] : ns.length
95 var s = ns.substring(with: NSRange(location: start, length: end - start))
96 while s.hasSuffix("\n") || s.hasSuffix("\r") { s.removeLast() }
97 return s
98 }
99
100 mutating func report(_ checker: LintChecker, at offset: Int, _ message: String, folder: String? = nil) {
101 guard !excluded.contains(where: { $0.contains(offset) }) else { return }
102 findings.append(LintFinding(offset: offset, line: lineIndex(offset) + 1, checker: checker, message: message, folder: folder))
103 }
104
105 func matches(_ pattern: String, caseInsensitive: Bool = false, anchorsMatchLines: Bool = true) -> [NSTextCheckingResult] {
106 var options: NSRegularExpression.Options = []
107 if caseInsensitive { options.insert(.caseInsensitive) }
108 if anchorsMatchLines { options.insert(.anchorsMatchLines) }
109 let regex = try! NSRegularExpression(pattern: pattern, options: options)
110 return regex.matches(in: text, range: NSRange(location: 0, length: ns.length))
111 }
112
113 func group(_ m: NSTextCheckingResult, _ i: Int) -> String? {
114 m.range(at: i).location == NSNotFound ? nil : ns.substring(with: m.range(at: i))
115 }
116
117 var folder: String? { path.map { ($0 as NSString).deletingLastPathComponent } }
118
119 // MARK: - Collecting
120
121 static let verbatimBlocks: Set<String> = ["comment", "example", "export", "src", "verse"]
122
123 /// The name after `#+begin_` on a block's first line, as written.
124 static func blockName(_ node: SyntaxNode) -> String {
125 let first = node.text.prefix { $0 != "\n" && $0 != "\r" }.drop { $0 == " " || $0 == "\t" }
126 return String(first.dropFirst("#+begin_".count).prefix { !$0.isWhitespace })
127 }
128
129 mutating func tag(_ node: SyntaxNode, _ tag: Tag) {
130 let first = lineIndex(node.range.lowerBound)
131 let last = lineIndex(max(node.range.lowerBound, node.range.upperBound - 1))
132 for i in first...last { lineTags[i] = tag }
133 }
134
135 mutating func walk(_ node: SyntaxNode) {
136 for child in node.children {
137 switch child.kind {
138 case .section, .zerothSection, .title, .linkDescription, .itemTag, .tableRow, .tableCell:
139 walk(child)
140 case .heading:
141 tag(child, .heading)
142 walk(child)
143 case .block:
144 tag(child, Self.verbatimBlocks.contains(Self.blockName(child).lowercased()) ? .verbatimBlock : .block)
145 blocks.append(child)
146 case .dynamicBlock:
147 tag(child, .dynamicBlock)
148 case .drawer:
149 tag(child, .drawer)
150 drawers.append(child)
151 walk(child)
152 case .propertyDrawer:
153 tag(child, .propertyDrawer)
154 propertyDrawers.append(child)
155 case .planning:
156 tag(child, .planning)
157 plannings.append(child)
158 case .clock:
159 tag(child, .other)
160 clocks.append(child)
161 case .paragraph:
162 tag(child, .paragraph)
163 walk(child)
164 case .keyword, .affiliatedKeyword:
165 tag(child, .other)
166 keywords.append(child)
167 case .footnoteDefinition:
168 tag(child, .other)
169 footnoteDefinitions.append(child)
170 walk(child)
171 case .link:
172 links.append(child)
173 walk(child)
174 case .footnoteReference:
175 footnoteReferences.append(child)
176 walk(child)
177 case .target:
178 targets.append(child)
179 case .timestamp:
180 timestamps.append(child)
181 case .bold, .italic, .underline, .strikeThrough, .citation, .citationReference, .superscript, .subscript, .radioTarget:
182 walk(child)
183 case .verbatim, .code, .statisticsCookie, .macro, .inlineSourceBlock, .latexFragment, .lineBreak, .entity, .exportSnippet,
184 .inlineBabelCall:
185 break
186 default:
187 tag(child, .other)
188 walk(child)
189 }
190 }
191 }
192
193 /// The bodies of entries tagged with the crypt tag that hold an armored message: from its
194 /// begin line through its end line.
195 func encryptedBodies() -> [Range<Int>] {
196 var ranges: [Range<Int>] = []
197 for (index, heading) in model.headings.enumerated() where heading.localTags.contains(env.cryptTag) {
198 let bodyEnd = model.headings.dropFirst(index + 1).first { $0.parent == index }?.sectionRange.lowerBound ?? heading.sectionRange.upperBound
199 let body = NSRange(location: heading.headingRange.upperBound, length: max(0, bodyEnd - heading.headingRange.upperBound))
200 let begin = ns.range(of: "-----BEGIN PGP MESSAGE-----", range: body)
201 guard begin.location != NSNotFound else { continue }
202 let after = NSRange(location: NSMaxRange(begin), length: NSMaxRange(body) - NSMaxRange(begin))
203 let end = ns.range(of: "-----END PGP MESSAGE-----", range: after)
204 let stop = end.location == NSNotFound ? NSMaxRange(body) : NSMaxRange(ns.lineRange(for: end))
205 ranges.append(ns.lineRange(for: begin).location..<stop)
206 }
207 return ranges
208 }
209}