org.eclipse.xtext.xbase.ui.contentassist.ReplacingAppendable Java Examples

The following examples show how to use org.eclipse.xtext.xbase.ui.contentassist.ReplacingAppendable. 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: SARLQuickfixProvider.java    From sarl with Apache License 2.0 6 votes vote down vote up
private void addAbstractKeyword(XtendTypeDeclaration typeDeclaration, IXtextDocument document,
		String declarationKeyword) throws BadLocationException {
	final ICompositeNode clazzNode = NodeModelUtils.findActualNodeFor(typeDeclaration);
	if (clazzNode == null) {
		throw new IllegalStateException("Cannot determine node for the type declaration" //$NON-NLS-1$
				+ typeDeclaration.getName());
	}
	int offset = -1;
	final Iterator<ILeafNode> nodes = clazzNode.getLeafNodes().iterator();
	while (offset == -1 && nodes.hasNext()) {
		final ILeafNode leafNode  = nodes.next();
		if (leafNode.getText().equals(declarationKeyword)) {
			offset = leafNode.getOffset();
		}
	}
	final ReplacingAppendable appendable = this.appendableFactory.create(document,
			(XtextResource) typeDeclaration.eResource(),
			offset, 0);
	appendable.append(getGrammarAccess()
			.getAbstractKeyword())
			.append(" "); //$NON-NLS-1$
	appendable.commitChanges();
}
 
Example #2
Source File: XbaseQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private void addTypeCastToImplicitReceiver(XFeatureCall featureCall, IModificationContext context,
		JvmType declaringType) throws BadLocationException {
	String receiver;
	if (featureCall.getImplicitReceiver() instanceof XAbstractFeatureCall)
		receiver = ((XAbstractFeatureCall) featureCall.getImplicitReceiver()).getFeature().getSimpleName();
	else return;
	List<INode> nodes = NodeModelUtils.findNodesForFeature(featureCall,
			XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE);
	if (nodes.isEmpty())
		return;
	INode firstNode = IterableExtensions.head(nodes);
	int offset = firstNode.getOffset();
	ReplacingAppendable appendable = appendableFactory.create(context.getXtextDocument(),
			(XtextResource) featureCall.eResource(), offset, 0);
	appendable.append("(");
	appendable.append(receiver);
	appendable.append(" as ");
	appendable.append(declaringType);
	appendable.append(").");
	appendable.commitChanges();
}
 
Example #3
Source File: ReplacingAppendableTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected XtextDocument insertListField(final String model, final String fieldName)
		throws Exception {
	final int cursorPosition = model.indexOf('|');
	String actualModel = model.replace("|", " ");
	final XtendFile file = testHelper.xtendFile("Foo", actualModel);
	final XtextDocument document = documentProvider.get();
	document.set(actualModel);
	XtextResource xtextResource = (XtextResource) file.eResource();
	document.setInput(xtextResource);
	final EObject context = eObjectAtOffsetHelper.resolveElementAt(xtextResource, cursorPosition);
	document.modify(new IUnitOfWork.Void<XtextResource>() {
		@Override
		public void process(XtextResource state) throws Exception {
			ReplacingAppendable a = appendableFactory.create(document, state, cursorPosition, 1);
			ITypeReferenceOwner owner = new StandardTypeReferenceOwner(services, context);
			LightweightTypeReference typeRef = owner.toLightweightTypeReference(services.getTypeReferences().getTypeForName(List.class, context, typesFactory.createJvmWildcardTypeReference()));
			a.append(typeRef);
			a.append(" ").append(fieldName);
			a.commitChanges();
		}
	});
	return document;
}
 
Example #4
Source File: XtendQuickfixProvider.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected void internalDoAddAbstractKeyword(EObject element, IModificationContext context)
		throws BadLocationException {
	if (element instanceof XtendFunction) {
		element = element.eContainer();
	}
	if (element instanceof XtendClass) {
		XtendClass clazz = (XtendClass) element;
		IXtextDocument document = context.getXtextDocument();
		ICompositeNode clazzNode = NodeModelUtils.findActualNodeFor(clazz);
		if (clazzNode == null)
			throw new IllegalStateException("Cannot determine node for clazz " + clazz.getName());
		int offset = -1;
		for (ILeafNode leafNode : clazzNode.getLeafNodes()) {
			if (leafNode.getText().equals("class")) {
				offset = leafNode.getOffset();
				break;
			}
		}
		ReplacingAppendable appendable = appendableFactory.create(document, (XtextResource) clazz.eResource(),
				offset, 0);
		appendable.append("abstract ");
		appendable.commitChanges();
	}
}
 
