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

The following examples show how to use org.eclipse.xtext.ui.editor.quickfix.Fix. 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: BslQuickFix.java    From ru.capralow.dt.bslls.validator with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Fix("bsl-language-server")
public void processBslLanguageServerDiagnostic(final Issue issue, final IssueResolutionAcceptor acceptor)
{
    String[] issueData = issue.getData();
    for (String issueLine : issueData)
    {
        if (issueLine.isEmpty())
            continue;

        String[] issueList = issueLine.split("[|]"); //$NON-NLS-1$

        String issueCommand = issueList[0];
        String issueMessage = issueList[1];
        Integer issueOffset = Integer.decode(issueList[2]);
        Integer issueLength = Integer.decode(issueList[3]);
        String issueNewText = issueList.length == 5 ? issueList[4] : ""; //$NON-NLS-1$

        acceptor.accept(issue, issueCommand, issueMessage, (String)null,
            new AbstractExternalQuickfixProvider.ExternalQuickfixModification<>(issue, EObject.class,
                module -> new ReplaceEdit(issueOffset, issueLength, issueNewText)));
    }
}
 
Example #2
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 #3
Source File: DotQuickfixProvider.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
@Fix(DotAttributes.STYLE__GCNE)
public void fixStyleAttributeValue(final Issue issue,
		IssueResolutionAcceptor acceptor) {

	String[] issueData = issue.getData();
	if (issueData == null || issueData.length < 2) {
		return;
	}
	String issueCode = issueData[0];

	switch (issueCode) {
	case DotStyleValidator.DEPRECATED_STYLE_ITEM:
		provideQuickfixesForDeprecatedStyleItem(issue, acceptor);
		break;
	case DotStyleValidator.DUPLICATED_STYLE_ITEM:
		provideQuickfixesForDuplicatedStyleItem(issue, acceptor);
		break;
	case DotStyleValidator.INVALID_STYLE_ITEM:
		provideQuickfixesForInvalidStyleItem(issue, acceptor);
	default:
		return;
	}
}
 
Example #4
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 #5
Source File: XtextGrammarQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Fix(EMPTY_KEYWORD)
public void replaceEmptyKeywordWithRuleName(final Issue issue, IssueResolutionAcceptor acceptor) {
	acceptor.accept(issue, "Replace empty keyword with rule name", "Replace empty keyword with rule name", NULL_QUICKFIX_IMAGE,
			new IModification() {
				@Override
				public void apply(IModificationContext context) throws Exception {
					final IXtextDocument document = context.getXtextDocument();
					final String containingRuleName = document.tryPriorityReadOnly(new IUnitOfWork<String, XtextResource>() {
						@Override
						public String exec(XtextResource state) throws Exception {
							return Optional.ofNullable(issue.getUriToProblem().fragment()).map(state::getEObject)
									.map(GrammarUtil::containingRule).map(AbstractRule::getName).map(Strings::toFirstLower)
									.orElse(null);
						}
					});
					if (containingRuleName != null) {
						final String quote = String.valueOf(document.getChar(issue.getOffset()));
						document.replace(issue.getOffset(), issue.getLength(), quote + containingRuleName + quote);
					}
				}
			});
}
 
Example #6
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 #7
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 #8
Source File: DotQuickfixProvider.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
@Fix(DotAttributes.LABEL__GCNE)
public void fixHtmlLabelAttributeValue(final Issue issue,
		IssueResolutionAcceptor acceptor) {
	String[] data = issue.getData();
	if (data == null || data.length < 4) {
		return;
	}

	String htmlLabelIssueCode = data[0];
	String htmlLabelUriToProblem = data[1];

	Issue.IssueImpl htmlLabelIssue = new Issue.IssueImpl();
	htmlLabelIssue.setCode(htmlLabelIssueCode);
	htmlLabelIssue.setData(data);
	htmlLabelIssue.setUriToProblem(URI.createURI(htmlLabelUriToProblem));

	new DotHtmlLabelQuickfixDelegator().provideQuickfixes(issue,
			htmlLabelIssue, acceptor);
}
 
