InlineLocalVarSettings (final GrVariable variable, Editor editor, boolean invokedOnReference) { final String localName = variable.getName(); final Project project = variable.getProject(); GrExpression initializer = null; Instruction writeInstr = null; GroovyControlFlow flow = null; //search for initializer to inline if (invokedOnReference) { LOG.assertTrue(editor != null, "null editor but invokedOnReference==true"); final PsiReference ref = TargetElementUtil.findReference(editor); LOG.assertTrue(ref != null); PsiElement cur = ref.getElement(); if (cur instanceof GrReferenceExpression) { GrControlFlowOwner controlFlowOwner; do { controlFlowOwner = ControlFlowUtils.findControlFlowOwner(cur); if (controlFlowOwner == null) break; flow = ControlFlowUtils.getGroovyControlFlow(controlFlowOwner); final List<BitSet> writes = ControlFlowUtils.inferWriteAccessMap(flow, variable); final PsiElement finalCur = cur; Instruction instruction = ControlFlowUtils.findInstruction(finalCur, flow.getFlow()); LOG.assertTrue(instruction != null); final BitSet prev = writes.get(instruction.num()); if (prev.cardinality() == 1) { writeInstr = flow.getFlow()[prev.nextSetBit(0)]; final PsiElement element = writeInstr.getElement(); if (element instanceof GrVariable) { initializer = ((GrVariable)element).getInitializerGroovy(); } else if (element instanceof GrReferenceExpression) { initializer = TypeInferenceHelper.getInitializerFor((GrReferenceExpression)element); } } PsiElement old_cur = cur; if (controlFlowOwner instanceof GrClosableBlock) { cur = controlFlowOwner; } else { PsiElement parent = controlFlowOwner.getParent(); if (parent instanceof GrMember) cur = ((GrMember)parent).getContainingClass(); } if (cur == old_cur) break; } while (initializer == null); } } else { flow = ControlFlowUtils.getGroovyControlFlow(ControlFlowUtils.findControlFlowOwner(variable)); initializer = variable.getInitializerGroovy(); writeInstr = ContainerUtil.find(flow.getFlow(), instruction -> instruction.getElement() == variable); } if (initializer == null || writeInstr == null) { String message = GroovyRefactoringBundle.message("cannot.find.a.single.definition.to.inline.local.var"); CommonRefactoringUtil.showErrorHint(variable.getProject(), editor, message, getInlineVariable(), HelpID.INLINE_VARIABLE); return null; } int writeInstructionNumber = writeInstr.num(); if (ApplicationManager.getApplication().isUnitTestMode()) { return new InlineLocalVarSettings(initializer, writeInstructionNumber, flow); } final String question = GroovyRefactoringBundle.message("inline.local.variable.prompt.0.1", localName); RefactoringMessageDialog dialog = new RefactoringMessageDialog(getInlineVariable(), question, HelpID.INLINE_VARIABLE, "OptionPane.questionIcon", true, project); if (dialog.showAndGet()) { return new InlineLocalVarSettings(initializer, writeInstructionNumber, flow); } return null; }