Example #5
Source File: SuppressWarningsAddModification.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Add SuppressWarnings annotation.
 *
 * @param element the element to receive the annotation.
 * @param annotation the suppress-warning annotation.
 * @param context the modification context.
 * @throws Exception if the document cannot be changed.
 */
protected void addAnnotation(EObject element, XAnnotation annotation,
		IModificationContext context) throws Exception {
	final ICompositeNode node = NodeModelUtils.findActualNodeFor(annotation);
	if (node != null) {
		final IXtextDocument document = context.getXtextDocument();
		final int startOffset = node.getOffset();
		final int parameterOffset = getTools().getOffsetForPattern(document, startOffset,
				"@\\s*" + toPattern(annotation.getAnnotationType().getQualifiedName()) //$NON-NLS-1$
				+ "\\s*\\(\\s*"); //$NON-NLS-1$
		final int insertOffset;
		if (document.getChar(parameterOffset) == '{') {
			insertOffset = parameterOffset + getTools().getSpaceSize(document, parameterOffset + 1) + 1;
		} else {
			insertOffset = parameterOffset;
		}
		final ReplacingAppendable appendable = getTools().getAppendableFactory().create(document,
				(XtextResource) element.eResource(), insertOffset, 0);
		appendable.append("\""); //$NON-NLS-1$
		appendable.append(extractId(this.code));
		appendable.append("\", "); //$NON-NLS-1$
		appendable.commitChanges();
	}
}
 
Example #6
Source File: SuppressWarningsAddModification.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Add SuppressWarnings annotation.
 *
 * @param element the element to receive the annotation.
 * @param context the modification context.
 * @param suppressWarningsAnnotation the type for the suppress warning annotation.
 * @throws Exception if the document cannot be changed.
 */
protected void addAnnotation(EObject element, IModificationContext context,
		JvmType suppressWarningsAnnotation) throws Exception {
	final ICompositeNode node = NodeModelUtils.findActualNodeFor(element);
	if (node != null) {
		final int insertOffset = node.getOffset();
		final IXtextDocument document = context.getXtextDocument();
		final int length = getTools().getSpaceSize(document, insertOffset);
		final ReplacingAppendable appendable = getTools().getAppendableFactory().create(document,
				(XtextResource) element.eResource(), insertOffset, length);
		appendable.append(getTools().getGrammarAccess().getCommercialAtKeyword());
		appendable.append(suppressWarningsAnnotation);
		appendable.append("(\""); //$NON-NLS-1$
		appendable.append(extractId(this.code));
		appendable.append("\")"); //$NON-NLS-1$
		appendable.newLine();
		appendable.commitChanges();
	}
}
 
Example #7
Source File: ActionAddModification.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(EObject element, IModificationContext context) throws Exception {
	final XtendTypeDeclaration container = EcoreUtil2.getContainerOfType(element, XtendTypeDeclaration.class);
	if (container != null) {
		final int insertOffset = getTools().getInsertOffset(container);
		final IXtextDocument document = context.getXtextDocument();
		final int length = getTools().getSpaceSize(document, insertOffset);
		final ReplacingAppendable appendable = getTools().getAppendableFactory().create(document,
				(XtextResource) element.eResource(), insertOffset, length);
		final boolean changeIndentation = container.getMembers().isEmpty();
		if (changeIndentation) {
			appendable.increaseIndentation();
		}
		appendable.newLine();
		appendable.append(
				getTools().getGrammarAccess().getDefKeyword());
		appendable.append(" "); //$NON-NLS-1$
		appendable.append(this.actionName);
		if (changeIndentation) {
			appendable.decreaseIndentation();
		}
		appendable.newLine();
		appendable.commitChanges();
	}
}
 
