Esempio n. 1
0
 Type tupleFromParameterList() {
   if (params.getParameters().isEmpty()) {
     return n.getUnit().getEmptyType();
   }
   List<Type> types = new ArrayList<>(params.getParameters().size());
   int firstDefaulted = -1;
   int count = 0;
   for (Tree.Parameter p : params.getParameters()) {
     types.add(p.getParameterModel().getType());
     if (p.getParameterModel().isDefaulted()) firstDefaulted = count;
     count++;
   }
   return n.getUnit()
       .getTupleType(
           types,
           params
               .getParameters()
               .get(params.getParameters().size() - 1)
               .getParameterModel()
               .isSequenced(),
           params
               .getParameters()
               .get(params.getParameters().size() - 1)
               .getParameterModel()
               .isAtLeastOne(),
           firstDefaulted);
 }
 @Override
 public void visit(Tree.InvocationExpression that) {
   ProducedType ort = requiredType;
   ProducedReference onat = namedArgTarget;
   PositionalArgumentList pal = that.getPositionalArgumentList();
   if (pal != null) {
     int pos;
     if (node == pal) {
       // TODO: this is wrong!!
       //      we need to look at the offset and
       //      determine if we are at the start
       //      or end of the parameter list!
       pos = pal.getPositionalArguments().size();
     } else {
       pos = pal.getPositionalArguments().size();
       for (int i = 0; i < pos; i++) {
         Tree.PositionalArgument pa = pal.getPositionalArguments().get(i);
         if (node.getStartIndex() >= pa.getStartIndex()
             && node.getStopIndex() <= pa.getStopIndex()) {
           pos = i;
           break;
         }
       }
     }
     ProducedReference pr = getTarget(that);
     if (pr != null) {
       List<Parameter> params = getParameters(pr);
       if (params != null && params.size() > pos) {
         Parameter param = params.get(pos);
         requiredType = pr.getTypedParameter(param).getFullType();
         if (param.isSequenced()) {
           requiredType = that.getUnit().getIteratedType(requiredType);
         }
       }
     }
   }
   NamedArgumentList nal = that.getNamedArgumentList();
   if (nal != null) {
     namedArgTarget = getTarget(that);
     if (namedArgTarget != null) {
       List<Parameter> params = getParameters(namedArgTarget);
       if (params != null && !params.isEmpty()) {
         Parameter param = params.get(params.size() - 1);
         if (param.isSequenced()) {
           requiredType = namedArgTarget.getTypedParameter(param).getFullType();
           requiredType = that.getUnit().getIteratedType(requiredType);
         }
       }
     }
   }
   super.visit(that);
   requiredType = ort;
   namedArgTarget = onat;
 }
 private String formatCeylonPosition(int position) {
   String result =
       ceylonLineMap.getLineNumber(position) + " : " + ceylonLineMap.getColumnNumber(position);
   if (ceylonNodesAtPosition != null) {
     if (ceylonNodesAtPosition.containsKey(position)) {
       List<String> nodeLabels = new LinkedList<String>();
       for (Node node : ceylonNodesAtPosition.get(position)) {
         nodeLabels.add(node.getNodeType() + " - " + node.getToken().getText());
       }
       result += "(" + nodeLabels + ")";
     }
   }
   return result;
 }
 public static String imports(Node node, ImportList til) {
   final List<Declaration> unused = new ArrayList<Declaration>();
   DetectUnusedImportsVisitor duiv = new DetectUnusedImportsVisitor(unused);
   til.visit(duiv);
   node.visit(duiv);
   return reorganizeImports(til, unused, Collections.<Declaration>emptyList());
 }
 private static boolean hasRealErrors(Node node) {
   for (Message m : node.getErrors()) {
     if (m instanceof AnalysisError) {
       return true;
     }
   }
   return false;
 }
 private static void addPackageCompletions(
     final int offset,
     final String prefix,
     Node node,
     List<ICompletionProposal> result,
     final int len,
     String pfp,
     final CeylonParseController cpc,
     final boolean withBody) {
   // TODO: someday it would be nice to propose from all packages
   //      and auto-add the module dependency!
   /*TypeChecker tc = CeylonBuilder.getProjectTypeChecker(cpc.getProject().getRawProject());
   if (tc!=null) {
   for (Module m: tc.getContext().getModules().getListOfModules()) {*/
   // Set<Package> packages = new HashSet<Package>();
   Unit unit = node.getUnit();
   if (unit != null) { // a null unit can occur if we have not finished parsing the file
     Module module = unit.getPackage().getModule();
     for (final Package p : module.getAllPackages()) {
       // if (!packages.contains(p)) {
       // packages.add(p);
       // if ( p.getModule().equals(module) || p.isShared() ) {
       final String pkg = escapePackageName(p);
       if (!pkg.isEmpty() && pkg.startsWith(pfp)) {
         boolean already = false;
         if (!pfp.equals(pkg)) {
           // don't add already imported packages, unless
           // it is an exact match to the typed path
           for (ImportList il : node.getUnit().getImportLists()) {
             if (il.getImportedScope() == p) {
               already = true;
               break;
             }
           }
         }
         if (!already) {
           result.add(
               new PackageProposal(
                   offset, prefix, withBody, len, p, pkg + (withBody ? " { ... }" : ""), cpc));
         }
       }
       // }
     }
   }
 }
 @Deprecated
 static void addRefineFormalMembersProposal(
     Collection<ICompletionProposal> proposals,
     Node n,
     Tree.CompilationUnit rootNode,
     boolean ambiguousError) {
   for (ICompletionProposal p : proposals) {
     if (p instanceof RefineFormalMembersProposal) {
       return;
     }
   }
   Node node;
   if (n instanceof Tree.ClassBody
       || n instanceof Tree.InterfaceBody
       || n instanceof Tree.ClassDefinition
       || n instanceof Tree.InterfaceDefinition
       || n instanceof Tree.ObjectDefinition
       || n instanceof Tree.ObjectExpression) {
     node = n;
   } else {
     FindBodyContainerVisitor v = new FindBodyContainerVisitor(n);
     v.visit(rootNode);
     node = v.getDeclaration();
   }
   if (node != null) {
     Scope scope = node.getScope();
     if (scope instanceof ClassOrInterface) {
       ClassOrInterface ci = (ClassOrInterface) scope;
       String name = ci.getName();
       if (name == null) {
         return;
       } else if (name.startsWith("anonymous#")) {
         name = "anonymous class";
       } else {
         name = "'" + name + "'";
       }
       String desc =
           ambiguousError
               ? "Refine inherited ambiguous and formal members of " + name
               : "Refine inherited formal members of " + name;
       proposals.add(new RefineFormalMembersProposal(node, rootNode, desc));
     }
   }
 }
 /**
  * Records <strong>either</strong> a literal argument to the annotation class instantiation:
  *
  * <pre>
  *    ... => AnnotationClass("", 1, true, 1.0, 'x')
  * </pre>
  *
  * <strong>Or</strong> a literal default argument in an annotation constructor:
  *
  * <pre>
  *     AnnotationClass ctor(String s="", Integer i=1,
  *             Boolean b=true, Float f=1.0,
  *             Character c='x') => ...
  * </pre>
  *
  * Literal is in the Javac sense.
  */
 private LiteralAnnotationTerm appendLiteralArgument(Node bme, LiteralAnnotationTerm argument) {
   if (spread) {
     bme.addError("compiler bug: spread static arguments not supported");
   }
   if (this.elements != null) {
     this.elements.addElement(argument);
   } else {
     this.term = argument;
   }
   return argument;
 }
