org.eclipse.xtext.validation.Issue Java Examples

The following examples show how to use org.eclipse.xtext.validation.Issue. 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: CheckQuickfixProvider.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Removes the guard statement occurring at offending position.
 *
 * @param issue
 *          the issue
 * @param acceptor
 *          the acceptor
 */
@Fix(IssueCodes.GUARDS_COME_FIRST)
@SuppressWarnings("unchecked")
public void removeGuardStatement(final Issue issue, final IssueResolutionAcceptor acceptor) {
  acceptor.accept(issue, Messages.CheckQuickfixProvider_REMOVE_GUARD_LABEL, Messages.CheckQuickfixProvider_REMOVE_GUARD_DESCN, NO_IMAGE, new ISemanticModification() {
    @Override
    public void apply(final EObject element, final IModificationContext context) {
      final XGuardExpression guard = EcoreUtil2.getContainerOfType(element, XGuardExpression.class);
      if (guard != null && guard.eContainingFeature().isMany()) {
        EList<? extends EObject> holder = (EList<? extends EObject>) guard.eContainer().eGet(guard.eContainingFeature());
        if (holder != null && holder.contains(guard)) {
          holder.remove(guard);
        }
      }
    }
  });
}
 
Example #2
Source File: IssueExpectations.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Matches the expectations in the added issues matchers against the given issues.
 *
 * @param issues
 *            the issues to match the expectations against
 * @param messages
 *            if this parameter is not <code>null</code>, this method will add an explanatory message for each
 *            mismatch
 * @return <code>true</code> if and only if every expectation was matched against an issue
 */
public boolean matchesAllExpectations(Collection<Issue> issues, List<String> messages) {
	Collection<Issue> issueCopy = new LinkedList<>(issues);
	Collection<IssueMatcher> matcherCopy = new LinkedList<>(issueMatchers);

	performMatching(issueCopy, matcherCopy, messages);
	if (inverted) {
		if (matcherCopy.isEmpty()) {
			explainExpectations(issueMatchers, messages, inverted);
			return false;
		}
	} else {
		if (!matcherCopy.isEmpty()) {
			explainExpectations(matcherCopy, messages, inverted);
			return false;
		}
	}
	return false;
}
 
Example #3
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 #4
Source File: Main.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
protected void runGenerator(final String string) {
	// load the resource
	final ResourceSet set = resourceSetProvider.get();
	final Resource resource = set.getResource(URI.createURI(string, false), true);

	// validate the resource
	final List<Issue> list = validator.validate(resource, CheckMode.ALL, CancelIndicator.NullImpl);
	if (!list.isEmpty()) {
		for (final Issue issue : list) {
			DEBUG.ERR(issue.toString());
		}
		return;
	}

	// configure and start the generator
	fileAccess.setOutputPath("src-gen/");
	generator.doGenerate(resource, fileAccess);

	DEBUG.LOG("Code generation finished.");
}
 