Example #8
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 #9
Source File: ReturnTypeAddModification.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(EObject element, IModificationContext context) throws Exception {
	final XtendExecutable xtendExecutable = EcoreUtil2.getContainerOfType(element, XtendExecutable.class);
	final int insertPosition;
	if (xtendExecutable.getExpression() == null) {
		final ICompositeNode functionNode = NodeModelUtils.findActualNodeFor(xtendExecutable);
		if (functionNode == null) {
			throw new IllegalStateException("functionNode may not be null"); //$NON-NLS-1$
		}
		insertPosition = functionNode.getEndOffset();
	} else {
		final ICompositeNode expressionNode = NodeModelUtils.findActualNodeFor(xtendExecutable.getExpression());
		if (expressionNode == null) {
			throw new IllegalStateException("expressionNode may not be null"); //$NON-NLS-1$
		}
		insertPosition = expressionNode.getOffset();
	}
	final ReplacingAppendable appendable = getTools().getAppendableFactory().create(context.getXtextDocument(),
			(XtextResource) xtendExecutable.eResource(), insertPosition, 0);
	if (xtendExecutable.getExpression() == null) {
		appendable.append(" "); //$NON-NLS-1$
	}
	appendable.append(getTools().getGrammarAccess().getColonKeyword());
	appendable.append(" "); //$NON-NLS-1$
	appendable.append(this.expectedType);
	if (xtendExecutable.getExpression() != null) {
		appendable.append(" "); //$NON-NLS-1$
	}
	appendable.commitChanges();
}
 
Example #10
Source File: CreateMemberQuickfixes.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected void newLocalVariableQuickfix(final String variableName, XAbstractFeatureCall call, Issue issue,
		IssueResolutionAcceptor issueResolutionAcceptor) {
	LightweightTypeReference variableType = getNewMemberType(call);
	final StringBuilderBasedAppendable localVarDescriptionBuilder = new StringBuilderBasedAppendable();
	localVarDescriptionBuilder.append("...").newLine();
	final String defaultValueLiteral = getDefaultValueLiteral(variableType);
	localVarDescriptionBuilder.append("val ").append(variableName).append(" = ").append(defaultValueLiteral);
	localVarDescriptionBuilder.newLine().append("...");
	issueResolutionAcceptor.accept(issue, "Create local variable '" + variableName + "'",
			localVarDescriptionBuilder.toString(), "fix_local_var.png",
			new SemanticModificationWrapper(issue.getUriToProblem(), new ISemanticModification() {
				@Override
				public void apply(/* @Nullable */ final EObject element, /* @Nullable */ final IModificationContext context) throws Exception {
					if (element != null) {
						XtendMember xtendMember = EcoreUtil2.getContainerOfType(element, XtendMember.class);
						if (xtendMember != null) {
							int offset = getFirstOffsetOfKeyword(xtendMember, "{");
							IXtextDocument xtextDocument = context.getXtextDocument();
							if (offset != -1 && xtextDocument != null) {
								final ReplacingAppendable appendable = appendableFactory.create(xtextDocument,
										(XtextResource) element.eResource(), offset, 0, new OptionalParameters() {{ 
											baseIndentationLevel = 1;	
										}});
								appendable.increaseIndentation().newLine().append("val ").append(variableName).append(" = ")
										.append(defaultValueLiteral);
								appendable.commitChanges();
							}
						}
					}
				}
			}));
}
 
