org.eclipse.xtext.ui.editor.quickfix.IssueResolutionAcceptor Java Examples

The following examples show how to use org.eclipse.xtext.ui.editor.quickfix.IssueResolutionAcceptor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: QuickfixCrossrefTestLanguageQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Fix(QuickfixCrossrefTestLanguageValidator.LOWERCASE)
public void fixLowercase(final Issue issue, IssueResolutionAcceptor acceptor) {
	acceptor.accept(issue, "fix lowercase", "fix lowercase", null, new ITextualMultiModification() {
		
		@Override
		public void apply(IModificationContext context) throws Exception {
			if (context instanceof IssueModificationContext) {
				Issue theIssue = ((IssueModificationContext) context).getIssue();
				IXtextDocument document = context.getXtextDocument();
				String upperCase = document.get(theIssue.getOffset(), theIssue.getLength()).toUpperCase();
				// uppercase + duplicate => allows offset change tests
				document.replace(theIssue.getOffset(), theIssue.getLength(), upperCase + "_" +upperCase);
			}
		}
	});
}
 
Example #2
Source File: XtextGrammarQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Fix(INVALID_PACKAGE_REFERENCE_INHERITED)
public void fixImportedPackageFromSuperGrammar(final Issue issue, IssueResolutionAcceptor acceptor) {
	if (issue.getData().length == 1)
		acceptor.accept(issue, 
				"Change to '" + issue.getData()[0] + "'", 
				"Fix the bogus package import\n" +
				"import '" + issue.getData()[0] + "'", NULL_QUICKFIX_IMAGE,
				new IModification() {
					@Override
					public void apply(IModificationContext context) throws BadLocationException {
						String replaceString = valueConverterService.toString(issue.getData()[0], "STRING");
						IXtextDocument document = context.getXtextDocument();
						String delimiter = document.get(issue.getOffset(), 1);
						if (!replaceString.startsWith(delimiter)) {
							replaceString = delimiter + replaceString.substring(1, replaceString.length() - 1) + delimiter; 
						}
						document.replace(issue.getOffset(), issue.getLength(), replaceString);
					}
				});
}
 
Example #3
Source File: ActionAddModification.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Create the quick fix if needed.
 *
 * <p>The user data contains the name of the container type, and the name of the new action.
 *
 * @param provider the quick fix provider.
 * @param issue the issue to fix.
 * @param acceptor the quick fix acceptor.
 */
public static void accept(SARLQuickfixProvider provider, Issue issue, IssueResolutionAcceptor acceptor) {
	final String[] data = issue.getData();
	if (data != null && data.length > 1) {
		final String actionName = data[1];
		final ActionAddModification modification = new ActionAddModification(actionName);
		modification.setIssue(issue);
		modification.setTools(provider);
		acceptor.accept(issue,
				MessageFormat.format(Messages.SARLQuickfixProvider_2, actionName),
				MessageFormat.format(Messages.SARLQuickfixProvider_3, actionName),
				JavaPluginImages.IMG_CORRECTION_ADD,
				modification,
				IProposalRelevance.ADD_UNIMPLEMENTED_METHODS);
	}
}
 
Example #4
Source File: CreateMemberQuickfixes.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected void newMethodQuickfixes(LightweightTypeReference containerType, String name, /* @Nullable */ LightweightTypeReference returnType,
	List<LightweightTypeReference> argumentTypes, XAbstractFeatureCall call, JvmDeclaredType callersType,
	final Issue issue, final IssueResolutionAcceptor issueResolutionAcceptor) {
	boolean isLocal = callersType == containerType.getType();
	boolean isStatic = isStaticAccess(call);
	boolean isAbstract = true;
	if(containerType.getType() instanceof JvmGenericType) {
		isAbstract = !((JvmGenericType) containerType.getType()).isInstantiateable();
	} else if(containerType.getType() instanceof JvmDeclaredType) {
		isAbstract = ((JvmDeclaredType) containerType.getType()).isAbstract();
	}
	if(containerType.getType() instanceof JvmDeclaredType) {
		JvmDeclaredType declaredType = (JvmDeclaredType) containerType.getType();
		newMethodQuickfix(declaredType, name, returnType, argumentTypes, isStatic, isAbstract, false, isLocal, call, issue, issueResolutionAcceptor);
	}
	if(!isLocal && !isStatic) {
		List<LightweightTypeReference> extensionMethodParameterTypes = newArrayList(argumentTypes);
		extensionMethodParameterTypes.add(0, containerType);
		newMethodQuickfix(callersType, name, returnType, extensionMethodParameterTypes, false, isAbstract, true, true, call, issue, issueResolutionAcceptor);
	}
}
 
