Ejemplo n.º 1
0
 private void checkVariable(Tree.Term term, Node node) {
   if (isEffectivelyBaseMemberExpression(term)) { // Note: other cases handled in ExpressionVisitor
     Tree.StaticMemberOrTypeExpression mte = (Tree.StaticMemberOrTypeExpression) term;
     Declaration member = mte.getDeclaration();
     if (member == declaration) {
       if ((declaration.isFormal() || declaration.isDefault()) && !isForwardReferenceable()) {
         term.addError(
             "member is formal or default and may not be assigned here: '"
                 + member.getName()
                 + "'");
       } else if (!isVariable() && !isLate()) {
         if (member instanceof Value) {
           if (node instanceof Tree.AssignOp) {
             term.addError(
                 "value is not a variable and may not be assigned here: '"
                     + member.getName()
                     + "'",
                 803);
           } else {
             term.addError("value is not a variable: '" + member.getName() + "'", 800);
           }
         } else {
           term.addError("not a variable value: '" + member.getName() + "'");
         }
       }
     }
   }
 }
Ejemplo n.º 2
0
 @Override
 public void visit(Tree.AttributeDeclaration that) {
   if (that.getDeclarationModel() == declaration) {
     Tree.SpecifierOrInitializerExpression sie = that.getSpecifierOrInitializerExpression();
     if (sie != null) {
       super.visit(that);
       specify();
     } else {
       super.visit(that);
       if (declaration.isToplevel() && !isNativeHeader(declaration) && !isLate()) {
         if (isVariable()) {
           that.addError(
               "toplevel variable value must be initialized: '" + declaration.getName() + "'");
         } else {
           that.addError("toplevel value must be specified: '" + declaration.getName() + "'");
         }
       } else if (declaration.isClassOrInterfaceMember()
           && !isNativeHeader(declaration)
           && !declaration.isFormal()
           && that.getDeclarationModel().getInitializerParameter() == null
           && !that.getDeclarationModel().isLate()
           && declarationSection) {
         that.addError(
             "forward declaration may not occur in declaration section: '"
                 + declaration.getName()
                 + "'",
             1450);
       }
     }
   } else {
     super.visit(that);
   }
 }
Ejemplo n.º 3
0
 private boolean hidesToplevel(Declaration dec) {
   for (Declaration d : unit.getDeclarations()) {
     String n = d.getName();
     if (d.isToplevel() && n != null && dec.getName().equals(n)) {
       return true;
     }
   }
   return false;
 }
Ejemplo n.º 4
0
 private void checkAliasCase(Tree.Alias alias, Declaration d) {
   if (alias != null) {
     Tree.Identifier id = alias.getIdentifier();
     int tt = id.getToken().getType();
     if (d instanceof TypeDeclaration && tt != CeylonLexer.UIDENTIFIER) {
       id.addError("imported type should have uppercase alias: '" + d.getName() + "'");
     } else if (d instanceof TypedDeclaration && tt != CeylonLexer.LIDENTIFIER) {
       id.addError("imported member should have lowercase alias: '" + d.getName() + "'");
     }
   }
 }
Ejemplo n.º 5
0
 private void importAllMembers(
     Package importedPackage, Set<String> ignoredMembers, ImportList il) {
   for (Declaration dec : importedPackage.getMembers()) {
     if (dec.isShared()
         && isResolvable(dec)
         && !ignoredMembers.contains(dec.getName())
         && !isNonimportable(importedPackage, dec.getName())) {
       addWildcardImport(il, dec);
     }
   }
 }