Example #11
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 #12
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 #13
Source File: XtendQuickfixProvider.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected void doOverrideMethods(final Issue issue, IssueResolutionAcceptor acceptor, String label, final String[] operationUris) {
	acceptor.accept(issue, label, label, "fix_indent.gif",
			new ISemanticModification() {
				@Override
				public void apply(EObject element, IModificationContext context) throws Exception {
					XtendTypeDeclaration clazz = (XtendTypeDeclaration) element;
					JvmGenericType inferredType = (JvmGenericType) associations.getInferredType(clazz);
					ResolvedFeatures resolvedOperations = overrideHelper.getResolvedFeatures(inferredType);
					IXtextDocument document = context.getXtextDocument();
					final int offset = insertionOffsets.getNewMethodInsertOffset(null, clazz);
					int currentIndentation = appendableFactory.getIndentationLevelAtOffset(offset, document, (XtextResource) clazz.eResource());
					final int indentationToUse = clazz.getMembers().isEmpty() ? currentIndentation + 1 : currentIndentation;
					ReplacingAppendable appendable = appendableFactory.create(document, (XtextResource) clazz.eResource(),
							offset, 0, new OptionalParameters() {{ 
								ensureEmptyLinesAround = true;
								baseIndentationLevel = indentationToUse;	
							}});
					boolean isFirst = true;
					for (String operationUriAsString : operationUris) {
						URI operationURI = URI.createURI(operationUriAsString);
						EObject overridden = clazz.eResource().getResourceSet().getEObject(operationURI, true);
						if (overridden instanceof JvmOperation) {
							if(!isFirst) 
								appendable.newLine().newLine();
							isFirst = false;
							
							superMemberImplementor.appendOverrideFunction(clazz, resolvedOperations.getResolvedOperation((JvmOperation) overridden),
									appendable);
						}
					}
					appendable.commitChanges();
				}
			});
}
 
Example #14
Source File: ImplementSuperMemberAssistTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testExistingStaticImport() throws Exception {
	ICompletionProposal[] proposals = newBuilder().append("import static java.util.Collection.*" +
			"class SpecialList extends java.util.ArrayList { removeAll").computeCompletionProposals();
	assertEquals(1, proposals.length);
	ImportOrganizingProposal proposal = (ImportOrganizingProposal) proposals[0];
	ReplacingAppendable appendable = proposal.getAppendable();
	RewritableImportSection importSection = appendable.getImportSection();
	List<ReplaceRegion> imports = importSection.rewrite();
	assertEquals(1, imports.size());
	assertEquals("import java.util.Collection", imports.get(0).getText().trim());
}
 
Example #15
Source File: XbaseQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Fix(IssueCodes.OPERATION_WITHOUT_PARENTHESES)
public void fixMissingParentheses(final Issue issue, IssueResolutionAcceptor acceptor) {
	acceptor.accept(issue, "Add parentheses", "Add parentheses", null, new ISemanticModification() {
		@Override
		public void apply(EObject element, IModificationContext context) throws Exception {
			ReplacingAppendable appendable = appendableFactory.create(context.getXtextDocument(),
					(XtextResource) element.eResource(), issue.getOffset() + issue.getLength(), 0);
			appendable.append("()");
			appendable.commitChanges();
		}
	});
}
 
Example #16
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();
				}

			});
}
 
Example #17
Source File: XbaseQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private void addTypeCastToExplicitReceiver(XAbstractFeatureCall featureCall, IModificationContext context,
		JvmType declaringType, EReference structuralFeature) throws BadLocationException {
	List<INode> nodes = NodeModelUtils.findNodesForFeature(featureCall, structuralFeature);
	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) featureCall.eResource(), offset, length);
	appendable.append("(");
	ListIterator<INode> nodeIter = nodes.listIterator();
	while (nodeIter.hasNext()) {
		String text = nodeIter.next().getText();
		if (nodeIter.previousIndex() == 0)
			appendable.append(Strings.removeLeadingWhitespace(text));
		else if (nodeIter.nextIndex() == nodes.size())
			appendable.append(Strings.trimTrailingLineBreak(text));
		else
			appendable.append(text);
	}
	appendable.append(" as ");
	appendable.append(declaringType);
	appendable.append(")");
	appendable.commitChanges();
}
 