Esempio n. 9
0
  public static Map<Declaration, String> getImports(
      Node node,
      final String packageName,
      final Tree.CompilationUnit ncu,
      final Set<String> packages) {
    final Map<Declaration, String> imports = new HashMap<Declaration, String>();
    node.visit(
        new Visitor() {
          private void add(Declaration d, Tree.Identifier id) {
            if (d != null && id != null) {
              String pn = d.getUnit().getPackage().getNameAsString();
              if (d.isToplevel()
                  && !pn.equals(packageName)
                  && !pn.equals(Module.LANGUAGE_MODULE_NAME)
                  && (ncu == null || !isImported(d, ncu))) {
                imports.put(d, id.getText());
                packages.add(pn);
              }
            }
          }

          @Override
          public void visit(Tree.BaseType that) {
            super.visit(that);
            add(that.getDeclarationModel(), that.getIdentifier());
          }

          @Override
          public void visit(Tree.BaseMemberOrTypeExpression that) {
            super.visit(that);
            add(that.getDeclaration(), that.getIdentifier());
          }

          @Override
          public void visit(Tree.MemberLiteral that) {
            add(that.getDeclaration(), that.getIdentifier());
          }
        });
    return imports;
  }
 public static String getModuleLabel(Node decl) {
   return decl.getUnit() == null
       ? "unknown module"
       : getLabel(decl.getUnit().getPackage().getModule());
 }
 protected void renameNode(TextChange tfc, Node node, Tree.CompilationUnit root) {
   Node identifyingNode = getIdentifier(node);
   tfc.addEdit(
       new ReplaceEdit(identifyingNode.getStartIndex(), identifyingNode.getDistance(), newName));
 }
 @Override
 public IRegion getHyperlinkRegion() {
   return new Region(id.getStartIndex(), id.getDistance());
 }
 public static void refineFormalMembers(CeylonEditor editor) throws ExecutionException {
   Tree.CompilationUnit cu = editor.getParseController().getRootNode();
   if (cu == null) return;
   Node node = getSelectedNode(editor);
   IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput());
   final TextChange change = new DocumentChange("Refine Formal Members", document);
   change.setEdit(new MultiTextEdit());
   // TODO: copy/pasted from CeylonQuickFixAssistant
   Tree.Body body;
   int offset;
   if (node instanceof Tree.ClassDefinition) {
     body = ((Tree.ClassDefinition) node).getClassBody();
     offset = -1;
   } else if (node instanceof Tree.InterfaceDefinition) {
     body = ((Tree.InterfaceDefinition) node).getInterfaceBody();
     offset = -1;
   } else if (node instanceof Tree.ObjectDefinition) {
     body = ((Tree.ObjectDefinition) node).getClassBody();
     offset = -1;
   } else if (node instanceof Tree.ClassBody || node instanceof Tree.InterfaceBody) {
     body = (Tree.Body) node;
     offset = editor.getSelection().getOffset();
   } else {
     // TODO run a visitor to find the containing body!
     return; // TODO popup error dialog
   }
   boolean isInterface = body instanceof Tree.InterfaceBody;
   // TODO: copy/pasted from ImplementFormalMembersProposal
   List<Statement> statements = body.getStatements();
   String indent;
   String bodyIndent = getIndent(body, document);
   if (statements.isEmpty()) {
     indent = "\n" + bodyIndent + getDefaultIndent();
     if (offset < 0) offset = body.getStartIndex() + 1;
   } else {
     Statement statement = statements.get(statements.size() - 1);
     indent = "\n" + getIndent(statement, document);
     if (offset < 0) offset = statement.getStopIndex() + 1;
   }
   StringBuilder result = new StringBuilder();
   Set<Declaration> already = new HashSet<Declaration>();
   for (DeclarationWithProximity dwp : getProposals(node, cu).values()) {
     Declaration d = dwp.getDeclaration();
     if (d.isFormal() && ((ClassOrInterface) node.getScope()).isInheritedFromSupertype(d)) {
       ProducedReference pr = getRefinedProducedReference(node, d);
       result
           .append(indent)
           .append(getRefinementTextFor(d, pr, isInterface, indent))
           .append(indent);
       importSignatureTypes(d, cu, already);
     }
   }
   try {
     if (document.getChar(offset) == '}' && result.length() > 0) {
       result.append("\n").append(bodyIndent);
     }
   } catch (BadLocationException e) {
     e.printStackTrace();
   }
   applyImports(change, already, cu);
   change.addEdit(new InsertEdit(offset, result.toString()));
   change.initializeValidationData(null);
   try {
     getWorkspace().run(new PerformChangeOperation(change), new NullProgressMonitor());
   } catch (CoreException ce) {
     throw new ExecutionException("Error cleaning imports", ce);
   }
 }
  @Deprecated
  // replaced by RefineFormalMembersQuickFix.ceylon
  private void refineFormalMembers(IDocument document) throws ExecutionException {
    if (rootNode == null) return;
    TextChange change = new DocumentChange("Refine Members", document);
    change.setEdit(new MultiTextEdit());
    // TODO: copy/pasted from CeylonQuickFixAssistant
    Tree.Body body;
    int offset;
    if (node instanceof Tree.ClassDefinition) {
      ClassDefinition classDefinition = (Tree.ClassDefinition) node;
      body = classDefinition.getClassBody();
      offset = -1;
    } else if (node instanceof Tree.InterfaceDefinition) {
      Tree.InterfaceDefinition interfaceDefinition = (Tree.InterfaceDefinition) node;
      body = interfaceDefinition.getInterfaceBody();
      offset = -1;
    } else if (node instanceof Tree.ObjectDefinition) {
      Tree.ObjectDefinition objectDefinition = (Tree.ObjectDefinition) node;
      body = objectDefinition.getClassBody();
      offset = -1;
    } else if (node instanceof Tree.ObjectExpression) {
      Tree.ObjectExpression objectExpression = (Tree.ObjectExpression) node;
      body = objectExpression.getClassBody();
      offset = -1;
    } else if (node instanceof Tree.ClassBody || node instanceof Tree.InterfaceBody) {
      body = (Tree.Body) node;
      IEditorPart editor = getCurrentEditor();
      if (editor instanceof CeylonEditor) {
        CeylonEditor ce = (CeylonEditor) editor;
        offset = ce.getSelection().getOffset();
      } else {
        offset = -1;
      }
    } else {
      return;
    }
    if (body == null) {
      return;
    }
    boolean isInterface = body instanceof Tree.InterfaceBody;
    List<Tree.Statement> statements = body.getStatements();
    String indent;
    //        String bodyIndent = getIndent(body, document);
    String bodyIndent = utilJ2C().indents().getIndent(node, document);
    String delim = utilJ2C().indents().getDefaultLineDelimiter(document);
    if (statements.isEmpty()) {
      indent = delim + bodyIndent + utilJ2C().indents().getDefaultIndent();
      if (offset < 0) {
        offset = body.getStartIndex() + 1;
      }
    } else {
      Tree.Statement statement = statements.get(statements.size() - 1);
      indent = delim + utilJ2C().indents().getIndent(statement, document);
      if (offset < 0) {
        offset = statement.getEndIndex();
      }
    }
    StringBuilder result = new StringBuilder();
    Set<Declaration> already = new HashSet<Declaration>();
    ClassOrInterface ci = (ClassOrInterface) node.getScope();
    Unit unit = node.getUnit();
    Set<String> ambiguousNames = new HashSet<String>();
    // TODO: does not return unrefined overloaded
    //      versions of a method with one overlaad
    //      already refined
    Collection<DeclarationWithProximity> proposals =
        ci.getMatchingMemberDeclarations(unit, ci, "", 0).values();
    for (DeclarationWithProximity dwp : proposals) {
      Declaration dec = dwp.getDeclaration();
      for (Declaration d : overloads(dec)) {
        try {
          if (d.isFormal() && ci.isInheritedFromSupertype(d)) {
            appendRefinementText(isInterface, indent, result, ci, unit, d);
            importProposals().importSignatureTypes(d, rootNode, already);
            ambiguousNames.add(d.getName());
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    for (TypeDeclaration superType : ci.getSupertypeDeclarations()) {
      for (Declaration m : superType.getMembers()) {
        try {
          if (m.getName() != null && m.isShared()) {
            Declaration r = ci.getMember(m.getName(), null, false);
            if ((r == null || !r.refines(m) && !r.getContainer().equals(ci))
                && ambiguousNames.add(m.getName())) {
              appendRefinementText(isInterface, indent, result, ci, unit, m);
              importProposals().importSignatureTypes(m, rootNode, already);
            }
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }

    try {
      if (document.getChar(offset) == '}' && result.length() > 0) {
        result.append(delim).append(bodyIndent);
      }
    } catch (BadLocationException e) {
      e.printStackTrace();
    }
    importProposals().applyImports(change, already, rootNode, document);
    change.addEdit(new InsertEdit(offset, result.toString()));
    change.initializeValidationData(null);
    try {
      getWorkspace().run(new PerformChangeOperation(change), new NullProgressMonitor());
    } catch (CoreException ce) {
      ce.printStackTrace();
    }
  }
 private void errorDefaultedParameter(Node d) {
   d.addError(
       "compiler bug: only literals, true, false, and annotation class instantiations are permitted as annotation parameter defaults");
 }