use of org.eclipse.jdt.ls.core.internal.corrections.InnovationContext in project eclipse.jdt.ls by eclipse.
the class MoveHandler method getSelectedMemberDeclaration.
private static BodyDeclaration getSelectedMemberDeclaration(ICompilationUnit unit, CodeActionParams params) {
int start = DiagnosticsHelper.getStartOffset(unit, params.getRange());
int end = DiagnosticsHelper.getEndOffset(unit, params.getRange());
InnovationContext context = new InnovationContext(unit, start, end - start);
context.setASTRoot(CodeActionHandler.getASTRoot(unit));
ASTNode node = context.getCoveredNode();
if (node == null) {
node = context.getCoveringNode();
}
while (node != null && !(node instanceof BodyDeclaration)) {
node = node.getParent();
}
if (node != null && (node instanceof MethodDeclaration || node instanceof FieldDeclaration || node instanceof AbstractTypeDeclaration) && JdtFlags.isStatic((BodyDeclaration) node)) {
return (BodyDeclaration) node;
}
return null;
}
use of org.eclipse.jdt.ls.core.internal.corrections.InnovationContext in project eclipse.jdt.ls by eclipse.
the class InferSelectionHandler method inferSelectionsForRefactor.
public static List<SelectionInfo> inferSelectionsForRefactor(InferSelectionParams params) {
final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.context.getTextDocument().getUri());
if (unit == null) {
return null;
}
int start = DiagnosticsHelper.getStartOffset(unit, params.context.getRange());
int end = DiagnosticsHelper.getEndOffset(unit, params.context.getRange());
InnovationContext context = new InnovationContext(unit, start, end - start);
List<SelectionInfo> selectionCandidates = new ArrayList<SelectionInfo>();
ASTNode parent = context.getCoveringNode();
try {
if (RefactorProposalUtility.EXTRACT_METHOD_COMMAND.equals(params.command)) {
while (parent != null && parent instanceof Expression) {
if (parent instanceof ParenthesizedExpression) {
parent = parent.getParent();
continue;
}
ExtractMethodRefactoring refactoring = new ExtractMethodRefactoring(context.getASTRoot(), parent.getStartPosition(), parent.getLength());
if (refactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
selectionCandidates.add(new SelectionInfo(parent.toString(), parent.getStartPosition(), parent.getLength()));
}
parent = parent.getParent();
}
} else if (RefactorProposalUtility.EXTRACT_VARIABLE_ALL_OCCURRENCE_COMMAND.equals(params.command) || RefactorProposalUtility.EXTRACT_VARIABLE_COMMAND.equals(params.command)) {
while (parent != null && parent instanceof Expression) {
if (parent instanceof ParenthesizedExpression) {
parent = parent.getParent();
continue;
}
ExtractTempRefactoring refactoring = new ExtractTempRefactoring(context.getASTRoot(), parent.getStartPosition(), parent.getLength());
if (refactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
selectionCandidates.add(new SelectionInfo(parent.toString(), parent.getStartPosition(), parent.getLength()));
}
parent = parent.getParent();
}
} else if (RefactorProposalUtility.EXTRACT_CONSTANT_COMMAND.equals(params.command)) {
while (parent != null && parent instanceof Expression) {
if (parent instanceof ParenthesizedExpression) {
parent = parent.getParent();
continue;
}
ExtractConstantRefactoring refactoring = new ExtractConstantRefactoring(context.getASTRoot(), parent.getStartPosition(), parent.getLength());
if (refactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
selectionCandidates.add(new SelectionInfo(parent.toString(), parent.getStartPosition(), parent.getLength()));
}
parent = parent.getParent();
}
} else if (RefactorProposalUtility.EXTRACT_FIELD_COMMAND.equals(params.command)) {
while (parent != null && parent instanceof Expression) {
if (parent instanceof ParenthesizedExpression) {
parent = parent.getParent();
continue;
}
ExtractFieldRefactoring refactoring = new ExtractFieldRefactoring(context.getASTRoot(), parent.getStartPosition(), parent.getLength());
if (refactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
List<String> scopes = RefactorProposalUtility.getInitializeScopes(refactoring);
if (!scopes.isEmpty()) {
selectionCandidates.add(new SelectionInfo(parent.toString(), parent.getStartPosition(), parent.getLength(), scopes));
}
}
parent = parent.getParent();
}
}
} catch (CoreException e) {
// do nothing.
}
if (selectionCandidates.size() == 0) {
return null;
}
return selectionCandidates;
}
use of org.eclipse.jdt.ls.core.internal.corrections.InnovationContext in project eclipse.jdt.ls by eclipse.
the class PrepareRenameHandler method prepareRename.
public Either<Range, PrepareRenameResult> prepareRename(TextDocumentPositionParams params, IProgressMonitor monitor) {
final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.getTextDocument().getUri());
if (unit != null) {
try {
OccurrencesFinder finder = new OccurrencesFinder();
CompilationUnit ast = CoreASTProvider.getInstance().getAST(unit, CoreASTProvider.WAIT_YES, monitor);
if (ast != null) {
int offset = JsonRpcHelpers.toOffset(unit.getBuffer(), params.getPosition().getLine(), params.getPosition().getCharacter());
String error = finder.initialize(ast, offset, 0);
if (error == null) {
OccurrenceLocation[] occurrences = finder.getOccurrences();
if (occurrences != null) {
for (OccurrenceLocation loc : occurrences) {
if (monitor.isCanceled()) {
return Either.forLeft(new Range());
}
if (loc.getOffset() <= offset && loc.getOffset() + loc.getLength() >= offset) {
InnovationContext context = new InnovationContext(unit, loc.getOffset(), loc.getLength());
context.setASTRoot(ast);
ASTNode node = context.getCoveredNode();
// Rename package is not fully supported yet.
if (!isBinaryOrPackage(node)) {
return Either.forLeft(JDTUtils.toRange(unit, loc.getOffset(), loc.getLength()));
}
}
}
}
}
}
} catch (CoreException e) {
JavaLanguageServerPlugin.logException("Problem computing occurrences for" + unit.getElementName() + " in prepareRename", e);
}
}
throw new ResponseErrorException(new ResponseError(ResponseErrorCode.InvalidRequest, "Renaming this element is not supported.", null));
}
use of org.eclipse.jdt.ls.core.internal.corrections.InnovationContext in project eclipse.jdt.ls by eclipse.
the class GetRefactorEditHandler method getEditsForRefactor.
public static RefactorWorkspaceEdit getEditsForRefactor(GetRefactorEditParams params) {
final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.context.getTextDocument().getUri());
if (unit == null) {
return null;
}
int start = DiagnosticsHelper.getStartOffset(unit, params.context.getRange());
int end = DiagnosticsHelper.getEndOffset(unit, params.context.getRange());
InnovationContext context = new InnovationContext(unit, start, end - start);
context.setASTRoot(CodeActionHandler.getASTRoot(unit));
IProblemLocationCore[] locations = CodeActionHandler.getProblemLocationCores(unit, params.context.getContext().getDiagnostics());
boolean problemsAtLocation = locations.length != 0;
String positionKey = DEFAULT_POSITION_KEY;
try {
Map formatterOptions = params.options == null ? null : FormatterHandler.getOptions(params.options, unit);
LinkedCorrectionProposal proposal = null;
if (RefactorProposalUtility.EXTRACT_VARIABLE_COMMAND.equals(params.command) || RefactorProposalUtility.EXTRACT_VARIABLE_ALL_OCCURRENCE_COMMAND.equals(params.command) || RefactorProposalUtility.EXTRACT_CONSTANT_COMMAND.equals(params.command)) {
SelectionInfo info = (params.commandArguments != null && !params.commandArguments.isEmpty()) ? JSONUtility.toModel(params.commandArguments.get(0), SelectionInfo.class) : null;
if (info != null) {
context = new InnovationContext(unit, info.offset, info.length);
}
proposal = (LinkedCorrectionProposal) getExtractVariableProposal(params.context, context, problemsAtLocation, params.command, formatterOptions);
} else if (RefactorProposalUtility.ASSIGN_VARIABLE_COMMAND.equals(params.command)) {
proposal = (LinkedCorrectionProposal) getAssignVariableProposal(params, context, problemsAtLocation, params.command, formatterOptions, locations);
} else if (RefactorProposalUtility.ASSIGN_FIELD_COMMAND.equals(params.command)) {
proposal = (LinkedCorrectionProposal) RefactorProposalUtility.getAssignFieldProposal(params.context, context, problemsAtLocation, formatterOptions, false, locations);
} else if (RefactorProposalUtility.EXTRACT_METHOD_COMMAND.equals(params.command)) {
SelectionInfo info = (params.commandArguments != null && !params.commandArguments.isEmpty()) ? JSONUtility.toModel(params.commandArguments.get(0), SelectionInfo.class) : null;
if (info != null) {
context = new InnovationContext(unit, info.offset, info.length);
}
proposal = (LinkedCorrectionProposal) getExtractMethodProposal(params.context, context, context.getCoveringNode(), problemsAtLocation, formatterOptions);
} else if (RefactorProposalUtility.CONVERT_VARIABLE_TO_FIELD_COMMAND.equals(params.command)) {
String initializeIn = (params.commandArguments != null && !params.commandArguments.isEmpty()) ? JSONUtility.toModel(params.commandArguments.get(0), String.class) : null;
proposal = (LinkedCorrectionProposal) RefactorProposalUtility.getConvertVariableToFieldProposal(params.context, context, problemsAtLocation, formatterOptions, initializeIn, false);
} else if (RefactorProposalUtility.EXTRACT_FIELD_COMMAND.equals(params.command)) {
String initializeIn = (params.commandArguments != null && !params.commandArguments.isEmpty()) ? JSONUtility.toModel(params.commandArguments.get(0), String.class) : null;
SelectionInfo info = (params.commandArguments != null && params.commandArguments.size() > 1) ? JSONUtility.toModel(params.commandArguments.get(1), SelectionInfo.class) : null;
if (info != null) {
context = new InnovationContext(unit, info.offset, info.length);
}
proposal = (LinkedCorrectionProposal) RefactorProposalUtility.getExtractFieldProposal(params.context, context, problemsAtLocation, formatterOptions, initializeIn, false);
} else if (InvertBooleanUtility.INVERT_VARIABLE_COMMAND.equals(params.command)) {
proposal = (LinkedCorrectionProposal) InvertBooleanUtility.getInvertVariableProposal(params.context, context, context.getCoveringNode(), false);
} else if (RefactorProcessor.CONVERT_ANONYMOUS_CLASS_TO_NESTED_COMMAND.equals(params.command)) {
proposal = RefactorProcessor.getConvertAnonymousToNestedProposal(params.context, context, context.getCoveringNode(), false);
positionKey = "type_name";
} else if (RefactorProposalUtility.INTRODUCE_PARAMETER_COMMAND.equals(params.command)) {
// String initializeIn = (params.commandArguments != null && !params.commandArguments.isEmpty()) ? JSONUtility.toModel(params.commandArguments.get(0), String.class) : null;
proposal = (LinkedCorrectionProposal) RefactorProposalUtility.getIntroduceParameterRefactoringProposals(params.context, context, context.getCoveringNode(), false, locations);
positionKey = null;
if (proposal instanceof RefactoringCorrectionProposal) {
RefactoringCorrectionProposal rcp = (RefactoringCorrectionProposal) proposal;
IntroduceParameterRefactoring refactoring = (IntroduceParameterRefactoring) rcp.getRefactoring();
ParameterInfo parameterInfo = refactoring.getAddedParameterInfo();
if (parameterInfo != null) {
positionKey = parameterInfo.getNewName();
}
}
}
if (proposal == null) {
return null;
}
Change change = proposal.getChange();
WorkspaceEdit edit = ChangeUtil.convertToWorkspaceEdit(change);
LinkedProposalModelCore linkedProposalModel = proposal.getLinkedProposalModel();
Command additionalCommand = null;
if (linkedProposalModel != null) {
LinkedProposalPositionGroupCore linkedPositionGroup = linkedProposalModel.getPositionGroup(positionKey, false);
if (linkedPositionGroup == null) {
Iterator<LinkedProposalPositionGroupCore> iter = linkedProposalModel.getPositionGroupCoreIterator();
while (iter.hasNext()) {
LinkedProposalPositionGroupCore lppgc = iter.next();
if (lppgc.getGroupId().startsWith(positionKey)) {
linkedPositionGroup = lppgc;
break;
}
}
}
PositionInformation highlightPosition = getFirstTrackedNodePositionBySequenceRank(linkedPositionGroup);
if (highlightPosition != null) {
int offset = highlightPosition.getOffset();
int length = highlightPosition.getLength();
RenamePosition renamePosition = new RenamePosition(JDTUtils.toURI(unit), offset, length);
additionalCommand = new Command("Rename", RENAME_COMMAND, Arrays.asList(renamePosition));
}
}
return new RefactorWorkspaceEdit(edit, additionalCommand);
} catch (CoreException e) {
// do nothing.
}
return null;
}
use of org.eclipse.jdt.ls.core.internal.corrections.InnovationContext in project eclipse.jdt.ls by eclipse.
the class CodeActionHandler method getCodeActionCommands.
public List<Either<Command, CodeAction>> getCodeActionCommands(CodeActionParams params, IProgressMonitor monitor) {
if (monitor.isCanceled()) {
return Collections.emptyList();
}
final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.getTextDocument().getUri());
if (unit == null || monitor.isCanceled()) {
return Collections.emptyList();
}
Map<String, Object> formattingOptions = ConfigurationHandler.getFormattingOptions(params.getTextDocument().getUri());
if (formattingOptions != null && !formattingOptions.isEmpty()) {
Object tabSizeValue = formattingOptions.get(Preferences.JAVA_CONFIGURATION_TABSIZE);
Object insertSpacesValue = formattingOptions.get(Preferences.JAVA_CONFIGURATION_INSERTSPACES);
Map<String, String> customOptions = new HashMap<>();
if (tabSizeValue != null) {
try {
int tabSize = Integer.parseInt(String.valueOf(tabSizeValue));
if (tabSize > 0) {
customOptions.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, Integer.toString(tabSize));
}
} catch (Exception ex) {
// do nothing
}
}
if (insertSpacesValue != null) {
boolean insertSpaces = Boolean.parseBoolean(String.valueOf(insertSpacesValue));
customOptions.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, insertSpaces ? JavaCore.SPACE : JavaCore.TAB);
}
if (!customOptions.isEmpty()) {
unit.setOptions(customOptions);
}
}
CompilationUnit astRoot = getASTRoot(unit, monitor);
if (astRoot == null || monitor.isCanceled()) {
return Collections.emptyList();
}
int start = DiagnosticsHelper.getStartOffset(unit, params.getRange());
int end = DiagnosticsHelper.getEndOffset(unit, params.getRange());
InnovationContext context = new InnovationContext(unit, start, end - start);
context.setASTRoot(astRoot);
List<Diagnostic> diagnostics = params.getContext().getDiagnostics().stream().filter((d) -> {
return JavaLanguageServerPlugin.SERVER_SOURCE_ID.equals(d.getSource());
}).collect(Collectors.toList());
IProblemLocationCore[] locations = getProblemLocationCores(unit, diagnostics);
if (monitor.isCanceled()) {
return Collections.emptyList();
}
List<String> codeActionKinds = new ArrayList<>();
if (params.getContext().getOnly() != null && !params.getContext().getOnly().isEmpty()) {
codeActionKinds.addAll(params.getContext().getOnly());
} else {
List<String> defaultCodeActionKinds = Arrays.asList(CodeActionKind.QuickFix, CodeActionKind.Refactor, JavaCodeActionKind.QUICK_ASSIST, CodeActionKind.Source);
codeActionKinds.addAll(defaultCodeActionKinds);
}
List<Either<Command, CodeAction>> codeActions = new ArrayList<>();
List<ChangeCorrectionProposal> proposals = new ArrayList<>();
ChangeCorrectionProposalComparator comparator = new ChangeCorrectionProposalComparator();
if (containsKind(codeActionKinds, CodeActionKind.QuickFix)) {
try {
codeActions.addAll(nonProjectFixProcessor.getCorrections(params, context, locations));
List<ChangeCorrectionProposal> quickfixProposals = this.quickFixProcessor.getCorrections(context, locations);
quickfixProposals.sort(comparator);
proposals.addAll(quickfixProposals);
} catch (CoreException e) {
JavaLanguageServerPlugin.logException("Problem resolving quick fix code actions", e);
}
}
if (monitor.isCanceled()) {
return Collections.emptyList();
}
if (containsKind(codeActionKinds, CodeActionKind.Refactor)) {
try {
List<ChangeCorrectionProposal> refactorProposals = this.refactorProcessor.getProposals(params, context, locations);
refactorProposals.sort(comparator);
proposals.addAll(refactorProposals);
} catch (CoreException e) {
JavaLanguageServerPlugin.logException("Problem resolving refactor code actions", e);
}
}
if (monitor.isCanceled()) {
return Collections.emptyList();
}
if (containsKind(codeActionKinds, JavaCodeActionKind.QUICK_ASSIST)) {
try {
List<ChangeCorrectionProposal> quickassistProposals = this.quickAssistProcessor.getAssists(params, context, locations);
quickassistProposals.sort(comparator);
proposals.addAll(quickassistProposals);
} catch (CoreException e) {
JavaLanguageServerPlugin.logException("Problem resolving quick assist code actions", e);
}
}
if (monitor.isCanceled()) {
return Collections.emptyList();
}
try {
for (ChangeCorrectionProposal proposal : proposals) {
Optional<Either<Command, CodeAction>> codeActionFromProposal = getCodeActionFromProposal(proposal, params.getContext());
if (codeActionFromProposal.isPresent() && !codeActions.contains(codeActionFromProposal.get())) {
codeActions.add(codeActionFromProposal.get());
}
}
} catch (CoreException e) {
JavaLanguageServerPlugin.logException("Problem converting proposal to code actions", e);
}
if (monitor.isCanceled()) {
return Collections.emptyList();
}
if (containsKind(codeActionKinds, CodeActionKind.Source)) {
codeActions.addAll(sourceAssistProcessor.getSourceActionCommands(params, context, locations, monitor));
}
if (monitor.isCanceled()) {
return Collections.emptyList();
}
populateDataFields(codeActions);
return codeActions;
}
Aggregations