Replace assert with lazy assert, times with repeat.

This commit is contained in:
Ilya Gorbunov
2015-10-01 20:13:34 +03:00
parent c1ba30b4bc
commit 3106458cc4
50 changed files with 79 additions and 87 deletions
@@ -63,7 +63,7 @@ public abstract class CoveringTryCatchNodeProcessor(parameterSize: Int) {
if (result == 0) {
result = instructionIndex(t1.startLabel) - instructionIndex(t2.startLabel)
if (result == 0) {
assert(false, "Error: support multicatch finallies: ${t1.handler}, ${t2.handler}")
assert(false) { "Error: support multicatch finallies: ${t1.handler}, ${t2.handler}" }
result = instructionIndex(t1.endLabel) - instructionIndex(t2.endLabel)
}
}
@@ -131,12 +131,12 @@ class IntervalMetaInfo<T : SplittableInterval<T>> {
fun processCurrent(curIns: LabelNode, directOrder: Boolean) {
getInterval(curIns, directOrder).forEach {
val added = currentIntervals.add(it)
assert(added, "Wrong interval structure: $curIns, $it")
assert(added) { "Wrong interval structure: $curIns, $it" }
}
getInterval(curIns, !directOrder).forEach {
val removed = currentIntervals.remove(it)
assert(removed, "Wrong interval structure: $curIns, $it")
assert(removed) { "Wrong interval structure: $curIns, $it" }
}
}
@@ -237,7 +237,7 @@ public open class DefaultSourceMapper(val sourceInfo: SourceInfo, override val p
/*Source Mapping*/
class SMAP(val fileMappings: List<FileMapping>) {
init {
assert(fileMappings.isNotEmpty(), "File Mappings shouldn't be empty")
assert(fileMappings.isNotEmpty()) { "File Mappings shouldn't be empty" }
}
val default: FileMapping
@@ -275,7 +275,7 @@ class RawFileMapping(val name: String, val path: String) {
}
fun initRange(start: Int, end: Int) {
assert(lineMappings.isEmpty(), "initRange should only be called for empty mapping")
assert(lineMappings.isEmpty()) { "initRange should only be called for empty mapping" }
for (index in start..end) {
lineMappings.put(index, index)
}
@@ -77,8 +77,7 @@ private fun insertSaveRestoreStackMarkers(
doneTryStartLabels.add(tryStartLabel)
val nopNode = tryStartLabel.findNextOrNull { it.hasOpcode() }!!
assert(nopNode.getOpcode() == Opcodes.NOP,
"${methodNode.instructions.indexOf(nopNode)}: try block should start with NOP")
assert(nopNode.getOpcode() == Opcodes.NOP) { "${methodNode.instructions.indexOf(nopNode)}: try block should start with NOP" }
val newTryStartLabel = LabelNode(Label())
newTryStartLabels[tryStartLabel] = newTryStartLabel
@@ -93,8 +92,7 @@ private fun insertSaveRestoreStackMarkers(
doneHandlerLabels.add(handlerStartLabel)
val storeNode = handlerStartLabel.findNextOrNull { it.hasOpcode() }!!
assert(storeNode.getOpcode() == Opcodes.ASTORE,
"${methodNode.instructions.indexOf(storeNode)}: handler should start with ASTORE")
assert(storeNode.getOpcode() == Opcodes.ASTORE) { "${methodNode.instructions.indexOf(storeNode)}: handler should start with ASTORE" }
methodNode.instructions.insert(storeNode, PseudoInsn.RESTORE_STACK_IN_TRY_CATCH.createInsnNode())
}
@@ -110,8 +108,7 @@ private fun collectDecompiledTryDescriptors(
) {
for (tcb in methodNode.tryCatchBlocks) {
if (tcb.isDefaultHandlerNode()) {
assert(decompiledTryDescriptorForHandler.containsKey(tcb.start),
"${methodNode.debugString(tcb)}: default handler should occur after some regular handler")
assert(decompiledTryDescriptorForHandler.containsKey(tcb.start)) { "${methodNode.debugString(tcb)}: default handler should occur after some regular handler" }
}
val decompiledTryDescriptor = decompiledTryDescriptorForHandler.getOrPut(tcb.handler) {
@@ -65,7 +65,7 @@ internal class FixStackContext(val methodNode: MethodNode) {
inlineMarkersStack.push(insnNode)
}
InlineCodegenUtil.isAfterInlineMarker(insnNode) -> {
assert(inlineMarkersStack.isNotEmpty(), "Mismatching after inline method marker at ${indexOf(insnNode)}")
assert(inlineMarkersStack.isNotEmpty()) { "Mismatching after inline method marker at ${indexOf(insnNode)}" }
openingInlineMethodMarker[insnNode] = inlineMarkersStack.pop()
}
}
@@ -78,23 +78,23 @@ internal class FixStackContext(val methodNode: MethodNode) {
private fun visitFixStackBeforeJump(insnNode: AbstractInsnNode) {
val next = insnNode.getNext()
assert(next.getOpcode() == Opcodes.GOTO, "${indexOf(insnNode)}: should be followed by GOTO")
assert(next.getOpcode() == Opcodes.GOTO) { "${indexOf(insnNode)}: should be followed by GOTO" }
breakContinueGotoNodes.add(next as JumpInsnNode)
}
private fun visitFakeAlwaysTrueIfeq(insnNode: AbstractInsnNode) {
assert(insnNode.getNext().getOpcode() == Opcodes.IFEQ, "${indexOf(insnNode)}: should be followed by IFEQ")
assert(insnNode.getNext().getOpcode() == Opcodes.IFEQ) { "${indexOf(insnNode)}: should be followed by IFEQ" }
fakeAlwaysTrueIfeqMarkers.add(insnNode)
}
private fun visitFakeAlwaysFalseIfeq(insnNode: AbstractInsnNode) {
assert(insnNode.getNext().getOpcode() == Opcodes.IFEQ, "${indexOf(insnNode)}: should be followed by IFEQ")
assert(insnNode.getNext().getOpcode() == Opcodes.IFEQ) { "${indexOf(insnNode)}: should be followed by IFEQ" }
fakeAlwaysFalseIfeqMarkers.add(insnNode)
}
private fun visitSaveStackBeforeTry(insnNode: AbstractInsnNode) {
val tryStartLabel = insnNode.getNext()
assert(tryStartLabel is LabelNode, "${indexOf(insnNode)}: save should be followed by a label")
assert(tryStartLabel is LabelNode) { "${indexOf(insnNode)}: save should be followed by a label" }
saveStackNodesForTryStartLabel[tryStartLabel as LabelNode] = insnNode
}
@@ -77,8 +77,7 @@ public class FixStackMethodTransformer : MethodTransformer() {
val expectedStackSize = analyzer.frames[labelIndex]?.getStackSize() ?: DEAD_CODE
if (actualStackSize != DEAD_CODE && expectedStackSize != DEAD_CODE) {
assert(expectedStackSize <= actualStackSize,
"Label at $labelIndex, jump at $gotoIndex: stack underflow: $expectedStackSize > $actualStackSize")
assert(expectedStackSize <= actualStackSize) { "Label at $labelIndex, jump at $gotoIndex: stack underflow: $expectedStackSize > $actualStackSize" }
val frame = analyzer.frames[gotoIndex]!!
actions.add({ replaceMarkerWithPops(methodNode, gotoNode.getPrevious(), expectedStackSize, frame) })
}
@@ -154,7 +153,7 @@ public class FixStackMethodTransformer : MethodTransformer() {
val savedStackDescriptor = localVariablesManager.getBeforeInlineDescriptor(inlineMarker)
val afterInlineFrame = analyzer.getFrame(inlineMarker) as FixStackAnalyzer.FixStackFrame?
if (afterInlineFrame != null && savedStackDescriptor.isNotEmpty()) {
assert(afterInlineFrame.getStackSize() <= 1, "Inline method should not leave more than 1 value on stack")
assert(afterInlineFrame.getStackSize() <= 1) { "Inline method should not leave more than 1 value on stack" }
if (afterInlineFrame.getStackSize() == 1) {
val afterInlineStackValues = afterInlineFrame.getStackContent()
val returnValue = afterInlineStackValues.last()
@@ -26,7 +26,7 @@ internal class LocalVariablesManager(val context: FixStackContext, val methodNod
numRestoreMarkers == 0
fun markRestoreNodeEmitted() {
assert(numRestoreMarkers > 0, "Emitted more restore markers than expected for $savedStackDescriptor")
assert(numRestoreMarkers > 0) { "Emitted more restore markers than expected for $savedStackDescriptor" }
numRestoreMarkers--
}
}
@@ -168,7 +168,7 @@ class SamAdapterFunctionsScope(storageManager: StorageManager) : JetScope by Jet
}
original as MyFunctionDescriptor
assert(original.original == original, "original in doSubstitute should have no other original")
assert(original.original == original) { "original in doSubstitute should have no other original" }
val substitutionMap = HashMap<TypeConstructor, TypeProjection>()
for (typeParameter in original.typeParameters) {
@@ -266,8 +266,8 @@ public class JetPsiFactory(private val project: Project) {
val function = createFunction("fun foo() { when(12) { " + entryText + " } }")
val whenEntry = PsiTreeUtil.findChildOfType(function, javaClass<JetWhenEntry>())
assert(whenEntry != null, "Couldn't generate when entry")
assert(entryText == whenEntry!!.getText(), "Generate when entry text differs from the given text")
assert(whenEntry != null) { "Couldn't generate when entry" }
assert(entryText == whenEntry!!.text) { "Generate when entry text differs from the given text" }
return whenEntry
}
@@ -41,7 +41,7 @@ public class KotlinStringLiteralTextEscaper(host: JetStringTemplateExpression):
is JetLiteralStringTemplateEntry -> {
val textRange = rangeInsideHost.intersection(childRange)!!.shiftRight(-childRange.getStartOffset())
outChars.append(child.getText(), textRange.getStartOffset(), textRange.getEndOffset())
textRange.getLength().times {
repeat(textRange.length) {
sourceOffsetsList.add(sourceOffset++)
}
}
@@ -52,7 +52,7 @@ public class KotlinStringLiteralTextEscaper(host: JetStringTemplateExpression):
}
val unescaped = child.getUnescapedValue()
outChars.append(unescaped)
unescaped.length().times {
repeat(unescaped.length()) {
sourceOffsetsList.add(sourceOffset)
}
sourceOffset += child.getTextLength()
@@ -23,7 +23,7 @@ import org.jetbrains.kotlin.lexer.JetModifierKeywordToken
public object ModifierMaskUtils {
init {
assert(MODIFIER_KEYWORDS_ARRAY.size() <= 32, "Current implementation depends on the ability to represent modifier list as bit mask")
assert(MODIFIER_KEYWORDS_ARRAY.size() <= 32) { "Current implementation depends on the ability to represent modifier list as bit mask" }
}
@JvmStatic
@@ -43,7 +43,7 @@ public object ModifierMaskUtils {
@JvmStatic
public fun maskHasModifier(mask: Int, modifierToken: JetModifierKeywordToken): Boolean {
val index = MODIFIER_KEYWORDS_ARRAY.indexOf(modifierToken)
assert(index >= 0, "All JetModifierKeywordTokens should be present in MODIFIER_KEYWORDS_ARRAY")
assert(index >= 0) { "All JetModifierKeywordTokens should be present in MODIFIER_KEYWORDS_ARRAY" }
return (mask and (1 shl index)) != 0
}
@@ -65,7 +65,7 @@ public class TypeResolver(
}
private fun resolveType(c: TypeResolutionContext, typeReference: JetTypeReference): JetType {
assert(!c.allowBareTypes, "Use resolvePossiblyBareType() when bare types are allowed")
assert(!c.allowBareTypes) { "Use resolvePossiblyBareType() when bare types are allowed" }
return resolvePossiblyBareType(c, typeReference).getActualType()
}
@@ -38,7 +38,7 @@ public class ResolutionTaskHolder<D : CallableDescriptor, F : D>(
}
private fun assertNotFinished() {
assert(internalTasks == null, "Can't add candidates after the resulting tasks were computed.")
assert(internalTasks == null) { "Can't add candidates after the resulting tasks were computed." }
}
public fun getTasks(): List<ResolutionTask<D, F>> {
@@ -328,7 +328,7 @@ public class TaskPrioritizer(
// For 'a.foo()' where foo has function type,
// a is explicitReceiver, foo is variableReceiver.
val variableReceiver = c.context.call.getDispatchReceiver()
assert(variableReceiver.exists(), "'Invoke' call hasn't got variable receiver")
assert(variableReceiver.exists()) { "'Invoke' call hasn't got variable receiver" }
// For invocation a.foo() explicit receiver 'a'
// can be a receiver for 'foo' variable
@@ -453,8 +453,8 @@ private class ConstantExpressionEvaluatorVisitor(
if (check == emptyUnaryFun) {
return result
}
assert (isIntegerType(receiver.value), "Only integer constants should be checked for overflow")
assert (name == "minus", "Only negation should be checked for overflow")
assert(isIntegerType(receiver.value)) { "Only integer constants should be checked for overflow" }
assert(name == "minus") { "Only negation should be checked for overflow" }
if (receiver.value == result) {
trace.report(Errors.INTEGER_OVERFLOW.on(callExpression.getStrictParentOfType<JetExpression>() ?: callExpression))
@@ -790,13 +790,13 @@ private fun parseBoolean(text: String): Boolean {
private fun createCompileTimeConstantForEquals(result: Any?, operationReference: JetExpression, factory: ConstantValueFactory): ConstantValue<*>? {
if (result is Boolean) {
assert(operationReference is JetSimpleNameExpression, "This method should be called only for equals operations")
assert(operationReference is JetSimpleNameExpression) { "This method should be called only for equals operations" }
val operationToken = (operationReference as JetSimpleNameExpression).getReferencedNameElementType()
val value: Boolean = when (operationToken) {
JetTokens.EQEQ -> result
JetTokens.EXCLEQ -> !result
JetTokens.IDENTIFIER -> {
assert (operationReference.getReferencedNameAsName() == OperatorConventions.EQUALS, "This method should be called only for equals operations")
assert(operationReference.getReferencedNameAsName() == OperatorConventions.EQUALS) { "This method should be called only for equals operations" }
result
}
else -> throw IllegalStateException("Unknown equals operation token: $operationToken ${operationReference.getText()}")
@@ -808,7 +808,7 @@ private fun createCompileTimeConstantForEquals(result: Any?, operationReference:
private fun createCompileTimeConstantForCompareTo(result: Any?, operationReference: JetExpression, factory: ConstantValueFactory): ConstantValue<*>? {
if (result is Int) {
assert(operationReference is JetSimpleNameExpression, "This method should be called only for compareTo operations")
assert(operationReference is JetSimpleNameExpression) { "This method should be called only for compareTo operations" }
val operationToken = (operationReference as JetSimpleNameExpression).getReferencedNameElementType()
return when (operationToken) {
JetTokens.LT -> factory.createBooleanValue(result < 0)
@@ -816,7 +816,7 @@ private fun createCompileTimeConstantForCompareTo(result: Any?, operationReferen
JetTokens.GT -> factory.createBooleanValue(result > 0)
JetTokens.GTEQ -> factory.createBooleanValue(result >= 0)
JetTokens.IDENTIFIER -> {
assert (operationReference.getReferencedNameAsName() == OperatorConventions.COMPARE_TO, "This method should be called only for compareTo operations")
assert(operationReference.getReferencedNameAsName() == OperatorConventions.COMPARE_TO) { "This method should be called only for compareTo operations" }
return factory.createIntValue(result)
}
else -> throw IllegalStateException("Unknown compareTo operation token: $operationToken")
@@ -35,7 +35,7 @@ public class FileBasedPackageMemberDeclarationProvider(
override fun doCreateIndex(index: AbstractPsiBasedDeclarationProvider.Index) {
for (file in packageFiles) {
for (declaration in file.getDeclarations()) {
assert(fqName == file.getPackageFqName(), "Files declaration utils contains file with invalid package")
assert(fqName == file.getPackageFqName()) { "Files declaration utils contains file with invalid package" }
index.putToIndex(declaration)
}
}
@@ -109,7 +109,7 @@ public open class LazyClassMemberScope(
override fun conflict(fromSuper: CallableMemberDescriptor, fromCurrent: CallableMemberDescriptor) {
val declaration = DescriptorToSourceUtils.descriptorToDeclaration(fromCurrent) as JetDeclaration?
assert(declaration != null, "fromCurrent can not be a fake override")
assert(declaration != null) { "fromCurrent can not be a fake override" }
trace.report(Errors.CONFLICTING_OVERLOADS.on(declaration, fromCurrent, fromCurrent.getContainingDeclaration().getName().asString()))
}
})
@@ -248,7 +248,7 @@ public object LightClassUtil {
if (declaration is JetPropertyAccessor) {
val propertyParent = declaration.parent
assert(propertyParent is JetProperty, "JetProperty is expected to be parent of accessor")
assert(propertyParent is JetProperty) { "JetProperty is expected to be parent of accessor" }
declaration = propertyParent as JetProperty
}
@@ -44,7 +44,7 @@ public class CapturedTypeApproximationTest() : JetLiteFixture() {
override fun createEnvironment(): KotlinCoreEnvironment = createEnvironmentWithMockJdk(ConfigurationKind.JDK_ONLY)
public fun doTest(filePath: String, vararg substitutions: String) {
assert(substitutions.size() in 1..2, "Captured type approximation test requires substitutions for (T) or (T, R)")
assert(substitutions.size() in 1..2) { "Captured type approximation test requires substitutions for (T) or (T, R)" }
val oneTypeVariable = substitutions.size() == 1
val declarationsText = JetTestUtils.doLoadFile(File(getTestDataPath() + "/declarations.kt"))
@@ -141,7 +141,7 @@ public class CapturedTypeApproximationTest() : JetLiteFixture() {
fun addRandomVariants(vararg randomVariants: String) {
variants.addAll(randomVariants.map { digits -> digits.map { digit -> digit - '0' } })
}
assert (typePatterns.size() == 5, "Generated random variants below depend on size 5")
assert(typePatterns.size() == 5) { "Generated random variants below depend on size 5" }
//From 021 the following is generated: In<Inv<Out<T>>>, where In = typePatterns[0], Inv = typePatterns[2], Out = typePatterns[1]
addRandomVariants("021", "111", "230", "421", "322", "120", "411", "102", "401", "012")
addRandomVariants("4243", "3103", "3043", "2003", "4442", "4143", "1440", "0303", "1302", "1332")
@@ -51,8 +51,7 @@ class PartialBodyResolveFilter(
init {
assert(declaration.isAncestor(elementToResolve))
assert(!JetPsiUtil.isLocal(declaration),
"Should never be invoked on local declaration otherwise we may miss some local declarations with type Nothing")
assert(!JetPsiUtil.isLocal(declaration)) { "Should never be invoked on local declaration otherwise we may miss some local declarations with type Nothing" }
declaration.forEachDescendantOfType<JetCallableDeclaration> { declaration ->
if (declaration.getTypeReference().containsProbablyNothing()) {
@@ -445,7 +444,7 @@ class PartialBodyResolveFilter(
) {
init {
if (selectorName == null) {
assert(receiverName == null, "selectorName is allowed to be null only when receiverName is also null (which means 'this')")
assert(receiverName == null) { "selectorName is allowed to be null only when receiverName is also null (which means 'this')" }
}
}
@@ -93,7 +93,7 @@ public object JarUserDataManager {
private fun storeUserData(counter: JarBooleanPropertyCounter, localJarFile: VirtualFile,
hasFileWithProperty: Boolean?, timestamp: Long? = null) {
assert(localJarFile.isInLocalFileSystem)
assert((timestamp == null) == (hasFileWithProperty == null), "Using empty timestamp is only allowed for storing not counted value")
assert((timestamp == null) == (hasFileWithProperty == null)) { "Using empty timestamp is only allowed for storing not counted value" }
localJarFile.putUserData(counter.key,
PropertyData(hasFileWithProperty, timestamp ?: localJarFile.timeStamp))
@@ -53,7 +53,7 @@ public class IDELightClassGenerationSupport(private val project: Project) : Ligh
private val psiManager: PsiManager = PsiManager.getInstance(project)
override fun getContextForPackage(files: Collection<JetFile>): LightClassConstructionContext {
assert(!files.isEmpty(), "No files in package")
assert(!files.isEmpty()) { "No files in package" }
return getContextForFiles(files)
}
@@ -90,7 +90,7 @@ public class IDELightClassGenerationSupport(private val project: Project) : Ligh
}
override fun getContextForFacade(files: Collection<JetFile>): LightClassConstructionContext {
assert(!files.isEmpty(), "No files in facade")
assert(!files.isEmpty()) { "No files in facade" }
return getContextForFiles(files)
}
@@ -65,7 +65,7 @@ internal class ProjectResolutionFacade(
}, false)
fun getAnalysisResultsForElements(elements: Collection<JetElement>): AnalysisResult {
assert(elements.isNotEmpty(), "elements collection should not be empty")
assert(elements.isNotEmpty()) { "elements collection should not be empty" }
val slruCache = synchronized(analysisResults) {
analysisResults.getValue()!!
}
@@ -63,7 +63,7 @@ private fun Project.getOrCreateElementsToShorten(): MutableSet<ShorteningRequest
}
public fun JetElement.addToShorteningWaitSet(options: Options = Options.DEFAULT) {
assert (ApplicationManager.getApplication()!!.isWriteAccessAllowed(), "Write access needed")
assert(ApplicationManager.getApplication()!!.isWriteAccessAllowed()) { "Write access needed" }
val project = getProject()
val elementPointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(this)
project.getOrCreateElementsToShorten().add(ShorteningRequest(elementPointer, options))
@@ -132,8 +132,7 @@ private class ClassClsStubBuilder(
if (!isClass() || !classProto.hasPrimaryConstructor()) return
val primaryConstructorProto = classProto.getPrimaryConstructor()
assert(classProto.getPrimaryConstructor().hasData(),
"Primary constructor in class is always non-default, so data should not be empty")
assert(classProto.getPrimaryConstructor().hasData()) { "Primary constructor in class is always non-default, so data should not be empty" }
createCallableStub(classOrObjectStub, primaryConstructorProto.getData(), c, ProtoContainer(classProto, null, c.nameResolver))
}
@@ -91,7 +91,7 @@ public class KotlinSuppressIntentionAction(
private fun suppressAtExpression(caretBox: CaretBox<JetExpression>, id: String) {
val suppressAt = caretBox.expression
assert(suppressAt !is JetDeclaration, "Declarations should have been checked for above")
assert(suppressAt !is JetDeclaration) { "Declarations should have been checked for above" }
val parentheses = JetPsiPrecedences.getPrecedence(suppressAt) > JetPsiPrecedences.PRECEDENCE_OF_PREFIX_EXPRESSION
val placeholderText = "PLACEHOLDER_ID"
@@ -59,7 +59,7 @@ public class BuiltInsReferenceResolver(val project: Project, val startupManager:
}
private fun initialize() {
assert(moduleDescriptor == null, "Attempt to initialize twice")
assert(moduleDescriptor == null) { "Attempt to initialize twice" }
val jetBuiltInsFiles = getJetBuiltInsFiles()
@@ -33,7 +33,7 @@ data class DataForConversion private constructor(
fun prepare(copiedCode: CopiedJavaCode, project: Project): DataForConversion {
val startOffsets = copiedCode.startOffsets.clone()
val endOffsets = copiedCode.endOffsets.clone()
assert(startOffsets.size() == endOffsets.size(), "Must have the same size")
assert(startOffsets.size() == endOffsets.size()) { "Must have the same size" }
var fileText = copiedCode.fileText
var file = PsiFileFactory.getInstance(project).createFileFromText(JavaLanguage.INSTANCE, fileText) as PsiJavaFile
@@ -476,7 +476,7 @@ private fun createFileForDebugger(codeFragment: JetCodeFragment,
.joinToString("\n"))
val extractedFunctionText = extractedFunction.text
assert(extractedFunctionText != null, "Text of extracted function shouldn't be null")
assert(extractedFunctionText != null) { "Text of extracted function shouldn't be null" }
fileText = fileText.replace("!FUNCTION!", extractedFunction.text!!)
val jetFile = codeFragment.createJetFile("debugFile.kt", fileText)
@@ -58,7 +58,7 @@ public class DeprecatedCallableAddReplaceWithIntention : JetSelfTargetingRangeIn
override fun applyTo(element: JetCallableDeclaration, editor: Editor) {
val replaceWith = element.suggestReplaceWith()!!
assert('\n' !in replaceWith.expression && '\r' !in replaceWith.expression, "Formatted expression text should not contain \\n or \\r")
assert('\n' !in replaceWith.expression && '\r' !in replaceWith.expression) { "Formatted expression text should not contain \\n or \\r" }
val annotationEntry = element.deprecatedAnnotationWithNoReplaceWith()!!
val psiFactory = JetPsiFactory(element)
@@ -53,7 +53,7 @@ public class AddGenericUpperBoundFix(
}
override fun invoke(project: Project, editor: Editor?, file: JetFile) {
assert(element.extendsBound == null, "Don't know what to do with existing bounds")
assert(element.extendsBound == null) { "Don't know what to do with existing bounds" }
val typeReference = JetPsiFactory(project).createType(renderedUpperBound)
val insertedTypeReference = element.setExtendsBound(typeReference)!!
@@ -48,7 +48,7 @@ public class AddNameToArgumentFix(argument: JetValueArgument) : JetIntentionActi
override fun invoke(project: Project, editor: Editor?, file: JetFile) {
val possibleNames = calculatePossibleArgumentNames()
assert(possibleNames.isNotEmpty(), "isAvailable() should be checked before invoke()")
assert(possibleNames.isNotEmpty()) { "isAvailable() should be checked before invoke()" }
if (possibleNames.size() == 1 || editor == null || !editor.component.isShowing) {
addName(project, element, possibleNames.first())
}
@@ -204,7 +204,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
fun build() {
try {
assert (config.currentEditor != null, "Can't run build() without editor")
assert(config.currentEditor != null) { "Can't run build() without editor" }
if (finished) throw IllegalStateException("Current builder has already finished")
buildNext(config.callableInfos.iterator())
}
@@ -141,7 +141,7 @@ public abstract class CallableRefactoring<T: CallableDescriptor>(
return true
}
assert(!closestModifiableDescriptors.isEmpty(), "Should contain original declaration or some of its super declarations")
assert(!closestModifiableDescriptors.isEmpty()) { "Should contain original declaration or some of its super declarations" }
val deepestSuperDeclarations =
(callableDescriptor as? CallableMemberDescriptor)?.let { OverrideResolver.getDeepestSuperDeclarations(it) }
?: Collections.singletonList(callableDescriptor)
@@ -199,7 +199,7 @@ abstract class OutputValueBoxer(val outputValues: List<OutputValue>) {
val module: ModuleDescriptor
) : OutputValueBoxer(outputValues) {
init {
assert(outputValues.size() <= 3, "At most 3 output values are supported")
assert(outputValues.size() <= 3) { "At most 3 output values are supported" }
}
companion object {
@@ -128,7 +128,7 @@ public class MoveKotlinFileHandler : MoveFileHandler() {
val newDirectory = file.parent ?: return
val packageNameInfo = file.getPackageNameInfo(newDirectory, true) ?: return
val newPackageName = packageNameInfo.newPackageName
assert(newPackageName.isSafe, newPackageName)
assert(newPackageName.isSafe) { newPackageName }
file.packageDirective?.fqName = newPackageName.toSafe()
}
@@ -187,7 +187,7 @@ public class RenameKotlinPropertyProcessor : RenamePsiElementProcessor() {
}
if (descriptor != null) {
assert(descriptor is PropertyDescriptor, "Property descriptor is expected")
assert(descriptor is PropertyDescriptor) { "Property descriptor is expected" }
val supers = OverrideResolver.getDeepestSuperDeclarations(descriptor as PropertyDescriptor)
@@ -61,7 +61,7 @@ public class KotlinAnnotatedElementsSearcher : QueryExecutor<PsiModifierListOwne
private val LOG = Logger.getInstance("#com.intellij.psi.impl.search.AnnotatedMembersSearcher")
public fun processAnnotatedMembers(annClass: PsiClass, useScope: SearchScope, consumer: (JetDeclaration) -> Boolean): Boolean {
assert(annClass.isAnnotationType(), "Annotation type should be passed to annotated members search")
assert(annClass.isAnnotationType()) { "Annotation type should be passed to annotated members search" }
val annotationFQN = annClass.getQualifiedName()
assert(annotationFQN != null)
@@ -58,10 +58,8 @@ class LightClassesClasspathSortingTest : KotlinCodeInsightTestCase() {
assertNotNull(psiClass, "Can't find class for $fqName")
psiClass!!
assert(psiClass is KotlinLightClassForExplicitDeclaration || psiClass is KotlinLightClassForFacade,
"Should be an explicit light class, but was $fqName ${psiClass.javaClass}")
assert(psiClass !is KotlinLightClassForDecompiledDeclaration,
"Should not be decompiled light class: $fqName ${psiClass.javaClass}")
assert(psiClass is KotlinLightClassForExplicitDeclaration || psiClass is KotlinLightClassForFacade) { "Should be an explicit light class, but was $fqName ${psiClass.javaClass}" }
assert(psiClass !is KotlinLightClassForDecompiledDeclaration) { "Should not be decompiled light class: $fqName ${psiClass.javaClass}" }
}
private fun getProjectDescriptor(dir: String) =
@@ -308,7 +308,7 @@ public abstract class AbstractKotlinEvaluateExpressionTest : KotlinDebuggerTestB
private fun loadTestDirectivesPairs(fileContent: String, directivePrefix: String, expectedPrefix: String): List<Pair<String, String>> {
val directives = InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileContent, directivePrefix)
val expected = InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileContent, expectedPrefix)
assert(directives.size() == expected.size(), "Sizes of test directives are different")
assert(directives.size() == expected.size()) { "Sizes of test directives are different" }
return directives.zip(expected)
}
@@ -37,7 +37,7 @@ public abstract class AbstractUsageHighlightingTest: JetLightCodeInsightFixtureT
data.init()
val caret = document.getText().indexOf(CARET_TAG)
assert(caret != -1, "Caret marker '$CARET_TAG' expected")
assert(caret != -1) { "Caret marker '$CARET_TAG' expected" }
WriteCommandAction.runWriteCommandAction(myFixture.getProject()) {
document.deleteString(caret, caret + CARET_TAG.length())
@@ -83,7 +83,7 @@ class CodeBuilder(private val topElement: PsiElement?, private var docConverter:
return this
}
assert(text.indexOf('\r') < 0, "No '\\r' allowed")
assert(text.indexOf('\r') < 0) { "No '\\r' allowed" }
if (endOfLineCommentAtEnd) {
if (text[0] != '\n') builder.append('\n')
@@ -158,7 +158,7 @@ public class KotlinBuilder : ModuleLevelBuilder(BuilderCategory.SOURCE_PROCESSOR
val lookupTracker =
project.container.getChild(LOOKUP_TRACKER)?.let {
assert("true".equals(System.getProperty("kotlin.jps.tests"), ignoreCase = true), "LOOKUP_TRACKER allowed only for jps tests")
assert("true".equals(System.getProperty("kotlin.jps.tests"), ignoreCase = true)) { "LOOKUP_TRACKER allowed only for jps tests" }
it.data
} ?: LookupTracker.DO_NOTHING
@@ -549,7 +549,7 @@ public class KotlinJpsBuildTest : AbstractKotlinJpsBuildTestCase() {
val result = HashSet<String>()
for (file in files) {
val relativePath = FileUtil.getRelativePath(baseDir, file)
assert(relativePath != null, "relativePath should not be null")
assert(relativePath != null) { "relativePath should not be null" }
result.add(toSystemIndependentName(relativePath!!))
}
return result
@@ -581,7 +581,7 @@ public class KotlinJpsBuildTest : AbstractKotlinJpsBuildTestCase() {
assertCanceled(buildResult)
buildResult.assertSuccessful()
assert(interval < 8000, "expected time for canceled compilation < 8000 ms, but $interval")
assert(interval < 8000) { "expected time for canceled compilation < 8000 ms, but $interval" }
val module = myProject.getModules().get(0)
assertFilesNotExistInOutput(module, "foo/Foo.class")
@@ -73,7 +73,7 @@ public abstract class MultipleModulesTranslationTest(main: String) : BasicTest(m
override fun additionalJsFiles(ecmaVersion: EcmaVersion): List<String> {
val result = super.additionalJsFiles(ecmaVersion)
val dirName = getTestName(true)
assert(dependencies != null, "dependencies should not be null")
assert(dependencies != null) { "dependencies should not be null" }
for (moduleName in dependencies!!.keySet()) {
if (moduleName != MAIN_MODULE_NAME) {
@@ -86,7 +86,7 @@ public abstract class MultipleModulesTranslationTest(main: String) : BasicTest(m
private fun readModuleDependencies(testDataDir: String): Map<String, List<String>> {
val dependenciesTxt = upsearchFile(testDataDir, "dependencies.txt")
assert(dependenciesTxt.isFile(), "moduleDependencies should not be null")
assert(dependenciesTxt.isFile()) { "moduleDependencies should not be null" }
val result = LinkedHashMap<String, List<String>>()
for (line in dependenciesTxt.readLines()) {
@@ -100,7 +100,7 @@ fun TranslationContext.getCallInfo(resolvedCall: ResolvedCall<out FunctionDescri
}
private fun TranslationContext.getDispatchReceiver(receiverValue: ReceiverValue): JsExpression {
assert(receiverValue.exists(), "receiverValue must be exist here")
assert(receiverValue.exists()) { "receiverValue must be exist here" }
return getDispatchReceiver(getReceiverParameterForReceiver(receiverValue))
}
@@ -86,7 +86,7 @@ private fun translateCall(context: TranslationContext,
explicitReceivers: ExplicitReceivers
): JsExpression {
if (resolvedCall is VariableAsFunctionResolvedCall) {
assert(explicitReceivers.extensionReceiver == null, "VariableAsFunctionResolvedCall must have one receiver")
assert(explicitReceivers.extensionReceiver == null) { "VariableAsFunctionResolvedCall must have one receiver" }
val variableCall = resolvedCall.variableCall
if (variableCall.expectedReceivers()) {
val newReceiver = CallTranslator.translateGet(context, variableCall, explicitReceivers.extensionOrDispatchReceiver)
@@ -137,7 +137,7 @@ public class DelegationTranslator(
val jsFunction = JsFunction(context().getScopeForDescriptor(setterDescriptor.getContainingDeclaration()),
"setter for " + setterDescriptor.getName().asString())
assert(setterDescriptor.getValueParameters().size() == 1, "Setter must have 1 parameter")
assert(setterDescriptor.getValueParameters().size() == 1) { "Setter must have 1 parameter" }
val defaultParameter = JsParameter(jsFunction.getScope().declareTemporary())
val defaultParameterRef = defaultParameter.getName().makeRef()
@@ -119,7 +119,7 @@ private class PropertyTranslator(
return generateDelegatedGetterFunction(getterDescriptor, delegatedCall)
}
assert(!descriptor.isExtension, "Unexpected extension property $descriptor}")
assert(!descriptor.isExtension) { "Unexpected extension property $descriptor}" }
val scope = context().getScopeForDescriptor(getterDescriptor.getContainingDeclaration())
val result = backingFieldReference(context(), descriptor)
val body = JsBlock(JsReturn(result))
@@ -157,7 +157,7 @@ private class PropertyTranslator(
val containingScope = context().getScopeForDescriptor(setterDescriptor.getContainingDeclaration())
val function = JsFunction(containingScope, JsBlock(), accessorDescription(setterDescriptor))
assert(setterDescriptor.getValueParameters().size() == 1, "Setter must have 1 parameter")
assert(setterDescriptor.getValueParameters().size() == 1) { "Setter must have 1 parameter" }
val correspondingPropertyName = setterDescriptor.getCorrespondingProperty().getName().asString()
val valueParameter = function.addParameter(correspondingPropertyName).getName()
val withAliased = context().innerContextWithAliased(setterDescriptor.getValueParameters().get(0), valueParameter.makeRef())
@@ -172,7 +172,7 @@ private class PropertyTranslator(
(delegatedJsCall as JsInvocation).getArguments().set(0, receiver.makeRef())
}
} else {
assert(!descriptor.isExtension, "Unexpected extension property $descriptor}")
assert(!descriptor.isExtension) { "Unexpected extension property $descriptor}" }
val assignment = assignmentToBackingField(withAliased, descriptor, valueParameter.makeRef())
function.addStatement(assignment.makeStmt())
}
@@ -143,8 +143,8 @@ public class CallArgumentTranslator private constructor(
}
if (isNativeFunctionCall && hasSpreadOperator) {
assert(argsBeforeVararg != null, "argsBeforeVararg should not be null")
assert(concatArguments != null, "concatArguments should not be null")
assert(argsBeforeVararg != null) { "argsBeforeVararg should not be null" }
assert(concatArguments != null) { "concatArguments should not be null" }
concatArguments!!.addAll(result)
@@ -269,7 +269,7 @@ public class CallArgumentTranslator private constructor(
}
private fun concatArgumentsIfNeeded(concatArguments: List<JsExpression>): JsExpression {
assert(concatArguments.size() > 0, "concatArguments.size should not be 0")
assert(concatArguments.size() > 0) { "concatArguments.size should not be 0" }
if (concatArguments.size() > 1) {
return JsInvocation(JsNameRef("concat", concatArguments.get(0)), concatArguments.subList(1, concatArguments.size()))
@@ -281,7 +281,7 @@ public class CallArgumentTranslator private constructor(
}
private fun prepareConcatArguments(arguments: List<ValueArgument>, list: List<JsExpression>): MutableList<JsExpression> {
assert(arguments.size() != 0, "arguments.size should not be 0")
assert(arguments.size() != 0) { "arguments.size should not be 0" }
assert(arguments.size() == list.size()) { "arguments.size: " + arguments.size() + " != list.size: " + list.size() }
val concatArguments = SmartList<JsExpression>()
@@ -127,7 +127,7 @@ object CallableReferenceTranslator {
private fun translateForExtensionFunction(descriptor: FunctionDescriptor, context: TranslationContext): JsExpression {
val receiverParameterDescriptor = descriptor.getExtensionReceiverParameter()
assert(receiverParameterDescriptor != null, "receiverParameter for extension should not be null")
assert(receiverParameterDescriptor != null) { "receiverParameter for extension should not be null" }
val jsFunctionRef = ReferenceTranslator.translateAsFQReference(descriptor, context)
if (descriptor.getVisibility() == Visibilities.LOCAL) {