Example #18
Source File: MissedMethodAddModification.java    From sarl with Apache License 2.0 4 votes vote down vote up
@Override
public void apply(EObject element, IModificationContext context) throws Exception {
	final XtendTypeDeclaration container = (XtendTypeDeclaration) element;
	final IXtextDocument document = context.getXtextDocument();
	final SARLQuickfixProvider tools = getTools();

	final JvmDeclaredType declaringType = (JvmDeclaredType) this.associations.getPrimaryJvmElement(container);

	final int insertOffset = tools.getInsertOffset(container);
	final int length = tools.getSpaceSize(document, insertOffset);
	final OptionalParameters options = new OptionalParameters();
	options.isJava = false;
	options.ensureEmptyLinesAround = false;
	options.baseIndentationLevel = 1;
	final ReplacingAppendable appendable = tools.getAppendableFactory().create(document,
			(XtextResource) container.eResource(), insertOffset, length, options);
	// Compute the type parameters' mapping
	final Map<String, JvmTypeReference> typeParameterMap = buildTypeParameterMapping(container);

	for (final JvmOperation operation : tools.getJvmOperationsFromURIs(container, this.operationUris)) {
		if (this.annotationUtils.findAnnotation(operation, SyntheticMember.class.getName()) == null
				&& !isGeneratedOperation(operation)) {

			appendable.newLine().newLine();

			final XtendMethodBuilder builder = this.methodBuilder.get();
			final SarlMethodBuilder sarlBuilder = (builder instanceof SarlMethodBuilder) ? (SarlMethodBuilder) builder : null;

			builder.setContext(declaringType);
			builder.setOwner(declaringType);
			builder.setMethodName(operation.getSimpleName());

			builder.setStaticFlag(false);
			builder.setOverrideFlag(!getTools().isIgnorable(IssueCodes.MISSING_OVERRIDE));
			builder.setAbstractFlag(false);

			builder.setBodyGenerator(null);

			builder.setVisibility(operation.getVisibility());
			builder.setTypeParameters(cloneTypeParameters(operation, declaringType));

			final QualifiedActionName qualifiedActionName = this.actionPrototypeProvider.createQualifiedActionName(
					declaringType,
					operation.getSimpleName());
			final InferredPrototype prototype = this.actionPrototypeProvider.createPrototypeFromJvmModel(
					// TODO More general context?
					this.actionPrototypeProvider.createContext(),
					qualifiedActionName,
					operation.isVarArgs(),
					operation.getParameters());
			final FormalParameterProvider formalParameters = prototype.getFormalParameters();

			int i = 0;
			for (final JvmFormalParameter parameter : operation.getParameters()) {
				final SarlParameterBuilder paramBuilder = (SarlParameterBuilder) builder.newParameterBuilder();
				paramBuilder.setName(parameter.getSimpleName());
				paramBuilder.setType(cloneTypeReference(parameter.getParameterType(), typeParameterMap));
				if (formalParameters.hasFormalParameterDefaultValue(i)) {
					final String defaultValue = formalParameters.getFormalParameterDefaultValueString(i);
					if (defaultValue != null) {
						paramBuilder.setDefaultValue(defaultValue);
					}
				}
				++i;
			}
			builder.setVarArgsFlag(operation.isVarArgs());

			builder.setReturnType(cloneTypeReference(operation.getReturnType(), typeParameterMap));

			builder.setExceptions(cloneTypeReferences(operation.getExceptions(), typeParameterMap));

			if (sarlBuilder != null) {
				final JvmAnnotationReference firedEvents = this.annotationUtils.findAnnotation(operation, FiredEvent.class.getName());
				if (firedEvents != null) {
					final List<JvmTypeReference> events = this.annotationUtils.findTypeValues(firedEvents);
					if (events != null) {
						sarlBuilder.setFires(cloneTypeReferences(events, typeParameterMap));
					}
				}
			}

			builder.build(appendable);
		}
	}
	appendable.newLine().decreaseIndentation().newLine();

	appendable.commitChanges();
}
 
