private void createSubChanges(
      final Variable parent, final TextFileChange change, final List<String> names) {
    final String parentMsgName =
        RUtil.formatVarName(RRefactoringAdapter.getUnquotedIdentifier(parent.fName));
    for (final Variable variable : parent.fSubVariables.values()) {
      if (variable.fNewName != null) {
        final String oldName = RRefactoringAdapter.getUnquotedIdentifier(variable.fName);
        final String oldMsgName = RUtil.formatVarName(oldName);
        final boolean isQuoted = (variable.fNewName.charAt(0) == '`');
        final GroupCategorySet set =
            new GroupCategorySet(
                new GroupCategory(
                    ((IRFrameInSource) parent.getParent()).getFrameId() + '$' + parent.fName,
                    NLS.bind(Messages.RenameInRegion_Changes_VariableGroup_name, parentMsgName),
                    "")); //$NON-NLS-1$
        final String message =
            NLS.bind(
                Messages.RenameInRegion_Changes_ReplaceOccurrenceOf_name,
                oldMsgName,
                parentMsgName);

        for (final RElementAccess access : variable.fAccessList) {
          final RAstNode nameNode = access.getNameNode();
          if (nameNode == null) {
            continue;
          }
          final String text =
              (isQuoted
                      && nameNode.getNodeType() == NodeType.SYMBOL
                      && nameNode.getOperator(0) == RTerminal.SYMBOL)
                  ? variable.fNewName
                  : RRefactoringAdapter.getUnquotedIdentifier(variable.fNewName);
          final IRegion nameRegion = RAst.getElementNameRegion(nameNode);
          TextChangeCompatibility.addTextEdit(
              change,
              message,
              new ReplaceEdit(nameRegion.getOffset(), nameRegion.getLength(), text),
              set);
        }
        names.add(oldName);
      }
    }
  }
 private void searchVariables(final RAstNode rootNode, final RefactoringStatus result) {
   fVariablesList = new HashMap<IRFrame, Map<String, Variable>>();
   final VariableSearcher searcher = new VariableSearcher();
   try {
     rootNode.acceptInR(searcher);
   } catch (final InvocationTargetException e) {
   }
   for (final Map<String, Variable> map : fVariablesList.values()) {
     for (final Variable var : map.values()) {
       checkVariables(var);
     }
   }
 }
 @Override
 public void visitNode(final RAstNode node) throws InvocationTargetException {
   if (node.getOffset() >= fStop || node.getStopOffset() < fStart) {
     return;
   }
   final Object[] attachments = node.getAttachments();
   for (final Object attachment : attachments) {
     if (attachment instanceof RElementAccess) {
       final RElementAccess access = (RElementAccess) attachment;
       if (access.getType() != RElementName.MAIN_DEFAULT) {
         continue;
       }
       final RAstNode nameNode = access.getNameNode();
       if (nameNode != null
           && nameNode.getOffset() >= fStart
           && nameNode.getStopOffset() <= fStop) {
         add(access);
       }
     }
   }
   node.acceptInRChildren(this);
 }
  private void createChanges(final TextFileChange change, final SubMonitor progress)
      throws BadLocationException, CoreException {
    fSourceUnit.connect(progress.newChild(1));
    try {
      final AbstractDocument document = fSourceUnit.getDocument(progress.newChild(1));
      final RCodeStyleSettings codeStyle = RRefactoringAdapter.getCodeStyle(fSourceUnit);

      RAstNode firstParentChild = (RAstNode) fFunction.getAdapter(IAstNode.class);
      while (true) {
        final RAstNode parent = firstParentChild.getRParent();
        if (parent == null
            || parent.getNodeType() == NodeType.SOURCELINES
            || parent.getNodeType() == NodeType.BLOCK) {
          break;
        }
        firstParentChild = parent;
      }

      final IRegion region = fAdapter.expandWhitespaceBlock(document, fOperationRegion);
      final int insertOffset =
          fAdapter
              .expandWhitespaceBlock(
                  document,
                  fAdapter.expandSelectionRegion(
                      document, new Region(firstParentChild.getOffset(), 0), fOperationRegion))
              .getOffset();
      final FDef fdefNode = (FDef) fFunction.getAdapter(FDef.class);
      final IRegion fbodyRegion =
          fAdapter.expandWhitespaceBlock(
              document,
              fAdapter.expandSelectionRegion(document, fdefNode.getContChild(), fOperationRegion));

      TextChangeCompatibility.addTextEdit(
          change,
          Messages.FunctionToS4Method_Changes_DeleteOld_name,
          new DeleteEdit(region.getOffset(), region.getLength()));

      final String nl = document.getDefaultLineDelimiter();
      final String argAssign = codeStyle.getArgAssignString();

      final StringBuilder sb = new StringBuilder();
      sb.append("setGeneric(\""); // $NON-NLS-1$
      sb.append(fFunctionName);
      sb.append("\","); // $NON-NLS-1$
      sb.append(nl);
      sb.append("function("); // $NON-NLS-1$
      boolean dots = false;
      for (final Variable variable : fVariablesList) {
        if (variable.getName().equals(RTerminal.S_ELLIPSIS)) {
          dots = true;
        }
        if (variable.getUseAsGenericArgument()) {
          sb.append(
              RElementName.create(RElementName.MAIN_DEFAULT, variable.getName()).getDisplayName());
          sb.append(", "); // $NON-NLS-1$
        }
      }
      if (!dots) {
        sb.append("..., "); // $NON-NLS-1$
      }
      sb.delete(sb.length() - 2, sb.length());
      sb.append(')');
      if (codeStyle.getNewlineFDefBodyBlockBefore()) {
        sb.append(nl);
      } else {
        sb.append(' ');
      }
      sb.append('{');
      sb.append(nl);
      sb.append("standardGeneric(\""); // $NON-NLS-1$
      sb.append(fFunctionName);
      sb.append("\")"); // $NON-NLS-1$
      sb.append(nl);
      sb.append("})"); // $NON-NLS-1$
      sb.append(nl);
      sb.append(nl);
      final String genericDef =
          RRefactoringAdapter.indent(sb, document, firstParentChild.getOffset(), fSourceUnit);
      TextChangeCompatibility.addTextEdit(
          change,
          Messages.FunctionToS4Method_Changes_AddGenericDef_name,
          new InsertEdit(insertOffset, genericDef));

      sb.setLength(0);
      sb.append("setMethod(\""); // $NON-NLS-1$
      sb.append(fFunctionName);
      sb.append("\","); // $NON-NLS-1$
      sb.append(nl);
      sb.append("signature("); // $NON-NLS-1$
      boolean hasType = false;
      for (final Variable variable : fVariablesList) {
        if (variable.getUseAsGenericArgument() && variable.getArgumentType() != null) {
          hasType = true;
          sb.append(
              RElementName.create(RElementName.MAIN_DEFAULT, variable.getName()).getDisplayName());
          sb.append(argAssign);
          sb.append("\""); // $NON-NLS-1$
          sb.append(variable.getArgumentType());
          sb.append("\", "); // $NON-NLS-1$
        }
      }
      if (hasType) {
        sb.delete(sb.length() - 2, sb.length());
      }
      sb.append("),"); // $NON-NLS-1$
      sb.append(nl);
      sb.append("function("); // $NON-NLS-1$
      final FDef.Args argsNode = fdefNode.getArgsChild();
      for (final Variable variable : fVariablesList) {
        sb.append(
            RElementName.create(RElementName.MAIN_DEFAULT, variable.getName()).getDisplayName());
        final FDef.Arg argNode = argsNode.getChild(variable.fArg.index);
        if (argNode.hasDefault()) {
          sb.append(argAssign);
          sb.append(
              document.get(
                  argNode.getDefaultChild().getOffset(), argNode.getDefaultChild().getLength()));
        }
        sb.append(", "); // $NON-NLS-1$
      }
      if (!fVariablesList.isEmpty()) {
        sb.delete(sb.length() - 2, sb.length());
      }
      sb.append(')');
      if (codeStyle.getNewlineFDefBodyBlockBefore()
          || fdefNode.getContChild().getNodeType() != NodeType.BLOCK) {
        sb.append(nl);
      } else {
        sb.append(' ');
      }
      sb.append(document.get(fbodyRegion.getOffset(), fbodyRegion.getLength()).trim());
      sb.append(")"); // $NON-NLS-1$
      sb.append(nl);
      final String methodDef =
          RRefactoringAdapter.indent(sb, document, firstParentChild.getOffset(), fSourceUnit);
      TextChangeCompatibility.addTextEdit(
          change,
          Messages.FunctionToS4Method_Changes_AddMethodDef_name,
          new InsertEdit(insertOffset, methodDef));
    } finally {
      fSourceUnit.disconnect(progress.newChild(1));
    }
  }
