Search in sources :

Example 26 with LightweightTypeReference

use of org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference in project xtext-xtend by eclipse.

the class CreateMemberQuickfixes method newLocalVariableQuickfix.

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();
                    }
                }
            }
        }
    }));
}
Also used : OptionalParameters(org.eclipse.xtext.xbase.ui.document.DocumentSourceAppender.Factory.OptionalParameters) LightweightTypeReference(org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference) XtendMember(org.eclipse.xtend.core.xtend.XtendMember) SemanticModificationWrapper(org.eclipse.xtext.ui.editor.model.edit.SemanticModificationWrapper) EObject(org.eclipse.emf.ecore.EObject) ISemanticModification(org.eclipse.xtext.ui.editor.model.edit.ISemanticModification) IModificationContext(org.eclipse.xtext.ui.editor.model.edit.IModificationContext) StringBuilderBasedAppendable(org.eclipse.xtext.xbase.compiler.StringBuilderBasedAppendable) ReplacingAppendable(org.eclipse.xtext.xbase.ui.contentassist.ReplacingAppendable) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument)

Example 27 with LightweightTypeReference

use of org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference in project xtext-xtend by eclipse.

the class XtendQuickfixProvider method specifyTypeExplicitly.

@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();
            }
        }
    });
}
Also used : XtendFunction(org.eclipse.xtend.core.xtend.XtendFunction) INode(org.eclipse.xtext.nodemodel.INode) LightweightTypeReference(org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference) JvmIdentifiableElement(org.eclipse.xtext.common.types.JvmIdentifiableElement) ISemanticModification(org.eclipse.xtext.ui.editor.model.edit.ISemanticModification) EStructuralFeature(org.eclipse.emf.ecore.EStructuralFeature) XtextResource(org.eclipse.xtext.resource.XtextResource) ReplacingAppendable(org.eclipse.xtext.xbase.ui.contentassist.ReplacingAppendable) CoreException(org.eclipse.core.runtime.CoreException) BadLocationException(org.eclipse.jface.text.BadLocationException) XtendField(org.eclipse.xtend.core.xtend.XtendField) EObject(org.eclipse.emf.ecore.EObject) IModificationContext(org.eclipse.xtext.ui.editor.model.edit.IModificationContext) Fix(org.eclipse.xtext.ui.editor.quickfix.Fix)

Example 28 with LightweightTypeReference

use of org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference in project xtext-xtend by eclipse.

the class MemberFromSuperImplementor method appendOverrideFunction.

