/**
   * Checks, whether giver selection is correct selection, or can be expanded to correct selection
   * region. As result will set this.actualSelection(Start|End) properly. In case of incorrect
   * selection, will return false.
   *
   * @param source
   * @param start
   * @param end
   * @return
   */
  protected boolean checkSelection(String source, int start, int end) {
    if (start > end) {
      int x = start;
      start = end;
      end = x;
    }
    if (start + 1 == end) {
      ISourceRange range = RubySyntaxUtils.getEnclosingName(source, end);
      if (range != null) {
        this.actualSelectionStart = range.getOffset();
        this.actualSelectionEnd = this.actualSelectionStart + range.getLength();
        // return true;
      }
      ISourceRange range2 = RubySyntaxUtils.insideMethodOperator(source, end);
      if (range != null && (range2 == null || range2.getLength() < range.getLength())) return true;
      if (range2 != null) {
        this.actualSelectionStart = range2.getOffset();
        this.actualSelectionEnd = this.actualSelectionStart + range2.getLength();
        return true;
      }
    } else {
      if (start >= 0 && end < source.length()) {
        String str = source.substring(start, end + 1);
        if (RubySyntaxUtils.isRubyName(str)) {
          this.actualSelectionStart = start;
          this.actualSelectionEnd = end + 1;
          return true;
        }
      }
    }

    return false;
  }
 private void printDefinition(StringBuffer buffer, String s, TypedDefinition typed) {
   buffer.append("<dd>"); // $NON-NLS-1$
   if (s != null && s.length() != 0) {
     if (typed == TypedDefinition.NONE) {
       buffer.append(s);
     } else if (typed == TypedDefinition.PARAM) {
       final ISourceRange param = getParamRange(s);
       if (param != null) {
         if (param.getOffset() > 0) {
           buffer.append("<i>");
           buffer.append(TextUtils.escapeHTML(s.substring(0, param.getOffset())));
           buffer.append("</i>");
         }
         buffer.append("<b>"); // $NON-NLS-1$
         buffer.append(
             TextUtils.escapeHTML(
                 s.substring(param.getOffset(), param.getOffset() + param.getLength())));
         buffer.append("</b>"); // $NON-NLS-1$
         buffer.append(s.substring(param.getOffset() + param.getLength()));
       } else {
         buffer.append(s);
       }
     } else {
       assert (typed == TypedDefinition.AUTO);
       int endOfType = skipTypeDefinition(s);
       if (endOfType > 0) {
         buffer.append("<i>");
         buffer.append(TextUtils.escapeHTML(s.substring(0, endOfType)));
         buffer.append("</i>");
       }
       buffer.append(s.substring(endOfType));
     }
   }
   buffer.append("</dd>"); // $NON-NLS-1$
 }
 /* (non-JavaDoc)
  * Method declared in IAction.
  */
 public final void run() {
   ITextSelection selection = getTextSelection();
   ISourceRange newRange = getNewSelectionRange(createSourceRange(selection), null);
   // Check if new selection differs from current selection
   if (selection.getOffset() == newRange.getOffset()
       && selection.getLength() == newRange.getLength()) return;
   fEditor.selectAndReveal(newRange.getOffset(), newRange.getLength());
 }
 public void update() {
   boolean enabled = false;
   ISourceReference ref = getSourceReference();
   if (ref != null) {
     ISourceRange range;
     try {
       range = ref.getSourceRange();
       enabled = range != null && range.getLength() > 0;
     } catch (ModelException e) {
       // enabled= false;
     }
   }
   setEnabled(enabled);
 }
  private boolean isCoveringFunction(IMethod fun, int offset) {
    try {
      ISourceRange sr = fun.getSourceRange();
      int declOff = sr.getOffset();
      int declLen = sr.getLength();
      int declEnd = declOff + declLen;

      int start = fun.getNameRange().getOffset();

      return start < offset && declEnd > offset;
    } catch (ModelException e) {
      throw new RuntimeException(e);
    }
  }
 /** @see ISourceReference */
 @Override
 public String getSource() throws ModelException {
   IOpenable openable = this.parent.getOpenableParent();
   IBuffer buffer = openable.getBuffer();
   if (buffer == null) {
     return null;
   }
   ISourceRange range = getSourceRange();
   int offset = range.getOffset();
   int length = range.getLength();
   if (offset == -1 || length == 0) {
     return null;
   }
   try {
     return buffer.getText(offset, length);
   } catch (RuntimeException e) {
     return null;
   }
 }
  /*
   * non java doc
   *
   * @see StructureSelectionAction#internalGetNewSelectionRange(ISourceRange,
   * ICompilationUnit, SelectionAnalyzer)
   */
  public ISourceRange internalGetNewSelectionRange(
      ISourceRange oldSourceRange, ISourceReference sr, SelectionAnalyzer selAnalyzer)
      throws ModelException {
    if (oldSourceRange.getLength() == 0 && selAnalyzer.getLastCoveringNode() != null) {
      ASTNode previousNode =
          NextNodeAnalyzer.perform(oldSourceRange.getOffset(), selAnalyzer.getLastCoveringNode());
      if (previousNode != null) return getSelectedNodeSourceRange(sr, previousNode);
    }
    org.eclipse.php.internal.core.ast.nodes.ASTNode first = selAnalyzer.getFirstSelectedNode();
    if (first == null) return getLastCoveringNodeRange(oldSourceRange, sr, selAnalyzer);

    org.eclipse.php.internal.core.ast.nodes.ASTNode parent = first.getParent();
    if (parent == null) return getLastCoveringNodeRange(oldSourceRange, sr, selAnalyzer);

    org.eclipse.php.internal.core.ast.nodes.ASTNode lastSelectedNode =
        selAnalyzer.getSelectedNodes()[selAnalyzer.getSelectedNodes().length - 1];
    org.eclipse.php.internal.core.ast.nodes.ASTNode nextNode =
        getNextNode(parent, lastSelectedNode);
    if (nextNode == parent) return getSelectedNodeSourceRange(sr, first.getParent());
    int offset = oldSourceRange.getOffset();
    int end = Math.min(sr.getSourceRange().getLength(), nextNode.getEnd() - 1);
    return createSourceRange(offset, end);
  }
  public IGoal[] init() {
    ClassVariableDeclarationGoal typedGoal = (ClassVariableDeclarationGoal) goal;
    IType[] types = typedGoal.getTypes();

    if (types == null) {
      TypeContext context = (TypeContext) typedGoal.getContext();
      types = PHPTypeInferenceUtils.getModelElements(context.getInstanceType(), context);
    }
    if (types == null) {
      return null;
    }

    IContext context = typedGoal.getContext();
    IModelAccessCache cache = null;
    if (context instanceof IModelCacheContext) {
      cache = ((IModelCacheContext) context).getCache();
    }

    String variableName = typedGoal.getVariableName();

    final List<IGoal> subGoals = new LinkedList<IGoal>();
    for (final IType type : types) {
      try {
        ITypeHierarchy hierarchy = null;
        if (cache != null) {
          hierarchy = cache.getSuperTypeHierarchy(type, null);
        }
        IField[] fields =
            PHPModelUtils.getTypeHierarchyField(type, hierarchy, variableName, true, null);
        Map<IType, IType> fieldDeclaringTypeSet = new HashMap<IType, IType>();
        for (IField field : fields) {
          IType declaringType = field.getDeclaringType();
          if (declaringType != null) {
            fieldDeclaringTypeSet.put(declaringType, type);
            ISourceModule sourceModule = declaringType.getSourceModule();
            ModuleDeclaration moduleDeclaration =
                SourceParserUtil.getModuleDeclaration(sourceModule);
            TypeDeclaration typeDeclaration =
                PHPModelUtils.getNodeByClass(moduleDeclaration, declaringType);

            if (typeDeclaration != null && field instanceof SourceRefElement) {
              SourceRefElement sourceRefElement = (SourceRefElement) field;
              ISourceRange sourceRange = sourceRefElement.getSourceRange();

              ClassDeclarationSearcher searcher =
                  new ClassDeclarationSearcher(
                      sourceModule,
                      typeDeclaration,
                      sourceRange.getOffset(),
                      sourceRange.getLength(),
                      null,
                      type,
                      declaringType);
              try {
                moduleDeclaration.traverse(searcher);
                if (searcher.getResult() != null) {
                  subGoals.add(new ExpressionTypeGoal(searcher.getContext(), searcher.getResult()));
                }
              } catch (Exception e) {
                if (DLTKCore.DEBUG) {
                  e.printStackTrace();
                }
              }
            }
          }
        }

        if (subGoals.size() == 0) {
          getGoalFromStaticDeclaration(variableName, subGoals, type, null);
        }
        fieldDeclaringTypeSet.remove(type);
        if (subGoals.size() == 0 && !fieldDeclaringTypeSet.isEmpty()) {
          for (Iterator iterator = fieldDeclaringTypeSet.keySet().iterator();
              iterator.hasNext(); ) {
            IType fieldDeclaringType = (IType) iterator.next();
            getGoalFromStaticDeclaration(
                variableName,
                subGoals,
                fieldDeclaringType,
                fieldDeclaringTypeSet.get(fieldDeclaringType));
          }
        }
      } catch (CoreException e) {
        if (DLTKCore.DEBUG) {
          e.printStackTrace();
        }
      }
    }

    resolveMagicClassVariableDeclaration(types, variableName, cache);

    return subGoals.toArray(new IGoal[subGoals.size()]);
  }
