protected void computeFeatureCallHighlighting(
     XAbstractFeatureCall featureCall, IHighlightedPositionAcceptor acceptor) {
   JvmIdentifiableElement feature = featureCall.getFeature();
   if (feature != null && !feature.eIsProxy()) {
     if (feature instanceof JvmField) {
       if (((JvmField) feature).isStatic()) {
         highlightFeatureCall(featureCall, acceptor, STATIC_FIELD);
       } else {
         highlightFeatureCall(featureCall, acceptor, FIELD);
       }
     } else if (feature instanceof JvmOperation && !featureCall.isOperation()) {
       JvmOperation jvmOperation = (JvmOperation) feature;
       if (jvmOperation.isStatic())
         highlightFeatureCall(featureCall, acceptor, STATIC_METHOD_INVOCATION);
     }
     if (!(featureCall instanceof XBinaryOperation
         || featureCall instanceof XUnaryOperation
         || featureCall instanceof XPostfixOperation)) {
       if (featureCall.isExtension()) {
         highlightFeatureCall(featureCall, acceptor, EXTENSION_METHOD_INVOCATION);
       } else {
         // Extensions without implicit first argument
         XExpression implicitReceiver = featureCall.getImplicitReceiver();
         if (implicitReceiver != null && implicitReceiver instanceof XAbstractFeatureCall) {
           if (isExtension(((XAbstractFeatureCall) implicitReceiver).getFeature()))
             highlightFeatureCall(featureCall, acceptor, EXTENSION_METHOD_INVOCATION);
         }
       }
     }
     if (feature instanceof JvmAnnotationTarget
         && DeprecationUtil.isDeprecated((JvmAnnotationTarget) feature)) {
       highlightFeatureCall(featureCall, acceptor, DEPRECATED_MEMBERS);
     }
   }
 }
 protected void computeInferredReturnTypes(JvmGenericType inferredJvmType) {
   Iterable<JvmOperation> operations = inferredJvmType.getDeclaredOperations();
   for (JvmOperation jvmOperation : operations) {
     if (!jvmOperation.eIsSet(TypesPackage.Literals.JVM_OPERATION__RETURN_TYPE))
       jvmOperation.setReturnType(getTypeProxy(jvmOperation));
   }
 }
 public boolean initialize(EObject xtendMethod, IRenameElementContext context) {
   Assert.isLegal(xtendMethod instanceof XtendFunction);
   Assert.isLegal(((XtendFunction) xtendMethod).isDispatch());
   Assert.isLegal(context instanceof DispatchMethodRenameContext);
   ResourceSet resourceSet = xtendMethod.eResource().getResourceSet();
   Map<URI, IJavaElement> jvm2JavaElements =
       ((DispatchMethodRenameContext) context).getJvm2JavaElements();
   for (URI dispatchOperationURI : jvm2JavaElements.keySet()) {
     JvmOperation dispatchOperation =
         (JvmOperation) resourceSet.getEObject(dispatchOperationURI, true);
     XtendFunction xtendDispatchMethod = associations.getXtendFunction(dispatchOperation);
     if (xtendDispatchMethod != null) {
       if (equal(xtendDispatchMethod.getName(), dispatchOperation.getSimpleName())) {
         // synthetic dispatcher
         dispatchers.add(dispatchOperation);
       } else {
         // xtend dispatch method
         XtendDispatchMethodChildStrategy xtendChildStrategy = childStrategyProvider.get();
         xtendChildStrategy.initialize(xtendDispatchMethod, context);
         children.add(xtendChildStrategy);
       }
     } else {
       // a dispatch method form a Java class
       JavaDispatchMethodChildStrategy jvmChildStrategy = javaStrategyProvider.get();
       jvmChildStrategy.initialize(dispatchOperation, context);
       children.add(jvmChildStrategy);
     }
   }
   return !children.isEmpty();
 }
Example #4
0
 @Test
 public void testEmptyListAsAnnotationValueDefault() {
   try {
     StringConcatenation _builder = new StringConcatenation();
     _builder.append("annotation Foo {");
     _builder.newLine();
     _builder.append("\t");
     _builder.append("String[] bar = #[]");
     _builder.newLine();
     _builder.append("}");
     _builder.newLine();
     String _string = _builder.toString();
     XtendAnnotationType _annotationType = this.annotationType(_string);
     JvmAnnotationType _inferredAnnotationType =
         this._iXtendJvmAssociations.getInferredAnnotationType(_annotationType);
     EList<JvmMember> _members = _inferredAnnotationType.getMembers();
     JvmMember _head = IterableExtensions.<JvmMember>head(_members);
     final JvmOperation inferred = ((JvmOperation) _head);
     JvmTypeReference _returnType = inferred.getReturnType();
     String _identifier = _returnType.getIdentifier();
     Assert.assertEquals("java.lang.String[]", _identifier);
     JvmAnnotationValue _defaultValue = inferred.getDefaultValue();
     Assert.assertTrue((_defaultValue instanceof JvmStringAnnotationValue));
     JvmAnnotationValue _defaultValue_1 = inferred.getDefaultValue();
     EList<String> _values = ((JvmStringAnnotationValue) _defaultValue_1).getValues();
     boolean _isEmpty = _values.isEmpty();
     Assert.assertTrue(_isEmpty);
   } catch (Throwable _e) {
     throw Exceptions.sneakyThrow(_e);
   }
 }