Example #9
Source File: XbaseQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Fix(IssueCodes.OBSOLETE_CAST)
public void fixObsoletCast(final Issue issue, IssueResolutionAcceptor acceptor) {
	String fixup = "Remove unnecessary cast";
	acceptor.accept(issue, fixup, fixup, null, new IModification() {
		@Override
		public void apply(IModificationContext context) throws Exception {
			final IXtextDocument document = context.getXtextDocument();
			ReplaceRegion replacement = document.tryReadOnly(new IUnitOfWork<ReplaceRegion, XtextResource>() {

				@Override
				public ReplaceRegion exec(XtextResource state) throws Exception {
					EObject type = state.getEObject(issue.getUriToProblem().fragment());
					XCastedExpression cast = EcoreUtil2.getContainerOfType(type, XCastedExpression.class);
					INode castNode = NodeModelUtils.findActualNodeFor(cast);
					INode targetNode = NodeModelUtils.findActualNodeFor(cast.getTarget());
					return new ReplaceRegion(castNode.getTotalTextRegion(), targetNode.getText());
				}
			});
			if (replacement != null) {
				document.replace(replacement.getOffset(), replacement.getLength(), replacement.getText());
			}
		}
	});
}
 
Example #10
Source File: CheckQuickfixProvider.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Fixes the severity range order by setting the lower severity level kind first and the severity of higher severity level last.
 *
 * @param issue
 *          the issue
 * @param acceptor
 *          the acceptor
 */
@Fix(IssueCodes.ILLEGAL_SEVERITY_RANGE_ORDER)
public void fixSeverityRangeOrder(final Issue issue, final IssueResolutionAcceptor acceptor) {
  acceptor.accept(issue, Messages.CheckQuickfixProvider_FIX_SEVERITY_RANGE_ORDER_LABEL, Messages.CheckQuickfixProvider_FIX_SEVERITY_RANGE_ORDER_DESCN, NO_IMAGE, new ISemanticModification() {
    @Override
    public void apply(final EObject element, final IModificationContext context) {
      final Check check = EcoreUtil2.getContainerOfType(element, Check.class);
      if (check != null && check.getSeverityRange() != null) {
        final SeverityRange range = check.getSeverityRange();
        SeverityKind oldMinSeverity = range.getMinSeverity();
        range.setMinSeverity(range.getMaxSeverity());
        range.setMaxSeverity(oldMinSeverity);
      }
    }
  });
}
 
Example #11
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 #12
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 #13
Source File: N4JSPackageJsonQuickfixProviderExtension.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/** Changes the project type to {@link ProjectType#VALIDATION} */
@Fix(IssueCodes.OUTPUT_AND_SOURCES_FOLDER_NESTING)
public void changeProjectTypeToValidation(Issue issue, IssueResolutionAcceptor acceptor) {
	String validationPT = ProjectType.VALIDATION.getName().toLowerCase();
	String title = "Change project type to '" + validationPT + "'";
	String descr = "The project type '" + validationPT
			+ "' does not generate code. Hence, output and source folders can be nested.";

	accept(acceptor, issue, title, descr, null, new N4Modification() {
		@Override
		public Collection<? extends IChange> computeChanges(IModificationContext context, IMarker marker,
				int offset, int length, EObject element) throws Exception {

			Resource resource = element.eResource();
			ProjectDescription prjDescr = EcoreUtil2.getContainerOfType(element, ProjectDescription.class);
			Collection<IChange> changes = new LinkedList<>();
			changes.add(PackageJsonChangeProvider.setProjectType(resource, ProjectType.VALIDATION, prjDescr));
			return changes;
		}

		@Override
		public boolean supportsMultiApply() {
			return false;
		}
	});
}
 
Example #14
Source File: FormatQuickfixProvider.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Semantic quickfix removing the override flag for a rule.
 *
 * @param issue
 *          the issue
 * @param acceptor
 *          the acceptor
 */
@Fix(FormatJavaValidator.OVERRIDE_ILLEGAL_CODE)
public void removeOverride(final Issue issue, final IssueResolutionAcceptor acceptor) {
  acceptor.accept(issue, "Remove override", "Remove override.", 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(false);
          return null;
        }
      });
    }
  });
}
 
Example #15
Source File: DotQuickfixProvider.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Fix(DotAttributes.OUTPUTORDER__G)
public void fixOutputOrderAttributeValue(final Issue issue,
		IssueResolutionAcceptor acceptor) {
	String invalidValue = issue.getData()[0];
	provideQuickfixes(invalidValue, OutputMode.values(), "graph outputMode", //$NON-NLS-1$
			issue, acceptor);
}
 
Example #16
Source File: DotQuickfixProvider.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Fix(DotAttributes.LAYOUT__G)
public void fixLayoutAttributeValue(final Issue issue,
		IssueResolutionAcceptor acceptor) {
	String invalidValue = issue.getData()[0];
	provideQuickfixes(invalidValue, Layout.values(), "graph layout", issue, //$NON-NLS-1$
			acceptor);
}
 
Example #17
Source File: DotQuickfixProvider.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Fix(DotAttributes.CLUSTERRANK__G)
public void fixClusterRankAttributeValue(final Issue issue,
		IssueResolutionAcceptor acceptor) {
	String invalidValue = issue.getData()[0];
	provideQuickfixes(invalidValue, ClusterMode.values(),
			"graph clusterMode", issue, //$NON-NLS-1$
			acceptor);
}
 