Exemple #9
0
  /**
   * Adds the self function with the relevant data to the proposals array
   *
   * @param context
   * @param reporter
   * @throws BadLocationException
   */
  protected void addSelf(AbstractCompletionContext context, ICompletionReporter reporter)
      throws BadLocationException {

    String prefix = context.getPrefix();
    SourceRange replaceRange = getReplacementRange(context);

    if (CodeAssistUtils.startsWithIgnoreCase("self", prefix)) {
      if (!context.getCompletionRequestor().isContextInformationMode()
          || prefix.length() == 4) { // "self".length()

        String suffix = getSuffix(context);

        // get the class data for "self". In case of null, the self
        // function will not be added
        IType selfClassData =
            CodeAssistUtils.getSelfClassData(context.getSourceModule(), context.getOffset());
        if (selfClassData != null) {
          try {
            IMethod ctor = null;
            for (IMethod method : selfClassData.getMethods()) {
              if (method.isConstructor()) {
                ctor = method;
                break;
              }
            }
            if (ctor != null) {
              ISourceRange sourceRange = selfClassData.getSourceRange();
              FakeMethod ctorMethod =
                  new FakeMethod(
                      (ModelElement) selfClassData,
                      "self",
                      sourceRange.getOffset(),
                      sourceRange.getLength(),
                      sourceRange.getOffset(),
                      sourceRange.getLength()) {
                    public boolean isConstructor() throws ModelException {
                      return true;
                    }
                  };
              ctorMethod.setParameters(ctor.getParameters());
              reporter.reportMethod(ctorMethod, suffix, replaceRange);
            } else {
              ISourceRange sourceRange = selfClassData.getSourceRange();
              reporter.reportMethod(
                  new FakeMethod(
                      (ModelElement) selfClassData,
                      "self",
                      sourceRange.getOffset(),
                      sourceRange.getLength(),
                      sourceRange.getOffset(),
                      sourceRange.getLength()),
                  "()",
                  replaceRange);
            }
          } catch (ModelException e) {
            PHPCorePlugin.log(e);
          }
        }
      }
    }
  }
  private void generate(
      final List<GetterSetterEntry> entries, final int modifier, final boolean generateComments)
      throws Exception {

    ISourceModule source = type.getSourceModule();
    String name = type.getElementName().replace("$", "");
    StringBuffer buffer = new StringBuffer(name);
    buffer.replace(0, 1, Character.toString(Character.toUpperCase(name.charAt(0))));
    name = buffer.toString();

    ASTParser parser = ASTParser.newParser(source);
    parser.setSource(document.get().toCharArray());

    Program program = parser.createAST(new NullProgressMonitor());
    //		program.recordModifications();
    //		AST ast = program.getAST();

    ISourceRange range = type.getSourceRange();
    ASTNode node = program.getElementAt(range.getOffset());

    if (!(node instanceof ClassDeclaration)) {
      return;
    }

    char indentChar = FormatPreferencesSupport.getInstance().getIndentationChar(document);
    String indent = String.valueOf(indentChar);

    ClassDeclaration clazz = (ClassDeclaration) node;
    Block body = clazz.getBody();
    List<Statement> bodyStatements = body.statements();

    int end = bodyStatements.get(bodyStatements.size() - 1).getEnd();

    if (insertFirst) {
      end = bodyStatements.get(0).getStart() - 1;
    } else if (insertAfter != null) {

      boolean found = false;

      for (IMethod method : type.getMethods()) {
        if (method == insertAfter) {
          ISourceRange r = method.getSourceRange();
          end = r.getOffset() + r.getLength();
          found = true;
        }
      }

      if (!found) {
        for (IField field : type.getFields()) {
          ISourceRange r = field.getSourceRange();
          end = r.getOffset() + r.getLength() + 1;
        }
      }
    }

    lineDelim = TextUtilities.getDefaultLineDelimiter(document);
    String methods = "";

    int i = 0;
    for (GetterSetterEntry entry : entries) {

      String code = "";

      if (!entry.isGetter) {
        code =
            GetterSetterUtil.getSetterStub(
                entry.field,
                entry.getIdentifier(),
                entry.getType(),
                generateComments,
                modifier,
                indent);

      } else {
        code =
            GetterSetterUtil.getGetterStub(
                entry.field, entry.getIdentifier(), generateComments, modifier, indent);
      }

      code = lineDelim + code;
      String formatted = indentPattern(code, indent, lineDelim);

      if (i++ == 0) {
        formatted = lineDelim + formatted;
      }

      methods += formatted;
    }

    document.replace(end, 0, methods);

    Formatter formatter = new Formatter();
    Region region = new Region(end, methods.length());
    formatter.format(document, region);
  }