Skip to content

Make all compilation warnings errors #341

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import groovy.util.*
import kotlinx.team.infra.*
import org.gradle.jvm.tasks.Jar
import org.jetbrains.kotlin.gradle.*

// atomicfu
buildscript {
Expand All @@ -23,6 +24,11 @@ repositories {
}

kotlin {
@OptIn(ExperimentalKotlinGradlePluginApi::class)
compilerOptions {
allWarningsAsErrors = true
}

jvm {
withJava()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
* Several {@link StressCTest tests} can refer to one structure
* (i.e. one test class could have several {@link StressCTest} annotations)
*/
@SuppressWarnings("removal")
public class CTestStructure {
public final List<ActorGenerator> actorGenerators;
public final List<ParameterGenerator<?>> parameterGenerators;
Expand Down
1 change: 0 additions & 1 deletion src/jvm/main/org/jetbrains/kotlinx/lincheck/LinChecker.kt
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,6 @@ class LinChecker(private val testClass: Class<*>, options: Options<*, *>?) {
if (failure == null)
return@forEachIndexed
if (minimizeFailedScenario && !isCustomScenario) {
var j = i + 1
reporter.logScenarioMinimization(scenario)
failure = failure.minimize { minimizedScenario ->
minimizedScenario.run(this, createVerifier())
Expand Down
1 change: 1 addition & 0 deletions src/jvm/main/org/jetbrains/kotlinx/lincheck/Options.kt
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ abstract class Options<OPT : Options<OPT, CTEST>, CTEST : CTestConfiguration> {
* If the check failed [[IllegalStateException]] was thrown.
*/
@Deprecated("Does nothing, because equals/hashcode don't always improve performance of verification")
@Suppress("UNUSED_PARAMETER")
fun requireStateEquivalenceImplCheck(require: Boolean): OPT = applyAndCast { }

/**
Expand Down
7 changes: 4 additions & 3 deletions src/jvm/main/org/jetbrains/kotlinx/lincheck/Reporter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ private data class ResultActorData(
: this(actor, result, (result as? ExceptionResult)?.let { exceptionStackTraces[it.throwable] }, hbClock)

override fun toString(): String {
return "${actor}${result.toString().let { ": $it" } ?: ""}" +
return "${actor}${result.toString().let { ": $it" }}" +
(exceptionInfo?.let { " #${it.number}" } ?: "") +
(hbClock?.takeIf { !it.empty }?.let { " $it" } ?: "")
}
Expand Down Expand Up @@ -644,6 +644,7 @@ private fun StringBuilder.appendTimeoutDeadlockWithDumpFailure(
appendExecutionScenarioWithResults(failure, exceptionStackTraces)
appendLine()
// Sort threads to produce same output for the same results
@Suppress("DEPRECATION") // Thread.id
for ((t, stackTrace) in failure.threadDump.entries.sortedBy { it.key.id }) {
val threadNumber = (t as? TestThread)?.name ?: "?"
appendLine("Thread-$threadNumber:")
Expand Down Expand Up @@ -692,8 +693,8 @@ private fun StringBuilder.appendValidationFailure(
): StringBuilder {
appendLine("= Validation function ${failure.validationFunctionName} has failed =")
appendExecutionScenarioWithResults(failure, exceptionStackTraces)
appendln()
appendln()
appendLine()
appendLine()
appendException(failure.exception)
return this
}
Expand Down
4 changes: 1 addition & 3 deletions src/jvm/main/org/jetbrains/kotlinx/lincheck/Result.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ sealed interface Result
/**
* Type of result used if the actor invocation returns any value.
*/
data class ValueResult @JvmOverloads constructor(val value: Any?) : Result {
data class ValueResult(val value: Any?) : Result {
override fun toString() = "$value"
}

Expand Down Expand Up @@ -73,8 +73,6 @@ class ExceptionResult private constructor(


companion object {
@Suppress("UNCHECKED_CAST")
@JvmOverloads
fun create(throwable: Throwable) = ExceptionResult(throwable)
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/jvm/main/org/jetbrains/kotlinx/lincheck/Utils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ internal fun collectThreadDump(runner: Runner) = Thread.getAllStackTraces().filt

internal val String.canonicalClassName get() = this.replace('/', '.')

@Suppress("DEPRECATION") // ThreadDeath
internal fun exceptionCanBeValidExecutionResult(exception: Throwable): Boolean {
return exception !is ThreadDeath && // used to stop thread in FixedActiveThreadsExecutor by calling thread.stop method
exception !is InternalLincheckTestUnexpectedException &&
Expand Down Expand Up @@ -222,6 +223,7 @@ internal val Class<*>.allDeclaredFieldWithSuperclasses get(): List<Field> {
return fields
}

@Suppress("DEPRECATION")
internal fun findFieldNameByOffset(targetType: Class<*>, offset: Long): String? {
// Extract the private offset value and find the matching field.
for (field in targetType.declaredFields) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,11 @@ class IntGen(randomProvider: RandomProvider, configuration: String) : ParameterG
override fun reset() = generator.resetRange()
}

class BooleanGen(randomProvider: RandomProvider, configuration: String) : ParameterGenerator<Boolean> {
class BooleanGen(
randomProvider: RandomProvider,
@Suppress("UNUSED_PARAMETER")
configuration: String
) : ParameterGenerator<Boolean> {
private val random = randomProvider.createRandom()

override fun generate() = random.nextBoolean()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ internal open class ParallelThreadsRunner(
// already cancelled via prompt cancellation, increment the counter back
completedOrSuspendedThreads.incrementAndGet()
}
@Suppress("UNCHECKED_CAST")
resWithCont.set(result to continuation as Continuation<Any?>)
}
}
Expand Down Expand Up @@ -182,6 +183,7 @@ internal open class ParallelThreadsRunner(
private var ensuredTestInstanceIsTransformed = false

private fun createTestInstance() {
@Suppress("DEPRECATION")
testInstance = testClass.newInstance()
if (strategy is ModelCheckingStrategy) {
// We pass the test instance to the strategy to initialize the call stack.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import java.util.concurrent.atomic.AtomicReferenceFieldUpdater
*/
internal object AtomicFieldUpdaterNames {

@Suppress("DEPRECATION")
internal fun getAtomicFieldUpdaterName(updater: Any): String? {
if (updater !is AtomicIntegerFieldUpdater<*> && updater !is AtomicLongFieldUpdater<*> && updater !is AtomicReferenceFieldUpdater<*, *>) {
throw IllegalArgumentException("Provided object is not a recognized Atomic*FieldUpdater type.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -262,11 +262,11 @@ abstract class ManagedStrategy(
)
check(sameResultTypes && sameResults) {
StringBuilder().apply {
appendln("Non-determinism found. Probably caused by non-deterministic code (WeakHashMap, Object.hashCode, etc).")
appendln("== Reporting the first execution without execution trace ==")
appendln(result.toLincheckFailure(scenario, null))
appendln("== Reporting the second execution ==")
appendln(loggedResults.toLincheckFailure(scenario, Trace(traceCollector!!.trace)).toString())
appendLine("Non-determinism found. Probably caused by non-deterministic code (WeakHashMap, Object.hashCode, etc).")
appendLine("== Reporting the first execution without execution trace ==")
appendLine(result.toLincheckFailure(scenario, null))
appendLine("== Reporting the second execution ==")
appendLine(loggedResults.toLincheckFailure(scenario, Trace(traceCollector!!.trace)).toString())
}.toString()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ internal class ModelCheckingStrategy(
protected fun chooseUnexploredNode(): Choice {
if (choices.size == 1) return choices.first()
// Choose a weighted random child.
val total = choices.sumByDouble { it.node.fractionUnexplored }
val total = choices.sumOf { it.node.fractionUnexplored }
val random = generationRandom.nextDouble() * total
var sumWeight = 0.0
choices.forEach { choice ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ internal class MethodCallTransformer(

override fun visitMethodInsn(opcode: Int, owner: String, name: String, desc: String, itf: Boolean) = adapter.run {
// TODO: do not ignore <init>
if (name == "<init>" || isIgnoredMethod(owner, name)) {
if (name == "<init>" || isIgnoredMethod(className = owner)) {
visitMethodInsn(opcode, owner, name, desc, itf)
return
}
Expand Down Expand Up @@ -116,7 +116,7 @@ internal class MethodCallTransformer(
}
}

private fun isIgnoredMethod(className: String, methodName: String) =
private fun isIgnoredMethod(className: String) =
className.startsWith("sun/nio/ch/lincheck/") ||
className.startsWith("org/jetbrains/kotlinx/lincheck/") ||
className == "kotlin/jvm/internal/Intrinsics" ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ internal object UnsafeHolder {
}
}

@Suppress("DEPRECATION")
internal inline fun <T> readFieldViaUnsafe(obj: Any?, field: Field, getter: Unsafe.(Any?, Long) -> T): T {
if (Modifier.isStatic(field.modifiers)) {
val base = UnsafeHolder.UNSAFE.staticFieldBase(field)
Expand Down
40 changes: 22 additions & 18 deletions src/jvm/main/org/jetbrains/kotlinx/lincheck/verifier/LTS.kt
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,15 @@ class LTS(private val sequentialSpecification: Class<*>) {
/**
* Computes or gets the existing transition from the current state by the given [actor].
*/
fun next(actor: Actor, expectedResult: Result, ticket: Int) = when(ticket) {
fun next(actor: Actor, expectedResult: Result, ticket: Int) = when (ticket) {
NO_TICKET -> nextByRequest(actor, expectedResult)
else -> nextByFollowUp(actor, ticket, expectedResult)
}

private fun createAtomicallySuspendedAndCancelledTransition() = copyAndApply { instance, suspendedOperations, resumedTicketsWithResults, continuationsMap ->
TransitionInfo(this, getResumedOperations(resumedTicketsWithResults).map { it.resumedActorTicket }.toSet(), NO_TICKET, null, Cancelled)
}
private fun createAtomicallySuspendedAndCancelledTransition() =
copyAndApply { _, _, resumedTicketsWithResults, _ ->
TransitionInfo(this, getResumedOperations(resumedTicketsWithResults).map { it.resumedActorTicket }.toSet(), NO_TICKET, null, Cancelled)
}

private fun nextByRequest(actor: Actor, expectedResult: Result): TransitionInfo? {
// Compute the transition following the sequential specification.
Expand Down Expand Up @@ -126,8 +127,8 @@ class LTS(private val sequentialSpecification: Class<*>) {

private fun Result.isLegalByFollowUp(transitionInfo: TransitionInfo) =
this == transitionInfo.result ||
this is ValueResult && transitionInfo.result is ValueResult && this.value == transitionInfo.result.value ||
this is ExceptionResult && transitionInfo.result is ExceptionResult && this.tClassCanonicalName == transitionInfo.result.tClassCanonicalName
this is ValueResult && transitionInfo.result is ValueResult && this.value == transitionInfo.result.value ||
this is ExceptionResult && transitionInfo.result is ExceptionResult && this.tClassCanonicalName == transitionInfo.result.tClassCanonicalName

private inline fun <T> copyAndApply(
action: (
Expand All @@ -145,7 +146,7 @@ class LTS(private val sequentialSpecification: Class<*>) {
try {
seqToCreate.forEach { it.invoke(instance, suspendedOperations, resumedTicketsWithResults, continuationsMap) }
} catch (e: Exception) {
throw IllegalStateException(e)
throw IllegalStateException(e)
}
return action(instance, suspendedOperations, resumedTicketsWithResults, continuationsMap)
}
Expand Down Expand Up @@ -192,14 +193,15 @@ class LTS(private val sequentialSpecification: Class<*>) {
FOLLOW_UP -> {
val (cont, suspensionPointRes) = resumedOperations[ticket]!!.contWithSuspensionPointRes
val finalRes = (
if (cont == null) suspensionPointRes // Resumed operation has no follow-up.
else {
cont.resumeWith(suspensionPointRes)
resumedOperations[ticket]!!.contWithSuspensionPointRes.second
})
if (cont == null) suspensionPointRes // Resumed operation has no follow-up.
else {
cont.resumeWith(suspensionPointRes)
resumedOperations[ticket]!!.contWithSuspensionPointRes.second
})
resumedOperations.remove(ticket)
createLincheckResult(finalRes)
}

CANCELLATION -> {
continuationsMap[Operation(this.actor, this.ticket, REQUEST)]!!.cancelByLincheck(promptCancellation = actor.promptCancellation)
val wasSuspended = suspendedOperations.removeIf { it.actor == actor && it.ticket == ticket }
Expand Down Expand Up @@ -259,6 +261,7 @@ class LTS(private val sequentialSpecification: Class<*>) {
}

private fun createInitialStateInstance(): Any {
@Suppress("DEPRECATION")
return sequentialSpecification.newInstance().also {
// the sequential version of the data structure used for verification
// may differ from the original parallel version,
Expand Down Expand Up @@ -297,24 +300,24 @@ class LTS(private val sequentialSpecification: Class<*>) {

fun generateDotGraph(): String {
val builder = StringBuilder()
builder.appendln("digraph {")
builder.appendln("\"${initialState.hashCode()}\" [style=filled, fillcolor=green]")
builder.appendLine("digraph {")
builder.appendLine("\"${initialState.hashCode()}\" [style=filled, fillcolor=green]")
builder.appendTransitions(initialState, IdentityHashMap())
builder.appendln("}")
builder.appendLine("}")
return builder.toString()
}

private fun StringBuilder.appendTransitions(state: State, visitedStates: IdentityHashMap<State, Unit>) {
state.transitionsByRequests.forEach { actor, transition ->
appendln("${state.hashCode()} -> ${transition.nextState.hashCode()} [ label=\"<R,$actor:${transition.result},${transition.ticket}>, rf=${transition.rf?.contentToString()}\" ]")
appendLine("${state.hashCode()} -> ${transition.nextState.hashCode()} [ label=\"<R,$actor:${transition.result},${transition.ticket}>, rf=${transition.rf?.contentToString()}\" ]")
if (visitedStates.put(transition.nextState, Unit) === null) appendTransitions(transition.nextState, visitedStates)
}
state.transitionsByFollowUps.forEach { ticket, transition ->
appendln("${state.hashCode()} -> ${transition.nextState.hashCode()} [ label=\"<F,$ticket:${transition.result},${transition.ticket}>, rf=${transition.rf?.contentToString()}\" ]")
appendLine("${state.hashCode()} -> ${transition.nextState.hashCode()} [ label=\"<F,$ticket:${transition.result},${transition.ticket}>, rf=${transition.rf?.contentToString()}\" ]")
if (visitedStates.put(transition.nextState, Unit) === null) appendTransitions(transition.nextState, visitedStates)
}
state.transitionsByCancellations.forEach { ticket, transition ->
appendln("${state.hashCode()} -> ${transition.nextState.hashCode()} [ label=\"<C,$ticket:${transition.result},${transition.ticket}>, rf=${transition.rf?.contentToString()}\" ]")
appendLine("${state.hashCode()} -> ${transition.nextState.hashCode()} [ label=\"<C,$ticket:${transition.result},${transition.ticket}>, rf=${transition.rf?.contentToString()}\" ]")
if (visitedStates.put(transition.nextState, Unit) === null) appendTransitions(transition.nextState, visitedStates)
}
}
Expand Down Expand Up @@ -371,6 +374,7 @@ internal class VerifierInterceptor(
return Continuation(StoreExceptionHandler() + Job()) { res ->
// write the result only if the operation has not been cancelled
if (!res.cancelledByLincheck()) {
@Suppress("UNCHECKED_CAST")
resumedTicketsWithResults[ticket] = ResumedResult(continuation as Continuation<Any?> to res)
.also { it.resumedActor = actor }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ abstract class VerifierState {
*/
protected abstract fun extractState(): Any

@Suppress("DEPRECATION")
override fun equals(other: Any?) =
(other is VerifierState) && (this.state == other.state)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@ import kotlin.reflect.*

abstract class AbstractLincheckTest(
private vararg val expectedFailures: KClass<out LincheckFailure>
) : VerifierState() {
) {
open fun <O: Options<O, *>> O.customize() {}
override fun extractState(): Any = System.identityHashCode(this)

private fun <O : Options<O, *>> O.runInternalTest() {
val failure: LincheckFailure? = checkImpl(this@AbstractLincheckTest::class.java)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,9 @@ class FAAQueue<T> {
fun enqueue(x: T) {
while (true) {
var tail = tail.get()
val tNext = tail.next.get()
// if (tNext != null) { // помогаем переместить TODO: bug
// Commenting the code below leads to a bug.
// val tNext = tail.next.get()
// if (tNext != null) {
// this.tail.compareAndSet(tail, tNext)
// continue
// }
Expand Down Expand Up @@ -116,6 +117,7 @@ class FAAQueue<T> {
if (dequeIndex >= SEGMENT_SIZE) {
continue
}
@Suppress("UNCHECKED_CAST")
return head.elements.getAndSet(dequeIndex, DONE) as T? ?: continue;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,4 @@ class IncorrectOnCancellationTest : AbstractLincheckTest(IncorrectResultsFailure
}
return 0
}

override fun extractState(): Any = 0 // constant state
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,4 @@ public void offer(Integer x) {
public Integer poll() {
return queue.poll();
}

@NotNull
@Override
protected Object extractState() {
List<Integer> elements = new ArrayList<>();
while (true) {
Integer el = poll();
if (el == null) break;
elements.add(el);
}
return elements;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ class IncorrectPromptCancellationSequential {
}
}

@Suppress("UNUSED_PARAMETER")
fun resumeOp(mode: Int): Int {
val cont = cont ?: return -1
cont.resume(Unit)
Expand Down
Loading