Exemple #5
0
  @Override
  public void doSubmitFileCommandToConsole(
      final String[] lines,
      final SrcfileData srcfile,
      final ISourceUnit su,
      final IProgressMonitor monitor)
      throws CoreException {
    if (srcfile != null
        && su instanceof IRWorkspaceSourceUnit
        && su.getModelTypeId() == RModel.TYPE_ID) {
      try {
        final IRModelInfo modelInfo =
            (IRModelInfo) su.getModelInfo(RModel.TYPE_ID, IRModelManager.MODEL_FILE, monitor);
        if (modelInfo != null) {
          final IRLangSourceElement fileElement = modelInfo.getSourceElement();
          final RAstNode rootNode = (RAstNode) fileElement.getAdapter(IAstNode.class);
          final List<? extends IRLangSourceElement> elements =
              modelInfo.getSourceElement().getSourceChildren(TAG_ELEMENT_FILTER);

          final List<String> elementIds = new ArrayList<String>(elements.size());
          final List<RObject> elementIndexes = new ArrayList<RObject>(elements.size());

          for (final IRLangSourceElement element : elements) {
            final FDef fdef = (FDef) element.getAdapter(FDef.class);
            if (fdef != null) {
              final String elementId = RDbg.getElementId(element);
              final RAstNode cont = fdef.getContChild();
              final int[] path = RAst.computeRExpressionIndex(cont, rootNode);
              if (elementId != null && path != null) {
                elementIds.add(elementId);
                elementIndexes.add(
                    fRObjectFactory.createVector(fRObjectFactory.createIntData(path)));
              }
            }
          }

          final FunctionCall prepare =
              createFunctionCall("rj:::.statet.prepareSource"); // $NON-NLS-1$
          prepare.add(
              fRObjectFactory.createList(
                  new RObject[] {
                    fRObjectFactory.createVector(
                        fRObjectFactory.createCharData(new String[] {srcfile.getPath()})),
                    fRObjectFactory.createVector(
                        fRObjectFactory.createNumData(new double[] {srcfile.getTimestamp()})),
                    fRObjectFactory.createVector(
                        fRObjectFactory.createIntData(new int[] {rootNode.getChildCount()})),
                    fRObjectFactory.createList(
                        elementIndexes.toArray(new RObject[elementIndexes.size()]),
                        elementIds.toArray(new String[elementIds.size()])),
                  },
                  new String[] {
                    "path", "timestamp", "exprsLength", "elementIds"
                  })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
          prepare.evalVoid(monitor);
        }
      } catch (final CoreException e) {
        RConsoleCorePlugin.log(
            new Status(
                IStatus.ERROR,
                RConsoleCorePlugin.PLUGIN_ID,
                -1,
                NLS.bind(
                    "An error occurred when preparing element tagging for file ''{0}''.",
                    srcfile.getPath()),
                e));
      }
    }
    super.doSubmitFileCommandToConsole(lines, srcfile, su, monitor);
  }