Example #5
Source File: CheckConfigurationStoreService.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Sets the project if an associated instance can be found for given context object.
 * <p>
 * This is the default implementation. Only platform URI-based schemas are supported. Other implementations may overwrite {@link #getProject()}.
 * </p>
 *
 * @param context
 *          the context object, potentially contained by an IProject
 */
protected void setProject(final Object context) {
  if (context instanceof IProject) {
    this.project = (IProject) context;
  } else if (context instanceof IFile) {
    this.project = ((IFile) context).getProject();
  } else {
    URI uri = null;
    if (context instanceof EObject && ((EObject) context).eResource() != null) {
      uri = ((EObject) context).eResource().getURI();
    }
    if (context instanceof Issue) {
      uri = ((Issue) context).getUriToProblem();
    }
    if (uri != null && uri.isPlatform()) {
      final IFile file = (IFile) ResourcesPlugin.getWorkspace().getRoot().findMember(uri.toPlatformString(true));
      this.project = file.getProject();
    }
  }
}
 
Example #6
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 #7
Source File: QuickfixTestBuilder.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public QuickfixTestBuilder create(final String fileName, final String model) {
  try {
    QuickfixTestBuilder _xblockexpression = null;
    {
      final String positionMarker = this.getPositionMarker(model);
      final IFile file = this._workbenchTestHelper.createFile(fileName, model.replace(positionMarker, ""));
      this.editor = this.openEditorSafely(file);
      final IXtextDocument document = this.editor.getDocument();
      Assert.assertNotNull("Error getting document from editor", document);
      final IUnitOfWork<List<Issue>, XtextResource> _function = (XtextResource it) -> {
        return this.issues = this._iResourceValidator.validate(it, CheckMode.NORMAL_AND_FAST, CancelIndicator.NullImpl);
      };
      document.<List<Issue>>readOnly(_function);
      this.caretOffset = model.indexOf(positionMarker);
      _xblockexpression = this;
    }
    return _xblockexpression;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #8
Source File: XtendQuickfixProvider.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Fix(IssueCodes.MISSING_OVERRIDE)
public void fixMissingOverride(final Issue issue, IssueResolutionAcceptor acceptor) {
	acceptor.accept(issue, "Change 'def' to 'override'", "Marks this function as 'override'", "fix_indent.gif",
			new ISemanticModification() {
				@Override
				public void apply(EObject element, IModificationContext context) throws Exception {
					replaceKeyword(grammarAccess.getMethodModifierAccess().findKeywords("def").get(0), "override", 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 #9
Source File: AddMarkersOperation.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void execute(final IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException {
	if (!resource.exists())
		return;
	if (deleteMarkers) {
		for (String markerId : getMarkerIds()) {
			resource.deleteMarkers(markerId, true, IResource.DEPTH_INFINITE);
		}
		deleteAnnotations(); // delete annotations set by Xtext validator independently from resource markers
	}
	if (!issues.isEmpty()) {
		// update
		for (Issue issue : issues) {
			if (monitor.isCanceled())
				throw new InterruptedException();
			markerCreator.createMarker(issue, resource, markerTypeProvider.getMarkerType(issue));
		}
	}
}
 
Example #10
Source File: GeneratorForTests.java    From xsemantics with Eclipse Public License 1.0 6 votes vote down vote up
public List<Issue> runGenerator(String string, ResourceSet set) {
	// load the resource
	Resource resource = set.getResource(URI.createURI(string), true);

	// validate the resource
	List<Issue> issues = validator.validate(resource, CheckMode.ALL,
			CancelIndicator.NullImpl);
	if (!issues.isEmpty()) {
		for (Issue issue : issues) {
			System.err.println(issue);
		}
		if (GeneratorUtils.hasErrors(issues))
			return issues;
	}

	fileAccess.setOutputPath(outputPath);
	generator.doGenerate(resource, fileAccess);

	System.out.println("Code generation finished.");

	return issues;
}
 
Example #11
Source File: XtextValidationTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testMissingArgument2() throws Exception {
	XtextResource resource = getResourceFromString(
			"grammar com.acme.Bar with org.eclipse.xtext.common.Terminals\n" +
			"generate metamodel 'myURI'\n" +
			"Model: rule=Rule<First=true>;\n" + 
			"Rule<First, Missing, AlsoMissing>: name=ID;");

	IResourceValidator validator = get(IResourceValidator.class);
	List<Issue> issues = validator.validate(resource, CheckMode.FAST_ONLY, CancelIndicator.NullImpl);
	assertEquals(issues.toString(), 1, issues.size());
	assertEquals("2 missing arguments for the following parameters: Missing, AlsoMissing", issues.get(0).getMessage());
}
 
Example #12
Source File: SARLQuickfixProvider.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Quick fix for "Override final operation".
 *
 * @param issue the issue.
 * @param acceptor the quick fix acceptor.
 */
@Fix(IssueCodes.OVERRIDDEN_FINAL)
public void fixOverriddenFinal(Issue issue, IssueResolutionAcceptor acceptor) {
	final MultiModification modifications = new MultiModification(
			this, issue, acceptor,
			Messages.SARLQuickfixProvider_0,
			Messages.SARLQuickfixProvider_1);
	modifications.bind(XtendTypeDeclaration.class, SuperTypeRemoveModification.class);
	modifications.bind(XtendMember.class, MemberRemoveModification.class);
}
 
Example #13
Source File: IShouldGenerate.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean shouldGenerate(Resource resource, CancelIndicator cancelIndicator) {
	if (!resource.getErrors().isEmpty()) {
		return false;
	}
	List<Issue> issues = resourceValidator.validate(resource, CheckMode.NORMAL_AND_FAST, cancelIndicator);
	return !exists(issues, (Issue issue) -> Objects.equal(issue.getSeverity(), Severity.ERROR));
}
 
Example #14
Source File: ImplementedTypeRemoveModification.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Create the quick fix if needed.
 *
 * <p>The first user data is the name of the type to remove.
 * The second parameter may be the type of the removal (see {@link RemovalType}).
 *
 * @param provider the quick fix provider.
 * @param issue the issue to fix.
 * @param acceptor the quick fix acceptor.
 * @param type the type of the modification.
 */
public static void accept(SARLQuickfixProvider provider, Issue issue, IssueResolutionAcceptor acceptor, RemovalType type) {
	final String[] data = issue.getData();
	RemovalType removalType = type;
	String redundantName = null;
	if (data != null && data.length >= 1) {
		redundantName = data[0];
		if (removalType == null && data.length >= 2) {
			final String mode = data[1];
			if (!Strings.isNullOrEmpty(mode)) {
				try {
					removalType = RemovalType.valueOf(mode.toUpperCase());
				} catch (Throwable exception) {
					//
				}
			}
		}
	}
	if (removalType == null) {
		removalType = RemovalType.OTHER;
	}
	final String msg;
	if (Strings.isNullOrEmpty(redundantName)) {
		msg = Messages.SARLQuickfixProvider_0;
	} else {
		msg = MessageFormat.format(Messages.SARLQuickfixProvider_6, redundantName);
	}

	final ImplementedTypeRemoveModification modification = new ImplementedTypeRemoveModification(removalType);
	modification.setIssue(issue);
	modification.setTools(provider);
	acceptor.accept(issue,
			msg,
			Messages.SARLQuickfixProvider_9,
			JavaPluginImages.IMG_CORRECTION_REMOVE,
			modification);
}
 
Example #15
Source File: GamlQuickfixProvider.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
@Fix (IGamlIssue.SHOULD_CAST)
public void shouldCast(final Issue issue, final IssueResolutionAcceptor acceptor) {
	final String[] data = issue.getData();
	if (data == null || data.length == 0) { return; }
	final String castingString = data[0];
	acceptor.accept(issue, "Cast the expression to " + castingString + "...", "", "",
			new Surround(issue.getOffset(), issue.getLength(), castingString + "(", ")"));
}
 
Example #16
Source File: CreateMemberQuickfixes.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected void newGetterQuickfixes(String name, XAbstractFeatureCall call, 
		final Issue issue, final IssueResolutionAcceptor issueResolutionAcceptor) {
	JvmDeclaredType callersType = getCallersType(call);
	LightweightTypeReference receiverType = getReceiverType(call);
	LightweightTypeReference fieldType = getNewMemberType(call);
	if(callersType != null && receiverType != null) {
		newMethodQuickfixes(receiverType, getAccessorMethodName("get", name), 
				fieldType, Collections.<LightweightTypeReference>emptyList(), call, 
				callersType, issue, issueResolutionAcceptor);
	}
}
 
Example #17
Source File: N4JSMarkerUpdater.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private void updateMarkersForExternalLibraries(Delta delta, ResourceSet resourceSet, IProgressMonitor monitor) {
	URI uri = delta.getUri();
	if (n4jsCore.isNoValidate(uri)) {
		return;
	}

	Resource resource = resourceSet.getResource(uri, true);
	IResourceValidator validator = getValidator(resource);
	IN4JSProject prj = n4jsCore.findProject(uri).orNull();
	CancelIndicator cancelIndicator = getCancelIndicator(monitor);

	if (prj != null && prj.isExternal() && prj.exists() && prj instanceof N4JSEclipseProject && uri.isFile()) {
		// transform file uri in workspace iResource
		IFile file = URIUtils.convertFileUriToPlatformFile(uri);

		if (file != null && resource != null) {
			List<Issue> list = validator.validate(resource, CheckMode.NORMAL_AND_FAST, cancelIndicator);

			if (SHOW_ONLY_EXTERNAL_ERRORS) {
				for (Iterator<Issue> iter = list.iterator(); iter.hasNext();) {
					if (iter.next().getSeverity() != Severity.ERROR) {
						iter.remove();
					}
				}
			}

			try {
				validatorExtension.createMarkers(file, resource, list);
			} catch (CoreException e) {
				e.printStackTrace();
			}
		}
	}
}
 
Example #18
Source File: AnnotationIssueProcessor.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void processIssues(List<Issue> issues, IProgressMonitor monitor) {
	updateMarkersOnModelChange = false;
	List<Annotation> toBeRemoved = getAnnotationsToRemove(monitor);
	Multimap<Position, Annotation> positionToAnnotations = ArrayListMultimap.create();
	Map<Annotation, Position> annotationToPosition = getAnnotationsToAdd(positionToAnnotations, issues, monitor);
	updateMarkerAnnotations(monitor);
	updateAnnotations(monitor, toBeRemoved, annotationToPosition);
	updateMarkersOnModelChange = true;
}
 
Example #19
Source File: XtextValidationTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testSupressedWarning_01() throws Exception {
	XtextResource resource = getResourceFromString(
			"grammar org.acme.Bar with org.eclipse.xtext.common.Terminals\n" +
			"generate metamodel 'myURI'\n" +
			 
			"Model: child=Child;\n" + 
			"/* SuppressWarnings[noInstantiation] */\n" +
			"Child: name=ID?;");
	assertTrue(resource.getErrors().toString(), resource.getErrors().isEmpty());
	assertTrue(resource.getWarnings().toString(), resource.getWarnings().isEmpty());

	IResourceValidator validator = get(IResourceValidator.class);
	List<Issue> issues = validator.validate(resource, CheckMode.FAST_ONLY, CancelIndicator.NullImpl);
	assertTrue(issues.toString(), issues.isEmpty());
}
 
Example #20
Source File: XtextValidationTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testExplicitOverride04() throws Exception {
	IResourceValidator validator = get(IResourceValidator.class);
	XtextResource resource = getResourceFromString(
			"grammar org.foo.Bar with org.eclipse.xtext.common.Terminals\n" +
			"@Override\n" +
			"terminal ID: ('a'..'z'|'A'..'Z'|'_');");
	List<Issue> issues = validator.validate(resource, CheckMode.FAST_ONLY, CancelIndicator.NullImpl);
	assertEquals(issues.toString(), 0, issues.size());
}
 
Example #21
Source File: N4JSDiagnosticConverter.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void convertResourceDiagnostic(Diagnostic diagnostic, Severity severity, IAcceptor<Issue> acceptor) {
	// START: Following copied from super method
	LSPIssue issue = new LSPIssue(); // Changed
	issue.setSyntaxError(diagnostic instanceof XtextSyntaxDiagnostic);
	issue.setSeverity(severity);
	issue.setLineNumber(diagnostic.getLine());
	issue.setColumn(diagnostic.getColumn());
	issue.setMessage(diagnostic.getMessage());

	if (diagnostic instanceof org.eclipse.xtext.diagnostics.Diagnostic) {
		org.eclipse.xtext.diagnostics.Diagnostic xtextDiagnostic = (org.eclipse.xtext.diagnostics.Diagnostic) diagnostic;
		issue.setOffset(xtextDiagnostic.getOffset());
		issue.setLength(xtextDiagnostic.getLength());
	}
	if (diagnostic instanceof AbstractDiagnostic) {
		AbstractDiagnostic castedDiagnostic = (AbstractDiagnostic) diagnostic;
		issue.setUriToProblem(castedDiagnostic.getUriToProblem());
		issue.setCode(castedDiagnostic.getCode());
		issue.setData(castedDiagnostic.getData());

		// START: Changes here
		INode node = ReflectionUtils.getMethodReturn(AbstractDiagnostic.class, "getNode", diagnostic);
		int posEnd = castedDiagnostic.getOffset() + castedDiagnostic.getLength();
		LineAndColumn lineAndColumn = NodeModelUtils.getLineAndColumn(node, posEnd);
		issue.setLineNumberEnd(lineAndColumn.getLine());
		issue.setColumnEnd(lineAndColumn.getColumn());
		// END: Changes here
	}
	issue.setType(CheckType.FAST);
	acceptor.accept(issue);
	// END: Following copied from super method
}
 
Example #22
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 #23
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 #24
Source File: SCTMarkerCreator.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void setMarkerAttributes(Issue issue, IResource resource, IMarker marker) throws CoreException {
	super.setMarkerAttributes(issue, resource, marker);
	if (issue instanceof SCTIssue) {
		marker.setAttribute(SCTMarkerType.SEMANTIC_ELEMENT_ID, ((SCTIssue) issue).getSemanticURI());
	}
}
 
Example #25
Source File: SARLQuickfixProvider.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Remove the element related to the issue, and the whitespaces after the element until the given separator.
 *
 * @param issue the issue.
 * @param document the document.
 * @param separator the separator to consider.
 * @return <code>true</code> if the separator was found, <code>false</code> if not.
 * @throws BadLocationException if there is a problem with the location of the element.
 */
public boolean removeToNextSeparator(Issue issue, IXtextDocument document, String separator)
		throws BadLocationException {
	// Skip spaces after the identifier until the separator
	int index = issue.getOffset() + issue.getLength();
	char c = document.getChar(index);
	while (Character.isWhitespace(c)) {
		index++;
		c = document.getChar(index);
	}

	// Test if it next non-space character is the separator
	final boolean foundSeparator = document.getChar(index) == separator.charAt(0);
	if (foundSeparator) {
		index++;
		c = document.getChar(index);
		// Skip the previous spaces
		while (Character.isWhitespace(c)) {
			index++;
			c = document.getChar(index);
		}

		final int newLength = index - issue.getOffset();
		document.replace(issue.getOffset(), newLength, ""); //$NON-NLS-1$
	}

	return foundSeparator;
}
 
Example #26
Source File: ProjectManager.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public void initialize(ProjectDescription description, IProjectConfig projectConfig,
		Procedure2<? super URI, ? super Iterable<Issue>> acceptor,
		IExternalContentSupport.IExternalContentProvider openedDocumentsContentProvider,
		Provider<Map<String, ResourceDescriptionsData>> indexProvider, CancelIndicator cancelIndicator) {
	this.projectDescription = description;
	this.projectConfig = projectConfig;
	this.baseDir = projectConfig.getPath();
	this.issueAcceptor = acceptor;
	this.openedDocumentsContentProvider = openedDocumentsContentProvider;
	this.indexProvider = indexProvider;
}
 
Example #27
Source File: CreateXtendTypeQuickfixes.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected void newLocalXtendAnnotationQuickfix(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) {
			AbstractAnnotationBuilder annotationBuilder = codeBuilderFactory.createAnnotationBuilder(inferredType);
			annotationBuilder.setAnnotationName(typeName);
			annotationBuilder.setVisibility(JvmVisibility.PUBLIC);
			annotationBuilder.setContext(xtendType);
			codeBuilderQuickfix.addQuickfix(annotationBuilder, "Create local Xtend annotation '@" + typeName + "'", issue, issueResolutionAcceptor);
		}
	}
}
 
Example #28
Source File: IssueUtil.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public Issue getIssueFromAnnotation(Annotation annotation) {
	if (annotation instanceof XtextAnnotation) {
		XtextAnnotation xtextAnnotation = (XtextAnnotation) annotation;
		return xtextAnnotation.getIssue();
	} else if(annotation instanceof MarkerAnnotation) {
		MarkerAnnotation markerAnnotation = (MarkerAnnotation)annotation;
		return createIssue(markerAnnotation.getMarker());
	} else
		return null;
}
 
Example #29
Source File: StringPropertyMatcher.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean matches(Issue issue) {
	String actualValue = safeGetValue(getActualValue.apply(issue));
	switch (mode) {
	case StartsWith:
		return actualValue.startsWith(expectedPattern);
	case EndsWith:
		return actualValue.endsWith(expectedPattern);
	case Equals:
		return actualValue.equals(expectedPattern);
	}

	// This should never happen lest we extended the enum without adding a case above!
	throw new IllegalStateException("Unknown string property matching mode: " + mode);
}
 
Example #30
Source File: XtextGrammarQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Fix(INVALID_METAMODEL_NAME)
public void fixInvalidMetaModelName(final Issue issue, IssueResolutionAcceptor acceptor) {
	final String metaModelName = issue.getData()[0];
	acceptor.accept(issue, "Fix metamodel name '" + metaModelName + "'", "Fix metamodel name '" + metaModelName
			+ "'", NULL_QUICKFIX_IMAGE, new IModification() {
		@Override
		public void apply(IModificationContext context) throws Exception {
			context.getXtextDocument().replace(issue.getOffset(), issue.getLength(), Strings.toFirstLower(metaModelName));
		}
	});
}