Example #5
Source File: XtendQuickfixProvider.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Fix(IssueCodes.OBSOLETE_OVERRIDE)
public void fixObsoleteOverride(final Issue issue, IssueResolutionAcceptor acceptor) {
	acceptor.accept(issue, "Change 'override' to 'def'", "Removes 'override' from this function", "fix_indent.gif",
			new ISemanticModification() {
				@Override
				public void apply(EObject element, IModificationContext context) throws Exception {
					replaceKeyword(grammarAccess.getMethodModifierAccess().findKeywords("override").get(0), "def", element,
							context.getXtextDocument());
					if (element instanceof XtendFunction) {
						XtendFunction function = (XtendFunction) element;
						for (XAnnotation anno : Lists.reverse(function.getAnnotations())) {
							if (anno != null && anno.getAnnotationType() != null && Override.class.getName().equals(anno.getAnnotationType().getIdentifier())) {
								ICompositeNode node = NodeModelUtils.findActualNodeFor(anno);
								context.getXtextDocument().replace(node.getOffset(), node.getLength(), "");
							}
						}
					}
				}
			});
}
 
Example #6
Source File: XtendQuickfixProvider.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Fix(IssueCodes.WRONG_PACKAGE)
public void fixPackageName(final Issue issue, IssueResolutionAcceptor acceptor) {
	if (issue.getData() != null && issue.getData().length == 1) {
		final String expectedPackage = issue.getData()[0];
		acceptor.accept(issue, "Change package declaration to '" + expectedPackage + "'", "Change package declaration to '" + expectedPackage + "'", "package_obj.gif",
				new ISemanticModification() {
					@Override
					public void apply(EObject element, IModificationContext context) throws Exception {
						XtendFile file = (XtendFile) element;
						String newPackageName = isEmpty(expectedPackage) ? null : expectedPackage;
						String oldPackageName = file.getPackage();
						for(EObject obj: file.eResource().getContents()) {
							if (obj instanceof JvmDeclaredType) {
								JvmDeclaredType type = (JvmDeclaredType) obj;
								String typePackage = type.getPackageName();
								if (Objects.equal(typePackage, oldPackageName) || typePackage != null && typePackage.startsWith(oldPackageName + ".")) {
									type.internalSetIdentifier(null);
									type.setPackageName(newPackageName);
								}
							}
						}
						file.setPackage(newPackageName);
					}
		});
	}
}
 