Example #18
Source File: DotQuickfixProvider.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Fix(DotAttributes.PAGEDIR__G)
public void fixPagedirAttributeValue(final Issue issue,
		IssueResolutionAcceptor acceptor) {
	String invalidValue = issue.getData()[0];
	provideQuickfixes(invalidValue, Pagedir.values(), "graph pagedir", //$NON-NLS-1$
			issue, acceptor);
}
 
Example #19
Source File: DotQuickfixProvider.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Fix(DotAttributes.RANK__S)
public void fixRankAttributeValue(final Issue issue,
		IssueResolutionAcceptor acceptor) {
	String invalidValue = issue.getData()[0];
	provideQuickfixes(invalidValue, RankType.values(), "subgraph rankType", //$NON-NLS-1$
			issue, acceptor);
}
 
Example #20
Source File: DotQuickfixProvider.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Fix(DotAttributes.DIR__E)
public void fixDirAttributeValue(final Issue issue,
		IssueResolutionAcceptor acceptor) {
	String invalidValue = issue.getData()[0];
	provideQuickfixes(invalidValue, DirType.values(), "edge dir", issue, //$NON-NLS-1$
			acceptor);
}
 
Example #21
Source File: DotQuickfixProvider.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Fix(DotAttributes.RANKDIR__G)
public void fixRankdirAttributeValue(final Issue issue,
		IssueResolutionAcceptor acceptor) {
	String invalidValue = issue.getData()[0];
	provideQuickfixes(invalidValue, Rankdir.values(), "graph rankdir", //$NON-NLS-1$
			issue, acceptor);
}
 
Example #22
Source File: DotQuickfixProvider.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Fix(DotAttributes.SHAPE__N)
public void fixShapeAttributeValue(final Issue issue,
		IssueResolutionAcceptor acceptor) {
	String invalidValue = issue.getData()[0];
	provideQuickfixes(invalidValue, PolygonBasedNodeShape.VALUES,
			"node shape", issue, //$NON-NLS-1$
			acceptor);
	provideQuickfixes(invalidValue, RecordBasedNodeShape.VALUES,
			"node shape", issue, //$NON-NLS-1$
			acceptor);
}
 
Example #23
Source File: DotQuickfixProvider.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Fix(DotAttributes.COLORSCHEME__GCNE)
public void fixColorschemeAttributeValue(final Issue issue,
		IssueResolutionAcceptor acceptor) {
	// TODO: use "graph colorscheme", "node colorscheme", "edge colorscheme"
	// as suffix.
	String invalidValue = issue.getData()[0];
	provideQuickfixes(invalidValue, DotColors.getColorSchemes(),
			"colorscheme", //$NON-NLS-1$
			issue, acceptor);
}
 
Example #24
Source File: CheckCfgQuickfixProvider.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Removes a duplicate catalog configuration.
 * 
 * @param issue
 *          the issue
 * @param acceptor
 *          the acceptor
 */