Ejemplo n.º 6
0
 public static Declaration getRefinedDeclaration(Declaration declaration) {
   // Reproduces the algorithm used to build the type hierarchy
   // first walk up the superclass hierarchy
   if (declaration.isClassOrInterfaceMember() && declaration.isShared()) {
     TypeDeclaration dec = (TypeDeclaration) declaration.getContainer();
     List<Type> signature = getSignature(declaration);
     Declaration refined = declaration.getRefinedDeclaration();
     while (dec != null) {
       Type extended = dec.getExtendedType();
       if (extended != null) {
         TypeDeclaration superDec = extended.getDeclaration();
         Declaration superMemberDec =
             superDec.getDirectMember(declaration.getName(), signature, false);
         if (superMemberDec != null) {
           Declaration superRefined = superMemberDec.getRefinedDeclaration();
           if (superRefined != null
               && refined != null
               && !isAbstraction(superMemberDec)
               && superRefined.equals(refined)) {
             return superMemberDec;
           }
         }
         dec = superDec;
       } else {
         dec = null;
       }
     }
     // now look at the very top of the hierarchy, even if it is an interface
     Declaration refinedDeclaration = refined;
     if (refinedDeclaration != null && !declaration.equals(refinedDeclaration)) {
       List<Declaration> directlyInheritedMembers =
           getInterveningRefinements(
               declaration.getName(),
               signature,
               refinedDeclaration,
               (TypeDeclaration) declaration.getContainer(),
               (TypeDeclaration) refinedDeclaration.getContainer());
       directlyInheritedMembers.remove(refinedDeclaration);
       // TODO: do something for the case of
       //      multiple intervening interfaces?
       if (directlyInheritedMembers.size() == 1) {
         // exactly one intervening interface
         return directlyInheritedMembers.get(0);
       } else {
         // no intervening interfaces
         return refinedDeclaration;
       }
     }
   }
   return null;
 }
Ejemplo n.º 7
0
 public static String getImportText(
     Set<String> packages, Map<Declaration, String> imports, String delim) {
   StringBuilder sb = new StringBuilder();
   for (String p : packages) {
     if (p.isEmpty()) {
       // can't import from default package
       continue;
     }
     sb.append("import ").append(p).append(" {").append(delim);
     boolean first = true;
     for (Map.Entry<Declaration, String> e : imports.entrySet()) {
       Declaration d = e.getKey();
       String pn = d.getUnit().getPackage().getQualifiedNameString();
       if (pn.equals(p)) {
         if (!first) {
           sb.append(",").append(delim);
         }
         sb.append(getDefaultIndent());
         String name = d.getName();
         String alias = e.getValue();
         if (!name.equals(alias)) {
           sb.append(alias).append("=");
         }
         sb.append(name);
         first = false;
       }
     }
     sb.append(delim).append("}").append(delim);
   }
   return sb.toString();
 }
 @Override
 public boolean getEnabled() {
   return declaration instanceof Declaration
       && declaration.getName() != null
       && project != null
       && (inSameProject(declaration) || inSameUnit());
 }
 private void addRemoval(Tree.Identifier id, Declaration d) {
   if (id != null
       && d != null
       && dec.equals(getAbstraction(d))
       && id.getText().equals(aid.getText())) {
     change.addEdit(new ReplaceEdit(id.getStartIndex(), id.getDistance(), dec.getName()));
   }
 }
Ejemplo n.º 10
0
 private void addWildcardImport(ImportList il, Declaration dec) {
   if (!hidesToplevel(dec)) {
     Import i = new Import();
     i.setAlias(dec.getName());
     i.setDeclaration(dec);
     i.setWildcardImport(true);
     addWildcardImport(il, dec, i);
   }
 }
