public TextRegion getImportRegion(XtextResource xtextResource) {
   XPackage xPackage = getXPackage(xtextResource);
   if (xPackage != null) {
     List<INode> xPackageNodes =
         NodeModelUtils.findNodesForFeature(xPackage, XcorePackage.Literals.XNAMED_ELEMENT__NAME);
     int begin;
     int size = xPackageNodes.size();
     if (size == 0) {
       begin = 0;
     } else {
       INode lastNode = xPackageNodes.get(size - 1);
       begin = lastNode.getOffset() + lastNode.getLength();
     }
     int end;
     EList<XAnnotationDirective> annotationDirectives = xPackage.getAnnotationDirectives();
     if (!annotationDirectives.isEmpty()) {
       ICompositeNode node = NodeModelUtils.getNode(annotationDirectives.get(0));
       end = node.getTotalOffset();
     } else {
       EList<XClassifier> classifiers = xPackage.getClassifiers();
       if (!classifiers.isEmpty()) {
         ICompositeNode node = NodeModelUtils.getNode(classifiers.get(0));
         end = node.getTotalOffset();
       } else {
         end = xtextResource.getParseResult().getRootNode().getTotalEndOffset();
       }
     }
     return new TextRegion(begin, end - begin);
   } else {
     return null;
   }
 }