public void appendOverrideFunction(final XtendTypeDeclaration overrider, final IResolvedOperation overriddenOperation, final ISourceAppender appendable) {
    final JvmDeclaredType inferredType = this.associations.getInferredType(overrider);
    final AbstractMethodBuilder methodBuilder = this.codeBuilderFactory.createMethodBuilder(inferredType);
    this.initializeExecutableBuilder(methodBuilder, inferredType, overriddenOperation);
    methodBuilder.setOverrideFlag(true);
    methodBuilder.setMethodName(overriddenOperation.getDeclaration().getSimpleName());
    methodBuilder.setReturnType(overriddenOperation.getResolvedReturnType());
    boolean _isSynchronized = overriddenOperation.getDeclaration().isSynchronized();
    if (_isSynchronized) {
        methodBuilder.setSynchronizedFlag(true);
    }
    boolean _isEmpty = overriddenOperation.getResolvedTypeParameters().isEmpty();
    boolean _not = (!_isEmpty);
    if (_not) {
        final ArrayList<JvmTypeParameter> typeParameters = CollectionLiterals.<JvmTypeParameter>newArrayList();
        final Procedure2<JvmTypeParameter, Integer> _function = (JvmTypeParameter typeParam, Integer idx) -> {
            final JvmTypeParameter newTypeParam = this.typesFactory.createJvmTypeParameter();
            newTypeParam.setName(typeParam.getName());
            final Consumer<LightweightTypeReference> _function_1 = (LightweightTypeReference it) -> {
                final JvmUpperBound upperBound = this.typesFactory.createJvmUpperBound();
                upperBound.setTypeReference(it.toJavaCompliantTypeReference());
                EList<JvmTypeConstraint> _constraints = newTypeParam.getConstraints();
                _constraints.add(upperBound);
            };
            overriddenOperation.getResolvedTypeParameterConstraints((idx).intValue()).forEach(_function_1);
            typeParameters.add(newTypeParam);
        };
        IterableExtensions.<JvmTypeParameter>forEach(overriddenOperation.getResolvedTypeParameters(), _function);
        methodBuilder.setTypeParameters(typeParameters);
    }
    boolean _isAbstract = overriddenOperation.getDeclaration().isAbstract();
    boolean _not_1 = (!_isAbstract);
    if (_not_1) {
        StringConcatenation _builder = new StringConcatenation();
        _builder.append("super.");
        {
            List<JvmTypeParameter> _resolvedTypeParameters = overriddenOperation.getResolvedTypeParameters();
            boolean _hasElements = false;
            for (final JvmTypeParameter typeParam : _resolvedTypeParameters) {
                if (!_hasElements) {
                    _hasElements = true;
                    _builder.append("<");
                } else {
                    _builder.appendImmediate(", ", "");
                }
                String _simpleName = typeParam.getSimpleName();
                _builder.append(_simpleName);
            }
            if (_hasElements) {
                _builder.append(">");
            }
        }
        String _simpleName_1 = overriddenOperation.getDeclaration().getSimpleName();
        _builder.append(_simpleName_1);
        _builder.append("(");
        final Function1<JvmFormalParameter, String> _function_1 = (JvmFormalParameter it) -> {
            return it.getSimpleName();
        };
        String _join = IterableExtensions.join(ListExtensions.<JvmFormalParameter, String>map(overriddenOperation.getDeclaration().getParameters(), _function_1), ", ");
        _builder.append(_join);
        _builder.append(")");
        final String body = _builder.toString();
        final Procedure1<? super ISourceAppender> superTypeRef = this.getImplementedInterface(inferredType, overriddenOperation.getDeclaration().getDeclaringType());
        final Procedure1<ISourceAppender> _function_2 = (ISourceAppender it) -> {
            if (superTypeRef != null) {
                superTypeRef.apply(it);
            }
            it.append(body);
        };
        methodBuilder.setBodyGenerator(_function_2);
    }
    boolean _isValid = methodBuilder.isValid();
    if (_isValid) {
        methodBuilder.build(appendable);
    }
}
Also used : LightweightTypeReference(org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference) JvmTypeParameter(org.eclipse.xtext.common.types.JvmTypeParameter) JvmDeclaredType(org.eclipse.xtext.common.types.JvmDeclaredType) ISourceAppender(org.eclipse.xtext.xbase.compiler.ISourceAppender) JvmUpperBound(org.eclipse.xtext.common.types.JvmUpperBound) Consumer(java.util.function.Consumer) JvmFormalParameter(org.eclipse.xtext.common.types.JvmFormalParameter) StringConcatenation(org.eclipse.xtend2.lib.StringConcatenation) JvmTypeConstraint(org.eclipse.xtext.common.types.JvmTypeConstraint) ArrayList(java.util.ArrayList) EList(org.eclipse.emf.common.util.EList) List(java.util.List) AbstractMethodBuilder(org.eclipse.xtend.ide.codebuilder.AbstractMethodBuilder)

Example 29 with LightweightTypeReference

use of org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference in project xtext-xtend by eclipse.

the class XtendReentrantTypeResolver method normalizeDispatchReturnType.

protected LightweightTypeReference normalizeDispatchReturnType(LightweightTypeReference declaredType, List<LightweightTypeReference> computedTypes, LightweightTypeReference implicitVoidOrNull, LightweightTypeReference thrownVoidOrNull, ResolvedTypes resolvedTypes) {
    LightweightTypeReference result = null;
    if (declaredType != null) {
        result = declaredType;
    } else {
        if (implicitVoidOrNull != null && !computedTypes.isEmpty()) {
            List<LightweightTypeReference> wrapped = Lists.newArrayListWithCapacity(computedTypes.size());
            for (int i = 0; i < computedTypes.size(); i++) {
                wrapped.add(computedTypes.get(i).getWrapperTypeIfPrimitive());
            }
            computedTypes = wrapped;
        }
        if (computedTypes.isEmpty() && implicitVoidOrNull != null) {
            result = implicitVoidOrNull;
        } else {
            if (computedTypes.isEmpty()) {
                if (thrownVoidOrNull == null) {
                    throw new IllegalStateException("thrownVoidOrNull may not be null in this situation");
                }
                result = thrownVoidOrNull;
            } else {
                result = getServices().getTypeConformanceComputer().getCommonSuperType(computedTypes, resolvedTypes.getReferenceOwner());
            }
        }
    }
    return result;
}
Also used : LightweightTypeReference(org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference)

Example 30 with LightweightTypeReference

use of org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference in project xtext-xtend by eclipse.

the class XtendReentrantTypeResolver method _computeTypes.

