User: joe Date: 20 Nov 26 17:16 Revision: 1a3346016a9eba14b618a26093b35aeed7419d68 Summary: Review round 1 TeamCity URL: http://ci.mcdev.io:80/viewModification.html?tab=vcsModificationFiles&modId=10815&personal=false Index: src/main/kotlin/platform/minecraft/unpick/UnpickAnnotator.kt =================================================================== --- src/main/kotlin/platform/minecraft/unpick/UnpickAnnotator.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/main/kotlin/platform/minecraft/unpick/UnpickAnnotator.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -28,6 +28,7 @@ import com.demonwav.mcdev.platform.minecraft.unpick.gen.psi.UnpickFlagsAttribute import com.demonwav.mcdev.platform.minecraft.unpick.gen.psi.UnpickFormatAttribute import com.demonwav.mcdev.platform.minecraft.unpick.gen.psi.UnpickFormatName +import com.demonwav.mcdev.platform.minecraft.unpick.gen.psi.UnpickGroupAttribute import com.demonwav.mcdev.platform.minecraft.unpick.gen.psi.UnpickGroupConstant import com.demonwav.mcdev.platform.minecraft.unpick.gen.psi.UnpickGroupDefinition import com.demonwav.mcdev.platform.minecraft.unpick.gen.psi.UnpickGroupName @@ -41,7 +42,6 @@ import com.demonwav.mcdev.platform.minecraft.unpick.gen.psi.UnpickTargetMethod import com.demonwav.mcdev.platform.minecraft.unpick.gen.psi.UnpickTypes import com.demonwav.mcdev.platform.minecraft.unpick.gen.psi.UnpickUnknownAttribute -import com.demonwav.mcdev.platform.minecraft.unpick.psi.mixins.UnpickHeaderMixin import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.Annotator import com.intellij.lang.annotation.HighlightSeverity @@ -58,6 +58,9 @@ class UnpickAnnotator : Annotator { override fun annotate(element: PsiElement, holder: AnnotationHolder) { + if (element is UnpickGroupAttribute) { + highlightAttributeName(element, holder) + } when (element) { is UnpickFile -> annotateFile(element, holder) is UnpickHeader -> annotateHeader(element, holder) @@ -91,7 +94,7 @@ } is UnpickTargetMethod -> annotateTargetMethod(element, holder) is UnpickMethodName -> { - element.highlight(holder, UnpickSyntaxHighlighter.METHOD_NAME) + holder.highlight(element, UnpickSyntaxHighlighter.METHOD_NAME) if (element.node.findChildByType(UnpickTypes.LT) != null) { val name = element.node.findChildByType(UnpickTypes.IDENTIFIER) if (name != null && name.text != "init" && name.text != "clinit") { @@ -105,43 +108,47 @@ holder.error(result.message, element) } } - is UnpickGroupName, is UnpickGroupRef -> element.highlight(holder, UnpickSyntaxHighlighter.GROUP_NAME) - is UnpickClassName, is UnpickPackageName -> element.highlight(holder, UnpickSyntaxHighlighter.CLASS_NAME) - is UnpickFieldName -> element.highlight(holder, UnpickSyntaxHighlighter.FIELD_NAME) + is UnpickGroupName, is UnpickGroupRef -> holder.highlight(element, UnpickSyntaxHighlighter.GROUP_NAME) + is UnpickClassName, is UnpickPackageName -> holder.highlight(element, UnpickSyntaxHighlighter.CLASS_NAME) + is UnpickFieldName -> holder.highlight(element, UnpickSyntaxHighlighter.FIELD_NAME) else -> when (element.elementType) { - UnpickTypes.KEYWORD -> element.highlight(holder, UnpickSyntaxHighlighter.KEYWORD) - UnpickTypes.METHOD_DESCRIPTOR -> UnpickDescriptors.validateMethod(element.text)?.let { - holder.error(it, element) + // Attribute names are highlighted with the attribute + UnpickTypes.KEYWORD -> if (element.parent !is UnpickGroupAttribute) { + holder.highlight(element, UnpickSyntaxHighlighter.KEYWORD) } - UnpickTypes.FIELD_DESCRIPTOR -> UnpickDescriptors.validateField(element.text)?.let { - holder.error(it, element) + UnpickTypes.METHOD_DESCRIPTOR -> if (!UnpickDescriptors.isValidMethod(element.text)) { + holder.error(MCDevBundle("minecraft.unpick.descriptor.invalid_method"), element) } + UnpickTypes.FIELD_DESCRIPTOR -> if (!UnpickDescriptors.isValidField(element.text)) { + holder.error(MCDevBundle("minecraft.unpick.descriptor.invalid_field"), element) - } - } - } + } + } + } + } private fun annotateFile(file: UnpickFile, holder: AnnotationHolder) { if (file.textLength == 0) { return } - val text = file.text + val text = file.viewProvider.contents val firstLineEnd = text.indexOfAny(charArrayOf('\r', '\n')).let { if (it == -1) text.length else it } - val firstLine = text.substring(0, firstLineEnd) + val firstLine = text.subSequence(0, firstLineEnd) val header = file.header if (header == null) { holder.newAnnotation(HighlightSeverity.ERROR, MCDevBundle("minecraft.unpick.annotator.missing_header")) - .range(TextRange(0, firstLine.length.coerceIn(1, file.textLength))) + .range(TextRange(0, firstLineEnd.coerceIn(1, file.textLength))) .create() return } // The reference implementation requires the first line to match exactly val version = header.version ?: return - if (version in UnpickHeaderMixin.SUPPORTED_VERSIONS && firstLine != "unpick v$version") { + val expectedFirstLine = "unpick v$version" + if (version in UnpickLanguage.SUPPORTED_VERSIONS && !firstLine.contentEquals(expectedFirstLine)) { holder.newAnnotation( HighlightSeverity.ERROR, - MCDevBundle("minecraft.unpick.annotator.malformed_header", "unpick v$version"), - ).range(TextRange(0, firstLine.length)).create() + MCDevBundle("minecraft.unpick.annotator.malformed_header", expectedFirstLine), + ).range(TextRange(0, firstLineEnd)).create() } } @@ -151,7 +158,7 @@ holder.error(MCDevBundle("minecraft.unpick.annotator.missing_version"), header.versionElement ?: header) return } - if (version !in UnpickHeaderMixin.SUPPORTED_VERSIONS) { + if (version !in UnpickLanguage.SUPPORTED_VERSIONS) { holder.newAnnotation( HighlightSeverity.WARNING, MCDevBundle("minecraft.unpick.annotator.unsupported_version", header.versionElement!!.text), @@ -159,13 +166,21 @@ } } + private fun highlightAttributeName(attribute: UnpickGroupAttribute, holder: AnnotationHolder) { + val name = attribute.node.findChildByType(UnpickTypes.KEYWORD) ?: return + holder.newSilentAnnotation(HighlightSeverity.INFORMATION) + .range(TextRange(attribute.textRange.startOffset, name.textRange.endOffset)) + .textAttributes(UnpickSyntaxHighlighter.ATTRIBUTE) + .create() + } + private fun annotateDataType(element: UnpickDataType, holder: AnnotationHolder) { val dataType = element.dataType if (dataType == null) { holder.error(MCDevBundle("minecraft.unpick.annotator.unknown_data_type", element.text), element) return } - element.highlight(holder, UnpickSyntaxHighlighter.KEYWORD) + holder.highlight(element, UnpickSyntaxHighlighter.DATA_TYPE) if (element.parent is UnpickGroupDefinition && !dataType.isValidGroupType) { holder.error(MCDevBundle("minecraft.unpick.annotator.invalid_group_data_type", element.text), element) } @@ -177,7 +192,7 @@ holder.error(MCDevBundle("minecraft.unpick.annotator.unknown_format", element.text), element) return } - element.highlight(holder, UnpickSyntaxHighlighter.KEYWORD) + holder.highlight(element, UnpickSyntaxHighlighter.FORMAT) val dataType = PsiTreeUtil.getParentOfType(element, UnpickGroupDefinition::class.java)?.dataType ?: return if (dataType.dataType?.isValidGroupType == true && !format.isApplicableTo(dataType.dataType!!)) { holder.error( @@ -241,7 +256,7 @@ newAnnotation(HighlightSeverity.ERROR, message).range(element).create() } - private fun PsiElement.highlight(holder: AnnotationHolder, key: TextAttributesKey) { - holder.newSilentAnnotation(HighlightSeverity.INFORMATION).range(this).textAttributes(key).create() + private fun AnnotationHolder.highlight(element: PsiElement, key: TextAttributesKey) { + newSilentAnnotation(HighlightSeverity.INFORMATION).range(element).textAttributes(key).create() } } Index: src/main/kotlin/platform/minecraft/unpick/UnpickColorSettingsPage.kt =================================================================== --- src/main/kotlin/platform/minecraft/unpick/UnpickColorSettingsPage.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/main/kotlin/platform/minecraft/unpick/UnpickColorSettingsPage.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -36,22 +36,22 @@ unpick v4 #: Colors in ARGB format - group int ARGBColor - @format hex + group int ARGBColor + @format hex net.minecraft.util.CommonColors.WHITE net.minecraft.util.CommonColors.BLACK # apply to floats in the default group globally - group float - @strict + group float + @strict net.minecraft.util.Mth.PI / 3 - group int - @scope class net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket - (int) net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket.MAX_PAYLOAD_SIZE:long + group int + @scope class net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket + (int) net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket.MAX_PAYLOAD_SIZE:long target_method net.minecraft.client.gui.GuiGraphics fill (IIIII)V - param 4 ARGBColor + param 4 ARGBColor target_field net.minecraft.core.particles.ColorParticleOption color I ARGBColor target_annotation net.minecraft.world.level.block.Block$UpdateFlags SetBlockFlag """.trimIndent() @@ -63,6 +63,10 @@ private object Const { val TAGS = mapOf( + "keyword" to UnpickSyntaxHighlighter.KEYWORD, + "attribute" to UnpickSyntaxHighlighter.ATTRIBUTE, + "type" to UnpickSyntaxHighlighter.DATA_TYPE, + "format" to UnpickSyntaxHighlighter.FORMAT, "group" to UnpickSyntaxHighlighter.GROUP_NAME, "class" to UnpickSyntaxHighlighter.CLASS_NAME, "field" to UnpickSyntaxHighlighter.FIELD_NAME, @@ -79,6 +83,14 @@ UnpickSyntaxHighlighter.ATTRIBUTE, ), AttributesDescriptor( + MCDevBundle.pointer("minecraft.unpick.color_settings.data_type"), + UnpickSyntaxHighlighter.DATA_TYPE, + ), + AttributesDescriptor( + MCDevBundle.pointer("minecraft.unpick.color_settings.format"), + UnpickSyntaxHighlighter.FORMAT, + ), + AttributesDescriptor( MCDevBundle.pointer("minecraft.unpick.color_settings.group_name"), UnpickSyntaxHighlighter.GROUP_NAME, ), Index: src/main/kotlin/platform/minecraft/unpick/UnpickCompletionContributor.kt =================================================================== --- src/main/kotlin/platform/minecraft/unpick/UnpickCompletionContributor.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/main/kotlin/platform/minecraft/unpick/UnpickCompletionContributor.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -24,6 +24,8 @@ import com.demonwav.mcdev.util.descriptor import com.demonwav.mcdev.util.findMethodsByInternalName import com.demonwav.mcdev.util.findQualifiedClass +import com.demonwav.mcdev.util.fullQualifiedName +import com.intellij.codeInsight.completion.AllClassesGetter import com.intellij.codeInsight.completion.CompletionContributor import com.intellij.codeInsight.completion.CompletionInitializationContext import com.intellij.codeInsight.completion.CompletionParameters @@ -31,9 +33,12 @@ import com.intellij.codeInsight.completion.CompletionType import com.intellij.codeInsight.completion.CompletionUtil import com.intellij.codeInsight.lookup.LookupElementBuilder +import com.intellij.psi.PsiClass +import com.intellij.psi.util.PsiUtil /** - * Completes keywords and descriptors. References (class, field, method and group names) complete themselves. + * Completes keywords, descriptors and fully qualified class names from their simple names. References (class, field, + * method and group names) complete themselves. * * The context is determined from the text of the current line rather than the PSI, which is unreliable in the * incomplete code being completed. @@ -50,7 +55,7 @@ return } val file = parameters.originalFile as? UnpickFile ?: return - val text = file.text + val text = file.viewProvider.contents val offset = parameters.offset.coerceAtMost(text.length) val lineStart = text.lastIndexOf('\n', offset - 1) + 1 val line = text.substring(lineStart, offset) @@ -59,68 +64,102 @@ } if (lineStart == 0) { - if (file.header == null && HEADER_PREFIX.matches(line)) { + if (file.header == null && Const.HEADER_PREFIX.matches(line)) { result.addElement(keyword("unpick v4")) } return } val wordResult = result.withPrefixMatcher(line.takeLastWhile { it.isLetterOrDigit() || it == '_' || it == '$' }) + val itemKeyword by lazy(LazyThreadSafetyMode.NONE) { currentItemKeyword(text, lineStart) } when { - ITEM_KEYWORD.matches(line) -> ITEM_KEYWORDS.forEach { wordResult.addElement(keyword(it)) } - GROUP_DATA_TYPE.matches(line) -> DataType.entries.filter { it.isValidGroupType } + Const.ITEM_KEYWORD.matches(line) -> Const.ITEM_KEYWORDS.forEach { wordResult.addElement(keyword(it)) } + Const.GROUP_DATA_TYPE.matches(line) -> DataType.entries.filter { it.isValidGroupType } .forEach { wordResult.addElement(keyword(it.keyword)) } - ATTRIBUTE.matches(line) -> ATTRIBUTES.forEach { wordResult.addElement(keyword(it)) } - SCOPE_KIND.matches(line) -> SCOPE_KINDS.forEach { wordResult.addElement(keyword(it)) } - FORMAT.matches(line) -> GroupFormat.entries.forEach { wordResult.addElement(keyword(it.keyword)) } - FIELD_SUFFIX.containsMatchIn(line) -> { + Const.ATTRIBUTE.matches(line) -> Const.ATTRIBUTES.forEach { wordResult.addElement(keyword(it)) } + Const.SCOPE_KIND.matches(line) -> Const.SCOPE_KINDS.forEach { wordResult.addElement(keyword(it)) } + Const.FORMAT.matches(line) -> GroupFormat.entries.forEach { wordResult.addElement(keyword(it.keyword)) } + Const.FIELD_SUFFIX.containsMatchIn(line) -> { wordResult.addElement(keyword("instance")) DataType.entries.forEach { wordResult.addElement(keyword(it.keyword)) } } - CAST.containsMatchIn(line) && currentItemKeyword(text, lineStart) == "group" -> + Const.CAST.containsMatchIn(line) && itemKeyword == "group" -> DataType.entries.filter { it.isPrimitive }.forEach { wordResult.addElement(keyword(it.keyword)) } - INDENTED_WORD.matches(line) && currentItemKeyword(text, lineStart) == "target_method" -> - TARGET_METHOD_ITEMS.forEach { wordResult.addElement(keyword(it)) } + Const.INDENTED_WORD.matches(line) && itemKeyword == "target_method" -> + Const.TARGET_METHOD_ITEMS.forEach { wordResult.addElement(keyword(it)) } else -> completeDescriptor(file, line, result) } + + val isClassNameStart = Const.ITEM_CLASS_NAME_START.matches(line) || + Const.SCOPE_CLASS_NAME_START.matches(line) || + Const.EXPRESSION_CLASS_NAME_START.matches(line) && itemKeyword == "group" + if (isClassNameStart) { + completeClassName(parameters, wordResult) - } + } + } private fun completeDescriptor(file: UnpickFile, line: String, result: CompletionResultSet) { - val methodMatch = TARGET_METHOD_DESCRIPTOR.matchEntire(line) ?: METHOD_SCOPE_DESCRIPTOR.matchEntire(line) + val methodMatch = Const.TARGET_METHOD_DESCRIPTOR.matchEntire(line) + ?: Const.METHOD_SCOPE_DESCRIPTOR.matchEntire(line) if (methodMatch != null) { val (className, methodName, typed) = methodMatch.destructured - val psiClass = findQualifiedClass(className.replace(Regex("\\s"), ""), file) ?: return + val psiClass = findQualifiedClass(className.replace(Const.WHITESPACE, ""), file) ?: return val descriptorResult = result.withPrefixMatcher(typed) - for (method in psiClass.findMethodsByInternalName(methodName.replace(Regex("\\s"), ""))) { + for (method in psiClass.findMethodsByInternalName(methodName.replace(Const.WHITESPACE, ""))) { method.descriptor?.let { descriptorResult.addElement(LookupElementBuilder.create(it)) } } return } - val fieldMatch = TARGET_FIELD_DESCRIPTOR.matchEntire(line) ?: return + val fieldMatch = Const.TARGET_FIELD_DESCRIPTOR.matchEntire(line) ?: return val (className, fieldName, typed) = fieldMatch.destructured - val psiClass = findQualifiedClass(className.replace(Regex("\\s"), ""), file) ?: return + val psiClass = findQualifiedClass(className.replace(Const.WHITESPACE, ""), file) ?: return val field = psiClass.findFieldByName(fieldName, true) ?: return field.descriptor?.let { result.withPrefixMatcher(typed).addElement(LookupElementBuilder.create(it)) } } /** + * Completes the simple name of a class to its fully qualified binary name. + */ + private fun completeClassName(parameters: CompletionParameters, result: CompletionResultSet) { + // Listing every class is too slow to do without a prefix unless explicitly requested + if (result.prefixMatcher.prefix.isEmpty() && parameters.invocationCount < 2) { + return + } + AllClassesGetter.processJavaClasses(parameters, result.prefixMatcher, parameters.invocationCount <= 1) { + psiClass -> + classLookup(psiClass)?.let(result::addElement) + } + } + + private fun classLookup(psiClass: PsiClass): LookupElementBuilder? { + val name = psiClass.name ?: return null + val binaryName = psiClass.fullQualifiedName ?: return null + val packageName = PsiUtil.getPackageName(psiClass) + return LookupElementBuilder.create(psiClass, binaryName) + .withLookupString(name) + .withPresentableText(name) + .withTailText(if (packageName.isNullOrEmpty()) null else " ($packageName)", true) + .withIcon(psiClass.getIcon(0)) + } + + /** * Finds the keyword of the item the line starting at [lineStart] belongs to. */ - private fun currentItemKeyword(text: String, lineStart: Int): String? { + private fun currentItemKeyword(text: CharSequence, lineStart: Int): String? { var start = lineStart while (start > 0) { start = text.lastIndexOf('\n', start - 2) + 1 val end = text.indexOf('\n', start).let { if (it == -1) text.length else it } - val line = text.substring(start, end) + val line = text.subSequence(start, end) if (line.isBlank() || line.trimStart().startsWith('#')) { continue } if (!line[0].isWhitespace()) { - return line.takeWhile { it.isLetterOrDigit() || it == '_' } + return line.takeWhile { it.isLetterOrDigit() || it == '_' }.toString() } } return null @@ -128,12 +167,13 @@ private fun keyword(text: String) = LookupElementBuilder.create(text).bold().withIcon(PlatformAssets.MINECRAFT_ICON) - private companion object { + private object Const { val ITEM_KEYWORDS = listOf("group", "target_method", "target_field", "target_annotation") val ATTRIBUTES = listOf("scope", "strict", "flags", "format") val SCOPE_KINDS = listOf("package", "class", "method") val TARGET_METHOD_ITEMS = listOf("param", "return") + val WHITESPACE = Regex("\\s") val HEADER_PREFIX = Regex("[a-z]*") val ITEM_KEYWORD = Regex("[a-z_]*") val GROUP_DATA_TYPE = Regex("group\\s+\\w*") @@ -144,6 +184,11 @@ val CAST = Regex("\\(\\s*\\w*$") val INDENTED_WORD = Regex("\\s+\\w*") + val ITEM_CLASS_NAME_START = Regex("target_(?:method|field|annotation)\\s+[\\w$]*") + val SCOPE_CLASS_NAME_START = Regex("\\s+@\\s*scope\\s+(?:class|method)\\s+[\\w$]*") + // The start of a line in a group, or after an operator or cast + val EXPRESSION_CLASS_NAME_START = Regex("(?:\\s+|.*[-+*/%&|^~()]\\s*)[\\w$]*") + private const val CLASS_NAME = "([\\w$]+(?:\\s*\\.\\s*[\\w$]+)*)" private const val METHOD_NAME = "([\\w$]+|<\\s*\\w+\\s*>)" val TARGET_METHOD_DESCRIPTOR = Regex("target_method\\s+$CLASS_NAME\\s+$METHOD_NAME\\s+(\\S*)") Index: src/main/kotlin/platform/minecraft/unpick/UnpickDescriptors.kt =================================================================== --- src/main/kotlin/platform/minecraft/unpick/UnpickDescriptors.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/main/kotlin/platform/minecraft/unpick/UnpickDescriptors.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -20,141 +20,16 @@ package com.demonwav.mcdev.platform.minecraft.unpick -import com.demonwav.mcdev.asset.MCDevBundle -import org.jetbrains.annotations.Nls - /** - * Validation and parsing of JVM descriptors appearing in unpick files. + * Validation of JVM descriptors appearing in unpick files. Valid descriptors can be parsed with ASM's + * [org.objectweb.asm.Type]. */ object UnpickDescriptors { + private const val FIELD_DESCRIPTOR = "\\[*(?:[BCDFIJSZ]|L[^.;\\[()]+;)" + private val FIELD_DESCRIPTOR_REGEX = Regex(FIELD_DESCRIPTOR) + private val METHOD_DESCRIPTOR_REGEX = Regex("\\((?:$FIELD_DESCRIPTOR)*\\)(?:V|$FIELD_DESCRIPTOR)") - data class MethodDescriptor(val parameters: List, val returnType: String) + fun isValidField(descriptor: String) = FIELD_DESCRIPTOR_REGEX.matches(descriptor) - /** - * Returns an error message if [descriptor] is not a valid field descriptor, otherwise `null`. - */ - @Nls - fun validateField(descriptor: String): String? { - val parser = Parser(descriptor) - parser.fieldDescriptor()?.let { return it } - if (!parser.atEnd) { - return MCDevBundle("minecraft.unpick.descriptor.trailing_characters") + fun isValidMethod(descriptor: String) = METHOD_DESCRIPTOR_REGEX.matches(descriptor) - } +} - return null - } - - /** - * Returns an error message if [descriptor] is not a valid method descriptor, otherwise `null`. - */ - @Nls - fun validateMethod(descriptor: String): String? { - if (!descriptor.startsWith('(')) { - return MCDevBundle("minecraft.unpick.descriptor.expected_method") - } - val parser = Parser(descriptor) - parser.pos++ - while (!parser.atEnd && parser.peek() != ')') { - parser.fieldDescriptor()?.let { return it } - } - if (parser.atEnd) { - return MCDevBundle("minecraft.unpick.descriptor.unexpected_end") - } - parser.pos++ - if (parser.atEnd) { - return MCDevBundle("minecraft.unpick.descriptor.unexpected_end") - } - if (parser.peek() == 'V') { - parser.pos++ - } else { - parser.fieldDescriptor()?.let { return it } - } - if (!parser.atEnd) { - return MCDevBundle("minecraft.unpick.descriptor.trailing_characters") - } - return null - } - - /** - * Splits a valid method descriptor into its parameter and return type descriptors. Returns `null` if the - * descriptor is invalid. - */ - fun parseMethod(descriptor: String): MethodDescriptor? { - if (validateMethod(descriptor) != null) { - return null - } - val parameters = mutableListOf() - val parser = Parser(descriptor) - parser.pos++ - while (parser.peek() != ')') { - val start = parser.pos - parser.fieldDescriptor() - parameters += descriptor.substring(start, parser.pos) - } - return MethodDescriptor(parameters, descriptor.substring(parser.pos + 1)) - } - - /** - * Converts a valid field descriptor, or `V`, to the name of the type as it would appear in Java source code. - */ - fun toJavaName(descriptor: String): String { - val dimensions = descriptor.takeWhile { it == '[' }.length - val element = when (val elementDesc = descriptor.substring(dimensions)) { - "B" -> "byte" - "C" -> "char" - "D" -> "double" - "F" -> "float" - "I" -> "int" - "J" -> "long" - "S" -> "short" - "Z" -> "boolean" - "V" -> "void" - else -> elementDesc.removePrefix("L").removeSuffix(";").replace('/', '.') - } - return element + "[]".repeat(dimensions) - } - - private class Parser(val text: String) { - var pos = 0 - - val atEnd: Boolean - get() = pos >= text.length - - fun peek() = text[pos] - - /** - * Skips over a field descriptor, returning an error message if it is invalid. - */ - @Nls - fun fieldDescriptor(): String? { - while (!atEnd && peek() == '[') { - pos++ - } - if (atEnd) { - return MCDevBundle("minecraft.unpick.descriptor.unexpected_end") - } - when (val c = peek()) { - 'B', 'C', 'D', 'F', 'I', 'J', 'S', 'Z' -> pos++ - 'L' -> { - pos++ - val start = pos - while (!atEnd && peek() != ';') { - val nameChar = peek() - if (nameChar == '.' || nameChar == '[' || nameChar == '(' || nameChar == ')') { - return MCDevBundle("minecraft.unpick.descriptor.illegal_character", nameChar) - } - pos++ - } - if (atEnd) { - return MCDevBundle("minecraft.unpick.descriptor.unexpected_end") - } - if (pos == start) { - return MCDevBundle("minecraft.unpick.descriptor.empty_class_name") - } - pos++ - } - else -> return MCDevBundle("minecraft.unpick.descriptor.illegal_character", c) - } - return null - } - } -} Index: src/main/kotlin/platform/minecraft/unpick/UnpickGroups.kt =================================================================== --- src/main/kotlin/platform/minecraft/unpick/UnpickGroups.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/main/kotlin/platform/minecraft/unpick/UnpickGroups.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -37,7 +37,7 @@ * Finds all definitions of the group with the given name, or of the default group if [name] is `null`. */ fun findDefinitions(context: PsiElement, name: String?): List { - return findFiles(context, name ?: UnpickGroupIndex.DEFAULT_GROUP_KEY).flatMap { file -> + return findFiles(context, name ?: UnpickGroupIndex.Util.DEFAULT_GROUP_KEY).flatMap { file -> file.groupDefinitions.filter { it.name == name } } } @@ -55,10 +55,10 @@ val index = FileBasedIndex.getInstance() val result = HashSet() index.processAllKeys( - UnpickGroupIndex.NAME, + UnpickGroupIndex.Util.NAME, { key -> - if (key != UnpickGroupIndex.DEFAULT_GROUP_KEY && key !in result) { - if (index.getContainingFiles(UnpickGroupIndex.NAME, key, scope).isNotEmpty()) { + if (key != UnpickGroupIndex.Util.DEFAULT_GROUP_KEY && key !in result) { + if (index.getContainingFiles(UnpickGroupIndex.Util.NAME, key, scope).isNotEmpty()) { result += key } } @@ -78,7 +78,8 @@ return listOfNotNull(ownFile) } val psiManager = PsiManager.getInstance(project) - val files = FileBasedIndex.getInstance().getContainingFiles(UnpickGroupIndex.NAME, key, searchScope(context)) + val files = FileBasedIndex.getInstance() + .getContainingFiles(UnpickGroupIndex.Util.NAME, key, searchScope(context)) val result = files.mapNotNull { psiManager.findFile(it) as? UnpickFile }.toMutableList() if (ownFile != null && ownFile !in result) { result += ownFile Index: src/main/kotlin/platform/minecraft/unpick/UnpickInnerClassReferencesSearcher.kt =================================================================== --- src/main/kotlin/platform/minecraft/unpick/UnpickInnerClassReferencesSearcher.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) +++ src/main/kotlin/platform/minecraft/unpick/UnpickInnerClassReferencesSearcher.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -0,0 +1,82 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.platform.minecraft.unpick + +import com.demonwav.mcdev.platform.minecraft.unpick.gen.psi.UnpickClassName +import com.intellij.openapi.application.QueryExecutorBase +import com.intellij.psi.PsiClass +import com.intellij.psi.PsiElement +import com.intellij.psi.PsiReference +import com.intellij.psi.search.GlobalSearchScope +import com.intellij.psi.search.RequestResultProcessor +import com.intellij.psi.search.UsageSearchContext +import com.intellij.psi.search.searches.ReferencesSearch +import com.intellij.psi.util.PsiUtil +import com.intellij.psi.util.parentOfType +import com.intellij.util.Processor + +/** + * Finds references to nested classes in unpick files. Class names in unpick files are binary names such as + * `Outer$Inner`, in which the default search doesn't find the name of the nested class as a separate word. Instead, + * this searches for the name of the top level class, which is followed by a `$`. + */ +class UnpickInnerClassReferencesSearcher : + QueryExecutorBase(true) { + + override fun processQuery(params: ReferencesSearch.SearchParameters, consumer: Processor) { + val target = params.elementToSearch as? PsiClass ?: return + val topLevelClass = PsiUtil.getTopLevelClass(target) ?: return + if (topLevelClass == target) { + return + } + val topLevelName = topLevelClass.name ?: return + + val scope = params.effectiveSearchScope.let { scope -> + if (scope is GlobalSearchScope) { + GlobalSearchScope.getScopeRestrictedByFileTypes(scope, UnpickFileType) + } else { + scope + } + } + params.optimizer.searchWord( + topLevelName, + scope, + UsageSearchContext.IN_CODE, + true, + target, + object : RequestResultProcessor() { + override fun processTextOccurrence( + element: PsiElement, + offsetInElement: Int, + consumer: Processor, + ): Boolean { + val className = element.parentOfType(withSelf = true) ?: return true + for (reference in className.references) { + if (reference.isReferenceTo(target) && !consumer.process(reference)) { + return false + } + } + return true + } + }, + ) + } +} Index: src/main/kotlin/platform/minecraft/unpick/UnpickLanguage.kt =================================================================== --- src/main/kotlin/platform/minecraft/unpick/UnpickLanguage.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/main/kotlin/platform/minecraft/unpick/UnpickLanguage.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -24,6 +24,11 @@ import java.io.Serial object UnpickLanguage : Language("Unpick") { + /** + * The versions of the unpick format that are supported. The lexer must be kept in sync with this. + */ + val SUPPORTED_VERSIONS = 3..4 + @Serial private fun readResolve(): Any = UnpickLanguage } Index: src/main/kotlin/platform/minecraft/unpick/UnpickLiterals.kt =================================================================== --- src/main/kotlin/platform/minecraft/unpick/UnpickLiterals.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/main/kotlin/platform/minecraft/unpick/UnpickLiterals.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -22,6 +22,7 @@ import com.demonwav.mcdev.asset.MCDevBundle import com.demonwav.mcdev.platform.minecraft.unpick.gen.psi.UnpickTypes +import com.intellij.codeInsight.CodeInsightUtilCore import com.intellij.psi.tree.IElementType import org.jetbrains.annotations.Nls @@ -164,50 +165,9 @@ */ private fun unquote(text: String): String? { val result = StringBuilder(text.length - 2) - var i = 1 - val end = text.length - 1 - while (i < end) { - val c = text[i] - if (c != '\\') { - result.append(c) - i++ - continue - } - i++ - if (i >= end) { + if (!CodeInsightUtilCore.parseStringCharacters(text.substring(1, text.length - 1), result, null)) { - return null - } + return null + } - when (val escape = text[i]) { - 'b' -> result.append('\b') - 't' -> result.append('\t') - 'n' -> result.append('\n') - 'f' -> result.append('\u000c') - 'r' -> result.append('\r') - '"', '\'', '\\' -> result.append(escape) - 'u' -> { - while (i < end && text[i] == 'u') { - i++ - } - if (i + 4 > end) { - return null - } - val code = text.substring(i, i + 4).toIntOrNull(16) ?: return null - result.append(code.toChar()) - i += 3 - } - in '0'..'7' -> { - val maxCount = if (escape <= '3') 3 else 2 - var count = 0 - while (count < maxCount && i + count < end && text[i + count] in '0'..'7') { - count++ - } - result.append(text.substring(i, i + count).toInt(8).toChar()) - i += count - 1 - } - else -> return null - } - i++ - } return result.toString() } } Index: src/main/kotlin/platform/minecraft/unpick/UnpickSyntaxHighlighter.kt =================================================================== --- src/main/kotlin/platform/minecraft/unpick/UnpickSyntaxHighlighter.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/main/kotlin/platform/minecraft/unpick/UnpickSyntaxHighlighter.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -22,6 +22,7 @@ import com.demonwav.mcdev.platform.minecraft.unpick.UnpickParserDefinition.TokenSets import com.demonwav.mcdev.platform.minecraft.unpick.gen.psi.UnpickTypes +import com.intellij.ide.highlighter.JavaHighlightingColors import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.HighlighterColors import com.intellij.openapi.editor.colors.TextAttributesKey @@ -58,7 +59,10 @@ val STRING = TextAttributesKey.createTextAttributesKey("UNPICK_STRING", DefaultLanguageHighlighterColors.STRING) val DESCRIPTOR = - TextAttributesKey.createTextAttributesKey("UNPICK_DESCRIPTOR", DefaultLanguageHighlighterColors.STRING) + TextAttributesKey.createTextAttributesKey( + "UNPICK_DESCRIPTOR", + DefaultLanguageHighlighterColors.STATIC_METHOD, + ) val OPERATOR = TextAttributesKey.createTextAttributesKey( "UNPICK_OPERATOR", @@ -89,8 +93,12 @@ TextAttributesKey.createTextAttributesKey("UNPICK_BAD_CHARACTER", HighlighterColors.BAD_CHARACTER) // Only applied by the annotator + val DATA_TYPE = + TextAttributesKey.createTextAttributesKey("UNPICK_DATA_TYPE", DefaultLanguageHighlighterColors.KEYWORD) + val FORMAT = + TextAttributesKey.createTextAttributesKey("UNPICK_FORMAT", DefaultLanguageHighlighterColors.CONSTANT) val GROUP_NAME = - TextAttributesKey.createTextAttributesKey("UNPICK_GROUP_NAME", DefaultLanguageHighlighterColors.CONSTANT) + TextAttributesKey.createTextAttributesKey("UNPICK_GROUP_NAME", JavaHighlightingColors.ENUM_NAME_ATTRIBUTES) val CLASS_NAME = TextAttributesKey.createTextAttributesKey( "UNPICK_CLASS_NAME", @@ -104,7 +112,7 @@ val METHOD_NAME = TextAttributesKey.createTextAttributesKey( "UNPICK_METHOD_NAME", - DefaultLanguageHighlighterColors.STATIC_METHOD, + DefaultLanguageHighlighterColors.FUNCTION_CALL, ) private val KEYWORD_KEYS = arrayOf(KEYWORD) Index: src/main/kotlin/platform/minecraft/unpick/eval/UnpickExpressionEvaluator.kt =================================================================== --- src/main/kotlin/platform/minecraft/unpick/eval/UnpickExpressionEvaluator.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/main/kotlin/platform/minecraft/unpick/eval/UnpickExpressionEvaluator.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -43,6 +43,7 @@ import com.intellij.psi.PsiModifier import com.intellij.psi.PsiPrimitiveType import com.intellij.psi.PsiReferenceExpression +import com.intellij.psi.PsiType import com.intellij.psi.PsiTypes import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager @@ -137,16 +138,93 @@ return@filter false } val fieldType = DataType.fromPsiType(field.type) ?: return@filter false - if (explicitType != null) { + val typeMatches = if (explicitType != null) { fieldType == explicitType } else { groupType != null && fieldType.canWidenTo(groupType) } + typeMatches && constantValue(field, fieldType) != null } } - private const val MAX_CLASS_FIELD_DEPTH = 8 + /** + * Returns the value of a constant field of the given type, or `null` if the field isn't a constant. A constant + * field is final and initialized to a compile-time constant (JLS 15.29), `null`, a class literal or another + * constant field. + * + * If the field is compiled and has no source, `null` and `Class` constants can't be distinguished from + * non-constant fields, so an unknown value is returned for them. + */ + fun constantValue(field: PsiField, type: DataType): UnpickValue? = constantValue(field, type, 0) + private fun constantValue(field: PsiField, type: DataType, depth: Int): UnpickValue? { + if (!field.hasModifierProperty(PsiModifier.FINAL)) { + return null + } + if (type.isPrimitive) { + val value = field.computeConstantValue() + val valueType = when (value) { + is Byte -> DataType.BYTE + is Short -> DataType.SHORT + is Char -> DataType.CHAR + is Int -> DataType.INT + is Long -> DataType.LONG + is Float -> DataType.FLOAT + is Double -> DataType.DOUBLE + else -> return null + } + return UnpickValue(valueType, value).convertTo(type) + } + if (type == DataType.STRING) { + (field.computeConstantValue() as? String)?.let { return UnpickValue(DataType.STRING, it) } + } else { + primitiveClassConstant(field)?.let { return UnpickValue(DataType.CLASS, it) } + } + + val sourceField = field.navigationElement as? PsiField ?: field + if (sourceField is PsiCompiledElement) { + return UnpickValue.unknown(type) + } + return when (val initializer = PsiUtil.skipParenthesizedExprDown(sourceField.initializer)) { + is PsiLiteralExpression -> if (initializer.firstChild.elementType == JavaTokenType.NULL_KEYWORD) { + UnpickValue(type, null) + } else { + null + } + is PsiClassObjectAccessExpression -> if (type == DataType.CLASS) { + UnpickValue(DataType.CLASS, initializer.operand.type) + } else { + null + } + is PsiReferenceExpression -> { + val referenced = initializer.resolve() as? PsiField + if (referenced != null && depth < MAX_FIELD_DEPTH && DataType.fromPsiType(referenced.type) == type) { + constantValue(referenced, type, depth + 1) + } else { + null + } + } + else -> null + } + } + + /** + * The `TYPE` fields of the boxed types are the class objects of the primitive types. + */ + private fun primitiveClassConstant(field: PsiField): PsiType? { + val containingClass = field.containingClass ?: return null + if (field.name != "TYPE") { + return null + } + if (containingClass.qualifiedName == CommonClassNames.JAVA_LANG_VOID) { + return PsiTypes.voidType() + } + val boxedType = JavaPsiFacade.getElementFactory(field.project).createType(containingClass) + return PsiPrimitiveType.getUnboxedType(boxedType) + } + + private const val MAX_FIELD_DEPTH = 8 + private class Evaluation( private val groupType: DataType?, private val wildcardField: PsiField?, @@ -220,18 +298,16 @@ if (operand == null) { return null } - if (!target.isPrimitive || !operand.type.isPrimitive) { - if (target != operand.type) { + if (!operand.canConvertTo(target)) { - typeProblem(expression, "minecraft.unpick.eval.bad_cast", operand.type.keyword, target.keyword) - return null - } + typeProblem(expression, "minecraft.unpick.eval.bad_cast", operand.type.keyword, target.keyword) + return null + } - } return operand.convertTo(target) } private fun evaluateBinary(expression: UnpickBinaryExpressionMixin): UnpickValue? { - val left = evaluate(expression.getLeft()) - val right = evaluate(expression.getRight()) + val left = evaluate(expression.left) + val right = evaluate(expression.right) if (left == null || right == null) { return null } @@ -272,8 +348,7 @@ return UnpickValue.unknown(resultType) } val distance = right.asLong().toInt() - val value = left.convertTo(resultType).value - return when (value) { + return when (val value = left.convertTo(resultType).value) { is Int -> UnpickValue( DataType.INT, when (operator) { @@ -305,7 +380,7 @@ right.asLong() == 0L ) { problems += UnpickProblem.DivisionByZero( - expression.getRight() ?: expression, + expression.right ?: expression, MCDevBundle("minecraft.unpick.eval.division_by_zero"), ) return UnpickValue.unknown(resultType) @@ -387,82 +462,18 @@ ) } - return when (fieldType) { - DataType.CLASS -> evaluateClassField(field) - DataType.STRING -> { - val value = field.computeConstantValue() - when { - value is String -> UnpickValue(DataType.STRING, value) - isNullInitializer(field) -> UnpickValue(DataType.STRING, null) - // Compiled fields initialized to null have no constant value to tell us that - field is PsiCompiledElement -> UnpickValue.unknown(DataType.STRING) - else -> { + val value = constantValue(field, fieldType) + if (value == null) { - fieldProblem(nameElement, "minecraft.unpick.eval.field_not_constant", name) + fieldProblem(nameElement, "minecraft.unpick.eval.field_not_constant", name) - UnpickValue.unknown(DataType.STRING) + return UnpickValue.unknown(fieldType) - } + } + // A wildcard without an explicit data type has the data type of the group + if (expression.isWildcard && explicitType == null && groupType != null && value.canConvertTo(groupType)) { + return value.convertTo(groupType) - } + } + return value - } + } - else -> { - val value = field.computeConstantValue() - val valueType = when (value) { - is Byte -> DataType.BYTE - is Short -> DataType.SHORT - is Char -> DataType.CHAR - is Int -> DataType.INT - is Long -> DataType.LONG - is Float -> DataType.FLOAT - is Double -> DataType.DOUBLE - else -> null - } - if (valueType != null) { - UnpickValue(valueType, value).convertTo(fieldType) - } else { - fieldProblem(nameElement, "minecraft.unpick.eval.field_not_constant", name) - UnpickValue.unknown(fieldType) - } - } - } - } - private fun isNullInitializer(field: PsiField): Boolean { - val initializer = PsiUtil.skipParenthesizedExprDown(field.initializer) - return initializer is PsiLiteralExpression && - initializer.firstChild.elementType == JavaTokenType.NULL_KEYWORD - } - - private fun evaluateClassField(field: PsiField, depth: Int = 0): UnpickValue { - // The TYPE fields of the boxed types are the class objects of the primitive types - val containingClass = field.containingClass - if (field.name == "TYPE" && containingClass != null) { - if (containingClass.qualifiedName == CommonClassNames.JAVA_LANG_VOID) { - return UnpickValue(DataType.CLASS, PsiTypes.voidType()) - } - val boxedType = JavaPsiFacade.getElementFactory(field.project).createType(containingClass) - PsiPrimitiveType.getUnboxedType(boxedType)?.let { return UnpickValue(DataType.CLASS, it) } - } - return when (val initializer = PsiUtil.skipParenthesizedExprDown(field.initializer)) { - is PsiClassObjectAccessExpression -> UnpickValue(DataType.CLASS, initializer.operand.type) - // Follow references to other class constants, such as Integer.TYPE - is PsiReferenceExpression -> { - val referenced = initializer.resolve() as? PsiField - if (referenced != null && depth < MAX_CLASS_FIELD_DEPTH && - DataType.fromPsiType(referenced.type) == DataType.CLASS - ) { - evaluateClassField(referenced, depth + 1).takeUnless { it.value is PsiField } - ?: UnpickValue(DataType.CLASS, field) - } else { - UnpickValue(DataType.CLASS, field) - } - } - is PsiLiteralExpression -> if (isNullInitializer(field)) { - UnpickValue(DataType.CLASS, null) - } else { - UnpickValue(DataType.CLASS, field) - } - else -> UnpickValue(DataType.CLASS, field) - } - } - private fun unaryPromote(type: DataType): DataType { return when (type) { DataType.BYTE, DataType.SHORT, DataType.CHAR -> DataType.INT Index: src/main/kotlin/platform/minecraft/unpick/eval/UnpickValue.kt =================================================================== --- src/main/kotlin/platform/minecraft/unpick/eval/UnpickValue.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/main/kotlin/platform/minecraft/unpick/eval/UnpickValue.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -21,24 +21,42 @@ package com.demonwav.mcdev.platform.minecraft.unpick.eval import com.demonwav.mcdev.platform.minecraft.unpick.DataType -import com.intellij.psi.PsiField +import com.demonwav.mcdev.util.ClassNameResolutionFailedException +import com.demonwav.mcdev.util.descriptor +import com.demonwav.mcdev.util.fullQualifiedName +import com.intellij.psi.PsiArrayType +import com.intellij.psi.PsiClassType +import com.intellij.psi.PsiPrimitiveType import com.intellij.psi.PsiType /** * The result of evaluating an unpick expression. * * The [value] is represented as a Kotlin [Byte], [Short], [Char], [Int], [Long], [Float], [Double] or [String] for the - * corresponding data types, or `null` for a `null` `String` or `Class` constant. A `Class` constant is represented by - * the [PsiType] it refers to if that can be determined, or otherwise by the [PsiField] it was read from. + * corresponding data types, as the [PsiType] referred to by a `Class` constant, or as `null` for a `null` `String` or + * `Class` constant. * * If [isKnown] is false then only the type of the expression is known, not its value. */ -class UnpickValue(val type: DataType, val value: Any?, val isKnown: Boolean = true) { +data class UnpickValue(val type: DataType, val value: Any?, val isKnown: Boolean = true) { + /** + * Whether this value can be converted to [target] by [convertTo]. + */ + fun canConvertTo(target: DataType) = target == type || type.isPrimitive && target.isPrimitive + + /** + * Converts this value to [target], as a Java cast would. Throws an [IllegalArgumentException] if the value cannot + * be converted, which can be checked with [canConvertTo]. + */ fun convertTo(target: DataType): UnpickValue { - if (target == type || !isKnown || !type.isPrimitive || !target.isPrimitive) { - return UnpickValue(target, value, isKnown) + require(canConvertTo(target)) { "Cannot convert $type to $target" } + if (target == type) { + return this } + if (!isKnown) { + return unknown(target) + } return UnpickValue(target, convert(value!!, target)) } @@ -48,14 +66,9 @@ else -> throw IllegalStateException("Not an integral value: $value") } - fun asDouble(): Double = when (value) { - is Char -> value.code.toDouble() - is Number -> value.toDouble() - else -> throw IllegalStateException("Not a numeric value: $value") - } - /** - * Converts the value to a string the same way Java string concatenation would. + * Converts the value to a string the same way Java string concatenation would, or returns `null` if that can't be + * determined. */ fun toJavaString(): String? { if (!isKnown) { @@ -66,6 +79,7 @@ is String -> value is Char -> value.toString() is Number -> value.toString() + is PsiType -> classToString(value) else -> null } } @@ -81,22 +95,40 @@ is Long -> "${value}L" is Float -> "${value}f" is PsiType -> value.presentableText + ".class" - is PsiField -> value.containingClass?.name + "." + value.name else -> value.toString() } } - override fun equals(other: Any?): Boolean { - return other is UnpickValue && other.isKnown && isKnown && other.type == type && other.value == value - } - - override fun hashCode() = 31 * type.hashCode() + value.hashCode() - - override fun toString() = "UnpickValue(type=$type, value=$value, isKnown=$isKnown)" - companion object { fun unknown(type: DataType) = UnpickValue(type, null, isKnown = false) + /** + * Returns the result of calling `toString()` on the `Class` object for [type], or `null` if it can't be + * determined. + */ + private fun classToString(type: PsiType): String? { + return try { + when (type) { + is PsiPrimitiveType -> type.name + is PsiArrayType -> if ((type.deepComponentType as? PsiClassType)?.resolve() == null && + type.deepComponentType !is PsiPrimitiveType + ) { + null + } else { + "class " + type.descriptor.replace('/', '.') + } + is PsiClassType -> { + val psiClass = type.resolve() ?: return null + val name = psiClass.fullQualifiedName ?: return null + if (psiClass.isInterface) "interface $name" else "class $name" + } + else -> null + } + } catch (_: ClassNameResolutionFailedException) { + null + } + } + private fun convert(value: Any, target: DataType): Any { if (value is Float || value is Double) { val d = (value as Number).toDouble() Index: src/main/kotlin/platform/minecraft/unpick/index/UnpickGroupIndex.kt =================================================================== --- src/main/kotlin/platform/minecraft/unpick/index/UnpickGroupIndex.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/main/kotlin/platform/minecraft/unpick/index/UnpickGroupIndex.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -35,7 +35,7 @@ * Indexes the names of the groups defined in each unpick file. The default group is indexed under the empty string. */ class UnpickGroupIndex : ScalarIndexExtension() { - override fun getName() = NAME + override fun getName() = Util.NAME override fun getVersion() = 1 @@ -50,11 +50,11 @@ private object Indexer : DataIndexer { override fun map(inputData: FileContent): Map { val file = inputData.psiFile as? UnpickFile ?: return emptyMap() - return file.groupDefinitions.associate { (it.name ?: DEFAULT_GROUP_KEY) to null } + return file.groupDefinitions.associate { (it.name ?: Util.DEFAULT_GROUP_KEY) to null } } } - companion object { + object Util { val NAME = ID.create("mcdev.UnpickGroupIndex") const val DEFAULT_GROUP_KEY = "" Index: src/main/kotlin/platform/minecraft/unpick/inspections/DuplicateUnpickConstantInspection.kt =================================================================== --- src/main/kotlin/platform/minecraft/unpick/inspections/DuplicateUnpickConstantInspection.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/main/kotlin/platform/minecraft/unpick/inspections/DuplicateUnpickConstantInspection.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -25,12 +25,14 @@ import com.demonwav.mcdev.platform.minecraft.unpick.eval.UnpickExpressionEvaluator import com.demonwav.mcdev.platform.minecraft.unpick.eval.UnpickExpressionEvaluator.EvaluatedConstant import com.demonwav.mcdev.platform.minecraft.unpick.eval.UnpickValue +import com.demonwav.mcdev.platform.minecraft.unpick.gen.psi.UnpickFieldExpression import com.demonwav.mcdev.platform.minecraft.unpick.gen.psi.UnpickGroupDefinition import com.demonwav.mcdev.platform.minecraft.unpick.gen.psi.UnpickVisitor import com.demonwav.mcdev.util.equivalentTo import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor +import com.intellij.psi.util.PsiTreeUtil class DuplicateUnpickConstantInspection : LocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = @@ -67,22 +69,21 @@ } val value = evaluated.value.convertTo(groupType) val other = byValue[value]?.firstOrNull { !it.isSameAs(evaluated) } ?: continue - val description = describe(evaluated) - val otherDescription = describeOther(other) + val wildcardField = evaluated.wildcardField holder.registerProblem( constant, - if (description == null) { + if (wildcardField == null) { MCDevBundle( "inspection.duplicate_unpick_constant.message", value.toDisplayString(), - otherDescription, + other.expandedText(), ) } else { MCDevBundle( "inspection.duplicate_unpick_constant.wildcard_message", - description, value.toDisplayString(), - otherDescription, + "${wildcardField.containingClass?.name}.${wildcardField.name}", + other.expandedText(), ) }, ) @@ -95,15 +96,16 @@ } /** - * Describes the field a wildcard was expanded to, or returns `null` if this isn't a wildcard constant. + * Returns the text of the constant, with the wildcard replaced by the field it was expanded to. */ - private fun describe(constant: EvaluatedConstant): String? { - val field = constant.wildcardField ?: return null - return "${field.containingClass?.name}.${field.name}" + private fun EvaluatedConstant.expandedText(): String { + val field = wildcardField ?: return constant.text + val wildcard = PsiTreeUtil.findChildrenOfType(constant, UnpickFieldExpression::class.java) + .firstNotNullOfOrNull { it.wildcardElement } + ?: return constant.text + return wildcard.textRange.shiftLeft(constant.textRange.startOffset).replace(constant.text, field.name) } - private fun describeOther(constant: EvaluatedConstant) = describe(constant) ?: constant.constant.text - private fun scopeKey(definition: UnpickGroupDefinition): Set { return definition.scopes.mapTo(HashSet()) { scope -> scope.text.split(Regex("\\s+")).joinToString(" ") } } Index: src/main/kotlin/platform/minecraft/unpick/inspections/UnpickTargetMismatchInspection.kt =================================================================== --- src/main/kotlin/platform/minecraft/unpick/inspections/UnpickTargetMismatchInspection.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/main/kotlin/platform/minecraft/unpick/inspections/UnpickTargetMismatchInspection.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -33,34 +33,36 @@ import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor +import org.objectweb.asm.Type class UnpickTargetMismatchInspection : LocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = object : UnpickVisitor() { override fun visitTargetMethod(element: UnpickTargetMethod) { - val descriptor = element.methodDescriptor?.text ?: return - val parsed = UnpickDescriptors.parseMethod(descriptor) ?: return + val descriptor = element.methodDescriptor?.text?.takeIf(UnpickDescriptors::isValidMethod) ?: return + val parameters = Type.getArgumentTypes(descriptor) + val returnType = Type.getReturnType(descriptor) for (param in element.targetMethodParamList) { val indexElement = param.index ?: continue val index = UnpickLiterals.parseInt(indexElement.text) ?: continue - if (index < 0 || index >= parsed.parameters.size) { + if (index < 0 || index >= parameters.size) { holder.registerProblem( indexElement, MCDevBundle( "inspection.unpick_target_mismatch.param_out_of_bounds", index, - parsed.parameters.size, + parameters.size, ), ) continue } - val paramDescriptor = parsed.parameters[index] - checkCompatible(param.groupRef, paramDescriptor) { groupName, groupType -> + val paramType = parameters[index] + checkCompatible(param.groupRef, paramType) { groupName, groupType -> MCDevBundle( "inspection.unpick_target_mismatch.param_incompatible", index, - UnpickDescriptors.toJavaName(paramDescriptor), + paramType.className, groupName, groupType.keyword, ) @@ -68,17 +70,17 @@ } for (ret in element.targetMethodReturnList) { - if (parsed.returnType == "V") { + if (returnType.sort == Type.VOID) { holder.registerProblem( ret.firstChild, MCDevBundle("inspection.unpick_target_mismatch.void_return"), ) continue } - checkCompatible(ret.groupRef, parsed.returnType) { groupName, groupType -> + checkCompatible(ret.groupRef, returnType) { groupName, groupType -> MCDevBundle( "inspection.unpick_target_mismatch.return_incompatible", - UnpickDescriptors.toJavaName(parsed.returnType), + returnType.className, groupName, groupType.keyword, ) @@ -89,9 +91,10 @@ override fun visitTargetField(element: UnpickTargetField) { val descriptorElement = element.fieldDescriptor ?: return val descriptor = descriptorElement.text - if (UnpickDescriptors.validateField(descriptor) != null) { + if (!UnpickDescriptors.isValidField(descriptor)) { return } + val type = Type.getType(descriptor) val field = element.fieldName?.resolveField() val actualDescriptor = field?.descriptor @@ -102,10 +105,10 @@ ) } - checkCompatible(element.groupRef, descriptor) { groupName, groupType -> + checkCompatible(element.groupRef, type) { groupName, groupType -> MCDevBundle( "inspection.unpick_target_mismatch.field_incompatible", - UnpickDescriptors.toJavaName(descriptor), + type.className, groupName, groupType.keyword, ) @@ -125,11 +128,11 @@ private inline fun checkCompatible( groupRef: UnpickGroupRef?, - targetDescriptor: String, + target: Type, message: (String, DataType) -> String, ) { groupRef ?: return - val targetType = DataType.fromDescriptor(targetDescriptor) + val targetType = DataType.fromDescriptor(target.descriptor) val groupTypes = groupRef.resolveDefinitions().mapNotNull { it.dataType?.dataType }.distinct() for (groupType in groupTypes) { if (targetType == null || !targetType.isTargetCompatibleWith(groupType)) { Index: src/main/kotlin/platform/minecraft/unpick/psi/UnpickClassReference.kt =================================================================== --- src/main/kotlin/platform/minecraft/unpick/psi/UnpickClassReference.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/main/kotlin/platform/minecraft/unpick/psi/UnpickClassReference.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -22,7 +22,9 @@ import com.demonwav.mcdev.platform.minecraft.unpick.gen.psi.UnpickClassName import com.demonwav.mcdev.platform.minecraft.unpick.gen.psi.UnpickTypes +import com.demonwav.mcdev.util.anonymousClasses import com.demonwav.mcdev.util.findQualifiedClass +import com.demonwav.mcdev.util.localClasses import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.util.TextRange import com.intellij.psi.JavaPsiFacade @@ -57,6 +59,8 @@ } } + override fun getCanonicalText() = targetName + override fun getVariants(): Array { val facade = JavaPsiFacade.getInstance(element.project) val scope = element.resolveScope @@ -64,7 +68,8 @@ val isInnerClass = targetName.lastIndexOf('$') > targetName.lastIndexOf('.') if (isInnerClass) { val outer = findQualifiedClass(parentName, element) ?: return ArrayUtil.EMPTY_OBJECT_ARRAY - return outer.innerClasses.mapNotNull { it.name }.map(LookupElementBuilder::create).toTypedArray() + return innerClassNames(outer).map { (name, psiClass) -> LookupElementBuilder.create(psiClass, name) } + .toTypedArray() } val parentPackage = facade.findPackage(parentName) ?: return ArrayUtil.EMPTY_OBJECT_ARRAY val packages = parentPackage.getSubPackages(scope).mapNotNull { it.name } @@ -77,6 +82,22 @@ return (packages + classes).toTypedArray() } + /** + * Returns the binary names of the classes directly inside [outer] relative to it, including local and anonymous + * classes, together with the classes they name. + */ + private fun innerClassNames(outer: PsiClass): List> { + val named = outer.innerClasses.mapNotNull { innerClass -> innerClass.name?.let { it to innerClass } } + val localIndices = HashMap() + val local = outer.localClasses.mapNotNull { localClass -> + val name = localClass.name ?: return@mapNotNull null + val index = localIndices.merge(name, 1, Int::plus) + "$index$name" to localClass + } + val anonymous = outer.anonymousClasses.mapIndexed { index, anonymousClass -> "${index + 1}" to anonymousClass } + return named + local + anonymous + } + override fun handleElementRename(newElementName: String): PsiElement { val identifier = element.node.getChildren(null).firstOrNull { it.elementType == UnpickTypes.IDENTIFIER && Index: src/main/kotlin/platform/minecraft/unpick/psi/mixins/UnpickBinaryExpressionMixin.kt =================================================================== --- src/main/kotlin/platform/minecraft/unpick/psi/mixins/UnpickBinaryExpressionMixin.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/main/kotlin/platform/minecraft/unpick/psi/mixins/UnpickBinaryExpressionMixin.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -26,9 +26,9 @@ import com.intellij.psi.tree.IElementType interface UnpickBinaryExpressionMixin : UnpickElement { - fun getLeft(): UnpickExpression + val left: UnpickExpression - fun getRight(): UnpickExpression? + val right: UnpickExpression? val operatorToken: PsiElement Index: src/main/kotlin/platform/minecraft/unpick/psi/mixins/UnpickHeaderMixin.kt =================================================================== --- src/main/kotlin/platform/minecraft/unpick/psi/mixins/UnpickHeaderMixin.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/main/kotlin/platform/minecraft/unpick/psi/mixins/UnpickHeaderMixin.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -20,6 +20,7 @@ package com.demonwav.mcdev.platform.minecraft.unpick.psi.mixins +import com.demonwav.mcdev.platform.minecraft.unpick.UnpickLanguage import com.demonwav.mcdev.platform.minecraft.unpick.psi.UnpickElement interface UnpickHeaderMixin : UnpickElement { @@ -29,9 +30,5 @@ val version: Int? val isSupportedVersion: Boolean - get() = version.let { it == null || it in SUPPORTED_VERSIONS } - - companion object { - val SUPPORTED_VERSIONS = 3..4 + get() = version.let { it == null || it in UnpickLanguage.SUPPORTED_VERSIONS } - } +} -} Index: src/main/kotlin/platform/minecraft/unpick/psi/mixins/impl/UnpickFieldNameImplMixin.kt =================================================================== --- src/main/kotlin/platform/minecraft/unpick/psi/mixins/impl/UnpickFieldNameImplMixin.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/main/kotlin/platform/minecraft/unpick/psi/mixins/impl/UnpickFieldNameImplMixin.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -21,6 +21,7 @@ package com.demonwav.mcdev.platform.minecraft.unpick.psi.mixins.impl import com.demonwav.mcdev.platform.minecraft.unpick.gen.psi.UnpickClassName +import com.demonwav.mcdev.platform.minecraft.unpick.gen.psi.UnpickFieldExpression import com.demonwav.mcdev.platform.minecraft.unpick.psi.UnpickElementFactory import com.demonwav.mcdev.platform.minecraft.unpick.psi.mixins.UnpickFieldNameMixin import com.demonwav.mcdev.util.cached @@ -29,6 +30,7 @@ import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.openapi.util.TextRange +import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiElement import com.intellij.psi.PsiField import com.intellij.psi.PsiReference @@ -52,11 +54,22 @@ override fun resolve(): PsiElement? = resolveField() override fun getVariants(): Array { - val owner = ownerClassName?.resolveClass() ?: return ArrayUtil.EMPTY_OBJECT_ARRAY - return owner.allFields.map { field -> + val ownerClassName = ownerClassName ?: return ArrayUtil.EMPTY_OBJECT_ARRAY + val fields = ownerClassName.resolveClass()?.allFields.orEmpty().map { field -> LookupElementBuilder.create(field).withTypeText(field.type.presentableText) - }.toTypedArray() - } + } + // While the owner of a field expression is being typed, its last part is parsed as the field name, and the + // rest is parsed as the owner even though it may be a package + val packageMembers = if (parent is UnpickFieldExpression) { + val psiPackage = JavaPsiFacade.getInstance(project).findPackage(ownerClassName.qualifiedName) + val scope = resolveScope + psiPackage?.getSubPackages(scope).orEmpty().map(LookupElementBuilder::create) + + psiPackage?.getClasses(scope).orEmpty().map(LookupElementBuilder::create) + } else { + emptyList() + } + return (fields + packageMembers).toTypedArray() + } override fun getRangeInElement(): TextRange = TextRange(0, textLength) Index: src/main/resources/META-INF/plugin.xml =================================================================== --- src/main/resources/META-INF/plugin.xml (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/main/resources/META-INF/plugin.xml (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -624,6 +624,7 @@ + Index: src/main/resources/messages/MinecraftDevelopmentBundle.properties =================================================================== --- src/main/resources/messages/MinecraftDevelopmentBundle.properties (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/main/resources/messages/MinecraftDevelopmentBundle.properties (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -398,7 +398,7 @@ inspection.duplicate_interface_prefix.message=Duplicate prefix ''{0}'' inspection.duplicate_unpick_constant.message=Constant evaluates to {0}, which is also the value of ''{1}'' inspection.duplicate_unpick_constant.name=Duplicate unpick constant -inspection.duplicate_unpick_constant.wildcard_message=Wildcard field ''{0}'' evaluates to {1}, which is also the value of ''{2}'' +inspection.duplicate_unpick_constant.wildcard_message=Constant evaluates to {0} when the wildcard is expanded to ''{1}'', which is also the value of ''{2}'' inspection.empty_implements.name=Empty @Implements inspection.empty_implements.message=@Implements is redundant inspection.entity_data_param.fix=Replace other entity class with this entity class @@ -955,11 +955,13 @@ minecraft.unpick.color_settings.bad_character=Bad character minecraft.unpick.color_settings.class_name=Class name minecraft.unpick.color_settings.comment=Comment +minecraft.unpick.color_settings.data_type=Data type minecraft.unpick.color_settings.descriptor=Descriptor minecraft.unpick.color_settings.display_name=Unpick minecraft.unpick.color_settings.doc_comment=Doc comment minecraft.unpick.color_settings.dot=Dot minecraft.unpick.color_settings.field_name=Field name +minecraft.unpick.color_settings.format=Format minecraft.unpick.color_settings.group_name=Group name minecraft.unpick.color_settings.keyword=Keyword minecraft.unpick.color_settings.method_name=Method name @@ -968,11 +970,8 @@ minecraft.unpick.color_settings.parentheses=Parentheses minecraft.unpick.color_settings.string=String minecraft.unpick.color_settings.unsupported=Unsupported version content -minecraft.unpick.descriptor.empty_class_name=Empty class name in descriptor -minecraft.unpick.descriptor.expected_method=Expected a method descriptor starting with '(' -minecraft.unpick.descriptor.illegal_character=Illegal character in descriptor: ''{0}'' -minecraft.unpick.descriptor.trailing_characters=Unexpected characters after the end of the descriptor -minecraft.unpick.descriptor.unexpected_end=Unexpected end of descriptor +minecraft.unpick.descriptor.invalid_field=Invalid field descriptor +minecraft.unpick.descriptor.invalid_method=Invalid method descriptor minecraft.unpick.eval.bad_binary_operands=Operator ''{0}'' cannot be applied to ''{1}'' and ''{2}'' minecraft.unpick.eval.bad_cast=Cannot cast ''{0}'' to ''{1}'' minecraft.unpick.eval.bad_unary_operand=Operator ''{0}'' cannot be applied to ''{1}'' Index: src/test/kotlin/platform/minecraft/unpick/UnpickAnnotatorTest.kt =================================================================== --- src/test/kotlin/platform/minecraft/unpick/UnpickAnnotatorTest.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/test/kotlin/platform/minecraft/unpick/UnpickAnnotatorTest.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -23,6 +23,7 @@ import com.demonwav.mcdev.framework.EdtInterceptor import com.demonwav.mcdev.framework.ProjectBuilderTest import org.intellij.lang.annotations.Language +import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @@ -39,6 +40,33 @@ } @Test + @DisplayName("Semantic Highlighting") + fun semanticHighlighting() { + buildProject { + unpick( + "test.unpick", + """ + unpick v4 + group int g + @scope class Foo + @format hex + 1 + """, + ) + } + val highlights = fixture.doHighlighting() + .filter { it.forcedTextAttributesKey != null } + .associate { it.text to it.forcedTextAttributesKey } + Assertions.assertEquals(UnpickSyntaxHighlighter.ATTRIBUTE, highlights["@scope"]) + Assertions.assertEquals(UnpickSyntaxHighlighter.ATTRIBUTE, highlights["@format"]) + Assertions.assertEquals(UnpickSyntaxHighlighter.KEYWORD, highlights["class"]) + Assertions.assertEquals(UnpickSyntaxHighlighter.DATA_TYPE, highlights["int"]) + Assertions.assertEquals(UnpickSyntaxHighlighter.FORMAT, highlights["hex"]) + Assertions.assertEquals(UnpickSyntaxHighlighter.GROUP_NAME, highlights["g"]) + Assertions.assertFalse("scope" in highlights) + } + + @Test @DisplayName("Unsupported Version Is Only A Warning") fun unsupportedVersion() = doTest( """ Index: src/test/kotlin/platform/minecraft/unpick/UnpickClassReferenceTest.kt =================================================================== --- src/test/kotlin/platform/minecraft/unpick/UnpickClassReferenceTest.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) +++ src/test/kotlin/platform/minecraft/unpick/UnpickClassReferenceTest.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -0,0 +1,193 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.platform.minecraft.unpick + +import com.demonwav.mcdev.framework.BaseMinecraftTest +import com.demonwav.mcdev.framework.EdtInterceptor +import com.intellij.psi.JavaPsiFacade +import com.intellij.psi.search.GlobalSearchScope +import com.intellij.psi.search.searches.ReferencesSearch +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(EdtInterceptor::class) +@DisplayName("Unpick Class Reference Tests") +class UnpickClassReferenceTest : BaseMinecraftTest() { + + @BeforeEach + fun setupProject() { + buildProject { + java( + "com/example/Outer.java", + """ + package com.example; + + public class Outer { + public static final int OUTER_VALUE = 1; + + public static class Middle { + public static class Inner { + public static final int INNER_VALUE = 2; + } + } + + public void method() { + class Local { + } + Runnable r = new Runnable() { + public void run() { + } + }; + } + } + """, + configure = false, + allowAst = true, + ) + unpick( + "usages.unpick", + """ + unpick v4 + group int + com.example.Outer${'$'}Middle${'$'}Inner.INNER_VALUE + com.example.Outer.OUTER_VALUE + target_field com.example.Outer${'$'}Middle${'$'}Inner INNER_VALUE I Foo + """, + configure = false, + ) + } + } + + private fun findClass(name: String) = + JavaPsiFacade.getInstance(project).findClass(name, GlobalSearchScope.allScope(project))!! + + private fun usagesInUnpick(className: String): List { + return ReferencesSearch.search(findClass(className)).findAll() + .filter { it.element.containingFile is UnpickFile } + .map { it.canonicalText } + } + + @Test + @DisplayName("Find Usages Of Inner Class") + fun findUsagesOfInnerClass() { + Assertions.assertEquals( + listOf("com.example.Outer\$Middle\$Inner", "com.example.Outer\$Middle\$Inner"), + usagesInUnpick("com.example.Outer.Middle.Inner"), + ) + } + + @Test + @DisplayName("Find Usages Of Middle Class") + fun findUsagesOfMiddleClass() { + Assertions.assertEquals( + listOf("com.example.Outer\$Middle", "com.example.Outer\$Middle"), + usagesInUnpick("com.example.Outer.Middle"), + ) + } + + @Test + @DisplayName("Find Usages Of Outer Class") + fun findUsagesOfOuterClass() { + Assertions.assertEquals(3, usagesInUnpick("com.example.Outer").size) + } + + @Test + @DisplayName("Rename Inner Class") + fun renameInnerClass() { + fixture.renameElement(findClass("com.example.Outer.Middle.Inner"), "Renamed") + val text = fixture.tempDirFixture.getFile("usages.unpick")!!.let { fixture.psiManager.findFile(it)!!.text } + Assertions.assertEquals(2, text.split("Outer\$Middle\$Renamed").size - 1, text) + } + + private fun complete(text: String): List { + fixture.configureByText("complete.unpick", text) + return fixture.completeBasic()?.map { it.lookupString }.orEmpty() + } + + @Test + @DisplayName("Inner Class Completion Includes Local And Anonymous Classes") + fun innerClassCompletion() { + val lookups = complete("unpick v4\ntarget_annotation com.example.Outer${'$'}\n") + Assertions.assertTrue("Middle" in lookups, lookups.toString()) + Assertions.assertTrue("1Local" in lookups, lookups.toString()) + Assertions.assertTrue("1" in lookups, lookups.toString()) + } + + @Test + @DisplayName("Field Expression Owner Completion") + fun fieldExpressionOwnerCompletion() { + val lookups = complete("unpick v4\ngroup int\n com.example.Ou\n") + Assertions.assertTrue(lookups.isEmpty() || "Outer" in lookups, lookups.toString()) + if (lookups.isEmpty()) { + Assertions.assertTrue(fixture.editor.document.text.contains("com.example.Outer")) + } + } + + @Test + @DisplayName("Field Expression Field Completion") + fun fieldExpressionFieldCompletion() { + val lookups = complete("unpick v4\ngroup int\n com.example.Outer.OUT\n") + if (lookups.isEmpty()) { + Assertions.assertTrue(fixture.editor.document.text.contains("Outer.OUTER_VALUE")) + } else { + Assertions.assertTrue("OUTER_VALUE" in lookups, lookups.toString()) + } + } + + @Test + @DisplayName("Simple Name Class Completion") + fun simpleNameClassCompletion() { + complete("unpick v4\ntarget_annotation Oute\n") + val text = fixture.editor.document.text + if (!text.contains("com.example.Outer")) { + fixture.lookup?.let { lookup -> + val item = lookup.items.first { it.lookupString == "com.example.Outer" || it.lookupString == "Outer" } + fixture.lookup.currentItem = item + fixture.finishLookup('\n') + } + } + Assertions.assertTrue( + fixture.editor.document.text.contains("target_annotation com.example.Outer"), + fixture.editor.document.text, + ) + } + + @Test + @DisplayName("Simple Name Field Expression Completion") + fun simpleNameFieldExpressionCompletion() { + complete("unpick v4\ngroup int\n Inne\n") + val text = fixture.editor.document.text + if (!text.contains("com.example.Outer\$Middle\$Inner")) { + fixture.lookup?.let { lookup -> + val item = lookup.items.first { it.lookupString.endsWith("Inner") } + fixture.lookup.currentItem = item + fixture.finishLookup('\n') + } + } + Assertions.assertTrue( + fixture.editor.document.text.contains(" com.example.Outer\$Middle\$Inner"), + fixture.editor.document.text, + ) + } +} Index: src/test/kotlin/platform/minecraft/unpick/UnpickExpressionEvaluatorTest.kt =================================================================== --- src/test/kotlin/platform/minecraft/unpick/UnpickExpressionEvaluatorTest.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/test/kotlin/platform/minecraft/unpick/UnpickExpressionEvaluatorTest.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -55,18 +55,39 @@ public static final Class INT_TYPE = Integer.TYPE; public static final Class STRING_CLASS = String.class; public static final String NULL_STRING = null; + public static final String ALIAS_NULL_STRING = NULL_STRING; + public static final Class IFACE_CLASS = Iface.class; + public static final Class ARRAY_CLASS = String[].class; + public static final Class NOT_CONSTANT_CLASS = Wild.class.getClass(); + public static int notFinal = 6; + public static final int NOT_CONSTANT = Integer.parseInt("7"); } """, configure = false, allowAst = true, ) + java( + "com/example/Iface.java", + """ + package com.example; + + public interface Iface { - } + } + """, + configure = false, + allowAst = true, + ) - } + } + } - private fun evaluate(type: String, expression: String): List { + private fun evaluateWithProblems(type: String, expression: String): UnpickExpressionEvaluator.Result { val file = fixture.configureByText("test.unpick", "unpick v4\ngroup $type\n $expression\n") val constant = PsiTreeUtil.findChildOfType(file, UnpickGroupConstant::class.java)!! - val result = UnpickExpressionEvaluator.evaluate(constant) + return UnpickExpressionEvaluator.evaluate(constant) + } + + private fun evaluate(type: String, expression: String): List { + val result = evaluateWithProblems(type, expression) Assertions.assertEquals(emptyList(), result.problems.map { it.message }, expression) return result.values.map { it.value.value } } @@ -119,9 +140,20 @@ assertValue("x1.0", "\"x\" + 1.0f", "String") assertValue("ss", "com.example.Wild.S + com.example.Wild.S", "String") assertValue(null, "com.example.Wild.NULL_STRING", "String") + assertValue(null, "com.example.Wild.ALIAS_NULL_STRING", "String") + assertValue("anull", "\"a\" + com.example.Wild.ALIAS_NULL_STRING", "String") } @Test + @DisplayName("Class Concatenation") + fun classConcatenation() { + assertValue("int", "\"\" + com.example.Wild.INT_TYPE", "String") + assertValue("class java.lang.String", "\"\" + com.example.Wild.STRING_CLASS", "String") + assertValue("interface com.example.Iface", "\"\" + com.example.Wild.IFACE_CLASS", "String") + assertValue("class [Ljava.lang.String;", "\"\" + com.example.Wild.ARRAY_CLASS", "String") + } + + @Test @DisplayName("Class Constants") fun classConstants() { assertValue(PsiTypes.intType(), "com.example.Wild.INT_TYPE", "Class") @@ -129,13 +161,23 @@ "java.lang.String", (evaluate("Class", "com.example.Wild.STRING_CLASS").single() as PsiType).canonicalText, ) + + val result = evaluateWithProblems("Class", "com.example.Wild.NOT_CONSTANT_CLASS") + Assertions.assertEquals( + listOf("Field 'NOT_CONSTANT_CLASS' is not initialized to a compile-time constant"), + result.problems.map { it.message }, + ) + Assertions.assertFalse(result.values.single().value.isKnown) } @Test @DisplayName("Wildcards") fun wildcards() { - Assertions.assertEquals(listOf(1, 2, 5.toByte()), evaluate("int", "com.example.Wild.*")) - Assertions.assertEquals(listOf(1, 2, 3L, 5.toByte()), evaluate("long", "com.example.Wild.*")) + // Wildcards only match constant fields, and have the type of the group + Assertions.assertEquals(listOf(1, 2, 5), evaluate("int", "com.example.Wild.*")) + Assertions.assertEquals(listOf(1L, 2L, 3L, 5L), evaluate("long", "com.example.Wild.*")) + Assertions.assertEquals(listOf(5.toByte()), evaluate("int", "com.example.Wild.*:byte")) + Assertions.assertEquals(listOf("s", null, null), evaluate("String", "com.example.Wild.*")) Assertions.assertEquals(listOf(3L), evaluate("long", "com.example.Wild.*:long")) Assertions.assertEquals(listOf(4), evaluate("int", "com.example.Wild.*:instance")) Assertions.assertEquals(listOf(11, 12, 15), evaluate("int", "com.example.Wild.* + 10")) Index: src/test/kotlin/platform/minecraft/unpick/UnpickInspectionsTest.kt =================================================================== --- src/test/kotlin/platform/minecraft/unpick/UnpickInspectionsTest.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/test/kotlin/platform/minecraft/unpick/UnpickInspectionsTest.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -235,6 +235,9 @@ group long 2 1 + 1 + group int W + com.example.Constants${'$'}Inner.* + com.example.Constants${'$'}Inner.* - 92 """, ) Index: src/test/kotlin/platform/minecraft/unpick/UnpickReferenceFixturesTest.kt =================================================================== --- src/test/kotlin/platform/minecraft/unpick/UnpickReferenceFixturesTest.kt (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ src/test/kotlin/platform/minecraft/unpick/UnpickReferenceFixturesTest.kt (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -110,17 +110,17 @@ "tokens_integer_out_of_bounds_positive_decimal.unpick" to "Integer out of bounds", "tokens_integer_out_of_bounds_positive_hex.unpick" to "Integer out of bounds", "tokens_integer_out_of_bounds_positive_octal.unpick" to "Integer out of bounds", - "tokens_field_descriptor_empty_object.unpick" to "Unexpected end of descriptor", - "tokens_field_descriptor_invalid_char.unpick" to "Illegal character in descriptor: 'X'", - "tokens_field_descriptor_object_illegal_bracket.unpick" to "Illegal character in descriptor: '['", - "tokens_field_descriptor_object_illegal_period.unpick" to "Illegal character in descriptor: '.'", - "tokens_field_descriptor_unterminated_object.unpick" to "Unexpected end of descriptor", - "tokens_field_descriptor_untyped_array.unpick" to "Unexpected end of descriptor", - "tokens_field_descriptor_void.unpick" to "Illegal character in descriptor: 'V'", - "tokens_method_descriptor_field_descriptor.unpick" to "Expected a method descriptor starting with '('", - "tokens_method_descriptor_no_return_type.unpick" to "Unexpected end of descriptor", - "tokens_method_descriptor_unclosed_paren.unpick" to "Unexpected end of descriptor", - "tokens_method_descriptor_void_parameter.unpick" to "Illegal character in descriptor: 'V'", + "tokens_field_descriptor_empty_object.unpick" to "Invalid field descriptor", + "tokens_field_descriptor_invalid_char.unpick" to "Invalid field descriptor", + "tokens_field_descriptor_object_illegal_bracket.unpick" to "Invalid field descriptor", + "tokens_field_descriptor_object_illegal_period.unpick" to "Invalid field descriptor", + "tokens_field_descriptor_unterminated_object.unpick" to "Invalid field descriptor", + "tokens_field_descriptor_untyped_array.unpick" to "Invalid field descriptor", + "tokens_field_descriptor_void.unpick" to "Invalid field descriptor", + "tokens_method_descriptor_field_descriptor.unpick" to "Invalid method descriptor", + "tokens_method_descriptor_no_return_type.unpick" to "Invalid method descriptor", + "tokens_method_descriptor_unclosed_paren.unpick" to "Invalid method descriptor", + "tokens_method_descriptor_void_parameter.unpick" to "Invalid method descriptor", ) } } Index: unpick-review.md =================================================================== --- unpick-review.md (revision ac067c6ef1ed01a34debcb869b4d3f26d3613a37) +++ unpick-review.md (revision 1a3346016a9eba14b618a26093b35aeed7419d68) @@ -1,26 +1,4 @@ -- I have updated the unpick spec to clarify that wildcard field expressions only match constant fields. Update the code to comply with this clarification. -- `UpickValue.toJavaString()` does not handle the case where the value is a `PsiType`. In this case, you should make it return the same result as if `Class.toString()` were called on the value if it were a `Class`. -- In `Evaluation.evaluateField`, `isNullInitializer` for string values isn't enough, as the string constant could be `null` due to being initialized to another string constant which is `null`. -- What's the logic behind class values being able to be `PsiField` as well? If you are unable to resolve what the field value is for whatever reason, return an unknown value. -- `UnpickValue.convertTo` should probably throw an exception if it's inconvertible. When you apply this change, check the call sites to make sure they properly handle the case where it's inconvertible. Maybe you should add a `canConvertTo` utility if it needs checking. -- You could make `UnpickValue` a data class, which would avoid you needing to implement `equals`, `hashCode`, and `toString`. -- Throughout your changes there are companion objects in IDE extension implementations which generate a warning in IntelliJ. Resolve these warnings by converting them to named objects, as we do in the rest of the project. Add this to your memory that this needs to be done in future. -- Inner class references indeed don't work as you predicted. Find a way to fix this. -- The error message in DuplicateUnpickConstantInspection is a bit off in the case of wildcard fields. It assumes that the value of the wildcard field expression is the final value of the expression. -- `UnpickDescriptors` is mostly unnecessary since we have ASM on the classpath. They can be validated with a simple regex (I think we already do this somewhere in the project) before being passed on to ASM. -- `UnpickClassReference.getVariants`, where it uses `outer.innerClasses`, does not take into account local or anonymous classes. Fix this. -- `UnpickBinaryExpressionMixin` could use properties rather than getter methods. -- It feels like `UnpickHeaderMixin.SUPPORTED_VERSIONS` can live in a better location. -- `UnpickAnnotator.annotateHeader` converts the whole file to a string, which is very inefficient. -- In `UnpickAnnotator`, it's a bit weird that `error` and `highlight` are structured differently with different receivers. -- `UnpickCompletionContributor.fillCompletionVariants` converts the whole file to a string, which is very inefficient. -- Look to see if there's a built-in replacement for `UnpickLiterals.unquote` (there might not be). -- I want some changes to the highlighting. Some of these may just be a problem in the preview in the color settings menu, some may be real issues: - - I want the attribute highlight to cover the attribute name, not just the `@` symbol. - - I want there to be a separate highlight color for data types. - - I want there to be a separate highlight color for group formats. - - I want the group name color to inherit from enum definitions/references rather than constants. - - I want descriptors to default to a different color than strings. -- Auto-completion of the owner class in field expressions doesn't work -- Auto-completion of classes should allow the user to type the simple name of the class, and then complete to the fully-qualified name. -- Docs are in Markdown Javadoc format. What would it take to be able to reuse the highlighting, completion features, etc, of that? Unless it's simple, don't implement it, just answer the question. \ No newline at end of file +- In `UnpickCompletionContributor`, it won't complete if `#` is in the line, even if that `#` is inside a string or char token. +- In `UnpickExpressionEvaluator.constantValue`, check if `field.computeConstantValue` is contractually guaranteed to return a value of the field's type, or `null`. If it is, the conversion below it can be elided. If not, you can still use `TypeConversionUtil.computeCastTo` to simplify this code and avoid the `when` statement. +- `UnpickDescriptors` doesn't contain anything specific to unpick. The stuff inside could be moved to generic ASM utilities. +- `UnpickClassReference.innerClassNames` could maybe also be a more generic utility, next to the other related utilities. \ No newline at end of file