Review fixes after automatic code analysis

This commit is contained in:
Mikhail Glukhikh
2015-04-20 19:01:05 +03:00
parent 27625b04e1
commit e64dab0ae9
23 changed files with 62 additions and 56 deletions
@@ -534,6 +534,7 @@ public class ExpressionCodegen extends JetVisitor<StackValue, StackValue> implem
}
JetExpression loopRange = forExpression.getLoopRange();
assert loopRange != null;
JetType loopRangeType = bindingContext.getType(loopRange);
assert loopRangeType != null;
Type asmLoopRangeType = asmType(loopRangeType);
@@ -3531,7 +3532,7 @@ public class ExpressionCodegen extends JetVisitor<StackValue, StackValue> implem
@Override
public StackValue visitArrayAccessExpression(@NotNull JetArrayAccessExpression expression, StackValue receiver) {
JetExpression array = expression.getArrayExpression();
JetType type = bindingContext.getType(array);
JetType type = array != null ? bindingContext.getType(array) : null;
Type arrayType = expressionType(array);
List<JetExpression> indices = expression.getIndexExpressions();
FunctionDescriptor operationDescriptor = (FunctionDescriptor) bindingContext.get(REFERENCE_TARGET, expression);
@@ -1266,7 +1266,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
result.addField((JetDelegatorByExpressionSpecifier) specifier, propertyDescriptor);
}
else {
JetType expressionType = bindingContext.getType(expression);
JetType expressionType = expression != null ? bindingContext.getType(expression) : null;
Type asmType =
expressionType != null ? typeMapper.mapType(expressionType) : typeMapper.mapType(getSuperClass(specifier));
result.addField((JetDelegatorByExpressionSpecifier) specifier, asmType, "$delegate_" + n);
@@ -283,6 +283,7 @@ public class PropertyCodegen {
}
private void generatePropertyDelegateAccess(JetProperty p, PropertyDescriptor propertyDescriptor) {
assert p.getDelegateExpression() != null: "Property must have a delegate expression here";
JetType delegateType = bindingContext.getType(p.getDelegateExpression());
if (delegateType == null) {
// If delegate expression is unresolved reference
@@ -515,6 +515,7 @@ class CodegenAnnotatingVisitor extends JetVisitorVoid {
int fieldNumber = mappings.size();
assert expression.getSubjectExpression() != null : "subject expression should be not null in a valid when by enums";
JetType type = bindingContext.getType(expression.getSubjectExpression());
assert type != null : "should not be null in a valid when by enums";
ClassDescriptor classDescriptor = (ClassDescriptor) type.getConstructor().getDeclarationDescriptor();
@@ -130,6 +130,7 @@ abstract public class SwitchCodegen {
}
protected void generateNullCheckIfNeeded() {
assert expression.getSubjectExpression() != null : "subject expression can't be null";
JetType subjectJetType = bindingContext.getType(expression.getSubjectExpression());
assert subjectJetType != null : "subject type can't be null (i.e. void)";
@@ -228,7 +228,7 @@ public class JavaNullabilityWarningsChecker : AdditionalTypeChecker {
when (expression.getOperationToken()) {
JetTokens.ELVIS -> {
val baseExpression = expression.getLeft()
val baseExpressionType = c.trace.getType(baseExpression) ?: return
val baseExpressionType = baseExpression?.let{ c.trace.getType(it) } ?: return
doIfNotNull(
DataFlowValueFactory.createDataFlowValue(baseExpression, baseExpressionType, c),
c
@@ -111,8 +111,7 @@ public final class WhenChecker {
for (JetWhenEntry entry : expression.getEntries()) {
for (JetWhenCondition condition : entry.getConditions()) {
if (condition instanceof JetWhenConditionWithExpression) {
JetType type = trace.getBindingContext().getType(((JetWhenConditionWithExpression) condition).getExpression()
);
JetType type = trace.getBindingContext().getType(((JetWhenConditionWithExpression) condition).getExpression());
if (type != null && KotlinBuiltIns.isNothingOrNullableNothing(type)) {
return true;
}
@@ -76,6 +76,7 @@ public interface BindingContext {
}
@Nullable
@Override
public JetType getType(@NotNull JetExpression expression) {
return null;
}
@@ -65,8 +65,8 @@ public class CompositeBindingContext private (
) : Diagnostics {
override fun iterator(): Iterator<Diagnostic> {
val emptyStream = listOf<Diagnostic>().stream()
return delegates.fold(emptyStream, { r, t -> r + t.stream() }).iterator()
val emptyStream = listOf<Diagnostic>().sequence()
return delegates.fold(emptyStream, { r, t -> r + t.sequence() }).iterator()
}
override val modificationTracker = object : ModificationTracker {
@@ -229,7 +229,7 @@ public class CallCompleter(
val deparenthesized = ArgumentTypeResolver.getLastElementDeparenthesized(expression, context)
if (deparenthesized == null) return
val recordedType = context.trace.getType(expression)
val recordedType = expression?.let { context.trace.getType(it) }
var updatedType: JetType? = recordedType
val results = completeCallForArgument(deparenthesized, context)
@@ -297,7 +297,7 @@ public class CallCompleter(
val expressions = ArrayList<JetExpression>()
var expression: JetExpression? = argumentExpression
while (expression != null) {
expressions.add(expression!!)
expressions.add(expression)
expression = deparenthesizeOrGetSelector(expression)
}
expressions.forEach { expression ->
@@ -94,7 +94,7 @@ public fun Call.getValueArgumentForExpression(expression: JetExpression): ValueA
else -> null
}
}
fun JetElement.isParenthesizedExpression() = stream(this) { it.deparenthesizeStructurally() }.any { it == expression }
fun JetElement.isParenthesizedExpression() = sequence(this) { it.deparenthesizeStructurally() }.any { it == expression }
return getValueArguments().firstOrNull { it?.getArgumentExpression()?.isParenthesizedExpression() ?: false }
}
@@ -475,7 +475,7 @@ private fun hasLongSuffix(text: String) = text.endsWith('l') || text.endsWith('L
public fun parseLong(text: String): Long? {
try {
fun substringLongSuffix(s: String) = if (hasLongSuffix(text)) s.substring(0, s.length - 1) else s
fun substringLongSuffix(s: String) = if (hasLongSuffix(text)) s.substring(0, s.length() - 1) else s
fun parseLong(text: String, radix: Int) = java.lang.Long.parseLong(substringLongSuffix(text), radix)
return when {
@@ -248,7 +248,7 @@ class ExpectedInfos(
ifExpression.getElse() -> {
val ifExpectedInfo = calculate(ifExpression)
val thenType = bindingContext.getType(ifExpression.getThen())
val thenType = ifExpression.getThen()?.let { bindingContext.getType(it) }
if (thenType != null)
ifExpectedInfo?.filter { it.type.isSubtypeOf(thenType) }
else
@@ -357,7 +357,7 @@ class SmartCompletion(
}
else if (descriptor is ClassDescriptor && descriptor.getModality() != Modality.ABSTRACT) {
val constructors = descriptor.getConstructors().filter(visibilityFilter)
if (constructors.size == 1) {
if (constructors.size() == 1) {
//TODO: this code is to be changed if overloads to start work after ::
return toLookupElement(constructors.single())
}
@@ -410,7 +410,7 @@ class SmartCompletion(
val operationToken = binaryExpression.getOperationToken()
if (operationToken != JetTokens.IN_KEYWORD && operationToken != JetTokens.NOT_IN || expressionWithType != binaryExpression.getRight()) return null
val leftOperandType = bindingContext.getType(binaryExpression.getLeft()) ?: return null
val leftOperandType = binaryExpression.getLeft()?.let { bindingContext.getType(it) } ?: return null
val scope = bindingContext.get(BindingContext.RESOLUTION_SCOPE, expressionWithType)
val detector = TypesWithContainsDetector(scope, leftOperandType, project, moduleDescriptor)
@@ -461,7 +461,7 @@ class SmartCompletion(
val insertHandler: InsertHandler<LookupElement> = object : InsertHandler<LookupElement> {
override fun handleInsert(context: InsertionContext, item: LookupElement) {
context.getDocument().replaceString(context.getStartOffset(), context.getTailOffset(), typeText)
context.setTailOffset(context.getStartOffset() + typeText.length)
context.setTailOffset(context.getStartOffset() + typeText.length())
shortenReferences(context, context.getStartOffset(), context.getTailOffset())
}
}
@@ -158,16 +158,16 @@ public class CheckPartialBodyResolveAction : AnAction() {
e.getPresentation().setEnabled(selectedKotlinFiles(e).any())
}
private fun selectedKotlinFiles(e: AnActionEvent): Stream<JetFile> {
val virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return streamOf()
val project = CommonDataKeys.PROJECT.getData(e.getDataContext()) ?: return streamOf()
private fun selectedKotlinFiles(e: AnActionEvent): Sequence<JetFile> {
val virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return sequenceOf()
val project = CommonDataKeys.PROJECT.getData(e.getDataContext()) ?: return sequenceOf()
return allKotlinFiles(virtualFiles, project)
}
private fun allKotlinFiles(filesOrDirs: Array<VirtualFile>, project: Project): Stream<JetFile> {
private fun allKotlinFiles(filesOrDirs: Array<VirtualFile>, project: Project): Sequence<JetFile> {
val manager = PsiManager.getInstance(project)
return allFiles(filesOrDirs)
.stream()
.sequence()
.map { manager.findFile(it) as? JetFile }
.filterNotNull()
}
@@ -61,8 +61,8 @@ public class FindImplicitNothingAction : AnAction() {
private fun find(files: Collection<JetFile>, project: Project) {
val progressIndicator = ProgressManager.getInstance().getProgressIndicator()
val found = ArrayList<JetCallExpression>()
for ((i, file) in files.withIndices()) {
progressIndicator?.setText("Scanning files: $i of ${files.size} file. ${found.size} occurences found")
for ((i, file) in files.withIndex()) {
progressIndicator?.setText("Scanning files: $i of ${files.size()} file. ${found.size()} occurences found")
progressIndicator?.setText2(file.getVirtualFile().getPath())
val resolutionFacade = file.getResolutionFacade()
@@ -91,7 +91,7 @@ public class FindImplicitNothingAction : AnAction() {
}
})
progressIndicator?.setFraction((i + 1) / files.size.toDouble())
progressIndicator?.setFraction((i + 1) / files.size().toDouble())
}
SwingUtilities.invokeLater {
@@ -102,7 +102,7 @@ public class FindImplicitNothingAction : AnAction() {
UsageViewManager.getInstance(project).showUsages(array<UsageTarget>(), usages, presentation)
}
else {
Messages.showInfoMessage(project, "Not found in ${files.size} file(s)", "Not Found")
Messages.showInfoMessage(project, "Not found in ${files.size()} file(s)", "Not Found")
}
}
}
@@ -144,16 +144,16 @@ public class FindImplicitNothingAction : AnAction() {
e.getPresentation().setEnabled(selectedKotlinFiles(e).any())
}
private fun selectedKotlinFiles(e: AnActionEvent): Stream<JetFile> {
val virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return streamOf()
val project = CommonDataKeys.PROJECT.getData(e.getDataContext()) ?: return streamOf()
private fun selectedKotlinFiles(e: AnActionEvent): Sequence<JetFile> {
val virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return sequenceOf()
val project = CommonDataKeys.PROJECT.getData(e.getDataContext()) ?: return sequenceOf()
return allKotlinFiles(virtualFiles, project)
}
private fun allKotlinFiles(filesOrDirs: Array<VirtualFile>, project: Project): Stream<JetFile> {
private fun allKotlinFiles(filesOrDirs: Array<VirtualFile>, project: Project): Sequence<JetFile> {
val manager = PsiManager.getInstance(project)
return allFiles(filesOrDirs)
.stream()
.sequence()
.map { manager.findFile(it) as? JetFile }
.filterNotNull()
}
@@ -130,8 +130,8 @@ public class ConvertToExpressionBodyIntention : JetSelfTargetingOffsetIndependen
var child = element.getFirstChild()
while (child != null) {
if (containsReturn(child!!)) return true
child = child!!.getNextSibling()
if (containsReturn(child)) return true
child = child.getNextSibling()
}
return false
@@ -45,7 +45,8 @@ public class DeclarationUtils {
private static JetType getPropertyTypeIfNeeded(@NotNull JetProperty property) {
if (property.getTypeReference() != null) return null;
JetType type = ResolvePackage.analyze(property, BodyResolveMode.FULL).getType(property.getInitializer());
JetExpression initializer = property.getInitializer();
JetType type = initializer != null ? ResolvePackage.analyze(property, BodyResolveMode.FULL).getType(initializer) : null;
return type == null || type.isError() ? null : type;
}
@@ -118,22 +118,22 @@ public class JetFunctionParameterInfoHandler implements ParameterInfoHandlerWith
}
@Override
public JetValueArgumentList findElementForParameterInfo(CreateParameterInfoContext context) {
public JetValueArgumentList findElementForParameterInfo(@NotNull CreateParameterInfoContext context) {
return findCall(context);
}
@Override
public void showParameterInfo(@NotNull JetValueArgumentList element, CreateParameterInfoContext context) {
public void showParameterInfo(@NotNull JetValueArgumentList element, @NotNull CreateParameterInfoContext context) {
context.showHint(element, element.getTextRange().getStartOffset(), this);
}
@Override
public JetValueArgumentList findElementForUpdatingParameterInfo(UpdateParameterInfoContext context) {
public JetValueArgumentList findElementForUpdatingParameterInfo(@NotNull UpdateParameterInfoContext context) {
return findCallAndUpdateContext(context);
}
@Override
public void updateParameterInfo(@NotNull JetValueArgumentList argumentList, UpdateParameterInfoContext context) {
public void updateParameterInfo(@NotNull JetValueArgumentList argumentList, @NotNull UpdateParameterInfoContext context) {
if (context.getParameterOwner() != argumentList) context.removeHint();
int offset = context.getOffset();
ASTNode child = argumentList.getNode().getFirstChildNode();
@@ -201,7 +201,7 @@ public class JetFunctionParameterInfoHandler implements ParameterInfoHandlerWith
}
@Override
public void updateUI(Pair<? extends FunctionDescriptor, ResolutionFacade> itemToShow, ParameterInfoUIContext context) {
public void updateUI(Pair<? extends FunctionDescriptor, ResolutionFacade> itemToShow, @NotNull ParameterInfoUIContext context) {
//todo: when we will have ability to pass Array as vararg, implement such feature here too?
if (context == null || context.getParameterOwner() == null || !context.getParameterOwner().isValid()) {
context.setUIComponentEnabled(false);
@@ -373,7 +373,7 @@ public class JetFunctionParameterInfoHandler implements ParameterInfoHandlerWith
return null;
}
final JetSimpleNameExpression callNameExpression = getCallSimpleNameExpression(argumentList);
JetSimpleNameExpression callNameExpression = getCallSimpleNameExpression(argumentList);
if (callNameExpression == null) {
return null;
}
@@ -74,7 +74,8 @@ public class AddNameToArgumentFix extends JetIntentionAction<JetValueArgument> {
if (resolvedCall == null) return Collections.emptyList();
CallableDescriptor callableDescriptor = resolvedCall.getResultingDescriptor();
JetType type = context.getType(argument.getArgumentExpression());
JetExpression argExpression = argument.getArgumentExpression();
JetType type = argExpression != null ? context.getType(argExpression) : null;
Set<String> usedParameters = QuickFixUtil.getUsedParameters(callElement, null, callableDescriptor);
List<String> names = Lists.newArrayList();
for (ValueParameterDescriptor parameter: callableDescriptor.getValueParameters()) {
@@ -169,7 +170,7 @@ public class AddNameToArgumentFix extends JetIntentionAction<JetValueArgument> {
return new JetSingleIntentionActionFactory() {
@Nullable
@Override
public IntentionAction createAction(Diagnostic diagnostic) {
public IntentionAction createAction(@NotNull Diagnostic diagnostic) {
JetValueArgument argument = QuickFixUtil.getParentElementOfType(diagnostic, JetValueArgument.class);
if (argument == null) return null;
List<String> possibleNames = generatePossibleNames(argument);
@@ -166,7 +166,7 @@ public abstract class ChangeFunctionSignatureFix extends JetIntentionAction<PsiE
public static JetSingleIntentionActionFactory createFactoryForParametersNumberMismatch() {
return new JetSingleIntentionActionFactory() {
@Override
public ChangeFunctionSignatureFix createAction(Diagnostic diagnostic) {
public ChangeFunctionSignatureFix createAction(@NotNull Diagnostic diagnostic) {
DiagnosticWithParameters2<JetFunction, Integer, List<JetType>> diagnosticWithParameters =
EXPECTED_PARAMETERS_NUMBER_MISMATCH.cast(diagnostic);
JetFunction functionLiteral = diagnosticWithParameters.getPsiElement();
@@ -77,7 +77,7 @@ public class KotlinIntroduceVariableHandler extends KotlinIntroduceHandlerBase {
private static final String INTRODUCE_VARIABLE = JetRefactoringBundle.message("introduce.variable");
@Override
public void invoke(@NotNull final Project project, final Editor editor, PsiFile file, DataContext dataContext) {
public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull PsiFile file, DataContext dataContext) {
JetRefactoringUtil.SelectExpressionCallback callback = new JetRefactoringUtil.SelectExpressionCallback() {
@Override
public void run(@Nullable JetExpression expression) {
@@ -222,15 +222,15 @@ public class JetPsiUnifier(
fun checkArguments(): Status? {
val args1 = rc1.getResultingDescriptor()?.getValueParameters()?.map { rc1.getValueArguments()[it] } ?: Collections.emptyList()
val args2 = rc2.getResultingDescriptor()?.getValueParameters()?.map { rc2.getValueArguments()[it] } ?: Collections.emptyList()
if (args1.size != args2.size) return UNMATCHED
if (rc1.getCall().getValueArguments().size != args1.size || rc2.getCall().getValueArguments().size != args2.size) return null
if (args1.size() != args2.size()) return UNMATCHED
if (rc1.getCall().getValueArguments().size() != args1.size() || rc2.getCall().getValueArguments().size() != args2.size()) return null
return (args1.stream() zip args2.stream()).fold(MATCHED) { s, p ->
return (args1.sequence() zip args2.sequence()).fold(MATCHED) { s, p ->
val (arg1, arg2) = p
s and when {
arg1 == arg2 -> MATCHED
arg1 == null || arg2 == null -> UNMATCHED
else -> (arg1.getArguments().stream() zip arg2.getArguments().stream()).fold(MATCHED) { s, p ->
else -> (arg1.getArguments().sequence() zip arg2.getArguments().sequence()).fold(MATCHED) { s, p ->
s and matchArguments(p.first, p.second)
}
}
@@ -365,7 +365,7 @@ public class JetPsiUnifier(
val args1 = type1.getArguments()
val args2 = type2.getArguments()
if (args1.size != args2.size) return UNMATCHED
if (args1.size() != args2.size()) return UNMATCHED
if (!args1.zip(args2).all {
it.first.getProjectionKind() == it.second.getProjectionKind() && matchTypes(it.first.getType(), it.second.getType()) == MATCHED }
) return UNMATCHED
@@ -379,7 +379,7 @@ public class JetPsiUnifier(
private fun matchTypes(types1: Collection<JetType>, types2: Collection<JetType>): Boolean {
fun sortTypes(types: Collection<JetType>) = types.sortBy{ DescriptorRenderer.DEBUG_TEXT.renderType(it) }
if (types1.size != types2.size) return false
if (types1.size() != types2.size()) return false
return (sortTypes(types1) zip sortTypes(types2)).all { matchTypes(it.first, it.second) == MATCHED }
}
@@ -454,7 +454,7 @@ public class JetPsiUnifier(
private fun matchMultiDeclarations(e1: JetMultiDeclaration, e2: JetMultiDeclaration): Boolean {
val entries1 = e1.getEntries()
val entries2 = e2.getEntries()
if (entries1.size != entries2.size) return false
if (entries1.size() != entries2.size()) return false
return entries1.zip(entries2).all { p ->
val (entry1, entry2) = p
@@ -514,7 +514,7 @@ public class JetPsiUnifier(
val params2 = desc2.getValueParameters()
val zippedParams = params1.zip(params2)
val parametersMatch =
(params1.size == params2.size) && zippedParams.all { matchTypes(it.first.getType(), it.second.getType()) == MATCHED }
(params1.size() == params2.size()) && zippedParams.all { matchTypes(it.first.getType(), it.second.getType()) == MATCHED }
if (!parametersMatch) return UNMATCHED
zippedParams.forEach { declarationPatternsToTargets.putValue(it.first, it.second) }
@@ -554,7 +554,7 @@ public class JetPsiUnifier(
matchPair: (Pair<T, T>) -> Boolean
): Boolean {
val zippedParams = declarations1 zip declarations2
if (declarations1.size != declarations2.size || !zippedParams.all { matchPair(it) }) return false
if (declarations1.size() != declarations2.size() || !zippedParams.all { matchPair(it) }) return false
zippedParams.forEach { declarationPatternsToTargets.putValue(it.first, it.second) }
return true
@@ -607,7 +607,7 @@ public class JetPsiUnifier(
val delegationInfo1 = getDelegationOrderInfo(decl1)
val delegationInfo2 = getDelegationOrderInfo(decl2)
if (delegationInfo1.orderInsensitive.size != delegationInfo2.orderInsensitive.size) return UNMATCHED
if (delegationInfo1.orderInsensitive.size() != delegationInfo2.orderInsensitive.size()) return UNMATCHED
@outer
for (specifier1 in delegationInfo1.orderInsensitive) {
for (specifier2 in delegationInfo2.orderInsensitive) {
@@ -626,7 +626,7 @@ public class JetPsiUnifier(
val sortedMembers1 = resolveAndSortDeclarationsByDescriptor(membersInfo1.orderInsensitive)
val sortedMembers2 = resolveAndSortDeclarationsByDescriptor(membersInfo2.orderInsensitive)
if ((sortedMembers1.size != sortedMembers2.size)) return UNMATCHED
if ((sortedMembers1.size() != sortedMembers2.size())) return UNMATCHED
if (sortedMembers1.zip(sortedMembers2).any {
val (d1, d2) = it
(matchDeclarations(d1.first, d2.first, d1.second, d2.second) ?: doUnify(d1.first, d2.first)) == UNMATCHED
@@ -735,9 +735,9 @@ public class JetPsiUnifier(
fun doUnify(target: JetPsiRange, pattern: JetPsiRange): Status {
val targetElements = target.elements
val patternElements = pattern.elements
if (targetElements.size != patternElements.size) return UNMATCHED
if (targetElements.size() != patternElements.size()) return UNMATCHED
return (targetElements.stream() zip patternElements.stream()).fold(MATCHED) { s, p ->
return (targetElements.sequence() zip patternElements.sequence()).fold(MATCHED) { s, p ->
if (s != UNMATCHED) s and doUnify(p.first, p.second) else s
}
}
@@ -856,7 +856,7 @@ public class JetPsiUnifier(
return with(Context(target, pattern)) {
val status = doUnify(target, pattern)
when {
substitution.size != descriptorToParameter.size ->
substitution.size() != descriptorToParameter.size() ->
Unmatched
status == MATCHED ->
if (weakMatches.isEmpty()) StronglyMatched(substitution) else WeaklyMatched(substitution, weakMatches)