@Override
protected void _computeTypes(Map<JvmIdentifiableElement, ResolvedTypes> preparedResolvedTypes, ResolvedTypes resolvedTypes, IFeatureScopeSession featureScopeSession, JvmOperation operation) {
    ResolvedTypes childResolvedTypes = preparedResolvedTypes.get(operation);
    if (childResolvedTypes == null) {
        if (preparedResolvedTypes.containsKey(operation))
            return;
        throw new IllegalStateException("No resolved type found. Type was: " + operation.getIdentifier());
    }
    if (dispatchHelper.isDispatcherFunction(operation)) {
        // no associated expression, we just resolve it to the common super type of all associated cases
        // see #createTypeProvider and #_doPrepare
        preparedResolvedTypes.put(operation, null);
        computeAnnotationTypes(childResolvedTypes, featureScopeSession, operation);
        mergeChildTypes(childResolvedTypes);
    } else if (dispatchHelper.isDispatchFunction(operation) && InferredTypeIndicator.isInferred(operation.getReturnType())) {
        JvmOperation dispatcher = dispatchHelper.getDispatcherOperation(operation);
        if (dispatcher == null) {
            super._computeTypes(preparedResolvedTypes, resolvedTypes, featureScopeSession, operation);
            return;
        }
        List<JvmOperation> dispatchCasesWithDeclaredReturnType = new ArrayList<JvmOperation>();
        List<JvmOperation> dispatchCasesWithInferredReturnType = new ArrayList<JvmOperation>();
        List<JvmOperation> dispatchCases = dispatchHelper.getLocalDispatchCases(dispatcher);
        for (JvmOperation dispatchCase : dispatchCases) {
            if (InferredTypeIndicator.isInferred(dispatchCase.getReturnType())) {
                dispatchCasesWithInferredReturnType.add(dispatchCase);
            } else {
                dispatchCasesWithDeclaredReturnType.add(dispatchCase);
            }
        }
        try {
            markComputing(dispatcher.getReturnType());
            LightweightTypeReference declaredDispatcherType = getReturnTypeOfOverriddenOperation(dispatcher, childResolvedTypes, featureScopeSession);
            List<LightweightTypeReference> dispatchCaseResults = Lists.newArrayListWithCapacity(dispatchCases.size());
            LightweightTypeReference implicitVoid = null;
            LightweightTypeReference thrownVoid = null;
            for (JvmOperation dispatchCase : dispatchCasesWithDeclaredReturnType) {
                ResolvedTypes dispatchCaseResolvedTypes = preparedResolvedTypes.get(dispatchCase);
                if (dispatchCaseResolvedTypes == null) {
                    if (preparedResolvedTypes.containsKey(dispatchCase)) {
                        dispatchCaseResolvedTypes = childResolvedTypes;
                    }
                }
                if (dispatchCaseResolvedTypes == null) {
                    throw new IllegalStateException("No resolved type found. Type was: " + dispatchCase.getIdentifier());
                }
                dispatchCaseResults.add(dispatchCaseResolvedTypes.getActualType(dispatchCase));
            }
            List<ResolvedTypes> mergeUs = Lists.newArrayList();
            for (JvmOperation dispatchCase : dispatchCasesWithInferredReturnType) {
                ResolvedTypes dispatchCaseResolvedTypes = dispatchCase == operation ? childResolvedTypes : preparedResolvedTypes.get(dispatchCase);
                if (dispatchCaseResolvedTypes == null) {
                    if (preparedResolvedTypes.containsKey(dispatchCase)) {
                        if (InferredTypeIndicator.isInferred(dispatchCase.getReturnType())) {
                            if (declaredDispatcherType == null) {
                                dispatchCaseResults.add(childResolvedTypes.getActualType(dispatchCase));
                            }
                        } else {
                            dispatchCaseResults.add(childResolvedTypes.getActualType(dispatchCase));
                        }
                    } else {
                        throw new IllegalStateException("No resolved type found. Type was: " + dispatchCase.getIdentifier());
                    }
                } else {
                    mergeUs.add(dispatchCaseResolvedTypes);
                    preparedResolvedTypes.put(dispatchCase, null);
                    OperationBodyComputationState state = new DispatchOperationBodyComputationState(dispatchCaseResolvedTypes, dispatchCase.isStatic() ? featureScopeSession : featureScopeSession.toInstanceContext(), dispatchCase, dispatcher, declaredDispatcherType);
                    addExtensionProviders(state, dispatchCase.getParameters());
                    ITypeComputationResult dispatchCaseResult = null;
                    try {
                        markComputing(dispatchCase.getReturnType());
                        dispatchCaseResult = state.computeTypes();
                    } finally {
                        unmarkComputing(dispatchCase.getReturnType());
                    }
                    if (InferredTypeIndicator.isInferred(dispatchCase.getReturnType())) {
                        if (declaredDispatcherType == null) {
                            LightweightTypeReference returnType = dispatchCaseResult.getReturnType();
                            if (returnType != null) {
                                if (returnType.isPrimitiveVoid()) {
                                    int conformanceFlags = dispatchCaseResult.getConformanceFlags();
                                    if ((conformanceFlags & ConformanceFlags.THROWN_EXCEPTION) == 0) {
                                        if ((conformanceFlags & ConformanceFlags.NO_IMPLICIT_RETURN) != 0) {
                                            dispatchCaseResults.add(returnType);
                                        } else {
                                            implicitVoid = returnType;
                                        }
                                    } else {
                                        thrownVoid = returnType;
                                    }
                                } else {
                                    dispatchCaseResults.add(returnType);
                                }
                            }
                        }
                    } else {
                        LightweightTypeReference explicitType = dispatchCaseResolvedTypes.getActualType(dispatchCase);
                        dispatchCaseResults.add(explicitType);
                    }
                    computeAnnotationTypes(dispatchCaseResolvedTypes, featureScopeSession, dispatchCase);
                    computeLocalTypes(preparedResolvedTypes, dispatchCaseResolvedTypes, featureScopeSession, dispatchCase);
                }
            }
            LightweightTypeReference commonDispatchType = normalizeDispatchReturnType(declaredDispatcherType, dispatchCaseResults, implicitVoid, thrownVoid, childResolvedTypes);
            if (commonDispatchType != null) {
                resolveDispatchCaseTypes(dispatcher, dispatchCasesWithInferredReturnType, commonDispatchType, featureScopeSession);
            }
            // deferred merge since #normalizeDispatchReturnType may add more hints to the different dispatch cases
            for (ResolvedTypes mergeMe : mergeUs) {
                mergeChildTypes(mergeMe);
            }
        } finally {
            unmarkComputing(dispatcher.getReturnType());
        }
    } else {
        super._computeTypes(preparedResolvedTypes, resolvedTypes, featureScopeSession, operation);
    }
}
Also used : JvmOperation(org.eclipse.xtext.common.types.JvmOperation) OperationBodyComputationState(org.eclipse.xtext.xbase.typesystem.internal.OperationBodyComputationState) LightweightTypeReference(org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference) ITypeComputationResult(org.eclipse.xtext.xbase.typesystem.computation.ITypeComputationResult) List(java.util.List) ArrayList(java.util.ArrayList) ResolvedTypes(org.eclipse.xtext.xbase.typesystem.internal.ResolvedTypes) IResolvedTypes(org.eclipse.xtext.xbase.typesystem.IResolvedTypes)