Ejemplo n.º 11
0
 static String getDescription(Declaration dec) {
   String desc = "'" + dec.getName() + "'";
   Scope container = dec.getContainer();
   if (container instanceof TypeDeclaration) {
     TypeDeclaration td = (TypeDeclaration) container;
     desc += " in '" + td.getName() + "'";
   }
   return desc;
 }
 @Override
 public void visit(Tree.DocLink that) {
   super.visit(that);
   // TODO: copy/paste from EnterAliasRefactoring
   Declaration base = that.getBase();
   if (base != null && dec.equals(base)) {
     Region region = DocLinks.nameRegion(that, 0);
     change.addEdit(new ReplaceEdit(region.getOffset(), region.getLength(), dec.getName()));
   }
 }
 public RenameRefactoring(IEditorPart editor) {
   super(editor);
   boolean identifiesDeclaration =
       node instanceof Tree.DocLink || getIdentifyingNode(node) instanceof Tree.Identifier;
   if (rootNode != null && identifiesDeclaration) {
     Referenceable refDec = getReferencedExplicitDeclaration(node, rootNode);
     if (refDec instanceof Declaration) {
       Declaration dec = (Declaration) refDec;
       declaration = dec.getRefinedDeclaration();
       newName = declaration.getName();
       String filename = declaration.getUnit().getFilename();
       renameFile = (declaration.getName() + ".ceylon").equals(filename);
     } else {
       declaration = null;
     }
   } else {
     declaration = null;
   }
 }
Ejemplo n.º 14
0
 private void importAllMembers(
     TypeDeclaration importedType, Set<String> ignoredMembers, ImportList til) {
   for (Declaration dec : importedType.getMembers()) {
     if (dec.isShared()
         && (dec.isStaticallyImportable() || isConstructor(dec))
         && isResolvable(dec)
         && !ignoredMembers.contains(dec.getName())) {
       addWildcardImport(til, dec, importedType);
     }
   }
 }
 protected void renameIdentifier(TextChange tfc, Tree.Identifier id, Tree.CompilationUnit root) {
   String name = declaration.getName();
   int loc = id.getText().indexOf(name);
   int start = id.getStartIndex();
   int len = id.getDistance();
   if (loc > 0) {
     tfc.addEdit(new ReplaceEdit(start + loc, name.length(), newName));
   } else {
     tfc.addEdit(new ReplaceEdit(start, len, escaping_.get_().toInitialLowercase(newName)));
   }
 }
Ejemplo n.º 16
0
 @Override
 public void visit(Tree.MethodDeclaration that) {
   if (that.getDeclarationModel() == declaration) {
     if (that.getSpecifierExpression() != null) {
       specify();
       super.visit(that);
     } else {
       super.visit(that);
       if (declaration.isToplevel() && !isNativeHeader(declaration)) {
         that.addError(
             "toplevel function must be specified: '"
                 + declaration.getName()
                 + "' may not be forward declared");
       } else if (declaration.isClassMember()
           && !isNativeHeader(declaration)
           && isInNativeContainer(declaration)) {
         that.addError(
             "member in native container must be native: '" + declaration.getName() + "'", 1450);
       } else if (declaration.isClassMember()
           && !isNativeHeader(declaration)
           && !declaration.isFormal()
           && that.getDeclarationModel().getInitializerParameter() == null
           && declarationSection) {
         that.addError(
             "forward declaration may not occur in declaration section: '"
                 + declaration.getName()
                 + "'",
             1450);
       } else if (declaration.isInterfaceMember()
           && !isNativeHeader(declaration)
           && !declaration.isFormal()) {
         that.addError(
             "interface method must be formal or specified: '" + declaration.getName() + "'",
             1400);
       }
     }
   } else {
     super.visit(that);
   }
 }
  private Referenceable resolveNative(
      Referenceable referenceable, Declaration dec, Backends backends) {
    Unit unit = dec.getUnit();
    Scope containerToSearchHeaderIn = null;
    if (unit instanceof CeylonBinaryUnit) {
      CeylonBinaryUnit binaryUnit = (CeylonBinaryUnit) unit;
      ExternalPhasedUnit phasedUnit = binaryUnit.getPhasedUnit();
      if (phasedUnit != null) {
        ExternalSourceFile sourceFile = phasedUnit.getUnit();
        if (sourceFile != null) {
          String sourceRelativePath =
              toJavaString(
                  binaryUnit
                      .getCeylonModule()
                      .toSourceUnitRelativePath(toCeylonString(unit.getRelativePath())));
          if (sourceRelativePath != null && sourceRelativePath.endsWith(".ceylon")) {
            for (Declaration sourceDecl : sourceFile.getDeclarations()) {
              if (sourceDecl.equals(dec)) {
                containerToSearchHeaderIn = sourceDecl.getContainer();
                break;
              }
            }
          } else {
            for (Declaration sourceDecl : sourceFile.getDeclarations()) {
              if (sourceDecl.getQualifiedNameString().equals(dec.getQualifiedNameString())) {
                containerToSearchHeaderIn = sourceDecl.getContainer();
                break;
              }
            }
          }
        }
      }
    } else {
      containerToSearchHeaderIn = dec.getContainer();
    }

    if (containerToSearchHeaderIn != null) {
      Declaration headerDeclaration = getNativeHeader(containerToSearchHeaderIn, dec.getName());
      if (headerDeclaration == null || !headerDeclaration.isNative()) return null;
      if (backends.header()) {
        referenceable = headerDeclaration;
      } else {
        if (headerDeclaration != null) {
          referenceable = getNativeDeclaration(headerDeclaration, supportedBackends());
        }
      }
    }
    return referenceable;
  }
