-
Notifications
You must be signed in to change notification settings - Fork 501
/
MaxLineLengthRule.kt
265 lines (242 loc) · 10.5 KB
/
MaxLineLengthRule.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package com.pinterest.ktlint.ruleset.standard
import com.pinterest.ktlint.core.Rule
import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.maxLineLengthProperty
import com.pinterest.ktlint.core.api.EditorConfigProperties
import com.pinterest.ktlint.core.api.UsesEditorConfigProperties
import com.pinterest.ktlint.core.ast.ElementType
import com.pinterest.ktlint.core.ast.isPartOf
import com.pinterest.ktlint.core.ast.isRoot
import com.pinterest.ktlint.core.ast.nextLeaf
import com.pinterest.ktlint.core.ast.parent
import com.pinterest.ktlint.core.ast.prevCodeSibling
import kotlin.properties.Delegates
import org.ec4j.core.model.PropertyType
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.PsiComment
import org.jetbrains.kotlin.com.intellij.psi.PsiElement
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.kdoc.psi.api.KDoc
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.KtPackageDirective
class MaxLineLengthRule :
Rule(
id = "max-line-length",
visitorModifiers = setOf(
VisitorModifier.RunAfterRule(
// This rule should run after all other rules. Each time a rule visitor is modified with
// RunAsLateAsPossible, it needs to be checked that this rule still runs after that new rule or that it
// won't be affected by that rule.
ruleId = "trailing-comma-on-call-site",
loadOnlyWhenOtherRuleIsLoaded = false,
runOnlyWhenOtherRuleIsEnabled = false
),
VisitorModifier.RunAfterRule(
// This rule should run after all other rules. Each time a rule visitor is modified with
// RunAsLateAsPossible, it needs to be checked that this rule still runs after that new rule or that it
// won't be affected by that rule.
ruleId = "trailing-comma-on-declaration-site",
loadOnlyWhenOtherRuleIsLoaded = false,
runOnlyWhenOtherRuleIsEnabled = false
),
VisitorModifier.RunAsLateAsPossible
)
),
UsesEditorConfigProperties {
override val editorConfigProperties: List<UsesEditorConfigProperties.EditorConfigProperty<*>> = listOf(
maxLineLengthProperty,
ignoreBackTickedIdentifierProperty
)
private var maxLineLength: Int = maxLineLengthProperty.defaultValue
private var rangeTree = RangeTree()
private var ignoreBackTickedIdentifier by Delegates.notNull<Boolean>()
override fun beforeFirstNode(editorConfigProperties: EditorConfigProperties) {
ignoreBackTickedIdentifier = editorConfigProperties.getEditorConfigValue(ignoreBackTickedIdentifierProperty)
maxLineLength = editorConfigProperties.getEditorConfigValue(maxLineLengthProperty)
}
override fun beforeVisitChildNodes(
node: ASTNode,
autoCorrect: Boolean,
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit
) {
if (maxLineLength <= 0) {
return
}
if (node.isRoot()) {
val errorOffset = arrayListOf<Int>()
node
.getElementsPerLine()
.filter { it.lineLength(ignoreBackTickedIdentifier) > maxLineLength }
.forEach { parsedLine ->
val el = parsedLine.elements.last()
if (!el.isPartOf(KDoc::class) && !el.isPartOfRawMultiLineString()) {
if (!el.isPartOf(PsiComment::class)) {
if (!el.isPartOf(KtPackageDirective::class) && !el.isPartOf(KtImportDirective::class)) {
// fixme:
// normally we would emit here but due to API limitations we need to hold off until
// node spanning the same offset is 'visit'ed
// (for ktlint-disable directive to have effect (when applied))
// this will be rectified in the upcoming release(s)
errorOffset.add(parsedLine.offset)
}
} else {
// Allow ktlint-disable comments to exceed max line length
if (!el.text.startsWith("// ktlint-disable")) {
// if comment is the only thing on the line - fine, otherwise emit an error
val prevLeaf = el.prevCodeSibling()
if (prevLeaf != null && prevLeaf.startOffset >= parsedLine.offset) {
// fixme:
// normally we would emit here but due to API limitations we need to hold off until
// node spanning the same offset is 'visit'ed
// (for ktlint-disable directive to have effect (when applied))
// this will be rectified in the upcoming release(s)
errorOffset.add(parsedLine.offset)
}
}
}
}
}
rangeTree = RangeTree(errorOffset)
} else if (!rangeTree.isEmpty() && node.psi is LeafPsiElement) {
rangeTree
.query(node.startOffset, node.startOffset + node.textLength)
.forEach { offset ->
emit(offset, "Exceeded max line length ($maxLineLength)", false)
}
}
}
private fun ASTNode.isPartOfRawMultiLineString() =
parent(ElementType.STRING_TEMPLATE, strict = false)
?.let { it.firstChildNode.text == "\"\"\"" && it.textContains('\n') } == true
public companion object {
internal const val KTLINT_IGNORE_BACKTICKED_IDENTIFIER_NAME = "ktlint_ignore_back_ticked_identifier"
private const val PROPERTY_DESCRIPTION = "Defines whether the backticked identifier (``) should be ignored"
public val ignoreBackTickedIdentifierProperty: UsesEditorConfigProperties.EditorConfigProperty<Boolean> =
UsesEditorConfigProperties.EditorConfigProperty(
type = PropertyType.LowerCasingPropertyType(
KTLINT_IGNORE_BACKTICKED_IDENTIFIER_NAME,
PROPERTY_DESCRIPTION,
PropertyType.PropertyValueParser.BOOLEAN_VALUE_PARSER,
setOf(true.toString(), false.toString())
),
defaultValue = false
)
}
}
private fun ASTNode.getElementsPerLine(): List<ParsedLine> {
val parsedLines = mutableListOf<ParsedLine>()
val lines = text.split("\n")
var offset = 0
for (line in lines) {
val elements = mutableListOf<ASTNode>()
var el = psi.findElementAt(offset)?.node
while (el != null && el.startOffset < offset + line.length) {
elements.add(el)
el = el.nextLeaf()
}
parsedLines.add(ParsedLine(line, offset, elements))
offset += line.length + 1 // +1 for the newline which is stripped due to the splitting of the lines
}
return parsedLines
}
private data class ParsedLine(
val line: String,
val offset: Int,
val elements: List<ASTNode>
) {
fun lineLength(ignoreBackTickedIdentifier: Boolean): Int {
return if (ignoreBackTickedIdentifier) {
line.length - totalLengthBacktickedElements()
} else {
line.length
}
}
private fun totalLengthBacktickedElements(): Int {
return elements
.filterIsInstance(PsiElement::class.java)
.filter { it.text.matches(isValueBetweenBackticks) }
.sumOf(PsiElement::getTextLength)
}
private companion object {
val isValueBetweenBackticks = Regex("`.*`")
}
}
@Deprecated("Marked for removal from public API in ktlint 0.48")
class RangeTree(seq: List<Int> = emptyList()) {
private var emptyArrayView = ArrayView(0, 0)
private var arr: IntArray = seq.toIntArray()
init {
if (arr.isNotEmpty()) {
arr.reduce { p, n -> require(p <= n) { "Input must be sorted" }; n }
}
}
// runtime: O(log(n)+k), where k is number of matching points
// space: O(1)
@Deprecated("Marked for removal from public API in ktlint 0.48")
fun query(vmin: Int, vmax: Int): RangeTree.ArrayView {
var r = arr.size - 1
if (r == -1 || vmax < arr[0] || arr[r] < vmin) {
return emptyArrayView
}
// binary search for min(arr[l] >= vmin)
var l = 0
while (l < r) {
val m = (r + l) / 2
if (vmax < arr[m]) {
r = m - 1
} else if (arr[m] < vmin) {
l = m + 1
} else {
// arr[l] ?<=? vmin <= arr[m] <= vmax ?<=? arr[r]
if (vmin <= arr[l]) break else l++ // optimization
r = m
}
}
if (l > r || arr[l] < vmin) {
return emptyArrayView
}
// find max(k) such as arr[k] < vmax
var k = l
while (k < arr.size) {
if (arr[k] >= vmax) {
break
}
k++
}
return ArrayView(l, k)
}
@Deprecated("Marked for removal from public API in ktlint 0.48")
fun isEmpty() = arr.isEmpty()
@Deprecated("Marked for removal from public API in ktlint 0.48")
inner class ArrayView(private var l: Int, private val r: Int) {
@Deprecated("Marked for removal from public API in ktlint 0.48")
val size: Int = r - l
@Deprecated("Marked for removal from public API in ktlint 0.48")
fun get(i: Int): Int {
if (i < 0 || i >= size) {
throw IndexOutOfBoundsException()
}
return arr[l + i]
}
@Deprecated("Marked for removal from public API in ktlint 0.48")
inline fun forEach(cb: (v: Int) -> Unit) {
var i = 0
while (i < size) {
cb(get(i++))
}
}
override fun toString(): String {
if (l == r) {
return "[]"
}
val sb = StringBuilder("[")
var i = l
while (i < r) {
sb.append(arr[i]).append(", ")
i++
}
sb.replace(sb.length - 2, sb.length, "")
sb.append("]")
return sb.toString()
}
}
}