Aggregations

LightweightTypeReference (org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference)83 Test (org.junit.Test)28 XtendFunction (org.eclipse.xtend.core.xtend.XtendFunction)23 XExpression (org.eclipse.xtext.xbase.XExpression)22 JvmOperation (org.eclipse.xtext.common.types.JvmOperation)20 StringConcatenation (org.eclipse.xtend2.lib.StringConcatenation)19 JvmFormalParameter (org.eclipse.xtext.common.types.JvmFormalParameter)16 XtendClass (org.eclipse.xtend.core.xtend.XtendClass)13 JvmDeclaredType (org.eclipse.xtext.common.types.JvmDeclaredType)10 XBlockExpression (org.eclipse.xtext.xbase.XBlockExpression)10 IFeatureCallArguments (org.eclipse.xtext.xbase.typesystem.arguments.IFeatureCallArguments)10 JvmTypeReference (org.eclipse.xtext.common.types.JvmTypeReference)9 XNumberLiteral (org.eclipse.xtext.xbase.XNumberLiteral)9 JvmType (org.eclipse.xtext.common.types.JvmType)8 ITypeReferenceOwner (org.eclipse.xtext.xbase.typesystem.references.ITypeReferenceOwner)8 EObject (org.eclipse.emf.ecore.EObject)7 JvmIdentifiableElement (org.eclipse.xtext.common.types.JvmIdentifiableElement)7 StandardTypeReferenceOwner (org.eclipse.xtext.xbase.typesystem.references.StandardTypeReferenceOwner)7 RichString (org.eclipse.xtend.core.xtend.RichString)6 JvmTypeParameter (org.eclipse.xtext.common.types.JvmTypeParameter)6