-
-
Notifications
You must be signed in to change notification settings - Fork 758
/
Analyzer.kt
243 lines (217 loc) · 10.3 KB
/
Analyzer.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
package io.gitlab.arturbosch.detekt.core
import io.github.detekt.psi.absolutePath
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.CompilerResources
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.CorrectableCodeSmell
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.FileProcessListener
import io.gitlab.arturbosch.detekt.api.Finding
import io.gitlab.arturbosch.detekt.api.Finding2
import io.gitlab.arturbosch.detekt.api.RequiresTypeResolution
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.RuleSet
import io.gitlab.arturbosch.detekt.api.RuleSetProvider
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.internal.whichDetekt
import io.gitlab.arturbosch.detekt.api.internal.whichJava
import io.gitlab.arturbosch.detekt.api.internal.whichOS
import io.gitlab.arturbosch.detekt.api.ruleId
import io.gitlab.arturbosch.detekt.core.rules.associateRuleIdsToRuleSetIds
import io.gitlab.arturbosch.detekt.core.suppressors.buildSuppressors
import io.gitlab.arturbosch.detekt.core.suppressors.isSuppressedBy
import io.gitlab.arturbosch.detekt.core.util.isActiveOrDefault
import io.gitlab.arturbosch.detekt.core.util.shouldAnalyzeFile
import org.jetbrains.kotlin.config.languageVersionSettings
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactoryImpl
import kotlin.reflect.full.hasAnnotation
private typealias FindingsResult = List<Map<RuleSet.Id, List<Finding2>>>
internal class Analyzer(
private val settings: ProcessingSettings,
private val providers: List<RuleSetProvider>,
private val processors: List<FileProcessListener>
) {
fun run(
ktFiles: Collection<KtFile>,
bindingContext: BindingContext = BindingContext.EMPTY
): Map<RuleSet.Id, List<Finding2>> {
val languageVersionSettings = settings.environment.configuration.languageVersionSettings
val dataFlowValueFactory = DataFlowValueFactoryImpl(languageVersionSettings)
val compilerResources = CompilerResources(languageVersionSettings, dataFlowValueFactory)
val findingsPerFile: FindingsResult =
if (settings.spec.executionSpec.parallelAnalysis) {
runAsync(ktFiles, bindingContext, compilerResources)
} else {
runSync(ktFiles, bindingContext, compilerResources)
}
if (bindingContext == BindingContext.EMPTY) {
warnAboutEnabledRequiresTypeResolutionRules()
}
val findingsPerRuleSet = HashMap<RuleSet.Id, List<Finding2>>()
for (findings in findingsPerFile) {
findingsPerRuleSet.mergeSmells(findings)
}
return findingsPerRuleSet
}
private fun runSync(
ktFiles: Collection<KtFile>,
bindingContext: BindingContext,
compilerResources: CompilerResources
): FindingsResult =
ktFiles.map { file ->
processors.forEach { it.onProcess(file, bindingContext) }
val findings = runCatching { analyze(file, bindingContext, compilerResources) }
.onFailure { throwIllegalStateException(file, it) }
.getOrDefault(emptyMap())
processors.forEach { it.onProcessComplete(file, findings, bindingContext) }
findings
}
private fun runAsync(
ktFiles: Collection<KtFile>,
bindingContext: BindingContext,
compilerResources: CompilerResources
): FindingsResult {
val service = settings.taskPool
val tasks: TaskList<Map<RuleSet.Id, List<Finding2>>?> = ktFiles.map { file ->
service.task {
processors.forEach { it.onProcess(file, bindingContext) }
val findings = analyze(file, bindingContext, compilerResources)
processors.forEach { it.onProcessComplete(file, findings, bindingContext) }
findings
}.recover { throwIllegalStateException(file, it) }
}
return awaitAll(tasks).filterNotNull()
}
private fun analyze(
file: KtFile,
bindingContext: BindingContext,
compilerResources: CompilerResources
): Map<RuleSet.Id, List<Finding2>> {
val activeRuleSetsToRuleSetConfigs = providers.asSequence()
.map { it to settings.config.subConfig(it.ruleSetId.value) }
.filter { (_, ruleSetConfig) -> ruleSetConfig.isActiveOrDefault(true) }
.map { (provider, ruleSetConfig) -> provider.instance() to ruleSetConfig }
.filter { (_, ruleSetConfig) -> ruleSetConfig.shouldAnalyzeFile(file) }
.toList()
val ruleIdsToRuleSetIds = associateRuleIdsToRuleSetIds(
activeRuleSetsToRuleSetConfigs.map { (ruleSet, _) -> ruleSet }
)
val (correctableRules, otherRules) = activeRuleSetsToRuleSetConfigs
.flatMap { (ruleSet, ruleSetConfig) ->
ruleSet.rules
.asSequence()
.map { (ruleId, ruleProvider) -> ruleProvider to ruleSetConfig.subConfig(ruleId.value) }
.filter { (_, config) -> config.isActiveOrDefault(false) }
.filter { (_, config) -> config.shouldAnalyzeFile(file) }
.map { (ruleProvider, config) -> ruleSet.id to ruleProvider(config) }
.filter { (_, rule) -> !file.isSuppressedBy(rule.ruleId, rule.aliases, ruleSet.id) }
}
.filter { (_, rule) ->
bindingContext != BindingContext.EMPTY || !rule::class.hasAnnotation<RequiresTypeResolution>()
}
.partition { (_, rule) -> rule.autoCorrect }
val result = HashMap<RuleSet.Id, MutableList<Finding2>>()
fun executeRules(rules: List<Pair<RuleSet.Id, Rule>>) {
for ((ruleSetId, rule) in rules) {
val findings = rule.visitFile(file, bindingContext, compilerResources)
.filterNot {
it.entity.ktElement?.isSuppressedBy(rule.ruleId, rule.aliases, ruleSetId) == true
}
.filterSuppressedFindings(rule, bindingContext)
for (finding in findings) {
val mappedRuleSet = checkNotNull(ruleIdsToRuleSetIds[rule.ruleId]) {
"Mapping for '${rule.ruleId}' expected."
}
result.computeIfAbsent(mappedRuleSet) { mutableListOf() }
.add(finding.toFinding2(rule.toRuleInfo(ruleSetId), rule.computeSeverity()))
}
}
}
executeRules(correctableRules)
executeRules(otherRules)
return result
}
private fun warnAboutEnabledRequiresTypeResolutionRules() {
providers.asSequence()
.map { it to settings.config.subConfig(it.ruleSetId.value) }
.filter { (_, ruleSetConfig) -> ruleSetConfig.isActiveOrDefault(true) }
.map { (provider, ruleSetConfig) -> provider.instance() to ruleSetConfig }
.flatMap { (ruleSet, ruleSetConfig) ->
ruleSet.rules
.asSequence()
.map { (ruleId, ruleProvider) -> ruleProvider to ruleSetConfig.subConfig(ruleId.value) }
.filter { (_, config) -> config.isActiveOrDefault(false) }
.map { (ruleProvider, config) -> ruleProvider(config) }
}
.filter { rule -> rule::class.hasAnnotation<RequiresTypeResolution>() }
.forEach { rule ->
settings.debug { "The rule '${rule.ruleId}' requires type resolution but it was run without it." }
}
}
}
private fun List<Finding>.filterSuppressedFindings(rule: Rule, bindingContext: BindingContext): List<Finding> {
val suppressors = buildSuppressors(rule, bindingContext)
return if (suppressors.isNotEmpty()) {
filter { finding -> !suppressors.any { suppressor -> suppressor.shouldSuppress(finding) } }
} else {
this
}
}
private fun MutableMap<RuleSet.Id, List<Finding2>>.mergeSmells(other: Map<RuleSet.Id, List<Finding2>>) {
for ((key, findings) in other.entries) {
merge(key, findings) { f1, f2 -> f1.plus(f2) }
}
}
private fun throwIllegalStateException(file: KtFile, error: Throwable): Nothing {
val message = """
Analyzing ${file.absolutePath()} led to an exception.
Location: ${error.stackTrace.firstOrNull()?.toString()}
The original exception message was: ${error.localizedMessage}
Running detekt '${whichDetekt()}' on Java '${whichJava()}' on OS '${whichOS()}'
If the exception message does not help, please feel free to create an issue on our GitHub page.
""".trimIndent()
throw IllegalStateException(message, error)
}
private fun Finding.toFinding2(rule: Finding2.RuleInfo, severity: Severity): Finding2 {
return when (this) {
is CorrectableCodeSmell -> Finding2Impl(rule, entity, message, references, severity, autoCorrectEnabled)
is CodeSmell -> Finding2Impl(rule, entity, message, references, severity)
else -> error("wtf?")
}
}
private fun Rule.toRuleInfo(ruleSetId: RuleSet.Id): Finding2.RuleInfo {
return Finding2Impl.RuleInfo(ruleId, ruleSetId, description)
}
private data class Finding2Impl(
override val ruleInfo: Finding2.RuleInfo,
override val entity: Entity,
override val message: String,
override val references: List<Entity>,
override val severity: Severity,
override val autoCorrectEnabled: Boolean = false,
) : Finding2 {
data class RuleInfo(
override val id: Rule.Id,
override val ruleSetId: RuleSet.Id,
override val description: String,
) : Finding2.RuleInfo
}
/**
* Compute severity in the priority order:
* - Severity of the rule
* - Severity of the parent ruleset
* - Default severity
*/
private fun Rule.computeSeverity(): Severity {
val configValue: String = config.valueOrNull(Config.SEVERITY_KEY)
?: config.parent?.valueOrNull(Config.SEVERITY_KEY)
?: return Severity.Error
return parseToSeverity(configValue)
}
internal fun parseToSeverity(severity: String): Severity {
val lowercase = severity.lowercase()
return Severity.entries.find { it.name.lowercase() == lowercase }
?: error("$severity is not a valid Severity. Allowed values are ${Severity.entries}")
}