Ejemplo n.º 18
0
 private void addWildcardImport(ImportList il, Declaration dec, Import i) {
   if (notOverloaded(dec)) {
     String alias = i.getAlias();
     if (alias != null) {
       Import o = unit.getImport(dec.getName());
       if (o != null && o.isWildcardImport()) {
         if (o.getDeclaration().equals(dec) || dec.isNativeHeader()) {
           // this case only happens in the IDE,
           // due to reuse of the Unit
           unit.getImports().remove(o);
           il.getImports().remove(o);
         } else if (!dec.isNative()) {
           i.setAmbiguous(true);
           o.setAmbiguous(true);
         }
       }
       unit.getImports().add(i);
       il.getImports().add(i);
     }
   }
 }
Ejemplo n.º 19
0
 private static void addImport(
     String targetPackage, Declaration dec, Tree.CompilationUnit cu, TextChange tc) {
   String name = dec.getName();
   String delim = getDefaultLineDelimiter(getDocument(tc));
   String indent = getDefaultIndent();
   boolean foundMoved = false;
   Tree.ImportList il = cu.getImportList();
   for (Tree.Import i : il.getImports()) {
     Referenceable model = i.getImportPath().getModel();
     if (model != null) {
       if (model.getNameAsString().equals(targetPackage)) {
         Tree.ImportMemberOrTypeList imtl = i.getImportMemberOrTypeList();
         if (imtl != null) {
           String addition;
           int offset;
           List<Tree.ImportMemberOrType> imts = imtl.getImportMemberOrTypes();
           if (imts.isEmpty()) {
             offset = getNodeStartOffset(imtl) + 1;
             addition = delim + indent + name;
             int len = getNodeLength(imtl);
             if (len == 2) {
               addition += delim;
             }
           } else {
             offset = getNodeEndOffset(imts.get(imts.size() - 1));
             addition = "," + delim + indent + name;
           }
           // TODO: the alias!
           tc.addEdit(new InsertEdit(offset, addition));
           foundMoved = true;
         }
         break;
       }
     }
   }
   if (!foundMoved) {
     String text = "import " + targetPackage + " {" + delim + indent + name + delim + "}" + delim;
     tc.addEdit(new InsertEdit(0, text));
   }
 }
Ejemplo n.º 20
0
 private boolean checkForHiddenToplevel(Tree.Identifier id, Import i, Tree.Alias alias) {
   for (Declaration d : unit.getDeclarations()) {
     String n = d.getName();
     Declaration idec = i.getDeclaration();
     if (d.isToplevel()
         && n != null
         && i.getAlias().equals(n)
         && !idec.equals(d)
         &&
         // it is legal to import an object declaration
         // in the current package without providing an
         // alias:
         !isLegalAliasFreeImport(d, idec)) {
       if (alias == null) {
         id.addError("toplevel declaration with this name declared in this unit: '" + n + "'");
       } else {
         alias.addError("toplevel declaration with this name declared in this unit: '" + n + "'");
       }
       return true;
     }
   }
   return false;
 }