Example #5
0
 protected IScope createLocalVarScopeForJvmOperation(JvmOperation context, IScope parentScope) {
   EList<JvmFormalParameter> parameters = context.getParameters();
   List<LocalVarDescription> descriptions = newArrayList();
   for (JvmFormalParameter p : parameters) {
     if (p.getName() != null)
       descriptions.add(new LocalVarDescription(QualifiedName.create(p.getName()), p));
   }
   return new JvmFeatureScope(parentScope, "operation " + context.getSimpleName(), descriptions);
 }
 protected void appendSyntheticDispatchMethods(XtendClass source, JvmGenericType target) {
   Multimap<Pair<String, Integer>, JvmOperation> methods =
       dispatchingSupport.getDispatchMethods(target);
   for (Pair<String, Integer> key : methods.keySet()) {
     Collection<JvmOperation> operations = methods.get(key);
     JvmOperation operation =
         deriveGenericDispatchOperationSignature(dispatchingSupport.sort(operations), target);
     operation.setSimpleName(key.getFirst());
   }
 }
Example #7
0
 public Method getMethod(JvmOperation operation) {
   Class<?> rawType = getRawType(operation.getDeclaringType());
   if (rawType == null) return null;
   Class<?>[] paramTypes = getParamTypes(operation);
   try {
     return rawType.getDeclaredMethod(operation.getSimpleName(), paramTypes);
   } catch (Exception e) {
     LOG.error("Can't find " + operation.getIdentifier(), e);
     return null;
   }
 }
 @Override
 protected JvmOperation getMethodFromType(EObject context, Class<?> type, String method) {
   JvmOperation result = super.getMethodFromType(context, type, method);
   if (result != null) {
     IJavaElement found = elementFinder.findElementFor(result);
     assertEquals(IJavaElement.METHOD, found.getElementType());
     assertEquals(result.getSimpleName(), found.getElementName());
     IMethod foundMethod = (IMethod) found;
     assertEquals(result.getParameters().size(), foundMethod.getNumberOfParameters());
   }
   return result;
 }
 private static JvmOperation mockJvmOperation(String name, boolean isAbstract) {
   JvmOperation operation = mock(JvmOperation.class);
   when(operation.isAbstract()).thenReturn(isAbstract);
   when(operation.isStatic()).thenReturn(false);
   when(operation.isDefault()).thenReturn(false);
   when(operation.isDeprecated()).thenReturn(false);
   when(operation.isFinal()).thenReturn(false);
   when(operation.isSynchronized()).thenReturn(false);
   when(operation.isNative()).thenReturn(false);
   when(operation.getSimpleName()).thenReturn(name);
   when(operation.getAnnotations()).thenReturn(new BasicEList<JvmAnnotationReference>());
   return operation;
 }
 protected String _case(
     JvmOperation input,
     XUnaryOperation context,
     EReference reference,
     JvmFeatureDescription jvmFeatureDescription) {
   if (input.getParameters().size() != 1) return INVALID_NUMBER_OF_ARGUMENTS;
   if (context.getOperand() != null) {
     JvmTypeReference operandType = getTypeProvider().getType(context.getOperand(), true);
     final JvmFormalParameter param = input.getParameters().get(0);
     if (!conformance.isConformant(param.getParameterType(), operandType, true))
       return INVALID_ARGUMENT_TYPES;
   }
   return null;
 }
 protected String _case(
     JvmOperation input,
     XAssignment context,
     EReference ref,
     JvmFeatureDescription jvmFeatureDescription) {
   final int irrelevantArguments = jvmFeatureDescription.getNumberOfIrrelevantArguments();
   if (input.getParameters().size() != (1 + irrelevantArguments))
     return INVALID_NUMBER_OF_ARGUMENTS;
   if (context.getValue() != null) {
     JvmTypeReference type = getTypeProvider().getType(context.getValue(), true);
     final JvmFormalParameter valueParam = input.getParameters().get(0 + irrelevantArguments);
     if (!isCompatibleArgument(valueParam.getParameterType(), type)) return INVALID_ARGUMENT_TYPES;
   }
   return null;
 }
 protected String _case(
     JvmOperation input,
     XMemberFeatureCall context,
     EReference ref,
     JvmFeatureDescription jvmFeatureDescription) {
   if (input.isStatic()
       && input.getParameters().size() == context.getMemberCallArguments().size()) {
     return INSTANCE_ACCESS_TO_STATIC_MEMBER;
   } else {
     return checkJvmOperation(
         input,
         context,
         context.isExplicitOperationCall(),
         jvmFeatureDescription,
         context.getMemberCallArguments());
   }
 }
 protected String _case(
     JvmOperation input,
     XBinaryOperation context,
     EReference ref,
     JvmFeatureDescription jvmFeatureDescription) {
   final int irrelevantArguments = jvmFeatureDescription.getNumberOfIrrelevantArguments();
   if (input.getParameters().size() - irrelevantArguments != 1) return INVALID_NUMBER_OF_ARGUMENTS;
   if (context.getRightOperand() != null && context.getLeftOperand() != null) {
     JvmTypeReference rightOperandType =
         getTypeProvider().getType(context.getRightOperand(), true);
     if (rightOperandType == null) return INVALID_ARGUMENT_TYPES;
     final JvmFormalParameter rightParam = input.getParameters().get(0 + irrelevantArguments);
     if (!conformance.isConformant(rightParam.getParameterType(), rightOperandType, true))
       return INVALID_ARGUMENT_TYPES;
   }
   return null;
 }
 protected IFeatureCallArguments toArguments(
     final String signature, final String invocation, final boolean receiver) {
   try {
     StringConcatenation _builder = new StringConcatenation();
     _builder.append("def void m(");
     _builder.append(signature, "");
     _builder.append(") {");
     _builder.newLineIfNotEmpty();
     _builder.append("\t");
     _builder.append("m(");
     _builder.append(invocation, "\t");
     _builder.append(")");
     _builder.newLineIfNotEmpty();
     _builder.append("}");
     _builder.newLine();
     final String functionString = _builder.toString();
     final XtendFunction function = this.function(functionString);
     XExpression _expression = function.getExpression();
     final XBlockExpression body = ((XBlockExpression) _expression);
     EList<XExpression> _expressions = body.getExpressions();
     XExpression _head = IterableExtensions.<XExpression>head(_expressions);
     final XFeatureCall featureCall = ((XFeatureCall) _head);
     final EList<XExpression> arguments = featureCall.getFeatureCallArguments();
     final JvmOperation operation =
         this._iXtendJvmAssociations.getDirectlyInferredOperation(function);
     EList<JvmFormalParameter> _parameters = operation.getParameters();
     ITypeReferenceOwner _owner = this.getOwner();
     final IFeatureCallArguments result =
         this.factory.createVarArgArguments(arguments, _parameters, receiver, _owner);
     Class<? extends IFeatureCallArguments> _class = result.getClass();
     boolean _equals = Objects.equal(_class, VarArgFeatureCallArguments.class);
     Assert.assertTrue(_equals);
     return result;
   } catch (Throwable _e) {
     throw Exceptions.sneakyThrow(_e);
   }
 }
