Code cleanup

This commit is contained in:
Him188 2020-11-08 09:52:29 +08:00
parent 65a65ffb03
commit e5a7df46de
32 changed files with 76 additions and 111 deletions

View File

@ -7,7 +7,7 @@
* https://github.com/mamoe/mirai/blob/master/LICENSE
*/
@file:Suppress("FunctionName", "INVISIBLE_MEMBER", "INVISIBLE_REFERENCE", "PRE_RELEASE_CLASS")
@file:Suppress("FunctionName", "INVISIBLE_MEMBER", "INVISIBLE_REFERENCE", "PRE_RELEASE_CLASS", "unused")
package net.mamoe.mirai.console.codegen
@ -59,9 +59,9 @@ class CodegenScope : MutableList<Replacer> by mutableListOf() {
@CodegenDsl
operator fun Codegen.invoke(ktTypes: Collection<KtType>) {
add(Replacer {
it + buildString {
ktTypes.forEach { applyTo(this, it) }
add(Replacer { str ->
str + buildString {
ktTypes.forEach { ktType -> applyTo(this, ktType) }
}
})
}

View File

@ -26,10 +26,6 @@ internal fun <A> Array<A>.arrangements(): List<Pair<A, A>> {
return result
}
internal fun <A> Array<A>.distinctArrangements(): List<Pair<A, A>> {
return this.arrangements().distinctBy { it.first.toString().hashCode() + it.second.toString().hashCode() }
}
internal object MessageScopeCodegen {
object IterableMessageScopeBuildersCodegen : RegionCodegen("MessageScope.kt"), DefaultInvoke {
@JvmStatic
@ -181,7 +177,7 @@ internal object MessageScopeCodegen {
ReplaceWith(
"this.asMessageScope()(action)",
"net.mamoe.mirai.console.util.asMessageScope",
"net.mamoe.mirai.console.util.invoke"
"net.mamoe.mirai.console.util.invoke",
)
)
public inline fun <R> ${a}.scopeWith(action: MessageScope.() -> R): R = asMessageScope()(action)

View File

@ -20,7 +20,7 @@ open class JClazz(val primitiveName: String, val packageName: String) {
open val funName: String = "value"
}
class JListClazz(val item: JClazz) : JClazz("List<${item.packageName}>", "List<${item.packageName}>") {
class JListClazz(item: JClazz) : JClazz("List<${item.packageName}>", "List<${item.packageName}>") {
override val funName = item.primitiveName.toLowerCase() + "List"
}

View File

@ -57,6 +57,7 @@ import kotlin.internal.LowPriorityInOverloadResolution
""".trimIndent()
fun genAllValueUseSite(): String = buildString {
@Suppress("SpellCheckingInspection")
fun appendln(@Language("kt") code: String) {
this.appendLine(code.trimIndent())
}
@ -112,6 +113,7 @@ fun genAllValueUseSite(): String = buildString {
// SPECIAL
appendLine()
@Suppress("unused", "SpellCheckingInspection", "KDocUnresolvedReference")
appendln(
"""
fun <T : PluginData> PluginData.value(default: T): Value<T> {
@ -153,7 +155,7 @@ fun genAllValueUseSite(): String = buildString {
""${'"'}
这种只保存引用的 Value 可能会导致意料之外的结果, 在使用时须保持谨慎.
对值的改变不会触发自动保存, 也不会同步到 UI . UI 中只能编辑序列化之后的值.
""${'"'}, level = RequiresOptIn.Level.WARNING
""${'"'}, level = RequiresOptIn.Level.WARNING,
)
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.FUNCTION)

View File

@ -52,6 +52,7 @@ import kotlinx.serialization.builtins.*
import net.mamoe.mirai.console.data.*
""".trimIndent()
@Suppress("SpellCheckingInspection")
fun genAllValueImpl(): String = buildString {
fun appendln(@Language("kt") code: String) {
this.appendLine(code.trimIndent())
@ -118,6 +119,7 @@ fun genAllValueImpl(): String = buildString {
for (collectionName in listOf("List", "Set")) {
for (number in NUMBERS + OTHER_PRIMITIVES) {
@Suppress("unused")
appendln(
"""
@JvmName("valueImplMutable${number}${collectionName}")
@ -164,6 +166,7 @@ fun genAllValueImpl(): String = buildString {
appendLine()
@Suppress("unused")
appendln(
"""
internal fun <T : PluginData> PluginData.valueImpl(default: T): Value<T> {
@ -230,6 +233,7 @@ fun genPrimitiveValueImpl(
""".trimIndent() + "\n"
@Suppress("SpellCheckingInspection")
fun genCollectionValueImpl(
collectionName: String,
kotlinTypeName: String,

View File

@ -107,10 +107,8 @@ fun codegen(targetFile: String, block: CodegenScope.() -> Unit) {
println("Codegen target: ${it.absolutePath}")
}.apply {
writeText(
CodegenScope().apply(block).also { list ->
list.forEach {
println("Applying replacement: $it")
}
CodegenScope().apply(block).onEach {
println("Applying replacement: $it")
}.applyTo(readText())
)
}

View File

@ -7,9 +7,12 @@
* https://github.com/mamoe/mirai/blob/master/LICENSE
*/
@file:Suppress("unused")
package net.mamoe.mirai.console
import net.mamoe.mirai.console.util.SemVersion
import net.mamoe.mirai.utils.MiraiExperimentalAPI
/**
@ -38,6 +41,7 @@ public interface MiraiConsoleFrontEndDescription {
*
* 返回 `null` 表示禁止 [MiraiConsole] 后端检查版本兼容性.
*/
@MiraiExperimentalAPI
public val compatibleBackendVersion: SemVersion? get() = null
/**

View File

@ -170,4 +170,5 @@ internal inline fun <R> MiraiLogger.runCatchingLog(message: (Throwable) -> Strin
}.getOrNull()
}
@Suppress("SpellCheckingInspection")
private const val MAGIC_NUMBER_CFST_INIT: Long = Long.MAX_VALUE

View File

@ -11,11 +11,6 @@
package net.mamoe.mirai.console.internal.data
import kotlinx.serialization.InternalSerializationApi
import kotlinx.serialization.serializer
import net.mamoe.yamlkt.Yaml
import kotlin.reflect.KClass
// TODO: 2020/6/24 优化性能: 引入一个 comparator 之类来替代将 Int 包装为 Value<Int> 后进行 containsKey 比较的方法
@ -245,6 +240,8 @@ internal inline fun <E, R> MutableSet<E>.shadowMap(
}
}
/*
internal inline fun <T> dynamicList(crossinline supplier: () -> List<T>): List<T> {
return object : List<T> {
override val size: Int get() = supplier().size
@ -304,7 +301,6 @@ internal inline fun <T> dynamicMutableList(crossinline supplier: () -> MutableLi
}
}
internal inline fun <T> dynamicMutableSet(crossinline supplier: () -> MutableSet<T>): MutableSet<T> {
return object : MutableSet<T> {
override val size: Int get() = supplier().size
@ -322,7 +318,7 @@ internal inline fun <T> dynamicMutableSet(crossinline supplier: () -> MutableSet
override fun hashCode(): Int = supplier().hashCode()
}
}
*/
@Suppress("UNCHECKED_CAST", "USELESS_CAST") // type inference bug
internal inline fun <K, V> MutableMap<K, V>.observable(crossinline onChanged: () -> Unit): MutableMap<K, V> {
return object : MutableMap<K, V>, Map<K, V> by (this as Map<K, V>) {
@ -472,7 +468,7 @@ internal inline fun <T> MutableSet<T>.observable(crossinline onChanged: () -> Un
}
}
/*
@OptIn(InternalSerializationApi::class)
internal fun <R : Any> Any.smartCastPrimitive(clazz: KClass<R>): R {
kotlin.runCatching {
@ -482,3 +478,4 @@ internal fun <R : Any> Any.smartCastPrimitive(clazz: KClass<R>): R {
}
}
*/

View File

@ -7,6 +7,8 @@
* https://github.com/mamoe/mirai/blob/master/LICENSE
*/
@file:Suppress("unused")
package net.mamoe.mirai.console.internal.data
import net.mamoe.mirai.console.data.PluginData

View File

@ -7,6 +7,8 @@
* https://github.com/mamoe/mirai/blob/master/LICENSE
*/
@file:Suppress("unused")
package net.mamoe.mirai.console.internal.data
import kotlinx.serialization.ExperimentalSerializationApi

View File

@ -102,7 +102,7 @@ internal fun PluginData.valueFromKTypeImpl(type: KType): SerializerAwareValue<*>
}
}
internal fun KClass<*>.createInstanceSmart(): Any? {
internal fun KClass<*>.createInstanceSmart(): Any {
return when (this) {
Byte::class -> 0.toByte()
Short::class -> 0.toShort()

View File

@ -39,7 +39,7 @@ internal fun parseFromStringImpl(string: String): AbstractPermitteeId {
val arg = str.substring(1)
if (arg == "*") return AnyContact
}
'm' -> kotlin.run {
'm' -> run {
val arg = str.substring(1)
if (arg == "*") return AnyMemberFromAnyGroup
else {
@ -56,7 +56,7 @@ internal fun parseFromStringImpl(string: String): AbstractPermitteeId {
}
}
}
't' -> kotlin.run {
't' -> run {
val arg = str.substring(1)
if (arg == "*") return AnyTempFromAnyGroup
else {

View File

@ -7,6 +7,8 @@
* https://github.com/mamoe/mirai/blob/master/LICENSE
*/
@file:Suppress("unused")
package net.mamoe.mirai.console.internal.util
import net.mamoe.mirai.console.internal.data.cast
@ -18,7 +20,6 @@ import java.util.*
import kotlin.reflect.KClass
import java.lang.reflect.Member as JReflectionMember
@Suppress("unused")
internal class ServiceList<T>(
internal val classLoader: ClassLoader,
internal val delegate: List<String>
@ -38,8 +39,8 @@ internal object PluginServiceHelper {
return delegate.mapNotNull { classLoader.loadService<T>(it) }
}
fun <T : Any> ClassLoader.loadService(
classname: String
private fun <T : Any> ClassLoader.loadService(
classname: String,
): T? {
@Suppress("UNCHECKED_CAST")
return kotlin.runCatching {

View File

@ -31,19 +31,8 @@ public data class PermissionId(
@ResolveContext(PERMISSION_NAME) public val name: String,
) {
init {
require(namespace.none { it.isWhitespace() }) {
"' ' is not allowed in namespace"
}
require(name.none { it.isWhitespace() }) {
"' ' is not allowed in name"
}
require(!namespace.contains(':')) {
"':' is not allowed in namespace"
}
require(!name.contains(':')) {
"':' is not allowed in name"
}
checkPermissionIdName(name)
checkPermissionIdName(namespace)
}
public object PermissionIdAsStringSerializer : KSerializer<PermissionId> by String.serializer().map(
@ -79,7 +68,7 @@ public data class PermissionId(
public fun checkPermissionIdName(@ResolveContext(PERMISSION_NAME) name: String) {
when {
name.isBlank() -> throw IllegalArgumentException("PermissionId.name should not be blank.")
name.any { it.isWhitespace() } -> throw IllegalArgumentException("Spaces are not yet allowed in PermissionId.name.")
name.any(Char::isWhitespace) -> throw IllegalArgumentException("Spaces are not yet allowed in PermissionId.name.")
name.contains(':') -> throw IllegalArgumentException("':' is forbidden in PermissionId.name.")
}
}
@ -92,7 +81,7 @@ public data class PermissionId(
public fun checkPermissionIdNamespace(@ResolveContext(PERMISSION_NAME) namespace: String) {
when {
namespace.isBlank() -> throw IllegalArgumentException("PermissionId.namespace should not be blank.")
namespace.any { it.isWhitespace() } -> throw IllegalArgumentException("Spaces are not yet allowed in PermissionId.namespace.")
namespace.any(Char::isWhitespace) -> throw IllegalArgumentException("Spaces are not yet allowed in PermissionId.namespace.")
namespace.contains(':') -> throw IllegalArgumentException("':' is forbidden in PermissionId.namespace.")
}
}

View File

@ -76,6 +76,7 @@ import net.mamoe.mirai.console.util.ConsoleExperimentalApi
* }
* ```
*
* @see StandardExportManagers
*/
@ConsoleExperimentalApi
public interface ExportManager {

View File

@ -555,7 +555,7 @@ private class CombinedScope(
private class CommandSenderAsMessageScope(
private val sender: CommandSender,
) : MessageScope {
override val realTarget: Any?
override val realTarget: Any
get() = sender.user ?: sender // ConsoleCommandSender
override suspend fun sendMessage(message: Message) {
@ -570,7 +570,7 @@ private class CommandSenderAsMessageScope(
private class ContactAsMessageScope(
private val sender: Contact,
) : MessageScope {
override val realTarget: Any?
override val realTarget: Any
get() = sender
override suspend fun sendMessage(message: Message) {

View File

@ -7,6 +7,8 @@
* https://github.com/mamoe/mirai/blob/master/LICENSE
*/
@file:Suppress("unused")
package net.mamoe.mirai.console.util
import net.mamoe.mirai.message.data.MessageChain

View File

@ -7,7 +7,7 @@
* https://github.com/mamoe/mirai/blob/master/LICENSE
*/
@file:Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE", "RESULT_CLASS_IN_RETURN_TYPE")
@file:Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE", "RESULT_CLASS_IN_RETURN_TYPE", "unused")
@file:JvmMultifileClass
@file:JvmName("ConsoleUtils")

View File

@ -23,6 +23,7 @@ internal class PluginDataTest {
val map2: MutableMap<String, MutableMap<String, String>> by value()
}
@Suppress("unused")
private val jsonPrettyPrint = Json { prettyPrint = true }
private val json = Json {}

View File

@ -16,9 +16,6 @@ import org.gradle.api.tasks.TaskContainer
import org.gradle.api.tasks.bundling.Jar
import org.gradle.kotlin.dsl.*
import upload.Bintray
import java.io.InputStream
import java.io.OutputStream
import java.security.MessageDigest
import java.util.*
import kotlin.reflect.KProperty
@ -35,7 +32,7 @@ import kotlin.reflect.KProperty
* Configures the [bintray][com.jfrog.bintray.gradle.BintrayExtension] extension.
*/
@PublishedApi
internal fun org.gradle.api.Project.`bintray`(configure: com.jfrog.bintray.gradle.BintrayExtension.() -> Unit): Unit =
internal fun Project.`bintray`(configure: com.jfrog.bintray.gradle.BintrayExtension.() -> Unit): Unit =
(this as org.gradle.api.plugins.ExtensionAware).extensions.configure("bintray", configure)
@PublishedApi
@ -47,7 +44,7 @@ internal operator fun <U : Task> RegisteringDomainObjectDelegateProviderWithType
)
@PublishedApi
internal val org.gradle.api.Project.`sourceSets`: org.gradle.api.tasks.SourceSetContainer
internal val Project.`sourceSets`: org.gradle.api.tasks.SourceSetContainer
get() =
(this as org.gradle.api.plugins.ExtensionAware).extensions.getByName("sourceSets") as org.gradle.api.tasks.SourceSetContainer
@ -59,48 +56,10 @@ internal operator fun <T> ExistingDomainObjectDelegate<out T>.getValue(receiver:
* Configures the [publishing][org.gradle.api.publish.PublishingExtension] extension.
*/
@PublishedApi
internal fun org.gradle.api.Project.`publishing`(configure: org.gradle.api.publish.PublishingExtension.() -> Unit): Unit =
internal fun Project.`publishing`(configure: org.gradle.api.publish.PublishingExtension.() -> Unit): Unit =
(this as org.gradle.api.plugins.ExtensionAware).extensions.configure("publishing", configure)
fun InputStream.md5(): ByteArray {
val digest = MessageDigest.getInstance("md5")
digest.reset()
use { input ->
object : OutputStream() {
override fun write(b: Int) {
digest.update(b.toByte())
}
}.use { output ->
input.copyTo(output)
}
}
return digest.digest()
}
@OptIn(ExperimentalUnsignedTypes::class)
@JvmOverloads
fun ByteArray.toUHexString(
separator: String = " ",
offset: Int = 0,
length: Int = this.size - offset
): String {
if (length == 0) {
return ""
}
val lastIndex = offset + length
return buildString(length * 2) {
this@toUHexString.forEachIndexed { index, it ->
if (index in offset until lastIndex) {
var ret = it.toUByte().toString(16).toUpperCase()
if (ret.length == 1) ret = "0$ret"
append(ret)
if (index < lastIndex - 1) append(separator)
}
}
}
}
inline fun Project.setupPublishing(
artifactId: String,
bintrayRepo: String = "mirai",

View File

@ -1,11 +1,13 @@
/*
* Copyright 2019-2020 Mamoe Technologies and contributors.
*
* 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
* Use of this source code is governed by the GNU AFFERO GENERAL PUBLIC LICENSE version 3 license that can be found through the following link.
*
* https://github.com/mamoe/mirai/blob/master/LICENSE
*/
* Copyright 2019-2020 Mamoe Technologies and contributors.
*
* 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
* Use of this source code is governed by the GNU AFFERO GENERAL PUBLIC LICENSE version 3 license that can be found through the following link.
*
* https://github.com/mamoe/mirai/blob/master/LICENSE
*/
@file:Suppress("MemberVisibilityCanBePrivate")
object Versions {
const val core = "1.3.2"
@ -17,7 +19,6 @@ object Versions {
const val kotlinStdlib = "1.4.10"
const val coroutines = "1.3.9"
const val collectionsImmutable = "0.3.2"
const val serialization = "1.0.0-RC"
const val ktor = "1.4.1"
const val atomicFU = "0.14.4"

View File

@ -127,7 +127,7 @@ Mirai Console 内建 [`SimpleCommand`] 与 [`CompositeCommand`] 拥有 [`Command
object MySimpleCommand : SimpleCommand(
MyPluginMain, "tell", "私聊",
description = "Tell somebody privately",
usage = "/tell <target> <message>" // usage 如不设置则自动根据带有 @Handler 的方法生成
usage = "/tell <target> <message>", // usage 如不设置则自动根据带有 @Handler 的方法生成
) {
@Handler // 标记这是指令处理器 // 函数名随意
suspend fun CommandSender.handle(target: User, message: String) { // 这两个参数会被作为指令参数要求

View File

@ -43,7 +43,7 @@
- Java 中的「方法」在 Kotlin 中均被称为「函数」。
- Kotlin 默认的访问权限是 `public`。如 Kotlin `class Test` 相当于 Java 的 `public class Test {}`
- Kotlin 的函数定义 `fun test(int: Int): String` 相当于 Java 的方法定义 `public String test(int int)`
- Kotlin 的函数定义 `fun test(int: Int): String` 相当于 Java 的方法定义 `public String test(int integer)`
### 在 Java 使用 Mirai Console 中的 Kotlin `suspend` 函数

View File

@ -7,6 +7,8 @@
* https://github.com/mamoe/mirai/blob/master/LICENSE
*/
@file:Suppress("unused")
package net.mamoe.mirai.console.compiler.common.resolve
import net.mamoe.mirai.console.compiler.common.castOrNull
@ -70,7 +72,7 @@ enum class ResolveContextKind {
;
companion object {
fun valueOfOrNull(string: String): ResolveContextKind? = values().find { it.name == string }
fun valueOfOrNull(string: String) = values().find { it.name == string }
}
}

View File

@ -7,6 +7,8 @@
* https://github.com/mamoe/mirai/blob/master/LICENSE
*/
@file:Suppress("unused")
package net.mamoe.mirai.console.compiler.common
import org.jetbrains.kotlin.name.FqName

View File

@ -4,7 +4,7 @@ Mirai Console Gradle 插件。
## 使用
参考 [ConfiguringProjects](../../docs/ConfiguringProjects.md#gradle)[
参考 [ConfiguringProjects](../../docs/ConfiguringProjects.md)
## 功能
@ -34,7 +34,7 @@ mirai { // this: MiraiConsoleExtension
}
```
DSL 详见 [MiraiConsoleExtension](src/main/kotlin/net/mamoe/mirai/console/gradle/MiraiConsoleExtension.kt)。
DSL 详见 [MiraiConsoleExtension](src/MiraiConsoleExtension.kt)。
#### 排除依赖

View File

@ -23,6 +23,7 @@ class QuickFixRegistrar : QuickFixContributor {
quickFixes.register(this, *factory)
}
@Suppress("unused")
fun DiagnosticFactory<*>.registerActions(vararg action: IntentionAction) {
quickFixes.register(this, *action)
}

View File

@ -9,7 +9,7 @@
package net.mamoe.mirai.console.intellij.diagnostics
import net.mamoe.mirai.console.intellij.resolve.getResolvedCallOrResolveToCall
import net.mamoe.mirai.console.intellij.resolve.getResolvedCall
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.psi.KtElement
@ -22,8 +22,8 @@ fun DeclarationCheckerContext.report(diagnostic: Diagnostic) {
val DeclarationCheckerContext.bindingContext get() = this.trace.bindingContext
fun KtElement?.getResolvedCallOrResolveToCall(
fun KtElement?.getResolvedCall(
context: DeclarationCheckerContext,
): ResolvedCall<out CallableDescriptor>? {
return this.getResolvedCallOrResolveToCall(context.bindingContext)
return this.getResolvedCall(context.bindingContext)
}

View File

@ -41,7 +41,7 @@ class CommandDeclarationLineMarkerProvider : LineMarkerProvider {
null,
GutterIconRenderer.Alignment.RIGHT
) {
override fun createGutterRenderer(): GutterIconRenderer? {
override fun createGutterRenderer(): GutterIconRenderer {
return object : LineMarkerInfo.LineMarkerGutterIconRenderer<PsiElement>(this) {
override fun getClickAction(): AnAction? = null
}

View File

@ -52,7 +52,7 @@ class PluginMainLineMarkerProvider : LineMarkerProvider {
null,
GutterIconRenderer.Alignment.CENTER
) {
override fun createGutterRenderer(): GutterIconRenderer? {
override fun createGutterRenderer(): GutterIconRenderer {
return object : LineMarkerInfo.LineMarkerGutterIconRenderer<PsiElement>(this) {
override fun getClickAction(): AnAction? = null
}

View File

@ -88,7 +88,7 @@ fun KtAnnotated.hasAnnotation(fqName: FqName): Boolean =
fun KtDeclaration.resolveAllCalls(bindingContext: BindingContext): Sequence<ResolvedCall<*>> {
return allChildrenWithSelf
.filterIsInstance<KtCallExpression>()
.mapNotNull { it.calleeExpression?.getResolvedCallOrResolveToCall(bindingContext) }
.mapNotNull { it.calleeExpression?.getResolvedCall(bindingContext) }
}
fun KtDeclaration.resolveAllCallsWithElement(bindingContext: BindingContext): Sequence<Pair<ResolvedCall<out CallableDescriptor>, KtCallExpression>> {
@ -122,7 +122,7 @@ val PsiElement.allChildrenFlat: Sequence<PsiElement>
inline fun <reified E> PsiElement.findChild(): E? = this.children.find { it is E } as E?
fun KtElement?.getResolvedCallOrResolveToCall(
fun KtElement?.getResolvedCall(
context: BindingContext,
): ResolvedCall<out CallableDescriptor>? {
return this?.getCall(context)?.getResolvedCall(context)