Ejemplo n.º 21
0
  public void createControl(Composite parent) {
    Composite result = new Composite(parent, SWT.NONE);
    setControl(result);
    GridLayout layout = new GridLayout();
    layout.numColumns = 3;
    result.setLayout(layout);
    Label title = new Label(result, SWT.LEFT);
    Declaration declaration = getRenameRefactoring().getDeclaration();
    String name = declaration.getName();
    title.setText(
        "Rename "
            + getRenameRefactoring().getCount()
            + " occurrences of declaration '"
            + name
            + "'.");
    GridData gd = new GridData();
    gd.horizontalSpan = 3;
    title.setLayoutData(gd);
    GridData gd2 = new GridData(GridData.FILL_HORIZONTAL);
    gd2.horizontalSpan = 3;
    new Label(result, SWT.SEPARATOR | SWT.HORIZONTAL).setLayoutData(gd2);

    Label label = new Label(result, SWT.RIGHT);
    label.setText("Rename to: ");
    final Text text = new Text(result, SWT.SINGLE | SWT.BORDER);
    GridData gd3 = new GridData();
    gd3.horizontalSpan = 2;
    text.setLayoutData(gd3);
    text.setText(getRenameRefactoring().getNewName());
    text.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
    text.addModifyListener(
        new ModifyListener() {
          @Override
          public void modifyText(ModifyEvent event) {
            String name = text.getText();
            validateIdentifier(name);
            getRenameRefactoring().setNewName(name);
          }
        });
    text.addKeyListener(new SubwordIterator(text));
    text.selectAll();
    text.setFocus();

    final Button renameSourceFile = new Button(result, SWT.CHECK);
    GridData gd4 = new GridData(GridData.FILL_HORIZONTAL);
    gd4.horizontalSpan = 3;
    gd4.grabExcessHorizontalSpace = true;
    renameSourceFile.setLayoutData(gd4);
    String filename = declaration.getUnit().getFilename();
    renameSourceFile.setText("Also rename source file '" + filename + "'");
    renameSourceFile.setSelection(getRenameRefactoring().isRenameFile());
    renameSourceFile.setEnabled(filename.endsWith(".ceylon"));
    renameSourceFile.addSelectionListener(
        new SelectionListener() {
          @Override
          public void widgetSelected(SelectionEvent e) {
            getRenameRefactoring().setRenameFile(renameSourceFile.getSelection());
          }

          @Override
          public void widgetDefaultSelected(SelectionEvent e) {}
        });

    final Button renameLocals = new Button(result, SWT.CHECK);
    renameLocals.setLayoutData(gd4);
    boolean typeDec = declaration instanceof TypeDeclaration;
    String txt = "Rename similarly-named values and functions";
    if (typeDec) txt += " of type '" + declaration.getName() + "'";
    renameLocals.setText(txt);
    renameLocals.setSelection(getRenameRefactoring().isRenameValuesAndFunctions());
    renameLocals.setEnabled(typeDec);
    renameLocals.addSelectionListener(
        new SelectionListener() {
          @Override
          public void widgetSelected(SelectionEvent e) {
            getRenameRefactoring().setRenameValuesAndFunctions(renameLocals.getSelection());
          }

          @Override
          public void widgetDefaultSelected(SelectionEvent e) {}
        });
  }
  @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();
    }
  }