Example #15
0
 protected IScope createTypeScope(
     JvmIdentifiableElement context, EReference reference, IScope parentScope) {
   if (context == null) return parentScope;
   if (context.eContainer() instanceof JvmIdentifiableElement) {
     parentScope =
         createTypeScope((JvmIdentifiableElement) context.eContainer(), reference, parentScope);
   }
   if (context instanceof JvmGenericType) {
     JvmGenericType genericType = (JvmGenericType) context;
     List<IEObjectDescription> descriptions = Lists.newArrayList();
     if (genericType.getSimpleName() != null) {
       QualifiedName inferredDeclaringTypeName = QualifiedName.create(genericType.getSimpleName());
       descriptions.add(EObjectDescription.create(inferredDeclaringTypeName, genericType));
     }
     for (JvmTypeParameter param : genericType.getTypeParameters()) {
       if (param.getSimpleName() != null) {
         QualifiedName paramName = QualifiedName.create(param.getSimpleName());
         descriptions.add(EObjectDescription.create(paramName, param));
       }
     }
     if (!descriptions.isEmpty()) return MapBasedScope.createScope(parentScope, descriptions);
   } else if (context instanceof JvmOperation) {
     JvmOperation operation = (JvmOperation) context;
     List<IEObjectDescription> descriptions = null;
     for (JvmTypeParameter param : operation.getTypeParameters()) {
       if (param.getSimpleName() != null) {
         if (descriptions == null) descriptions = Lists.newArrayList();
         QualifiedName paramName = QualifiedName.create(param.getSimpleName());
         descriptions.add(EObjectDescription.create(paramName, param));
       }
     }
     if (descriptions != null && !descriptions.isEmpty())
       return MapBasedScope.createScope(parentScope, descriptions);
   }
   return parentScope;
 }
 protected String _case(
     JvmOperation input,
     XFeatureCall context,
     EReference reference,
     JvmFeatureDescription jvmFeatureDescription) {
   if (context.getDeclaringType() != null) {
     if (!input.isStatic()) return STATIC_ACCESS_TO_INSTANCE_MEMBER;
   }
   return checkJvmOperation(
       input,
       context,
       context.isExplicitOperationCall(),
       jvmFeatureDescription,
       context.getFeatureCallArguments());
 }
 protected SignatureHashBuilder appendSignature(JvmOperation operation) {
   appendVisibility(operation.getVisibility()).append(" ");
   if (operation.isAbstract()) append("abstract ");
   if (operation.isStatic()) append("static ");
   if (operation.isFinal()) append("final ");
   appendType(operation.getReturnType())
       .appendTypeParameters(operation)
       .append(" ")
       .append(operation.getSimpleName())
       .append("(");
   for (JvmFormalParameter p : operation.getParameters()) {
     appendType(p.getParameterType());
     append(" ");
   }
   append(") ");
   for (JvmTypeReference ex : operation.getExceptions()) {
     appendType(ex).append(" ");
   }
   return this;
 }
 protected String checkJvmOperation(
     JvmOperation input,
     XAbstractFeatureCall context,
     boolean isExplicitOperationCall,
     JvmFeatureDescription jvmFeatureDescription,
     EList<XExpression> arguments) {
   List<XExpression> actualArguments =
       featureCall2JavaMapping.getActualArguments(
           context, input, jvmFeatureDescription.getImplicitReceiver());
   if (!isValidNumberOfArguments(input, actualArguments)) return INVALID_NUMBER_OF_ARGUMENTS;
   if (!isExplicitOperationCall
       && !isSugaredMethodInvocationWithoutParanthesis(jvmFeatureDescription))
     return METHOD_ACCESS_WITHOUT_PARENTHESES;
   if (!context.getTypeArguments().isEmpty() // raw type or type inference
       && input.getTypeParameters().size() != context.getTypeArguments().size())
     return INVALID_NUMBER_OF_TYPE_ARGUMENTS;
   // TODO check type parameter bounds against type arguments
   if (!areArgumentTypesValid(input, actualArguments)) return INVALID_ARGUMENT_TYPES;
   return null;
 }