Example #7
Source File: CheckCfgQuickfixProvider.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Fix severity by setting it to a legal value as is defined by severity range of referenced check. Legal
 * severities are passed as issue data (org.eclipse.xtext.validation.Issue#getData()).
 * 
 * @param issue
 *          the issue
 * @param acceptor
 *          the acceptor
 */
@Fix(IssueCodes.SEVERITY_NOT_ALLOWED)
public void fixSeverityToMaxSeverity(final Issue issue, final IssueResolutionAcceptor acceptor) {
  if (issue.getData() != null) {
    for (final String severityProposal : issue.getData()) {
      final String label = NLS.bind(Messages.CheckCfgQuickfixProvider_CORRECT_SEVERITY_LABEL, severityProposal);
      final String descn = NLS.bind(Messages.CheckCfgQuickfixProvider_CORRECT_SEVERITY_DESCN, severityProposal);

      acceptor.accept(issue, label, descn, NO_IMAGE, new IModification() {
        public void apply(final IModificationContext context) throws BadLocationException {
          IXtextDocument xtextDocument = context.getXtextDocument();
          xtextDocument.replace(issue.getOffset(), issue.getLength(), severityProposal);
        }
      });
    }
  }
}
 
Example #8
Source File: FormatQuickfixProvider.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Semantic quickfix setting the override flag for a rule.
 *
 * @param issue
 *          the issue
 * @param acceptor
 *          the acceptor
 */
@Fix(FormatJavaValidator.OVERRIDE_MISSING_CODE)
public void setOverride(final Issue issue, final IssueResolutionAcceptor acceptor) {
  acceptor.accept(issue, "Set override", "Set override flag.", null, new IModification() {
    @Override
    public void apply(final IModificationContext context) throws BadLocationException {
      context.getXtextDocument().modify(new IUnitOfWork<Void, XtextResource>() {
        @Override
        public java.lang.Void exec(final XtextResource state) {
          Rule rule = (Rule) state.getEObject(issue.getUriToProblem().fragment());
          rule.setOverride(true);
          return null;
        }
      });
    }
  });
}
 
Example #9
Source File: XtextGrammarQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Fix(XtextLinkingDiagnosticMessageProvider.UNRESOLVED_RULE)
public void fixUnresolvedRule(final Issue issue, IssueResolutionAcceptor acceptor) {
	final String ruleName = issue.getData()[0];
	acceptor.accept(issue, "Create rule '" + ruleName + "'", "Create rule '" + ruleName + "'", NULL_QUICKFIX_IMAGE,
			new ISemanticModification() {
				@Override
				public void apply(final EObject element, IModificationContext context) throws BadLocationException {
					AbstractRule abstractRule = EcoreUtil2.getContainerOfType(element, ParserRule.class);
					ICompositeNode node = NodeModelUtils.getNode(abstractRule);
					int offset = node.getEndOffset();
					String nl = context.getXtextDocument().getLineDelimiter(0);
					StringBuilder builder = new StringBuilder(nl+nl);
					if (abstractRule instanceof TerminalRule)
						builder.append("terminal ");
					String newRule = builder.append(ruleName).append(":" + nl + "\t" + nl + ";").toString();
					context.getXtextDocument().replace(offset, 0, newRule);
				}
			});
	createLinkingIssueResolutions(issue, acceptor);
}
 
Example #10
Source File: CreateJavaTypeQuickfixes.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void addQuickfixes(Issue issue, IssueResolutionAcceptor issueResolutionAcceptor,
		IXtextDocument xtextDocument, XtextResource resource, 
		EObject referenceOwner, EReference unresolvedReference)
		throws Exception {
	String typeString = (issue.getData() != null && issue.getData().length > 0) 
			? issue.getData()[0] 
			: xtextDocument.get(issue.getOffset(), issue.getLength());
	Pair<String, String> packageAndType = typeNameGuesser.guessPackageAndTypeName(referenceOwner, typeString);
	String packageName = packageAndType.getFirst();
	if(isEmpty(packageAndType.getSecond()))
		return;
	String typeName = packageAndType.getSecond();
	if (unresolvedReference == XbasePackage.Literals.XCONSTRUCTOR_CALL__CONSTRUCTOR) {
		if(((XConstructorCall)referenceOwner).getConstructor().eIsProxy())
			newJavaClassQuickfix(typeName, packageName, resource, issue, issueResolutionAcceptor);
	} else if(unresolvedReference == XbasePackage.Literals.XTYPE_LITERAL__TYPE
			|| unresolvedReference == TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE) {
		newJavaClassQuickfix(typeName, packageName, resource, issue, issueResolutionAcceptor);
		newJavaInterfaceQuickfix(typeName, packageName, resource, issue, issueResolutionAcceptor);
	} else if(unresolvedReference == XAnnotationsPackage.Literals.XANNOTATION__ANNOTATION_TYPE) {
		newJavaAnnotationQuickfix(typeName, packageName, resource, issue, issueResolutionAcceptor);
	}
}
 
Example #11
Source File: DotQuickfixProvider.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
private void provideQuickfixesInvalidArrowShapeModifier(Issue issue,
		String suffix, IssueResolutionAcceptor acceptor) {
	String[] issueData = issue.getData();
	String modifier = issueData[1];
	final int modifierIndex = Integer.parseInt(issueData[2]);

	acceptor.accept(issue, "Remove the '" + modifier + "' modifier.", //$NON-NLS-1$ //$NON-NLS-2$
			"Remove the invalid '" + modifier + "' modifier.", DELETE_IMAGE, //$NON-NLS-1$ //$NON-NLS-2$
			new ChangingDotAttributeValueSemanticModification() {
				@Override
				public String getNewValue(String currentValue) {
					return new StringBuilder(currentValue)
							.deleteCharAt(modifierIndex).toString();
				}
			});
}
 
Example #12
Source File: CreateXtendTypeQuickfixes.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected void newXtendAnnotationQuickfix(final String typeName, final String explicitPackage, final XtextResource resource, Issue issue,
		IssueResolutionAcceptor issueResolutionAcceptor) {
	String packageDescription = getPackageDescription(explicitPackage);
	issueResolutionAcceptor.accept(issue, "Create Xtend annotation '" + typeName + "'" + packageDescription,
			"Opens the new Xtend annotation wizard to create the type '" + typeName + "'" + packageDescription, "xtend_file.png",
			new IModification() {
				@Override
				public void apply(/* @Nullable */ IModificationContext context) throws Exception {
					runAsyncInDisplayThread(new Runnable() {
						@Override
						public void run() {
							NewElementWizard newXtendAnnotationWizard = newXtendAnnotationWizardProvider.get();
							WizardDialog dialog = createWizardDialog(newXtendAnnotationWizard);
							NewXtendAnnotationWizardPage page = (NewXtendAnnotationWizardPage) newXtendAnnotationWizard.getStartingPage();
							configureWizardPage(page, resource.getURI(), typeName, explicitPackage);
							dialog.open();
						}
					});
				}
			});
}
 
Example #13
Source File: DotQuickfixProvider.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
private void provideQuickfixesForDuplicatedStyleItem(Issue issue,
		IssueResolutionAcceptor acceptor) {
	final String styleItem = issue.getData()[1];

	String label = "Remove '" + styleItem + "' style attribute value."; //$NON-NLS-1$ //$NON-NLS-2$
	String description = "Remove the redundant '" + styleItem //$NON-NLS-1$
			+ "' style attribute value."; //$NON-NLS-1$

	ISemanticModification semanticModification = new ChangingDotAttributeValueSemanticModification() {
		@Override
		public String getNewValue(String currentValue) {
			return currentValue.replaceFirst(styleItem + ",", "").trim(); //$NON-NLS-1$ //$NON-NLS-2$
		}
	};

	acceptor.accept(issue, label, description, DELETE_IMAGE,
			semanticModification);
}
 
Example #14
Source File: QuickfixCrossrefTestLanguageQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Fix(QuickfixCrossrefTestLanguageValidator.BAD_NAME_IN_SUBELEMENTS)
public void fixBadNames(final Issue issue, IssueResolutionAcceptor acceptor) {
	acceptor.acceptMulti(issue, "Fix Bad Names", "Fix Bad Names", null, (Element main, ICompositeModificationContext<Element> ctx) -> {
		ctx.addModification(main.eContainer(), c -> {
			List<Element> siblings = (List<Element>) main.eContainer().eGet(main.eContainmentFeature());
			int index = siblings.indexOf(main);
			Element newEle = QuickfixCrossrefFactory.eINSTANCE.createElement();
			newEle.setName("newElement");
			siblings.add(index, newEle);
		});
		for (String s : issue.getData()[0].split(";")) {
			EObject ele = main.eResource().getEObject(s);
			Assert.assertTrue(ele instanceof Element);
			ctx.addModification((Element) ele, e -> {
				e.setName("goodname");
			});
		}
	});
}
 
Example #15
Source File: CreateXtendTypeQuickfixes.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected void newLocalXtendClassQuickfix(String typeName, XtextResource resource, Issue issue,
		IssueResolutionAcceptor issueResolutionAcceptor) {
	EObject eObject = resource.getEObject(issue.getUriToProblem().fragment());
	XtendTypeDeclaration xtendType = getAnnotationTarget(eObject);
	if(xtendType != null) {
		JvmDeclaredType inferredType = associations.getInferredType(xtendType);
		if(inferredType != null) {
			AbstractClassBuilder classBuilder = codeBuilderFactory.createClassBuilder(inferredType);
			classBuilder.setClassName(typeName);
			classBuilder.setVisibility(JvmVisibility.PUBLIC);
			classBuilder.setContext(xtendType);
			classBuilder.setImage("xtend_file.png");
			codeBuilderQuickfix.addQuickfix(classBuilder, "Create local Xtend class '" + typeName + "'", issue, issueResolutionAcceptor);
		}
	}
}
 
Example #16
Source File: CreateXtendTypeQuickfixes.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected void newXtendClassQuickfix(final String typeName, final String explicitPackage, final XtextResource resource, Issue issue,
		IssueResolutionAcceptor issueResolutionAcceptor) {
	String packageDescription = getPackageDescription(explicitPackage);
	issueResolutionAcceptor.accept(issue, "Create Xtend class '" + typeName + "'" + packageDescription,
			"Opens the new Xtend class wizard to create the type '" + typeName + "'" + packageDescription, "xtend_file.png",
			new IModification() {
				@Override
				public void apply(/* @Nullable */ IModificationContext context) throws Exception {
					runAsyncInDisplayThread(new Runnable() {
						@Override
						public void run() {
							NewElementWizard newXtendClassWizard = newXtendClassWizardProvider.get();
							WizardDialog dialog = createWizardDialog(newXtendClassWizard);
							NewXtendClassWizardPage page = (NewXtendClassWizardPage) newXtendClassWizard.getStartingPage();
							configureWizardPage(page, resource.getURI(), typeName, explicitPackage);
							dialog.open();
						}
					});
				}
			});
}
 
Example #17
Source File: CodeBuilderQuickfix.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public void addQuickfix(final ICodeBuilder builder, final String label, final Issue issue, final IssueResolutionAcceptor acceptor) {
  boolean _isValid = builder.isValid();
  if (_isValid) {
    IModification _switchResult = null;
    boolean _matched = false;
    if (builder instanceof ICodeBuilder.Xtend) {
      _matched=true;
      _switchResult = this.getXtendModification(((ICodeBuilder.Xtend)builder));
    }
    if (!_matched) {
      if (builder instanceof ICodeBuilder.Java) {
        _matched=true;
        _switchResult = this.getJavaModification(((ICodeBuilder.Java)builder));
      }
    }
    final IModification modification = _switchResult;
    acceptor.accept(issue, label, builder.getPreview(), builder.getImage(), modification);
  }
}
 
Example #18
Source File: CheckQuickfixProvider.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Fixes an illegally set default severity. The default severity must be within given severity range.
 *
 * @param issue
 *          the issue
 * @param acceptor
 *          the acceptor
 */
@Fix(IssueCodes.DEFAULT_SEVERITY_NOT_IN_RANGE)
public void fixIllegalDefaultSeverity(final Issue issue, final IssueResolutionAcceptor acceptor) {
  if (issue.getData() != null) {
    for (final String severityProposal : issue.getData()) {
      final String label = NLS.bind(Messages.CheckQuickfixProvider_DEFAULT_SEVERITY_FIX_LABEL, severityProposal);
      final String descn = NLS.bind(Messages.CheckQuickfixProvider_DEFAULT_SEVERITY_FIX_DESCN, severityProposal);

      acceptor.accept(issue, label, descn, NO_IMAGE, new IModification() {
        @Override
        public void apply(final IModificationContext context) throws BadLocationException {
          IXtextDocument xtextDocument = context.getXtextDocument();
          xtextDocument.replace(issue.getOffset(), issue.getLength(), severityProposal);
        }
      });
    }
  }
}
 
Example #19
Source File: N4JSPackageJsonQuickfixProviderExtension.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/** Registers all npms */
@Fix(IssueCodes.NON_REGISTERED_PROJECT)
public void registerNPMs(Issue issue, IssueResolutionAcceptor acceptor) {
	final String label = "Register npm(s)";
	final String description = "Registers all not registered npms so that they can be imported by modules.";

	N4Modification modification = new N4Modification() {
		@Override
		public Collection<? extends IChange> computeChanges(IModificationContext context, IMarker marker,
				int offset, int length, EObject element) throws Exception {

			Function<IProgressMonitor, IStatus> registerFunction = new Function<>() {
				@Override
				public IStatus apply(IProgressMonitor monitor) {
					indexSynchronizer.synchronizeNpms(monitor);
					return statusHelper.OK();
				}
			};
			wrapWithMonitor(label, "Error during registering of npm(s)", registerFunction);
			return Collections.emptyList();
		}
	};

	accept(acceptor, issue, label, description, null, modification);
}
 
Example #20
Source File: ReturnTypeAddModification.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Create the quick fix if needed.
 *
 * <p>User data contains the name of the expected type.
 *
 * @param provider the quick fix provider.
 * @param issue the issue to fix.
 * @param acceptor the quick fix acceptor.
 */
public static void accept(SARLQuickfixProvider provider, Issue issue, IssueResolutionAcceptor acceptor) {
	final String[] data = issue.getData();
	if (data != null && data.length > 0) {
		final String expectedType = data[0];
		final ReturnTypeAddModification modification = new ReturnTypeAddModification(expectedType);
		modification.setIssue(issue);
		modification.setTools(provider);
		acceptor.accept(issue,
				MessageFormat.format(Messages.SARLQuickfixProvider_13, expectedType),
				Messages.SARLQuickfixProvider_14,
				JavaPluginImages.IMG_CORRECTION_ADD,
				modification,
				IProposalRelevance.CHANGE_RETURN_TYPE);
	}
}
 
Example #21
Source File: DotHtmlLabelQuickfixDelegator.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
public void provideQuickfixes(Issue originalIssue, Issue subgrammarIssue,
		IssueResolutionAcceptor acceptor) {
	List<IssueResolution> resolutions = getResolutions(subgrammarIssue);
	for (IssueResolution issueResolution : resolutions) {
		acceptor.accept(originalIssue, issueResolution.getLabel(),
				issueResolution.getDescription(),
				issueResolution.getImage(), new ISemanticModification() {

					@Override
					public void apply(EObject element,
							IModificationContext context) throws Exception {
						Attribute attribute = (Attribute) element;
						String originalText = attribute.getValue()
								.toValue();
						String modifiedText = getModifiedText(originalText,
								issueResolution);
						attribute.setValue(ID.fromValue(modifiedText,
								ID.Type.HTML_STRING));
					}
				});
	}
}
 
Example #22
Source File: XtendQuickfixProvider.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Fix(IssueCodes.WRONG_FILE)
public void fixFileName(final Issue issue, IssueResolutionAcceptor acceptor) {
	if (issue.getData() != null && issue.getData().length == 1) {
		final String expectedFileName = issue.getData()[0];
		final IFile iFile = projectUtil.findFileStorage(issue.getUriToProblem(), true);
		final IPath pathToMoveTo = iFile.getParent().getFullPath().append(expectedFileName)
				.addFileExtension(iFile.getFileExtension());
		if (!iFile.getWorkspace().getRoot().exists(pathToMoveTo)) {
			final String label = "Rename file to '" + expectedFileName + ".xtend'";
			acceptor.accept(issue, label, label, "xtend_file.png", new IModification() {
				@Override
				public void apply(IModificationContext context) throws Exception {
					runAsyncInDisplayThread(new Runnable() {
						@Override
						public void run() {
							try {
								iFile.move(pathToMoveTo, IResource.KEEP_HISTORY, null);
							} catch (CoreException e) {
								logger.error(e);
							}
						}
					});
				}
			});
		}
	}
}
 
Example #23
Source File: XtendQuickfixProvider.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void createLinkingIssueQuickfixes(Issue issue, IssueResolutionAcceptor issueResolutionAcceptor, 
		IXtextDocument xtextDocument, XtextResource resource, 
		EObject referenceOwner, EReference unresolvedReference) throws Exception {
	javaTypeQuickfixes.addQuickfixes(issue, issueResolutionAcceptor, xtextDocument, resource, referenceOwner, unresolvedReference);
	createTypeQuickfixes.addQuickfixes(issue, issueResolutionAcceptor, xtextDocument, resource, referenceOwner, unresolvedReference);
	createMemberQuickfixes.addQuickfixes(issue, issueResolutionAcceptor, xtextDocument, resource, referenceOwner, unresolvedReference);
}
 
Example #24
Source File: CheckQuickfixProvider.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Removes a duplicate parameter definition.
 *
 * @param issue
 *          the issue
 * @param acceptor
 *          the acceptor
 */
@Fix(IssueCodes.DUPLICATE_PARAMETER_DEFINITION)
public void removeDuplicateParameterDefinition(final Issue issue, final IssueResolutionAcceptor acceptor) {
  acceptor.accept(issue, Messages.CheckQuickfixProvider_REMOVE_PARAM_DEF_LABEL, Messages.CheckQuickfixProvider_REMOVE_PARAM_DEF_DESCN, null, new ISemanticModification() {
    @Override
    public void apply(final EObject element, final IModificationContext context) {
      Check check = EcoreUtil2.getContainerOfType(element, Check.class);
      check.getFormalParameters().remove(element);
    }
  });
}
 
Example #25
Source File: XtendQuickfixProvider.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Fix(IssueCodes.API_TYPE_INFERENCE)
public void specifyTypeExplicitly(Issue issue, IssueResolutionAcceptor acceptor) {
	acceptor.accept(issue, "Infer type", "Infer type", null, new ISemanticModification() {
		@Override
		public void apply(EObject element, IModificationContext context) throws Exception {
			EStructuralFeature featureAfterType = null;
			JvmIdentifiableElement jvmElement = null;
			if (element instanceof XtendFunction) {
				XtendFunction function = (XtendFunction) element;
				if (function.getCreateExtensionInfo() == null) {
					featureAfterType = XtendPackage.Literals.XTEND_FUNCTION__NAME;
				} else {
					featureAfterType = XtendPackage.Literals.XTEND_FUNCTION__CREATE_EXTENSION_INFO;
				}
				jvmElement = associations.getDirectlyInferredOperation((XtendFunction) element);
			} else if (element instanceof XtendField) {
				featureAfterType = XtendPackage.Literals.XTEND_FIELD__NAME;
				jvmElement = associations.getJvmField((XtendField) element);
			}
			
			if (jvmElement != null) {
				LightweightTypeReference type = batchTypeResolver.resolveTypes(element).getActualType(jvmElement);
				INode node = Iterables.getFirst(NodeModelUtils.findNodesForFeature(element, featureAfterType), null);
				
				if (node == null) {
					throw new IllegalStateException("Could not determine node for " + element);
				}
				if (type == null) {
					throw new IllegalStateException("Could not determine type for " + element);
				}
				ReplacingAppendable appendable = appendableFactory.create(context.getXtextDocument(),
						(XtextResource) element.eResource(), node.getOffset(), 0);
				appendable.append(type);
				appendable.append(" ");
				appendable.commitChanges();
			}
		}
	});
}
 
Example #26
Source File: CheckQuickfixProvider.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Add explicit ID to a check, autogenerated from its label.
 *
 * @param issue
 *          the issue
 * @param acceptor
 *          the acceptor
 */
@Fix(IssueCodes.MISSING_ID_ON_CHECK)
public void addIdToCheck(final Issue issue, final IssueResolutionAcceptor acceptor) {
  acceptor.accept(issue, Messages.CheckQuickfixProvider_ADD_ID_LABEL, NLS.bind(Messages.CheckQuickfixProvider_ADD_ID_DESCN, CHECK), NO_IMAGE, (final EObject element, final IModificationContext context) -> {
    final Check check = EcoreUtil2.getContainerOfType(element, Check.class);
    if (check != null) {
      final String label = check.getLabel();
      final String id = CheckUtil.toIdentifier(label);
      check.setId(id);
    }
  });
}
 
Example #27
Source File: CheckQuickfixProvider.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Fixes the wrong package name.
 *
 * @param issue
 *          the issue
 * @param acceptor
 *          the acceptor
 */
@Fix(IssueCodes.WRONG_PACKAGE)
public void fixPackageName(final Issue issue, final IssueResolutionAcceptor acceptor) {
  acceptor.accept(issue, Messages.CheckQuickfixProvider_CORRECT_PKG_NAME_LABEL, Messages.CheckQuickfixProvider_CORRECT_PKG_NAME_DESCN, NO_IMAGE, new IModification() {
    @Override
    public void apply(final IModificationContext context) throws BadLocationException {
      IXtextDocument xtextDocument = context.getXtextDocument();
      final String packageName = resourceUtil.getNameOfContainingPackage(xtextDocument);
      if (packageName != null) {
        xtextDocument.replace(issue.getOffset(), issue.getLength(), packageName);
      }
    }
  });
}
 
Example #28
Source File: GamlQuickfixProvider.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
@Fix (IGamlIssue.WRONG_VALUE)
public void replaceValue(final Issue issue, final IssueResolutionAcceptor acceptor) {
	final String[] data = issue.getData();
	if (data == null || data.length == 0) { return; }
	final String value = data[0];
	acceptor.accept(issue, "Replace with " + value + "...", "", "",
			new Replace(issue.getOffset(), issue.getLength(), value));
}
 
Example #29
Source File: XbaseQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Filter quickfixes for types and constructors.
 */
@Override
public void createLinkingIssueResolutions(final Issue issue, final IssueResolutionAcceptor issueResolutionAcceptor) {
	final IModificationContext modificationContext = getModificationContextFactory().createModificationContext(
			issue);
	final IXtextDocument xtextDocument = modificationContext.getXtextDocument();
	if (xtextDocument != null) {
		xtextDocument.tryReadOnly(new CancelableUnitOfWork<Void, XtextResource>() {
			@Override
			public java.lang.Void exec(XtextResource state, CancelIndicator cancelIndicator) throws Exception {
				try {
					EObject target = state.getEObject(issue.getUriToProblem().fragment());
					EReference reference = getUnresolvedEReference(issue, target);
					if (reference != null && reference.getEReferenceType() != null) {
						createLinkingIssueQuickfixes(issue,
								getCancelableAcceptor(issueResolutionAcceptor, cancelIndicator), xtextDocument,
								state, target, reference);
					}
				} catch (WrappedException e) {
					// issue information seems to be out of sync, e.g. there is no
					// EObject with the given fragment
				}
				return null;
			}
		});
	}
}
 
Example #30
Source File: XbaseQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Fix(IssueCodes.REDUNDANT_CASE)
public void fixRedundantCase(final Issue issue, IssueResolutionAcceptor acceptor) {
	acceptor.accept(issue, "Remove redundant case.", "Remove redundant case.", null, new ReplaceModification(issue,
			""));
	acceptor.accept(issue, "Assign empty expression.", "Assign empty expression.", null,
			new ISemanticModification() {

				@Override
				public void apply(EObject element, IModificationContext context) throws Exception {
					XSwitchExpression switchExpression = EcoreUtil2.getContainerOfType(element,
							XSwitchExpression.class);
					if (switchExpression == null) {
						return;
					}
					XCasePart casePart = IterableExtensions.last(switchExpression.getCases());
					if (casePart == null || !(casePart.isFallThrough() && casePart.getThen() == null)) {
						return;
					}
					List<INode> nodes = NodeModelUtils.findNodesForFeature(casePart,
							XbasePackage.Literals.XCASE_PART__FALL_THROUGH);
					if (nodes.isEmpty()) {
						return;
					}
					INode firstNode = IterableExtensions.head(nodes);
					INode lastNode = IterableExtensions.last(nodes);
					int offset = firstNode.getOffset();
					int length = lastNode.getEndOffset() - offset;
					ReplacingAppendable appendable = appendableFactory.create(context.getXtextDocument(),
							(XtextResource) element.eResource(), offset, length);
					appendable.append(": {");
					appendable.increaseIndentation().newLine();
					appendable.decreaseIndentation().newLine().append("}");
					appendable.commitChanges();
				}

			});
}