Ejemplo n.º 23
0
 @Override
 public void visit(Tree.SpecifierStatement that) {
   Tree.Term term = that.getBaseMemberExpression();
   boolean parameterized = false;
   while (term instanceof Tree.ParameterizedExpression) {
     Tree.ParameterizedExpression pe = (Tree.ParameterizedExpression) term;
     term = pe.getPrimary();
     parameterized = true;
   }
   if (term instanceof Tree.StaticMemberOrTypeExpression) {
     Tree.StaticMemberOrTypeExpression bme = (Tree.StaticMemberOrTypeExpression) term;
     //            Declaration member = getTypedDeclaration(bme.getScope(),
     //                    name(bme.getIdentifier()), null, false, bme.getUnit());
     Declaration member = bme.getDeclaration();
     if (member == declaration) {
       if ((declaration.isFormal() || declaration.isDefault()) && !isForwardReferenceable()) {
         // TODO: is this error correct?! look at the condition above
         bme.addError(
             "member is formal and may not be specified: '"
                 + member.getName()
                 + "' is declared formal");
       }
       if (that.getRefinement()) {
         declare();
       }
       Tree.SpecifierExpression se = that.getSpecifierExpression();
       boolean lazy = se instanceof Tree.LazySpecifierExpression;
       if (declaration instanceof Value) {
         Value value = (Value) declaration;
         if (!value.isVariable() && lazy != value.isTransient()) {
           // check that all assignments to a non-variable, in
           // different paths of execution, all use the same
           // kind of specifier, all =>, or all =
           // TODO: sometimes this error appears only because
           //       of a later line which illegally reassigns
           se.addError(
               "value must be specified using => lazy specifier: '" + member.getName() + "'");
         }
         if (lazy) {
           if (value.isVariable()) {
             se.addError(
                 "variable value may not be specified using => lazy specifier: '"
                     + member.getName()
                     + "'");
           } else if (value.isLate()) {
             se.addError(
                 "late reference may not be specified using => lazy specifier: '"
                     + member.getName()
                     + "'");
           }
         }
       }
       if (!lazy || !parameterized) {
         se.visit(this);
       }
       boolean constant = !isVariable() && !isLate();
       Scope scope = that.getScope();
       if (constant && !declaration.isDefinedInScope(scope)) {
         // this error is added by ExpressionVisitor
         //                    that.addError("inherited member is not variable and may not be
         // specified here: '" +
         //                            member.getName() + "'");
       } else if (!declared && constant) {
         bme.addError(shortdesc() + " is not yet declared: '" + member.getName() + "'");
       } else if (inLoop && constant && !(endsInBreakReturnThrow && lastContinue == null)) {
         if (specified.definitely) {
           bme.addError(
               longdesc() + " is aready definitely specified: '" + member.getName() + "'", 803);
         } else {
           bme.addError(
               longdesc() + " is not definitely unspecified in loop: '" + member.getName() + "'",
               803);
         }
       } else if (withinDeclaration && constant && !that.getRefinement()) {
         Declaration dec = getContainingDeclarationOfScope(scope);
         if (dec != null && dec.equals(member)) {
           bme.addError(
               "cannot specify "
                   + shortdesc()
                   + " from within its own body: '"
                   + member.getName()
                   + "'");
         } else {
           bme.addError(
               "cannot specify "
                   + shortdesc()
                   + " declared in outer scope: '"
                   + member.getName()
                   + "'",
               803);
         }
       } else if (specified.possibly && constant) {
         if (specified.definitely) {
           bme.addError(
               longdesc() + " is aready definitely specified: '" + member.getName() + "'", 803);
         } else {
           bme.addError(
               longdesc() + " is not definitely unspecified: '" + member.getName() + "'", 803);
         }
       } else {
         specify();
         term.visit(this);
       }
       if (lazy && parameterized) {
         se.visit(this);
       }
     } else {
       super.visit(that);
     }
   } else {
     super.visit(that);
   }
 }