Example #19
0
 @Test
 public void testEnumArtificialMethods() {
   try {
     StringConcatenation _builder = new StringConcatenation();
     _builder.append("package bar");
     _builder.newLine();
     _builder.newLine();
     _builder.append("enum Foo {");
     _builder.newLine();
     _builder.append("}");
     _builder.newLine();
     String _string = _builder.toString();
     XtendEnum _enumeration = this.enumeration(_string);
     JvmEnumerationType _inferredEnumerationType =
         this._iXtendJvmAssociations.getInferredEnumerationType(_enumeration);
     final EList<JvmMember> inferred = _inferredEnumerationType.getMembers();
     int _size = inferred.size();
     Assert.assertEquals(2, _size);
     JvmMember _get = inferred.get(0);
     final JvmOperation values = ((JvmOperation) _get);
     String _identifier = values.getIdentifier();
     Assert.assertEquals("bar.Foo.values()", _identifier);
     boolean _isStatic = values.isStatic();
     Assert.assertTrue(_isStatic);
     JvmVisibility _visibility = values.getVisibility();
     Assert.assertEquals(JvmVisibility.PUBLIC, _visibility);
     JvmMember _get_1 = inferred.get(1);
     final JvmOperation valueOf = ((JvmOperation) _get_1);
     String _identifier_1 = valueOf.getIdentifier();
     Assert.assertEquals("bar.Foo.valueOf(java.lang.String)", _identifier_1);
     boolean _isStatic_1 = valueOf.isStatic();
     Assert.assertTrue(_isStatic_1);
     JvmVisibility _visibility_1 = valueOf.getVisibility();
     Assert.assertEquals(JvmVisibility.PUBLIC, _visibility_1);
   } catch (Throwable _e) {
     throw Exceptions.sneakyThrow(_e);
   }
 }
  protected void convertFunctionType(
      final JvmTypeReference expectedType,
      final JvmTypeReference functionType,
      final ITreeAppendable appendable,
      final Later expression,
      XExpression context) {
    //		JvmTypeReference resolvedLeft = closures.getResolvedExpectedType(expectedType,
    // functionType);
    if (expectedType.getIdentifier().equals(Object.class.getName())
        || EcoreUtil.equals(expectedType.getType(), functionType.getType())
        || ((expectedType instanceof JvmSynonymTypeReference)
            && Iterables.any(
                ((JvmSynonymTypeReference) expectedType).getReferences(),
                new Predicate<JvmTypeReference>() {
                  public boolean apply(@Nullable JvmTypeReference ref) {
                    return EcoreUtil.equals(ref.getType(), functionType.getType());
                  }
                }))) {
      // same raw type but different type parameters
      // at this point we know that we are compatible so we have to convince the Java compiler about
      // that ;-)
      if (!getTypeConformanceComputer().isConformant(expectedType, functionType)) {
        // insert a cast
        appendable.append("(");
        serialize(expectedType, context, appendable);
        appendable.append(")");
      }
      expression.exec(appendable);
      return;
    }
    JvmOperation operation = closures.findImplementingOperation(expectedType, context.eResource());
    if (operation == null) {
      throw new IllegalStateException(
          "expected type " + expectedType + " not mappable from " + functionType);
    }
    JvmType declaringType =
        (expectedType instanceof JvmParameterizedTypeReference)
            ? expectedType.getType()
            : operation.getDeclaringType();
    final JvmTypeReference typeReferenceWithPlaceHolder =
        getTypeReferences().createTypeRef(declaringType);
    ITypeArgumentContext typeArgumentContext =
        contextProvider.getTypeArgumentContext(
            new TypeArgumentContextProvider.AbstractRequest() {
              @Override
              public JvmTypeReference getExpectedType() {
                return functionType;
              }

              @Override
              public JvmTypeReference getDeclaredType() {
                return typeReferenceWithPlaceHolder;
              }

              @Override
              public String toString() {
                return "TypeConvertingCompiler.convertFunctionType [expected="
                    + functionType
                    + ",declared="
                    + typeReferenceWithPlaceHolder
                    + "]";
              }
            });
    JvmTypeReference resolvedExpectedType =
        typeArgumentContext.resolve(typeReferenceWithPlaceHolder);
    appendable.append("new ");
    serialize(resolvedExpectedType, context, appendable, true, false);
    appendable.append("() {");
    appendable.increaseIndentation().increaseIndentation();
    appendable.newLine().append("public ");
    serialize(
        typeArgumentContext.resolve(operation.getReturnType()), context, appendable, true, false);
    appendable.append(" ").append(operation.getSimpleName()).append("(");
    EList<JvmFormalParameter> params = operation.getParameters();
    for (Iterator<JvmFormalParameter> iterator = params.iterator(); iterator.hasNext(); ) {
      JvmFormalParameter p = iterator.next();
      final String name = p.getName();
      serialize(
          typeArgumentContext.resolve(p.getParameterType()), context, appendable, false, false);
      appendable.append(" ").append(name);
      if (iterator.hasNext()) appendable.append(",");
    }
    appendable.append(") {");
    appendable.increaseIndentation();
    if (!getTypeReferences().is(operation.getReturnType(), Void.TYPE))
      appendable.newLine().append("return ");
    else appendable.newLine();
    expression.exec(appendable);
    appendable.append(".");
    JvmOperation actualOperation =
        closures.findImplementingOperation(functionType, context.eResource());
    appendable.append(actualOperation.getSimpleName());
    appendable.append("(");
    for (Iterator<JvmFormalParameter> iterator = params.iterator(); iterator.hasNext(); ) {
      JvmFormalParameter p = iterator.next();
      final String name = p.getName();
      appendable.append(name);
      if (iterator.hasNext()) appendable.append(",");
    }
    appendable.append(");");
    appendable.decreaseIndentation();
    appendable.newLine().append("}");
    appendable.decreaseIndentation().decreaseIndentation();
    appendable.newLine().append("}");
  }
 public void revertDeclarationChange(ResourceSet resourceSet) {
   for (IRenameStrategy child : children) child.revertDeclarationChange(resourceSet);
   for (JvmOperation dispatcher : dispatchers) {
     dispatcher.setSimpleName(getOriginalName());
   }
 }
 public void applyDeclarationChange(String newName, ResourceSet resourceSet) {
   for (IRenameStrategy child : children) child.applyDeclarationChange(newName, resourceSet);
   for (JvmOperation dispatcher : dispatchers) {
     dispatcher.setSimpleName(newName);
   }
 }
  public CharSequence apply(ImportManager importManager) {
    JvmOperation cacheMethod =
        (JvmOperation)
            logicalContainerProvider.getLogicalContainer(createExtensionInfo.getCreateExpression());
    StringBuilderBasedAppendable appendable = new StringBuilderBasedAppendable(importManager);
    JvmDeclaredType containerType = cacheMethod.getDeclaringType();
    JvmTypeReference listType = typeReferences.getTypeForName(ArrayList.class, containerType);
    JvmTypeReference collectonLiterals =
        typeReferences.getTypeForName(CollectionLiterals.class, containerType);
    String cacheVarName = cacheField.getSimpleName();
    String cacheKeyVarName = appendable.declareVariable("CacheKey", "_cacheKey");
    appendable.append("final ");
    typeReferenceSerializer.serialize(listType, containerType, appendable);
    appendable.append(cacheKeyVarName).append(" = ");
    typeReferenceSerializer.serialize(collectonLiterals, containerType, appendable);
    appendable.append(".newArrayList(");
    EList<JvmFormalParameter> list = cacheMethod.getParameters();
    for (Iterator<JvmFormalParameter> iterator = list.iterator(); iterator.hasNext(); ) {
      JvmFormalParameter jvmFormalParameter = iterator.next();
      appendable.append(getVarName(jvmFormalParameter));
      if (iterator.hasNext()) {
        appendable.append(", ");
      }
    }
    appendable.append(");");
    // declare result variable
    JvmTypeReference returnType = typeProvider.getType(createExtensionInfo.getCreateExpression());
    appendable.append("\nfinal ");
    typeReferenceSerializer.serialize(returnType, containerType, appendable);
    String resultVarName = "_result";
    appendable.append(" ").append(resultVarName).append(";");
    // open synchronize block
    appendable.append("\nsynchronized (").append(cacheVarName).append(") {");
    appendable.increaseIndentation();
    // if the cache contains the key return the previously created object.
    appendable
        .append("\nif (")
        .append(cacheVarName)
        .append(".containsKey(")
        .append(cacheKeyVarName)
        .append(")) {");
    appendable.increaseIndentation();
    appendable
        .append("\nreturn ")
        .append(cacheVarName)
        .append(".get(")
        .append(cacheKeyVarName)
        .append(");");
    appendable.decreaseIndentation().append("\n}");
    // execute the creation
    compiler.toJavaStatement(createExtensionInfo.getCreateExpression(), appendable, true);
    appendable.append("\n");
    appendable.append(resultVarName).append(" = ");
    compiler.toJavaExpression(createExtensionInfo.getCreateExpression(), appendable);
    appendable.append(";");

    // store the newly created object in the cache
    appendable
        .append("\n")
        .append(cacheVarName)
        .append(".put(")
        .append(cacheKeyVarName)
        .append(", ")
        .append(resultVarName)
        .append(");");

    // close synchronize block
    appendable.decreaseIndentation();
    appendable.append("\n}");
    appendable
        .append("\n")
        .append(initializerMethod.getSimpleName())
        .append("(")
        .append(resultVarName);
    for (JvmFormalParameter parameter : cacheMethod.getParameters()) {
      appendable.append(", ").append(parameter.getName());
    }
    appendable.append(");");
    // return the result
    appendable.append("\nreturn ");
    appendable.append(resultVarName).append(";");
    return appendable.toString();
  }