Example #19
Source File: XtendQuickfixProvider.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Fix(org.eclipse.xtext.xbase.validation.IssueCodes.UNHANDLED_EXCEPTION)
public void addThrowsDeclaration(final Issue issue, IssueResolutionAcceptor acceptor) {
	if (issue.getData() != null && issue.getData().length > 0)
		acceptor.accept(issue, "Add throws declaration", "Add throws declaration", "fix_indent.gif",
				new ISemanticModification() {
					@Override
					public void apply(EObject element, IModificationContext context) throws Exception {
						String[] issueData = issue.getData(); 
						XtendExecutable xtendExecutable = EcoreUtil2.getContainerOfType(element, XtendExecutable.class);
						XtextResource xtextResource = (XtextResource) xtendExecutable.eResource();
						List<JvmType> exceptions = getExceptions(issueData, xtextResource);
						if (exceptions.size() > 0) {
							int insertPosition;
							if (xtendExecutable.getExpression() == null) {
								ICompositeNode functionNode = NodeModelUtils.findActualNodeFor(xtendExecutable);
								if (functionNode == null)
									throw new IllegalStateException("functionNode may not be null");
								insertPosition = functionNode.getEndOffset();
							} else {
								ICompositeNode expressionNode = NodeModelUtils.findActualNodeFor(xtendExecutable.getExpression());
								if (expressionNode == null)
									throw new IllegalStateException("expressionNode may not be null");
								insertPosition = expressionNode.getOffset();
							}
							ReplacingAppendable appendable = appendableFactory.create(context.getXtextDocument(),
									(XtextResource) xtendExecutable.eResource(), insertPosition, 0);
							if (xtendExecutable.getExpression() == null) 
								appendable.append(" ");
							EList<JvmTypeReference> thrownExceptions = xtendExecutable.getExceptions();
							if (thrownExceptions.isEmpty())
								appendable.append("throws ");
							else
								appendable.append(", ");
							for(int i = 0; i < exceptions.size(); i++) {
								appendable.append(exceptions.get(i));
								if (i != exceptions.size() - 1) {
									appendable.append(", ");
								}
							}
							if (xtendExecutable.getExpression() != null) 
								appendable.append(" ");
							appendable.commitChanges();
						}
					}
				});
}
 
Example #20
Source File: ImplementMemberFromSuperAssist.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
protected ImportOrganizingProposal createCompletionProposal(ReplacingAppendable appendable, Region replaceRegion,
		StyledString displayString, Image image) {
	return new ImportOrganizingProposal(appendable, replaceRegion.getOffset(), replaceRegion.getLength(),
			replaceRegion.getOffset(), image, displayString);
}
 
Example #21
Source File: ImplementMemberFromSuperAssist.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
protected ICompletionProposal createOverrideMethodProposal(XtendTypeDeclaration model, IResolvedExecutable overrideable,
		final ContentAssistContext context, IProposalConflictHelper conflictHelper) {
	IXtextDocument document = context.getDocument();
	XtextResource resource = (XtextResource) model.eResource();
	int offset = context.getReplaceRegion().getOffset();
	int currentIndentation = appendableFactory.getIndentationLevelAtOffset(offset, document, resource);
	final int indentationLevel = currentIndentation == 0 ? 1 : currentIndentation;
	ReplacingAppendable appendable = appendableFactory.create(document, resource, offset, context.getReplaceRegion().getLength(), new OptionalParameters() {{ 
				ensureEmptyLinesAround = true;
				baseIndentationLevel = indentationLevel;	
			}});
	final String simpleName;
	JvmExecutable declaration = overrideable.getDeclaration();
	if (overrideable instanceof IResolvedOperation) {
		implementor.appendOverrideFunction(model, (IResolvedOperation) overrideable, appendable);
		simpleName = overrideable.getDeclaration().getSimpleName();
	} else if (model instanceof XtendClass) {
		implementor.appendConstructorFromSuper((XtendClass) model, (IResolvedConstructor) overrideable, appendable);
		simpleName = "new";
	} else {
		return null;
	}
	String code = appendable.getCode();
	if (!isValidProposal(code.trim(), context, conflictHelper) && !isValidProposal(simpleName, context, conflictHelper))
		return null;
	ImageDescriptor imageDescriptor = images.forOperation(declaration.getVisibility(), adornments.getOverrideAdornment(declaration));
	ImportOrganizingProposal completionProposal = createCompletionProposal(appendable, context.getReplaceRegion(),
			getLabel(overrideable), imageHelper.getImage(imageDescriptor));
	Matcher matcher = bodyExpressionPattern.matcher(code);
	if (matcher.find()) {
		int bodyExpressionLength = matcher.end(1) - matcher.start(1);
		int bodyExpressionStart = matcher.start(1) + appendable.getTotalOffset() - completionProposal.getReplacementOffset();
		if (bodyExpressionLength == 0) {
			completionProposal.setCursorPosition(bodyExpressionStart);
		} else {
			completionProposal.setSelectionStart(completionProposal.getReplacementOffset() + bodyExpressionStart);
			completionProposal.setSelectionLength(bodyExpressionLength);
			completionProposal.setAutoInsertable(false);
			completionProposal.setCursorPosition(bodyExpressionStart + bodyExpressionLength);
			completionProposal.setSimpleLinkedMode(context.getViewer(), '\t');
		}
	}
	completionProposal.setPriority(getPriority(model, declaration, context));
	completionProposal.setMatcher(new PrefixMatcher() {

		@Override
		public boolean isCandidateMatchingPrefix(String name, String prefix) {
			PrefixMatcher delegate = context.getMatcher();
			boolean result = delegate.isCandidateMatchingPrefix(simpleName, prefix);
			return result;
		}
		
	});
	return completionProposal;
}
 