Ejemplo n.º 24
0
  private void visitReference(Tree.Primary that) {
    Declaration member;
    boolean assigned;
    boolean metamodel;
    if (that instanceof Tree.MemberOrTypeExpression) {
      Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) that;
      member = mte.getDeclaration();
      assigned = mte.getAssigned();
      metamodel = false;
    } else if (that instanceof Tree.MetaLiteral) {
      Tree.MetaLiteral ml = (Tree.MetaLiteral) that;
      member = ml.getDeclaration();
      assigned = false;
      metamodel = true;
    } else {
      return;
    }

    if (member == declaration && member.isDefinedInScope(that.getScope())) {
      if (!declared) {
        // you are allowed to refer to later
        // declarations in a class declaration
        // section or interface
        if (withinAttributeInitializer
            && member instanceof Value
            && !(((Value) member).isTransient())) {
          that.addError(
              "reference to value within its initializer: '" + member.getName() + "'", 1460);
        } else if (!metamodel && !isForwardReferenceable() && !hasParameter) {
          Scope container = declaration.getContainer();
          if (container instanceof Class) {
            that.addError(
                "forward reference to class member in initializer: '"
                    + member.getName()
                    + "' is not yet declared (forward references must occur in declaration section)");
          } else {
            that.addError(
                "forward reference to local declaration: '"
                    + member.getName()
                    + "' is not yet declared");
          }
        }
      } else if (!specified.definitely || declaration.isFormal()) {
        // you are allowed to refer to formal
        // declarations in a class declaration
        // section or interface
        if (declaration.isFormal()) {
          if (!isForwardReferenceable()) {
            that.addError(
                "formal member may not be used in initializer: '" + member.getName() + "'");
          }
        } else if (!metamodel
            && !isNativeHeader(declaration)
            && (!isLate() || !isForwardReferenceable())) {
          if (isVariable()) {
            that.addError("not definitely initialized: '" + member.getName() + "'");
          } else {
            that.addError("not definitely specified: '" + member.getName() + "'");
          }
        }
      }
      if (!assigned && member.isDefault() && !isForwardReferenceable()) {
        that.addError("default member may not be used in initializer: '" + member.getName() + "'");
      }
      if (inAnonFunctionOrComprehension && specified.definitely && isVariable()) {
        that.addError(
            "variable member may not be captured by comprehension or function in extends clause: '"
                + member.getName()
                + "'");
      }
    }
  }
Ejemplo n.º 25
0
 private String importMember(Tree.ImportMemberOrType member, TypeDeclaration td, ImportList il) {
   Tree.Identifier id = member.getIdentifier();
   if (id == null) {
     return null;
   }
   Import i = new Import();
   member.setImportModel(i);
   Tree.Alias alias = member.getAlias();
   String name = name(id);
   if (alias == null) {
     i.setAlias(name);
   } else {
     i.setAlias(name(alias.getIdentifier()));
   }
   Declaration m = td.getMember(name, null, false);
   if (m == null) {
     String correction = correct(td, null, unit, name);
     String message = correction == null ? "" : " (did you mean '" + correction + "'?)";
     id.addError(
         "imported declaration not found: '" + name + "' of '" + td.getName() + "'" + message,
         100);
     unit.getUnresolvedReferences().add(id);
   } else {
     List<Declaration> members = m.getContainer().getMembers();
     for (Declaration d : members) {
       String dn = d.getName();
       if (dn != null && dn.equals(name) && !d.sameKind(m) && !d.isAnonymous()) {
         // crazy interop cases like isOpen() + open()
         id.addError("ambiguous member declaration: '" + name + "' of '" + td.getName() + "'");
         return null;
       }
     }
     if (!m.isShared()) {
       id.addError(
           "imported declaration is not shared: '" + name + "' of '" + td.getName() + "'", 400);
     } else if (!declaredInPackage(m, unit)) {
       if (m.isPackageVisibility()) {
         id.addError(
             "imported package private declaration is not visible: '"
                 + name
                 + "' of '"
                 + td.getName()
                 + "'");
       } else if (m.isProtectedVisibility()) {
         id.addError(
             "imported protected declaration is not visible: '"
                 + name
                 + "' of '"
                 + td.getName()
                 + "'");
       }
     }
     i.setTypeDeclaration(td);
     if (!m.isStaticallyImportable()
         && !isToplevelClassConstructor(td, m)
         && !isToplevelAnonymousClass(m.getContainer())) {
       if (alias == null) {
         member.addError("does not specify an alias");
       }
     }
     i.setDeclaration(m);
     member.setDeclarationModel(m);
     if (il.hasImport(m)) {
       id.addError("already imported: '" + name + "' of '" + td.getName() + "'");
     } else {
       if (m.isStaticallyImportable()
           || isToplevelClassConstructor(td, m)
           || isToplevelAnonymousClass(m.getContainer())) {
         if (!checkForHiddenToplevel(id, i, alias)) {
           addImport(member, il, i);
         }
       } else {
         addMemberImport(member, il, i);
       }
     }
     checkAliasCase(alias, m);
   }
   if (m != null) {
     importMembers(member, m);
   }
   // imtl.addError("member aliases may not have member aliases");
   return name;
 }