Example #24
0
 public void generateBodyAnnotations(final XPackage pack) {
   final HashSet<ETypedElement> processed = CollectionLiterals.<ETypedElement>newHashSet();
   EList<XClassifier> _classifiers = pack.getClassifiers();
   for (final XClassifier xClassifier : _classifiers) {
     if ((xClassifier instanceof XDataType)) {
       final XDataType xDataType = ((XDataType) xClassifier);
       XDataTypeMapping _mapping = this.mappings.getMapping(xDataType);
       final EDataType eDataType = _mapping.getEDataType();
       final XBlockExpression createBody = xDataType.getCreateBody();
       XDataTypeMapping _mapping_1 = this.mappings.getMapping(xDataType);
       final JvmOperation creator = _mapping_1.getCreator();
       boolean _and = false;
       boolean _notEquals = (!Objects.equal(createBody, null));
       if (!_notEquals) {
         _and = false;
       } else {
         boolean _notEquals_1 = (!Objects.equal(creator, null));
         _and = (_notEquals && _notEquals_1);
       }
       if (_and) {
         final XcoreAppendable appendable = this.createAppendable();
         EList<JvmFormalParameter> _parameters = creator.getParameters();
         JvmFormalParameter _get = _parameters.get(0);
         appendable.declareVariable(_get, "it");
         JvmTypeReference _returnType = creator.getReturnType();
         Set<JvmTypeReference> _emptySet = Collections.<JvmTypeReference>emptySet();
         this.compiler.compile(createBody, appendable, _returnType, _emptySet);
         String _string = appendable.toString();
         String _extractBody = this.extractBody(_string);
         EcoreUtil.setAnnotation(eDataType, GenModelPackage.eNS_URI, "create", _extractBody);
       }
       final XBlockExpression convertBody = xDataType.getConvertBody();
       XDataTypeMapping _mapping_2 = this.mappings.getMapping(xDataType);
       final JvmOperation converter = _mapping_2.getConverter();
       boolean _and_1 = false;
       boolean _notEquals_2 = (!Objects.equal(convertBody, null));
       if (!_notEquals_2) {
         _and_1 = false;
       } else {
         boolean _notEquals_3 = (!Objects.equal(converter, null));
         _and_1 = (_notEquals_2 && _notEquals_3);
       }
       if (_and_1) {
         final XcoreAppendable appendable_1 = this.createAppendable();
         EList<JvmFormalParameter> _parameters_1 = converter.getParameters();
         JvmFormalParameter _get_1 = _parameters_1.get(0);
         appendable_1.declareVariable(_get_1, "it");
         JvmTypeReference _returnType_1 = converter.getReturnType();
         Set<JvmTypeReference> _emptySet_1 = Collections.<JvmTypeReference>emptySet();
         this.compiler.compile(convertBody, appendable_1, _returnType_1, _emptySet_1);
         String _string_1 = appendable_1.toString();
         String _extractBody_1 = this.extractBody(_string_1);
         EcoreUtil.setAnnotation(eDataType, GenModelPackage.eNS_URI, "convert", _extractBody_1);
       }
     } else {
       final XClass xClass = ((XClass) xClassifier);
       XClassMapping _mapping_3 = this.mappings.getMapping(xClass);
       final EClass eClass = _mapping_3.getEClass();
       EList<EStructuralFeature> _eAllStructuralFeatures = eClass.getEAllStructuralFeatures();
       for (final EStructuralFeature eStructuralFeature : _eAllStructuralFeatures) {
         boolean _add = processed.add(eStructuralFeature);
         if (_add) {
           final XStructuralFeature xFeature = this.mappings.getXFeature(eStructuralFeature);
           boolean _notEquals_4 = (!Objects.equal(xFeature, null));
           if (_notEquals_4) {
             final XBlockExpression getBody = xFeature.getGetBody();
             boolean _notEquals_5 = (!Objects.equal(getBody, null));
             if (_notEquals_5) {
               XFeatureMapping _mapping_4 = this.mappings.getMapping(xFeature);
               final JvmOperation getter = _mapping_4.getGetter();
               final XcoreAppendable appendable_2 = this.createAppendable();
               JvmTypeReference _returnType_2 = getter.getReturnType();
               Set<JvmTypeReference> _emptySet_2 = Collections.<JvmTypeReference>emptySet();
               this.compiler.compile(getBody, appendable_2, _returnType_2, _emptySet_2);
               String _string_2 = appendable_2.toString();
               String _extractBody_2 = this.extractBody(_string_2);
               EcoreUtil.setAnnotation(
                   eStructuralFeature, GenModelPackage.eNS_URI, "get", _extractBody_2);
             }
           }
         }
       }
       EList<EOperation> _eAllOperations = eClass.getEAllOperations();
       for (final EOperation eOperation : _eAllOperations) {
         boolean _add_1 = processed.add(eOperation);
         if (_add_1) {
           final XOperation xOperation = this.mappings.getXOperation(eOperation);
           boolean _notEquals_6 = (!Objects.equal(xOperation, null));
           if (_notEquals_6) {
             final XBlockExpression body = xOperation.getBody();
             boolean _notEquals_7 = (!Objects.equal(body, null));
             if (_notEquals_7) {
               XOperationMapping _mapping_5 = this.mappings.getMapping(xOperation);
               final JvmOperation jvmOperation = _mapping_5.getJvmOperation();
               boolean _notEquals_8 = (!Objects.equal(jvmOperation, null));
               if (_notEquals_8) {
                 final XcoreAppendable appendable_3 = this.createAppendable();
                 JvmDeclaredType _declaringType = jvmOperation.getDeclaringType();
                 appendable_3.declareVariable(_declaringType, "this");
                 JvmDeclaredType _declaringType_1 = jvmOperation.getDeclaringType();
                 EList<JvmTypeReference> _superTypes = _declaringType_1.getSuperTypes();
                 final JvmTypeReference superType =
                     IterableExtensions.<JvmTypeReference>head(_superTypes);
                 boolean _notEquals_9 = (!Objects.equal(superType, null));
                 if (_notEquals_9) {
                   JvmType _type = superType.getType();
                   appendable_3.declareVariable(_type, "super");
                 }
                 EList<JvmFormalParameter> _parameters_2 = jvmOperation.getParameters();
                 for (final JvmFormalParameter parameter : _parameters_2) {
                   String _name = parameter.getName();
                   appendable_3.declareVariable(parameter, _name);
                 }
                 JvmTypeReference _returnType_3 = jvmOperation.getReturnType();
                 EList<JvmTypeReference> _exceptions = jvmOperation.getExceptions();
                 HashSet<JvmTypeReference> _hashSet = new HashSet<JvmTypeReference>(_exceptions);
                 this.compiler.compile(body, appendable_3, _returnType_3, _hashSet);
                 String _string_3 = appendable_3.toString();
                 String _extractBody_3 = this.extractBody(_string_3);
                 EcoreUtil.setAnnotation(
                     eOperation, GenModelPackage.eNS_URI, "body", _extractBody_3);
               }
             }
           }
         }
       }
     }
   }
 }
 protected void createFeatureNodesForType(
     IOutlineNode parentNode,
     XtendTypeDeclaration xtendType,
     JvmDeclaredType inferredType,
     final JvmDeclaredType baseType,
     Set<JvmFeature> processedFeatures,
     int inheritanceDepth) {
   if (xtendType instanceof XtendClass) {
     for (JvmOperation operation : inferredType.getDeclaredOperations()) {
       if (dispatchHelper.isDispatcherFunction(operation)) {
         JvmOperation dispatcher = operation;
         XtendFeatureNode dispatcherNode =
             createNodeForFeature(parentNode, baseType, dispatcher, dispatcher, inheritanceDepth);
         if (dispatcherNode != null) {
           dispatcherNode.setDispatch(true);
           processedFeatures.add(dispatcher);
           boolean inheritsDispatchCases = false;
           Iterable<JvmOperation> dispatchCases;
           if (getCurrentMode() == SHOW_INHERITED_MODE)
             dispatchCases = dispatchHelper.getAllDispatchCases(dispatcher);
           else {
             dispatchCases = newArrayList(dispatchHelper.getLocalDispatchCases(dispatcher));
             sort(
                 (List<JvmOperation>) dispatchCases,
                 new Comparator<JvmOperation>() {
                   public int compare(JvmOperation o1, JvmOperation o2) {
                     return baseType.getMembers().indexOf(o1) - baseType.getMembers().indexOf(o2);
                   }
                 });
           }
           for (JvmOperation dispatchCase : dispatchCases) {
             inheritsDispatchCases |= dispatchCase.getDeclaringType() != baseType;
             XtendFunction xtendFunction = associations.getXtendFunction(dispatchCase);
             if (xtendFunction == null) {
               createNodeForFeature(
                   dispatcherNode, baseType, dispatchCase, dispatchCase, inheritanceDepth);
             } else {
               createNodeForFeature(
                   dispatcherNode, baseType, dispatchCase, xtendFunction, inheritanceDepth);
             }
             processedFeatures.add(dispatchCase);
           }
           if (inheritsDispatchCases)
             dispatcherNode.setImageDescriptor(
                 images.forDispatcherFunction(
                     dispatcher.getVisibility(),
                     adornments.get(dispatcher) | JavaElementImageDescriptor.OVERRIDES));
         }
       }
     }
   }
   for (JvmFeature feature : filter(inferredType.getMembers(), JvmFeature.class)) {
     if (!processedFeatures.contains(feature)) {
       EObject primarySourceElement = associations.getPrimarySourceElement(feature);
       createNodeForFeature(
           parentNode,
           baseType,
           feature,
           primarySourceElement != null ? primarySourceElement : feature,
           inheritanceDepth);
     }
   }
   if (getCurrentMode() == SHOW_INHERITED_MODE) {
     if (inferredType instanceof JvmGenericType) {
       JvmTypeReference extendedClass = ((JvmGenericType) inferredType).getExtendedClass();
       if (extendedClass != null)
         createInheritedFeatureNodes(
             parentNode, baseType, processedFeatures, inheritanceDepth, extendedClass);
       for (JvmTypeReference extendedInterface :
           ((JvmGenericType) inferredType).getExtendedInterfaces()) {
         createInheritedFeatureNodes(
             parentNode, baseType, processedFeatures, inheritanceDepth, extendedInterface);
       }
     }
   }
 }
 /**
  * @return a {@link JvmOperation} with common denominator argument types of all given operations
  */
 protected JvmOperation deriveGenericDispatchOperationSignature(
     List<JvmOperation> sortedOperations, JvmGenericType target) {
   if (sortedOperations.isEmpty()) return null;
   final Iterator<JvmOperation> iterator = sortedOperations.iterator();
   JvmOperation first = iterator.next();
   JvmOperation result = typesFactory.createJvmOperation();
   target.getMembers().add(result);
   for (int i = 0; i < first.getParameters().size(); i++) {
     JvmFormalParameter parameter = typesFactory.createJvmFormalParameter();
     result.getParameters().add(parameter);
     parameter.setParameterType(getTypeProxy(parameter));
     JvmFormalParameter parameter2 = first.getParameters().get(i);
     parameter.setName(parameter2.getName());
   }
   jvmTypesBuilder.setBody(result, compileStrategies.forDispatcher(result, sortedOperations));
   JvmVisibility commonVisibility = null;
   boolean isFirst = true;
   boolean allStatic = true;
   for (JvmOperation jvmOperation : sortedOperations) {
     Iterable<XtendFunction> xtendFunctions =
         filter(associations.getSourceElements(jvmOperation), XtendFunction.class);
     for (XtendFunction func : xtendFunctions) {
       JvmVisibility xtendVisibility =
           func.eIsSet(Xtend2Package.Literals.XTEND_FUNCTION__VISIBILITY)
               ? func.getVisibility()
               : null;
       if (isFirst) {
         commonVisibility = xtendVisibility;
         isFirst = false;
       } else if (commonVisibility != xtendVisibility) {
         commonVisibility = null;
       }
       associator.associate(func, result);
       if (!func.isStatic()) allStatic = false;
     }
     for (JvmTypeReference declaredException : jvmOperation.getExceptions())
       result.getExceptions().add(cloneWithProxies(declaredException));
   }
   if (commonVisibility == null) result.setVisibility(JvmVisibility.PUBLIC);
   else result.setVisibility(commonVisibility);
   result.setStatic(allStatic);
   return result;
 }
  protected void transform(XtendFunction source, JvmGenericType container) {
    JvmOperation operation = typesFactory.createJvmOperation();
    container.getMembers().add(operation);
    associator.associatePrimary(source, operation);
    String sourceName = source.getName();
    JvmVisibility visibility = source.getVisibility();
    if (source.isDispatch()) {
      if (!source.eIsSet(Xtend2Package.Literals.XTEND_FUNCTION__VISIBILITY))
        visibility = JvmVisibility.PROTECTED;
      sourceName = "_" + sourceName;
    }
    operation.setSimpleName(sourceName);
    operation.setVisibility(visibility);
    operation.setStatic(source.isStatic());
    for (XtendParameter parameter : source.getParameters()) {
      JvmFormalParameter jvmParam = typesFactory.createJvmFormalParameter();
      jvmParam.setName(parameter.getName());
      jvmParam.setParameterType(cloneWithProxies(parameter.getParameterType()));
      operation.getParameters().add(jvmParam);
      associator.associate(parameter, jvmParam);
      jvmTypesBuilder.translateAnnotationsTo(parameter.getAnnotations(), jvmParam);
    }
    JvmTypeReference returnType = null;
    if (source.getReturnType() != null) {
      returnType = cloneWithProxies(source.getReturnType());
    } else {
      returnType = getTypeProxy(operation);
    }
    operation.setReturnType(returnType);
    copyAndFixTypeParameters(source.getTypeParameters(), operation);
    for (JvmTypeReference exception : source.getExceptions()) {
      operation.getExceptions().add(cloneWithProxies(exception));
    }
    jvmTypesBuilder.translateAnnotationsTo(source.getAnnotationInfo().getAnnotations(), operation);
    CreateExtensionInfo createExtensionInfo = source.getCreateExtensionInfo();
    if (createExtensionInfo != null) {
      JvmTypeReference arrayList =
          typeReferences.getTypeForName(ArrayList.class, container, typeReferences.wildCard());
      JvmTypeReference hashMap =
          typeReferences.getTypeForName(
              HashMap.class, container, arrayList, cloneWithProxies(returnType));

      JvmField cacheVar =
          jvmTypesBuilder.toField(
              source, CREATE_CHACHE_VARIABLE_PREFIX + source.getName(), hashMap);
      cacheVar.setFinal(true);
      jvmTypesBuilder.setInitializer(cacheVar, compileStrategies.forCacheVariable(container));
      container.getMembers().add(cacheVar);

      JvmOperation initializer = typesFactory.createJvmOperation();
      container.getMembers().add(initializer);
      initializer.setSimpleName(CREATE_INITIALIZER_PREFIX + source.getName());
      initializer.setVisibility(JvmVisibility.PRIVATE);
      initializer.setReturnType(typeReferences.getTypeForName(Void.TYPE, source));
      for (JvmTypeReference exception : source.getExceptions()) {
        initializer.getExceptions().add(cloneWithProxies(exception));
      }

      jvmTypesBuilder.setBody(
          operation, compileStrategies.forCacheMethod(createExtensionInfo, cacheVar, initializer));

      // the first parameter is the created object
      JvmFormalParameter jvmParam = typesFactory.createJvmFormalParameter();
      jvmParam.setName(createExtensionInfo.getName());
      jvmParam.setParameterType(getTypeProxy(createExtensionInfo.getCreateExpression()));
      initializer.getParameters().add(jvmParam);
      associator.associate(createExtensionInfo, jvmParam);

      // add all others
      for (XtendParameter parameter : source.getParameters()) {
        jvmParam = typesFactory.createJvmFormalParameter();
        jvmParam.setName(parameter.getName());
        jvmParam.setParameterType(cloneWithProxies(parameter.getParameterType()));
        initializer.getParameters().add(jvmParam);
        associator.associate(parameter, jvmParam);
      }
      associator.associate(source, initializer);
      associator.associateLogicalContainer(createExtensionInfo.getCreateExpression(), operation);
      associator.associateLogicalContainer(source.getExpression(), initializer);
    } else {
      associator.associateLogicalContainer(source.getExpression(), operation);
    }
    jvmTypesBuilder.setDocumentation(operation, jvmTypesBuilder.getDocumentation(source));
  }