Example #22
Source File: JavaTypeQuickfixes.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@SuppressWarnings("restriction")
protected void createImportProposals(final JvmDeclaredType contextType, final Issue issue, String typeName, IJavaSearchScope searchScope,
		final IssueResolutionAcceptor acceptor) throws JavaModelException {
	if(contextType != null) {
		final IVisibilityHelper visibilityHelper = getVisibilityHelper(contextType);
		final Pair<String, String> packageAndType = typeNameGuesser.guessPackageAndTypeName(contextType, typeName);
		final String wantedPackageName = packageAndType.getFirst();
		org.eclipse.jdt.internal.core.search.BasicSearchEngine searchEngine = new org.eclipse.jdt.internal.core.search.BasicSearchEngine();
		final char[] wantedPackageChars = (isEmpty(wantedPackageName)) ? null : wantedPackageName.toCharArray();
		final String wantedTypeName = packageAndType.getSecond();
		searchEngine.searchAllTypeNames(wantedPackageChars, SearchPattern.R_EXACT_MATCH, wantedTypeName.toCharArray(),
				SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, IJavaSearchConstants.TYPE, searchScope, new org.eclipse.jdt.internal.core.search.IRestrictedAccessTypeRequestor() {
					
					@Override
					public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames,
							String path, org.eclipse.jdt.internal.compiler.env.AccessRestriction access) {
						final String qualifiedTypeName = getQualifiedTypeName(packageName, enclosingTypeNames,
								simpleTypeName);
						if(access == null || (access.getProblemId() != IProblem.ForbiddenReference && !access.ignoreIfBetter())){
							JvmType importType = services.getTypeReferences().findDeclaredType(qualifiedTypeName, contextType);
							if(importType instanceof JvmDeclaredType
									&& visibilityHelper.isVisible((JvmDeclaredType)importType)) {
								StringBuilder label = new StringBuilder("Import '");
								label.append(simpleTypeName);
								label.append("' (");
								label.append(packageName);
								if(enclosingTypeNames.length > 0) {
									for(char[] enclosingTypeName: enclosingTypeNames) {
										label.append(".");
										label.append(enclosingTypeName);
									}
								}
								label.append(")");
								acceptor.accept(issue, label.toString(), label.toString(), "impc_obj.gif", new ISemanticModification() {
									@Override
									public void apply(EObject element, IModificationContext context) throws Exception {
										ReplacingAppendable appendable = appendableFactory.create(context.getXtextDocument(),
												(XtextResource) element.eResource(), 0, 0);
										appendable.append(services.getTypeReferences().findDeclaredType(qualifiedTypeName, element));
										appendable.insertNewImports();
									}
								}, jdtTypeRelevance.getRelevance(qualifiedTypeName, wantedTypeName) + 100);
							}
						}
					}
				}, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, new NullProgressMonitor());
	}
}
 
Example #23
Source File: SARLQuickfixProvider.java    From sarl with Apache License 2.0 2 votes vote down vote up
/** Replies the factory for appendable.
 *
 * @return the appendable factory.
 */
public ReplacingAppendable.Factory getAppendableFactory() {
	return this.appendableFactory;
}