Ejemplo n.º 26
0
 static void addCreateMemberProposal(
     Collection<ICompletionProposal> proposals,
     DefinitionGenerator dg,
     Declaration typeDec,
     PhasedUnit unit,
     Tree.Declaration decNode,
     Tree.Body body,
     Tree.Statement statement) {
   IFile file = getFile(unit);
   TextFileChange change = new TextFileChange("Create Member", file);
   change.setEdit(new MultiTextEdit());
   IDocument doc = EditorUtil.getDocument(change);
   String indentBefore;
   String indentAfter;
   String indent;
   int offset;
   List<Tree.Statement> statements = body.getStatements();
   String delim = getDefaultLineDelimiter(doc);
   if (statements.isEmpty()) {
     String bodyIndent = getIndent(decNode, doc);
     indent = bodyIndent + getDefaultIndent();
     indentBefore = delim + indent;
     try {
       boolean singleLineBody =
           doc.getLineOfOffset(body.getStartIndex()) == doc.getLineOfOffset(body.getStopIndex());
       if (singleLineBody) {
         indentAfter = delim + bodyIndent;
       } else {
         indentAfter = "";
       }
     } catch (BadLocationException e) {
       e.printStackTrace();
       indentAfter = delim;
     }
     offset = body.getStartIndex() + 1;
   } else {
     Tree.Statement st;
     if (statement != null
         && statement.getUnit().equals(body.getUnit())
         && statement.getStartIndex() >= body.getStartIndex()
         && statement.getStopIndex() <= body.getStopIndex()) {
       st = statements.get(0);
       for (Tree.Statement s : statements) {
         if (statement.getStartIndex() >= s.getStartIndex()
             && statement.getStopIndex() <= s.getStopIndex()) {
           st = s;
         }
       }
       indent = getIndent(st, doc);
       indentBefore = "";
       indentAfter = delim + indent;
       offset = st.getStartIndex();
     } else {
       st = statements.get(statements.size() - 1);
       indent = getIndent(st, doc);
       indentBefore = delim + indent;
       indentAfter = "";
       offset = st.getStopIndex() + 1;
     }
   }
   String generated =
       typeDec instanceof Interface
           ? dg.generateSharedFormal(indent, delim)
           : dg.generateShared(indent, delim);
   String def = indentBefore + generated + indentAfter;
   int il = applyImports(change, dg.getImports(), unit.getCompilationUnit(), doc);
   change.addEdit(new InsertEdit(offset, def));
   String desc = "Create " + memberKind(dg) + " in '" + typeDec.getName() + "'";
   int exitPos = dg.getNode().getStopIndex() + 1;
   proposals.add(
       new CreateProposal(
           def,
           desc,
           body.getScope(),
           body.getUnit(),
           dg.getReturnType(),
           dg.getImage(),
           offset + il,
           change,
           exitPos,
           dg instanceof ObjectClassDefinitionGenerator));
 }
 private RemoveAliasProposal(IFile file, Declaration dec, TextFileChange change) {
   super("Remove alias of '" + dec.getName() + "'", change, null, REMOVE_CORR);
 }