Esempio n. 2
0
 /** @since 2.3 */
 protected void validateReferencedMetamodel(ReferencedMetamodel ref) {
   if (ref.getEPackage() != null && !ref.getEPackage().eIsProxy()) return;
   EReference eref = XtextPackage.Literals.ABSTRACT_METAMODEL_DECLARATION__EPACKAGE;
   List<INode> nodes = NodeModelUtils.findNodesForFeature(ref, eref);
   String refName = nodes.isEmpty() ? "(unknown)" : NodeModelUtils.getTokenText(nodes.get(0));
   String grammarName = GrammarUtil.getGrammar(ref).getName();
   String msg = "The EPackage " + refName + " in grammar " + grammarName + " could not be found. ";
   msg += "You might want to register that EPackage in your workflow file.";
   throw new IllegalStateException(msg);
 }
  @Override
  public IHyperlink[] createHyperlinksByOffset(
      XtextResource resource, int offset, boolean createMultipleHyperlinks) {
    IHyperlink[] links = super.createHyperlinksByOffset(resource, offset, createMultipleHyperlinks);

    EObject eo = eObjectAtOffsetHelper.resolveElementAt(resource, offset);
    if (eo instanceof ControllerHandledValueProperty) {
      INode n = NodeModelUtils.getNode(eo);

      if (n != null) {
        INode currentNode = NodeModelUtils.findLeafNodeAtOffset(n, offset);
        List<INode> l =
            NodeModelUtils.findNodesForFeature(
                eo, FXGraphPackage.Literals.CONTROLLER_HANDLED_VALUE_PROPERTY__METHODNAME);
        if (l.contains(currentNode)) {
          Region region = new Region(currentNode.getOffset(), currentNode.getLength());

          Model m = (Model) eo.eResource().getContents().get(0);

          if (m != null) {
            ComponentDefinition def = m.getComponentDef();
            if (def != null) {
              if (def.getController() != null && def.getController().getType() != null) {
                IType t = getJDTType(def.getController().getType());
                if (t != null) {
                  IFXCtrlClass fxClass =
                      FXPlugin.getClassmodel().findCtrlClass(t.getJavaProject(), t);
                  if (fxClass != null) {
                    IFXCtrlEventMethod fxp =
                        fxClass.getAllEventMethods().get(currentNode.getText());
                    if (fxp != null) {
                      HyperlinkImpl h = new HyperlinkImpl(region, fxp.getJavaElement());
                      if (links == null || links.length == 0) {
                        return new IHyperlink[] {h};
                      } else {
                        IHyperlink[] rv = new IHyperlink[links.length + 1];
                        System.arraycopy(links, 0, rv, 0, rv.length);
                        rv[rv.length - 1] = h;
                        return rv;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }

    return links;
  }
 public void syncConstructs(EList<sigConstruct> model, Element e) {
   sigConstruct ll;
   for (sigConstruct contr : model) {
     if (contr instanceof includeConstruct) {
       includeConstruct inc = (includeConstruct) contr;
       String importName = NodeModelUtils.getNode(inc).getText().substring(9);
       if (importName.startsWith("t.")) {
         String proj = contr.eResource().getURI().segment(1);
         URI ol = contr.eResource().getURI();
         Logger.getAnonymousLogger().info(ol.toString());
         URI nu = URI.createURI("platform:/resource/" + proj + "/source/test.elf");
         Logger.getAnonymousLogger().info(nu.toString());
         Resource res = contr.eResource().getResourceSet().getResource(nu, true);
         TreeIterator<EObject> iter = res.getAllContents();
         while (iter.hasNext()) {
           EObject node = iter.next();
           if (node instanceof signatureDeclaration
               && ((signatureDeclaration) node).getSigName().equals(importName.substring(2))) {
             ((includeConstruct) contr).setNamespace((signatureDeclaration) node);
           }
         }
       }
       if (sigObjMap.containsKey(importName)) {
         ((includeConstruct) contr).setNamespace((signatureDeclaration) sigObjMap.get(importName));
       }
     }
     if (contr instanceof structConstruct) {
       structConstruct inc = (structConstruct) contr;
       String totalText = NodeModelUtils.getNode(inc).getText();
       String importName = totalText.substring(totalText.indexOf(':') + 1).trim();
       if (sigObjMap.containsKey(importName)) {
         ((structConstruct) contr).setNamespace((signatureDeclaration) sigObjMap.get(importName));
       }
     }
     /*	String namespace = ((includeConstruct) contr).getNamespace();
     	if (namespace.indexOf('.')==-1) { // local link
     		if (sigObjMap.containsKey(namespace)) {
     			((includeConstruct) contr).setHyper(((signatureDeclaration) sigObjMap.get(namespace)).getDefs());
     			continue;
     		}
     		if (viewObjMap.containsKey(namespace)) {
     			((includeConstruct) contr).setHyper(((viewDeclaration) viewObjMap.get(namespace)).getViewDefs());
     			continue;
     		}
     	}
     } */
   }
 }
 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();
 }
 public List<ReplaceRegion> rewrite() {
   removeObsoleteStaticImports();
   final List<ReplaceRegion> replaceRegions = newArrayList();
   if (isSort) {
     List<XImportDeclaration> allImportDeclarations = newArrayList();
     allImportDeclarations.addAll(originalImportDeclarations);
     allImportDeclarations.addAll(addedImportDeclarations);
     allImportDeclarations.removeAll(removedImportDeclarations);
     String newImportSection = serializeImports(allImportDeclarations);
     importRegion = regionUtil.addLeadingWhitespace(importRegion, resource);
     importRegion = regionUtil.addTrailingWhitespace(importRegion, resource);
     return singletonList(new ReplaceRegion(importRegion, newImportSection));
   } else {
     for (XImportDeclaration removedImportDeclaration : removedImportDeclarations) {
       ICompositeNode node = NodeModelUtils.findActualNodeFor(removedImportDeclaration);
       if (node != null) {
         ITextRegion textRegion = node.getTextRegion();
         textRegion = regionUtil.addTrailingSingleWhitespace(textRegion, lineSeparator, resource);
         replaceRegions.add(new ReplaceRegion(textRegion, ""));
       }
     }
     addSectionToAppend(
         new IAcceptor<ReplaceRegion>() {
           @Override
           public void accept(ReplaceRegion t) {
             replaceRegions.add(t);
           }
         });
   }
   return replaceRegions;
 }
 @Override
 public ITextRegion getSignificantTextRegion(EObject element) {
   if (element instanceof XSwitchExpression
       && ((XSwitchExpression) element).getLocalVarName() != null) {
     return getLocationOfAttribute(
         element, XbasePackage.Literals.XSWITCH_EXPRESSION__LOCAL_VAR_NAME, -1, true);
   }
   if (element instanceof XAbstractFeatureCall) {
     XAbstractFeatureCall typeLiteral =
         typeLiteralHelper.getRootTypeLiteral((XAbstractFeatureCall) element);
     if (typeLiteral != null) {
       if (typeLiteral instanceof XMemberFeatureCall) {
         XAbstractFeatureCall target =
             (XAbstractFeatureCall) ((XMemberFeatureCall) typeLiteral).getMemberCallTarget();
         if (target.isTypeLiteral()) {
           return super.getSignificantTextRegion(typeLiteral);
         }
       }
       INode node = NodeModelUtils.findActualNodeFor(typeLiteral);
       if (node != null) {
         return toZeroBasedRegion(node.getTextRegionWithLineInformation());
       }
     }
   }
   return super.getSignificantTextRegion(element);
 }
 @Override
 protected PsiElement getInternalNavigationElement() {
   List<INode> _findNodesForFeature = NodeModelUtils.findNodesForFeature(this.owner, this.feature);
   final Function1<INode, Iterable<ILeafNode>> _function =
       new Function1<INode, Iterable<ILeafNode>>() {
         @Override
         public Iterable<ILeafNode> apply(final INode it) {
           return it.getLeafNodes();
         }
       };
   List<Iterable<ILeafNode>> _map =
       ListExtensions.<INode, Iterable<ILeafNode>>map(_findNodesForFeature, _function);
   Iterable<ILeafNode> _flatten = Iterables.<ILeafNode>concat(_map);
   final Function1<ILeafNode, Boolean> _function_1 =
       new Function1<ILeafNode, Boolean>() {
         @Override
         public Boolean apply(final ILeafNode it) {
           boolean _isHidden = it.isHidden();
           return Boolean.valueOf((!_isHidden));
         }
       };
   Iterable<ILeafNode> _filter = IterableExtensions.<ILeafNode>filter(_flatten, _function_1);
   ILeafNode _head = IterableExtensions.<ILeafNode>head(_filter);
   ASTNode _aSTNode = this.xtextFile.getASTNode(_head);
   return _aSTNode.getPsi();
 }
 protected ICrossReferenceDescription getCrossReferenceDescription() {
   ICrossReferenceDescription _xblockexpression = null;
   {
     ASTNode _node = this.myElement.getNode();
     IElementType _elementType = _node.getElementType();
     EObject _grammarElement = ((IGrammarAwareElementType) _elementType).getGrammarElement();
     final CrossReference crossReference = ((CrossReference) _grammarElement);
     BaseXtextFile _xtextFile = this.myElement.getXtextFile();
     ASTNode _node_1 = this.myElement.getNode();
     final INode node = _xtextFile.getINode(_node_1);
     final EObject context = NodeModelUtils.findActualSemanticObjectFor(node);
     final EReference reference = GrammarUtil.getReference(crossReference);
     List<INode> _findNodesForFeature = NodeModelUtils.findNodesForFeature(context, reference);
     Iterable<Pair<Integer, INode>> _indexed =
         IterableExtensions.<INode>indexed(_findNodesForFeature);
     final Function1<Pair<Integer, INode>, Boolean> _function =
         new Function1<Pair<Integer, INode>, Boolean>() {
           @Override
           public Boolean apply(final Pair<Integer, INode> it) {
             boolean _and = false;
             INode _value = it.getValue();
             int _totalOffset = _value.getTotalOffset();
             int _totalOffset_1 = node.getTotalOffset();
             boolean _lessEqualsThan = (_totalOffset <= _totalOffset_1);
             if (!_lessEqualsThan) {
               _and = false;
             } else {
               INode _value_1 = it.getValue();
               int _totalEndOffset = _value_1.getTotalEndOffset();
               int _totalEndOffset_1 = node.getTotalEndOffset();
               boolean _greaterEqualsThan = (_totalEndOffset >= _totalEndOffset_1);
               _and = _greaterEqualsThan;
             }
             return Boolean.valueOf(_and);
           }
         };
     Pair<Integer, INode> _findFirst =
         IterableExtensions.<Pair<Integer, INode>>findFirst(_indexed, _function);
     Integer _key = null;
     if (_findFirst != null) {
       _key = _findFirst.getKey();
     }
     final Integer index = _key;
     _xblockexpression = this.crossReferenceDescriptionProvider.get(context, reference, index);
   }
   return _xblockexpression;
 }
Esempio n. 10
0
 protected String serialize(final EObject obj) {
   final ICompositeNode node = NodeModelUtils.getNode(obj);
   boolean _equals = Objects.equal(node, null);
   if (_equals) {
     return "";
   }
   return node.getText();
 }
Esempio n. 11
0
 public String serialize(final EObject obj) {
   ICompositeNode _node = NodeModelUtils.getNode(obj);
   String _text = null;
   if (_node != null) {
     _text = _node.getText();
   }
   return _text;
 }
Esempio n. 12
0
 @SuppressWarnings("unchecked")
 public <T> T get(
     Class<T> expectedType, Map<Class<? extends Annotation>, IParameterProvider> context) {
   XtextResource xtextResource =
       context.get(ThisResource.class).get(XtextResource.class, context);
   return (T)
       NodeModelUtils.findLeafNodeAtOffset(
           xtextResource.getParseResult().getRootNode(), getOffset());
 }
Esempio n. 13
0
 public void addError(String message) {
   if (csElement instanceof ModelElementCS) {
     ModelElementCS csModelElement = (ModelElementCS) csElement;
     INode node = NodeModelUtils.getNode(csModelElement);
     Resource.Diagnostic resourceDiagnostic = new ValidationDiagnostic(node, message);
     csModelElement.eResource().getErrors().add(resourceDiagnostic);
   } else {
     logger.error(message);
   }
 }
 protected void highlightFeatureCall(
     XAbstractFeatureCall featureCall, IHighlightedPositionAcceptor acceptor, String id) {
   //		highlightDeprecation(acceptor, featureCall, null, featureCall.getFeature());
   if (featureCall.isTypeLiteral()) {
     ICompositeNode node = NodeModelUtils.findActualNodeFor(featureCall);
     highlightNode(acceptor, node, id);
   } else {
     highlightFeature(
         acceptor, featureCall, XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, id);
   }
 }
Esempio n. 15
0
 protected EObject find(Class<?> expectedType, INode node, Set<EObject> visited) {
   EObject current = node.getSemanticElement();
   int startoffset = node.getOffset();
   EObject result = null;
   while (current != null && NodeModelUtils.getNode(current).getOffset() >= startoffset) {
     if (expectedType.isInstance(current)) result = current;
     visited.add(current);
     current = current.eContainer();
   }
   return result;
 }
Esempio n. 16
0
 protected EStructuralFeatureAndEObject find(XtextResource resource, int offset) {
   INode leaf =
       NodeModelUtils.findLeafNodeAtOffset(resource.getParseResult().getRootNode(), offset);
   NodeIterator ni = null;
   while (ni == null || ni.hasNext()) {
     INode next = ni == null ? leaf : ni.next();
     if (ni == null) ni = new NodeIterator(leaf);
     EObject object = NodeModelUtils.findActualSemanticObjectFor(next);
     INode current = next;
     do {
       Assignment ass = GrammarUtil.containingAssignment(current.getGrammarElement());
       if (ass != null) {
         EStructuralFeature feat = object.eClass().getEStructuralFeature(ass.getFeature());
         if (feat != null && matches(object, feat)) return create(object, feat);
       }
       current = current.getParent();
     } while (current != null && object == NodeModelUtils.findActualSemanticObjectFor(current));
   }
   throw new RuntimeException("No EStructuralFeature found at offset " + offset);
 }
 protected <T extends EObject> void remove(
     EObject element, Class<T> type, IModificationContext context) throws BadLocationException {
   T container = EcoreUtil2.getContainerOfType(element, type);
   if (container == null) {
     return;
   }
   ICompositeNode node = NodeModelUtils.findActualNodeFor(container);
   if (node == null) {
     return;
   }
   remove(context.getXtextDocument(), node);
 }
Esempio n. 18
0
 protected EObject find(XtextResource res, int offset, Class<?> expectedType) {
   INode leaf = NodeModelUtils.findLeafNodeAtOffset(res.getParseResult().getRootNode(), offset);
   Set<EObject> visited = Sets.newHashSet();
   NodeIterator ni = null;
   while (ni == null || ni.hasNext()) {
     INode next = ni == null ? leaf : ni.next();
     if (ni == null) ni = new NodeIterator(leaf);
     EObject result = find(expectedType, next, visited);
     if (result != null) return result;
   }
   return null;
 }
 protected int[] getOffsetAndLength(XIfExpression ifExpression, ICompositeNode node) {
   int offset = node.getOffset();
   int length = node.getLength();
   if (ifExpression.getElse() != null) {
     ICompositeNode elseNode = NodeModelUtils.findActualNodeFor(ifExpression.getElse());
     if (elseNode != null) {
       length = elseNode.getOffset() - offset;
     }
   } else {
     XIfExpression parentIfExpression =
         EcoreUtil2.getContainerOfType(ifExpression.eContainer(), XIfExpression.class);
     if (parentIfExpression != null && parentIfExpression.getElse() == ifExpression) {
       ICompositeNode thenNode = NodeModelUtils.findActualNodeFor(parentIfExpression.getThen());
       if (thenNode != null) {
         int endOffset = thenNode.getEndOffset();
         length = length + (offset - endOffset);
         offset = endOffset;
       }
     }
   }
   return new int[] {offset, length};
 }
 protected void highlightAnnotation(
     XAnnotation annotation,
     IHighlightedPositionAcceptor acceptor,
     String highlightingConfiguration) {
   JvmType annotationType = annotation.getAnnotationType();
   if (annotationType != null
       && !annotationType.eIsProxy()
       && annotationType instanceof JvmAnnotationType) {
     ICompositeNode xannotationNode = NodeModelUtils.findActualNodeFor(annotation);
     if (xannotationNode != null) {
       ILeafNode firstLeafNode =
           NodeModelUtils.findLeafNodeAtOffset(xannotationNode, xannotationNode.getOffset());
       if (firstLeafNode != null)
         highlightNode(acceptor, firstLeafNode, highlightingConfiguration);
     }
     highlightReferenceJvmType(
         acceptor,
         annotation,
         XAnnotationsPackage.Literals.XANNOTATION__ANNOTATION_TYPE,
         annotationType,
         highlightingConfiguration);
   }
 }
 @Override
 protected ITextRegion getLocationOfCrossReference(
     EObject owner, EReference reference, int indexInList, boolean isSignificant) {
   if (owner instanceof XMemberFeatureCall
       && reference == XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE
       && ((XMemberFeatureCall) owner).isTypeLiteral()) {
     List<INode> featureNodes = NodeModelUtils.findNodesForFeature(owner, reference);
     ITextRegion result = ITextRegion.EMPTY_REGION;
     if (!featureNodes.isEmpty()) {
       INode featureNode = featureNodes.get(0);
       result = result.merge(toZeroBasedRegion(featureNode.getTextRegionWithLineInformation()));
       List<INode> targetNodes =
           NodeModelUtils.findNodesForFeature(
               owner, XbasePackage.Literals.XMEMBER_FEATURE_CALL__MEMBER_CALL_TARGET);
       if (!targetNodes.isEmpty()) {
         INode targetNode = targetNodes.get(0);
         result = result.merge(toZeroBasedRegion(targetNode.getTextRegionWithLineInformation()));
       }
       return result;
     }
   }
   return super.getLocationOfCrossReference(owner, reference, indexInList, isSignificant);
 }
 public Set<QualifiedName> getImportedNames(XtextResource resource) {
   XPackage xPackage = getXPackage(resource);
   String packageName = xPackage.getName();
   List<String> implicitPackageImports = newArrayList(packageName, "java.lang");
   Set<QualifiedName> importedNames = newLinkedHashSet();
   Map<String, QualifiedName> implicitAliases = getImplicitAliases();
   for (INode node : XcoreUtil.importableCrossReferences(xPackage)) {
     CrossReference grammarElement = (CrossReference) node.getGrammarElement();
     EObject container = grammarElement.eContainer();
     if (container instanceof Assignment) {
       String name = node.getText().trim();
       if (name.endsWith("::")) {
         name = name.substring(0, name.length() - 2);
       }
       QualifiedName actualQualifiedName = nameConverter.toQualifiedName(name);
       Assignment assignment = (Assignment) container;
       String feature = assignment.getFeature();
       EObject semanticObject = NodeModelUtils.findActualSemanticObjectFor(node);
       EStructuralFeature eStructuralFeature =
           semanticObject.eClass().getEStructuralFeature(feature);
       if (!eStructuralFeature.isMany()) {
         EObject eCrossReference = (EObject) semanticObject.eGet(eStructuralFeature);
         EObject eContainer = eCrossReference.eContainer();
         if (eContainer != xPackage
             && !(eContainer instanceof XPackage
                 && "xcore.lang".equals(((XPackage) eContainer).getName()))
             && !(eContainer instanceof GenPackage
                 && packageName.equals(((GenPackage) eContainer).getQualifiedPackageName()))
             && !(eCrossReference instanceof JvmDeclaredType
                 && implicitPackageImports.contains(
                     ((JvmDeclaredType) eCrossReference).getPackageName()))) {
           QualifiedName fullyQualifiedName = nameProvider.getFullyQualifiedName(eCrossReference);
           if (fullyQualifiedName != null
               && !actualQualifiedName.equals(fullyQualifiedName)
               && !fullyQualifiedName.equals(implicitAliases.get(name))) {
             importedNames.add(fullyQualifiedName);
           }
         }
       } else {
         throw new RuntimeException("Not expecting multi-valued cross references in these models");
       }
     } else {
       throw new RuntimeException(
           "Expecting all cross references to be part of an assignment in these models");
     }
   }
   return importedNames;
 }
Esempio n. 23
0
 protected void error(String message, EObject source, Keyword keyword, int index, String code) {
   final String[] issueData = null;
   ICompositeNode rootNode = NodeModelUtils.findActualNodeFor(source);
   if (rootNode != null) {
     INode child = findNode(source, false, rootNode, keyword, new int[] {index});
     if (child != null) {
       int offset = child.getTotalOffset();
       int length = child.getTotalLength();
       getMessageAcceptor().acceptError(message, source, offset, length, code, issueData);
       return;
     }
   }
   error(
       message,
       source,
       (EStructuralFeature) null,
       ValidationMessageAcceptor.INSIGNIFICANT_INDEX,
       code);
 }
Esempio n. 24
0
 protected String computeFieldName(XtendField field, JvmGenericType declaringType) {
   if (field.getName() != null) return field.getName();
   JvmTypeReference type = field.getType();
   String name = null;
   if (type != null) {
     while (type instanceof JvmGenericArrayTypeReference) {
       type = ((JvmGenericArrayTypeReference) type).getComponentType();
     }
     if (type instanceof JvmParameterizedTypeReference) {
       List<INode> nodes =
           NodeModelUtils.findNodesForFeature(
               type, TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE);
       if (!nodes.isEmpty()) {
         String typeName = nodes.get(0).getText().trim();
         int lastDot = typeName.lastIndexOf('.');
         if (lastDot != -1) {
           typeName = typeName.substring(lastDot + 1);
         }
         name = "_" + Strings.toFirstLower(typeName);
       }
     }
   }
   return name;
 }
 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();
 }
 public String genGetUnassignedRuleCallToken(
     final JavaFile file, final AbstractRule rule, final boolean isAbstract) {
   if ((rule instanceof TerminalRule)) {
     boolean _and = false;
     if (!this.detectSyntheticTerminals) {
       _and = false;
     } else {
       boolean _isSyntheticTerminalRule =
           this.syntheticTerminalDetector.isSyntheticTerminalRule(((TerminalRule) rule));
       _and = _isSyntheticTerminalRule;
     }
     if (_and) {
       StringConcatenation _builder = new StringConcatenation();
       _builder.append("/**");
       _builder.newLine();
       _builder.append(" ");
       _builder.append(
           "* Synthetic terminal rule. The concrete syntax is to be specified by clients.");
       _builder.newLine();
       {
         if ((!isAbstract)) {
           _builder.append(" * Defaults to the empty string.");
         }
       }
       _builder.newLineIfNotEmpty();
       _builder.append(" ");
       _builder.append("*/");
       _builder.newLine();
       _builder.append("protected ");
       {
         if (isAbstract) {
           _builder.append("abstract ");
         }
       }
       _builder.append("String ");
       CharSequence _unassignedCalledTokenRuleName = this.unassignedCalledTokenRuleName(rule);
       _builder.append(_unassignedCalledTokenRuleName, "");
       _builder.append("(EObject semanticObject, RuleCall ruleCall, INode node)");
       {
         if (isAbstract) {
           _builder.append(";");
         } else {
           _builder.append(" { return \"\"; }");
         }
       }
       _builder.newLineIfNotEmpty();
       return _builder.toString();
     }
   }
   StringConcatenation _builder_1 = new StringConcatenation();
   _builder_1.append("/**");
   _builder_1.newLine();
   _builder_1.append(" ");
   _builder_1.append("* ");
   ICompositeNode _node = NodeModelUtils.getNode(rule);
   String _textWithoutComments = this.textWithoutComments(_node);
   String _trim = _textWithoutComments.trim();
   String _replace = _trim.replace("\n", "\n* ");
   _builder_1.append(_replace, " ");
   _builder_1.newLineIfNotEmpty();
   _builder_1.append(" ");
   _builder_1.append("*/");
   _builder_1.newLine();
   _builder_1.append("protected String ");
   CharSequence _unassignedCalledTokenRuleName_1 = this.unassignedCalledTokenRuleName(rule);
   _builder_1.append(_unassignedCalledTokenRuleName_1, "");
   _builder_1.append("(EObject semanticObject, RuleCall ruleCall, INode node) {");
   _builder_1.newLineIfNotEmpty();
   _builder_1.append("\t");
   _builder_1.append("if (node != null)");
   _builder_1.newLine();
   _builder_1.append("\t\t");
   _builder_1.append("return getTokenText(node);");
   _builder_1.newLine();
   _builder_1.append("\t");
   _builder_1.append("return \"");
   AbstractElement _alternatives = rule.getAlternatives();
   HashSet<AbstractElement> _newHashSet = CollectionLiterals.<AbstractElement>newHashSet();
   String _defaultValue = this.defaultValue(_alternatives, _newHashSet);
   String _convertToJavaString = Strings.convertToJavaString(_defaultValue);
   _builder_1.append(_convertToJavaString, "\t");
   _builder_1.append("\";");
   _builder_1.newLineIfNotEmpty();
   _builder_1.append("}");
   _builder_1.newLine();
   return _builder_1.toString();
 }
 private IRegion[] regionOf(Content content) {
   ICompositeNode node = NodeModelUtils.getNode(content);
   int length = node.getLength();
   int offset = node.getOffset();
   return new Region[] {new Region(offset, length)};
 }
Esempio n. 28
0
 private String textOf(EObject object) {
   return NodeModelUtils.getTokenText(NodeModelUtils.getNode(object));
 }
  private void calculateVersionProposals(
      EObject model,
      ContentAssistContext context,
      ICompletionProposalAcceptor acceptor,
      boolean majorVersionsOnly) {
    ICompositeNode parentNode = NodeModelUtils.findActualNodeFor(model).getParent();
    Iterable<ILeafNode> leafs = parentNode.getLeafNodes();
    Iterable<ILeafNode> nonHidden =
        Iterables.filter(
            leafs,
            new Predicate<ILeafNode>() {

              public boolean apply(ILeafNode node) {
                return !node.isHidden();
              }
            });
    Model bizModel = null;
    EObject curObj = model;
    while (!(curObj instanceof Model) && curObj.eContainer() != null) {
      curObj = curObj.eContainer();
    }
    if (curObj instanceof Model) {
      bizModel = (Model) curObj;
      EList<Import> imports = bizModel.getImports();
      List<String> importedNamespaces =
          Lists.newArrayList(
              Lists.transform(
                  imports,
                  new Function<Import, String>() {

                    public String apply(Import from) {
                      return from.getImportedNamespace().replaceAll("\\.\\*", "");
                    }
                  }));
      Iterator<ILeafNode> leafIt = nonHidden.iterator();
      if (model.eContainer() instanceof CapabilityRef) {
        CapabilityRef capRef = (CapabilityRef) model.eContainer();
        boolean versionConstraintFound = false;
        StringBuilder nameParts = new StringBuilder();
        while (leafIt.hasNext() && !versionConstraintFound) {
          ILeafNode curNode = leafIt.next();
          if (curNode.getSemanticElement() instanceof VersionRef) versionConstraintFound = true;
          else nameParts.append(curNode.getText());
        }
        String typeName = nameParts.toString().trim().replaceAll("\\[\\]", "").trim();
        final List<String> classNames =
            Lists.newArrayList(
                BusinessDslPackage.Literals.SIMPLE_CAPABILITY.getName(),
                BusinessDslPackage.Literals.CAPABILITY_VARIANT.getName());
        Iterable<String> canditateVersions =
            getCanditateVersions(typeName, classNames, importedNamespaces, majorVersionsOnly);
        for (String version : canditateVersions) {
          acceptor.accept(createCompletionProposal(version, context));
        }
      } else if (model.eContainer() instanceof ServiceRef) {
        ServiceRef capRef = (ServiceRef) model.eContainer();
        boolean versionConstraintFound = false;
        StringBuilder nameParts = new StringBuilder();
        while (leafIt.hasNext() && !versionConstraintFound) {
          ILeafNode curNode = leafIt.next();
          if (curNode.getSemanticElement() instanceof VersionRef) versionConstraintFound = true;
          else nameParts.append(curNode.getText());
        }
        String typeName = nameParts.toString().trim().replaceAll("\\[\\]", "").trim();
        Iterable<String> canditateVersions =
            getCanditateVersions(
                typeName,
                ServiceDslPackage.Literals.SERVICE.getName(),
                importedNamespaces,
                majorVersionsOnly);
        for (String version : canditateVersions) {
          acceptor.accept(createCompletionProposal(version, context));
        }
      } else if (model.eContainer() instanceof EventRef) {
        EventRef eventRef = (EventRef) model.eContainer();
        boolean versionConstraintFound = false;
        StringBuilder nameParts = new StringBuilder();
        while (leafIt.hasNext() && !versionConstraintFound) {
          ILeafNode curNode = leafIt.next();
          if (curNode.getSemanticElement() instanceof VersionRef) versionConstraintFound = true;
          else nameParts.append(curNode.getText());
        }
        String typeName = nameParts.toString().trim().replaceAll("\\[\\]", "").trim();
        final List<String> classNames =
            Lists.newArrayList(
                ServiceDslPackage.Literals.EVENT.getName(),
                ServiceDslPackage.Literals.EVENT.getName());
        Iterable<String> canditateVersions =
            getCanditateVersions(typeName, classNames, importedNamespaces, majorVersionsOnly);
        for (String version : canditateVersions) {
          acceptor.accept(createCompletionProposal(version, context));
        }
      } else if (model.eContainer() instanceof OperationRef) {
        boolean versionConstraintFound = false;
        StringBuilder nameParts = new StringBuilder();
        while (leafIt.hasNext() && !versionConstraintFound) {
          ILeafNode curNode = leafIt.next();
          if (curNode.getSemanticElement() instanceof VersionRef) versionConstraintFound = true;
          else nameParts.append(curNode.getText());
        }
        String typeName = nameParts.toString().trim().replaceAll("\\[\\]", "").trim();
        String[] opNameParts = typeName.split("\\.");
        if (opNameParts.length > 1) {
          typeName = typeName.replaceAll("\\." + opNameParts[opNameParts.length - 1], "");
        }
        String className = ServiceDslPackage.Literals.SERVICE.getName();
        Iterable<String> canditateVersions =
            getCanditateVersions(typeName, className, importedNamespaces, majorVersionsOnly);
        for (String version : canditateVersions) {
          acceptor.accept(createCompletionProposal(version, context));
        }
      } else {
        if (majorVersionsOnly) acceptor.accept(createCompletionProposal("1", context));
        else acceptor.accept(createCompletionProposal("1.0", context));
      }
    }
  }
 protected void highlightNumberLiterals(
     XNumberLiteral literal, IHighlightedPositionAcceptor acceptor) {
   ICompositeNode node = NodeModelUtils.findActualNodeFor(literal);
   ITextRegion textRegion = node.getTextRegion();
   acceptor.addPosition(textRegion.getOffset(), textRegion.getLength(), NUMBER_ID);
 }