@Fix(IssueCodes.DUPLICATE_CATALOG_CONFIGURATION)
public void removeDuplicateCatalogConfiguration(final Issue issue, final IssueResolutionAcceptor acceptor) {
  acceptor.accept(issue, Messages.CheckCfgQuickfixProvider_REMOVE_DUPLICATE_CATALOG_LABEL, Messages.CheckCfgQuickfixProvider_REMOVE_DUPLICATE_CATALOG_DESCN, null, new ISemanticModification() {
    public void apply(final EObject element, final IModificationContext context) {
      CheckConfiguration configuration = EcoreUtil2.getContainerOfType(element, CheckConfiguration.class);
      configuration.getLegacyCatalogConfigurations().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.MISSING_CONSTRUCTOR)
public void addConstuctorFromSuper(final Issue issue, IssueResolutionAcceptor acceptor) {
	if (issue.getData() != null) {
		for(int i=0; i<issue.getData().length; i+=2) {
			final URI constructorURI = URI.createURI(issue.getData()[i]);
			String javaSignature = issue.getData()[i+1];
			String xtendSignature = "new" + javaSignature.substring(javaSignature.indexOf('('));
			acceptor.accept(issue, "Add constructor " + xtendSignature, "Add constructor " + xtendSignature, "fix_indent.gif",
				new ISemanticModification() {
					@Override
					public void apply(EObject element, IModificationContext context) throws Exception {
						XtendClass clazz = (XtendClass) element;
						JvmGenericType inferredType = associations.getInferredType(clazz);
						ResolvedFeatures features = overrideHelper.getResolvedFeatures(inferredType);
						ReplacingAppendable appendable = appendableFactory.create(context.getXtextDocument(), (XtextResource) clazz.eResource(),
								insertionOffsets.getNewConstructorInsertOffset(null, clazz), 0, new OptionalParameters() {{ 
									ensureEmptyLinesAround = true;
									baseIndentationLevel = 1;	
								}});
						EObject constructor = clazz.eResource().getResourceSet().getEObject(constructorURI, true);
						if (constructor instanceof JvmConstructor) {
							superMemberImplementor.appendConstructorFromSuper(
									clazz,
									new ResolvedConstructor((JvmConstructor) constructor, features.getType()),
									appendable);
						}
						appendable.commitChanges();
					}
				});
		}
	}
}
 
Example #26
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 fixWrongFileRenameClass(final Issue issue, final IssueResolutionAcceptor acceptor) {
	URI uri = issue.getUriToProblem();
	String className = uri.trimFileExtension().lastSegment();
	String label = String.format("Rename class to '%s'", className);
	acceptor.accept(issue, label, label, null, (element, context) -> {
		context.getXtextDocument().modify(resource -> {
			IRenameElementContext renameContext = renameContextFactory.createRenameElementContext(element, null,
					new TextSelection(context.getXtextDocument(), issue.getOffset(), issue.getLength()), resource);
			final ProcessorBasedRefactoring refactoring = renameRefactoringProvider.getRenameRefactoring(renameContext);
			((RenameElementProcessor) refactoring.getProcessor()).setNewName(className);
			PlatformUI.getWorkbench().getActiveWorkbenchWindow().run(true, true, monitor -> {
				try {
					if (!refactoring.checkFinalConditions(monitor).isOK())
						return;
					Change change = refactoring.createChange(monitor);
					change.initializeValidationData(monitor);
					PerformChangeOperation performChangeOperation = new PerformChangeOperation(change);
					performChangeOperation.setUndoManager(RefactoringCore.getUndoManager(), refactoring.getName());
					performChangeOperation.setSchedulingRule(ResourcesPlugin.getWorkspace().getRoot());
					performChangeOperation.run(monitor);
				} catch (CoreException e) {
					logger.error(e);
				}
			});
			return null;
		});
	});
}
 
Example #27
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 #28
Source File: XtendQuickfixProvider.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Fix(IssueCodes.IMPLICIT_RETURN) 
public void fixImplicitReturn(final Issue issue, IssueResolutionAcceptor acceptor){
	acceptor.accept(issue, "Add \"return\" keyword", "Add \"return\" keyword", null, new ISemanticModification() {
		@Override
		public void apply(EObject element, IModificationContext context) throws Exception {
			ICompositeNode node = NodeModelUtils.findActualNodeFor(element);
			ReplacingAppendable appendable = appendableFactory.create(context.getXtextDocument(), (XtextResource) element.eResource(), node.getOffset(), 0);
			appendable.append("return ");
			appendable.commitChanges();
		}
	});
}
 
Example #29
Source File: XtendQuickfixProvider.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Fix(IssueCodes.UNNECESSARY_MODIFIER)
public void removeUnnecessaryModifier(final Issue issue, IssueResolutionAcceptor acceptor) {
	String[] issueData = issue.getData();
	if(issueData==null || issueData.length==0) {
		return;
	}
	// use the same label, description and image
	// to be able to use the quickfixes (issue resolution) in batch mode
	String label = "Remove the unnecessary modifier.";
	String description = "The modifier is unnecessary and could be removed.";
	String image = "fix_indent.gif";
	
	acceptor.accept(issue, label, description, image, new ITextualMultiModification() {
		
		@Override
		public void apply(IModificationContext context) throws Exception {
			if (context instanceof IssueModificationContext) {
				Issue theIssue = ((IssueModificationContext) context).getIssue();
				Integer offset = theIssue.getOffset();
				IXtextDocument document = context.getXtextDocument();
				document.replace(offset, theIssue.getLength(), "");
				while (Character.isWhitespace(document.getChar(offset))) {
					document.replace(offset, 1, "");
				}
			}
		}
	});
}
 
Example #30
Source File: XtendQuickfixProvider.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Fix(IssueCodes.MISSING_ABSTRACT)
public void makeClassAbstract(final Issue issue, IssueResolutionAcceptor acceptor) {
	acceptor.accept(issue, "Make class abstract", "Make class abstract", "fix_indent.gif",
			new ISemanticModification() {
				@Override
				public void apply(EObject element, IModificationContext context) throws Exception {
					internalDoAddAbstractKeyword(element, context);
				}
			});
}