List of usage examples for org.eclipse.jdt.core.dom NodeFinder perform
public static ASTNode perform(ASTNode root, int start, int length)
From source file:JavaCompleter.java
License:Apache License
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); Scanner s = null;/*from w w w . j a v a 2 s .co m*/ for (String filename = in.readLine(); filename != null; filename = in.readLine()) { s = new Scanner(new File(filename)); s.useDelimiter("\\Z"); ASTParser parser = ASTParser.newParser(AST.JLS4); parser.setSource(s.next().toCharArray()); parser.setKind(ASTParser.K_COMPILATION_UNIT); ASTNode file = parser.createAST(null); ASTNode range = NodeFinder.perform(file, 200, 201); System.out.println(range.getNodeType()); } }
From source file:com.ibm.wala.ide.util.JdtUtil.java
License:Open Source License
public static ASTNode getOriginalNode(ASTNode root, JdtPosition pos) { return NodeFinder.perform(root, pos.getFirstOffset(), pos.getLastOffset() - pos.getFirstOffset()); }
From source file:de.ahoehma.jdt.quickfix.DeleteNodeCorrectionProposal.java
License:Open Source License
@Override protected void addEdits(final IDocument doc, final TextEdit root) throws CoreException { // build a full AST final CompilationUnit unit = SharedASTProvider.getAST(getCompilationUnit(), SharedASTProvider.WAIT_YES, null);//w w w . ja v a 2 s . com final ASTNode name = NodeFinder.perform(unit, fOffset, fLength); if (name instanceof SimpleName) { final SimpleName[] names = LinkedNodeFinder.findByProblems(unit, (SimpleName) name); if (names != null) { for (int i = 0; i < names.length; i++) { final SimpleName curr = names[i]; final ASTNode parent = curr.getParent(); root.addChild(new DeleteEdit(parent.getStartPosition(), parent.getLength())); } return; } } root.addChild(new DeleteEdit(fOffset, fLength)); }
From source file:edu.illinois.keshmesh.transformer.core.LCK02JFixer.java
License:Open Source License
@Override public Change createChange(IProgressMonitor progressMonitor) throws CoreException, OperationCanceledException { ITextFileBufferManager textFileBufferManager = null; try {/*w ww . j av a2 s .co m*/ //Retrieving the Document out of IPath textFileBufferManager = FileBuffers.getTextFileBufferManager(); textFileBufferManager.connect(bugPosition.getSourcePath(), LocationKind.LOCATION, progressMonitor); ITextFileBuffer textFileBuffer = textFileBufferManager.getTextFileBuffer(bugPosition.getSourcePath(), LocationKind.IFILE); IDocument document = textFileBuffer.getDocument(); try { Logger.log(document.get(bugPosition.getFirstOffset(), bugPosition.getLength())); } catch (BadLocationException e1) { e1.printStackTrace(); } // Parsing the Document ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setKind(ASTParser.K_COMPILATION_UNIT); parser.setSource(document.get().toCharArray()); parser.setResolveBindings(true); CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(progressMonitor); //Rewriting the AST int bugLineOffset = document.getLineInformation(bugPosition.getFirstLine() - 1).getOffset(); int bugLineLength = document.getLineInformation(bugPosition.getFirstLine() - 1).getLength(); String bugLineContent = document.get(bugLineOffset, bugLineLength); String syncCommand = "synchronized"; int syncIndex = bugLineContent.indexOf(syncCommand); int start_comment_index = bugLineContent.indexOf("/*"); int end_comment_index = bugLineContent.indexOf("*/"); String temp_bugLineContent = bugLineContent; int temp_syncIndex = syncIndex; int temp_beginIndex = 0; // there is a possibility of having synchronized word within comments while (start_comment_index >= 0 && end_comment_index > 0 && temp_bugLineContent.length() > 0 && temp_syncIndex > start_comment_index) { temp_beginIndex += (end_comment_index + 2); temp_bugLineContent = temp_bugLineContent.substring(end_comment_index + 2); temp_syncIndex = temp_bugLineContent.indexOf(syncCommand); start_comment_index = temp_bugLineContent.indexOf("/*"); end_comment_index = temp_bugLineContent.indexOf("*/"); syncIndex = temp_beginIndex + temp_syncIndex; } String bugLineContentAfterSynch = bugLineContent.substring(syncIndex + syncCommand.length()); int openParenthesisIndex = bugLineContentAfterSynch.indexOf('(') + syncIndex + syncCommand.length(); int myFirstOffset = bugLineOffset + syncIndex; int index = openParenthesisIndex; int pcounter = 1; while (pcounter != 0 && index < bugLineLength) { index++; if (bugLineContent.charAt(index) == ')') { pcounter--; } else if (bugLineContent.charAt(index) == '(') { pcounter++; } } int myLastOffset = bugLineOffset + index; ASTNode monitorNode = NodeFinder.perform(compilationUnit, myFirstOffset, myLastOffset - myFirstOffset + 1); SynchronizedStatement synchronizedStatement = (SynchronizedStatement) monitorNode; AST ast = synchronizedStatement.getAST(); ASTRewrite rewriter = ASTRewrite.create(ast); ASTParser expressionParser = ASTParser.newParser(AST.JLS3); expressionParser.setKind(ASTParser.K_EXPRESSION); expressionParser .setSource(CollectionUtils.getTheOnlyElementOf(fixInformation.getTypeNames()).toCharArray()); ASTNode astNode = expressionParser.createAST(progressMonitor); rewriter.set(synchronizedStatement, SynchronizedStatement.EXPRESSION_PROPERTY, astNode, null); TextEdit textEdit = rewriter.rewriteAST(document, null); try { textEdit.apply(document); } catch (MalformedTreeException e) { e.printStackTrace(); } catch (BadLocationException e) { e.printStackTrace(); } //Committing changes to the source file textFileBuffer.commit(progressMonitor, true); } catch (BadLocationException e) { throw new RuntimeException(e); } finally { textFileBufferManager.disconnect(bugPosition.getSourcePath(), LocationKind.LOCATION, progressMonitor); } return null; }
From source file:edu.illinois.keshmesh.transformer.core.LCK03JFixer.java
License:Open Source License
/** * FIXME://ww w . jav a 2 s . c o m * * Break the method into smaller ones. * * Rethrow the exception as CoreException * * Preserve comments. * * Preserve formatting. * */ @Override public Change createChange(IProgressMonitor progressMonitor) throws CoreException, OperationCanceledException { ITextFileBufferManager textFileBufferManager = null; try { //Retrieving the Document out of IPath textFileBufferManager = FileBuffers.getTextFileBufferManager(); textFileBufferManager.connect(bugPosition.getSourcePath(), LocationKind.LOCATION, progressMonitor); ITextFileBuffer textFileBuffer = textFileBufferManager.getTextFileBuffer(bugPosition.getSourcePath(), LocationKind.IFILE); IDocument document = textFileBuffer.getDocument(); try { Logger.log(document.get(bugPosition.getFirstOffset(), bugPosition.getLength())); } catch (BadLocationException e1) { e1.printStackTrace(); } // Parsing the Document ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setKind(ASTParser.K_COMPILATION_UNIT); parser.setSource(document.get().toCharArray()); parser.setResolveBindings(true); CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(progressMonitor); // Retrieving the begin and end indexes of synchronized command int bugLineOffset = document.getLineInformation(bugPosition.getFirstLine() - 1).getOffset(); int bugLineLength = document.getLineInformation(bugPosition.getFirstLine() - 1).getLength(); String bugLine = document.get(bugLineOffset, bugLineLength); int syncCommandBeginIndex = getSynchronizedCommandBeginIndex(bugLine); int syncCommandLastIndex = getSynchronizedCommandLastIndex(bugLine, syncCommandBeginIndex); // Extracting the synchronized command expression String bugLineAfterSync = bugLine.substring(syncCommandBeginIndex + SYNC_COMMAND.length()); int openParenthesisIndex = bugLineAfterSync.indexOf('(') + syncCommandBeginIndex + SYNC_COMMAND.length(); String synchExpression = bugLine.substring(openParenthesisIndex + 1, syncCommandLastIndex); // Computing the begin and end offset of the synchronized command int syncCommandBeginOffset = bugLineOffset + syncCommandBeginIndex; int syncCommandLastOffset = bugLineOffset + syncCommandLastIndex; // Getting the synchronized command AST node ASTNode monitorNode = NodeFinder.perform(compilationUnit, syncCommandBeginOffset, syncCommandLastOffset - syncCommandBeginOffset + 1); SynchronizedStatement synchronizedStatement = (SynchronizedStatement) monitorNode; List synchBodyStatements = synchronizedStatement.getBody().statements(); // Creating a "local variable assignment" statement and a try/catch/final block to be replaced at monitor node place //AST ast = synchronizedStatement.getAST(); ASTRewrite rewriter = ASTRewrite.create(compilationUnit.getAST()); String localVarNameForLock = "tempLock"; String localVarAssignment = LCK03JBugPattern.LOCK + " " + localVarNameForLock + " = " + synchExpression + ";\n"; String tryFinalBlockStatements = "try {\n" + localVarNameForLock + ".lock();\n"; for (Object statement : synchBodyStatements) { tryFinalBlockStatements += statement; } tryFinalBlockStatements += "} finally {\n" + localVarNameForLock + ".unlock();\n}"; // Rewriting the monitor node ASTNode astNode = rewriter.createStringPlaceholder(localVarAssignment + tryFinalBlockStatements, TryStatement.TRY_STATEMENT); rewriter.replace(synchronizedStatement, astNode, null); TextEdit textEdit = rewriter.rewriteAST(document, null); UndoEdit undoEdit = textEdit.apply(document); //Committing changes to the source file textFileBuffer.commit(progressMonitor, true); } catch (BadLocationException e) { throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Failed to fix LCK03J.", e)); } finally { textFileBufferManager.disconnect(bugPosition.getSourcePath(), LocationKind.LOCATION, progressMonitor); } return null; }
From source file:io.spring.boot.development.eclipse.resolution.ConfigurationClassConstructorInjectionMarkerResolution.java
License:Open Source License
@Override public void run(final IMarker marker) { try {// w ww.java 2 s . co m ICompilationUnit sourceUnit = (ICompilationUnit) JavaCore.create(marker.getResource()); CompilationUnit compilationUnit = parse(sourceUnit); compilationUnit.recordModifications(); int start = (int) marker.getAttribute(IMarker.CHAR_START); ASTNode node = NodeFinder.perform(compilationUnit, start, ((int) marker.getAttribute(IMarker.CHAR_END)) - start); convertToConstructorInjection(compilationUnit, findDeclaringType(node)); Document document = new Document(sourceUnit.getSource()); TextEdit changes = compilationUnit.rewrite(document, null); changes.apply(document); sourceUnit.getBuffer().setContents(document.get()); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:jmockit.assist.HyperlinkDetector.java
License:Open Source License
@Override public final IHyperlink[] detectHyperlinks(final ITextViewer textViewer, final IRegion region, final boolean canShowMultipleHyperlinks) { ITextEditor textEditor = (ITextEditor) getAdapter(ITextEditor.class); if (region == null || !(textEditor instanceof JavaEditor)) { return null; }/* w ww . j av a2 s.c om*/ ITypeRoot input = EditorUtility.getEditorInputJavaElement(textEditor, false); if (input == null) { return null; } IAction openAction = textEditor.getAction("OpenEditor"); //$NON-NLS-1$ if (!(openAction instanceof SelectionDispatchAction)) { return null; } ITypeBinding paramType = null; IRegion wordRegion = null; IMethodBinding mockMethod = null, realMethod = null; CompilationUnit astRoot = ASTUtil.getAstOrParse(input, null); if (astRoot == null) { return null; } ASTNode node = NodeFinder.perform(astRoot, region.getOffset(), 1); if (node instanceof SimpleName && node.getParent() instanceof MethodDeclaration) { MethodDeclaration mdec = (MethodDeclaration) node.getParent(); mockMethod = mdec.resolveBinding(); paramType = MockUtil.findMockedType(mdec, mockMethod); wordRegion = new Region(node.getStartPosition(), node.getLength()); if (paramType != null && mockMethod != null) { realMethod = MockUtil.findRealMethodInType(paramType, mockMethod, astRoot.getAST()); } } if (realMethod != null && wordRegion != null) { SelectionDispatchAction dispatchAction = (SelectionDispatchAction) openAction; return new IHyperlink[] { new OpenMockedMethodHyperlink(dispatchAction, realMethod, wordRegion) }; } return null; }
From source file:jmockit.assist.JmockitProposalComputer.java
License:Open Source License
@Override public final List<ICompletionProposal> computeCompletionProposals(final ContentAssistInvocationContext context, final IProgressMonitor mon) { ITypeBinding mockType = null, paramType = null; ICompilationUnit cunit = getCompilationUnit(context); CompilationUnit astRoot = null;//from ww w . j a v a 2 s . c o m if (cunit != null) { astRoot = ASTUtil.getAstOrParse(cunit, mon); if (astRoot != null) { ASTNode node = NodeFinder.perform(astRoot, context.getInvocationOffset(), 1); mockType = MockUtil.getMockType(node); paramType = findMockedTypeFromNode(node); } } if (paramType != null && mockType != null) { try { return getProposals(context, paramType, cunit, mockType, astRoot.getAST()); } catch (Exception e) { fErrorMessage = e.getMessage(); Activator.log(e); } } return Collections.emptyList(); }
From source file:jmockit.assist.MockMethodCompletionProposal.java
License:Open Source License
@Override protected final boolean updateReplacementString(final IDocument document, final char trigger, final int offset, final ImportRewrite importRw) throws CoreException, BadLocationException { try {/*from ww w . j av a 2s.com*/ Document recoveredDocument = new Document(); CompilationUnit unit = getRecoveredAST(document, offset, recoveredDocument); initContext(offset, importRw, unit); ASTNode node = NodeFinder.perform(unit, offset, 1); AST ast = unit.getAST(); ASTRewrite rewrite = ASTRewrite.create(ast); CodeGenerationSettings settings = getCodeGenSettings(); MethodDeclaration stub = createMockMethodStub(ast, rewrite, settings); String methodDeclarationText = generateMethodDeclaration(document, recoveredDocument, node, rewrite, settings, stub); setReplacementString(methodDeclarationText); } catch (Exception exception) { Activator.log(exception); } return true; }
From source file:mychangedetector.copyclasses.MyRenameLinkedMode.java
License:Open Source License
public void start() { if (getActiveLinkedMode() != null) { // for safety; should already be handled in RenameJavaElementAction fgActiveLinkedMode.startFullDialog(); return;/*www .ja va2 s . c o m*/ } ISourceViewer viewer = fEditor.getViewer(); IDocument document = viewer.getDocument(); fOriginalSelection = viewer.getSelectedRange(); int offset = fOriginalSelection.x; try { CompilationUnit root = SharedASTProvider.getAST(getCompilationUnit(), SharedASTProvider.WAIT_YES, null); fLinkedPositionGroup = new LinkedPositionGroup(); ASTNode selectedNode = NodeFinder.perform(root, fOriginalSelection.x, fOriginalSelection.y); if (!(selectedNode instanceof SimpleName)) { return; // TODO: show dialog } SimpleName nameNode = (SimpleName) selectedNode; if (viewer instanceof ITextViewerExtension6) { IUndoManager undoManager = ((ITextViewerExtension6) viewer).getUndoManager(); if (undoManager instanceof IUndoManagerExtension) { IUndoManagerExtension undoManagerExtension = (IUndoManagerExtension) undoManager; IUndoContext undoContext = undoManagerExtension.getUndoContext(); IOperationHistory operationHistory = OperationHistoryFactory.getOperationHistory(); fStartingUndoOperation = operationHistory.getUndoOperation(undoContext); } } fOriginalName = nameNode.getIdentifier(); final int pos = nameNode.getStartPosition(); ASTNode[] sameNodes = LinkedNodeFinder.findByNode(root, nameNode); //TODO: copied from LinkedNamesAssistProposal#apply(..): // sort for iteration order, starting with the node @ offset Arrays.sort(sameNodes, new Comparator() { public int compare(Object o1, Object o2) { return rank((ASTNode) o1) - rank((ASTNode) o2); } /** * Returns the absolute rank of an <code>ASTNode</code>. Nodes * preceding <code>pos</code> are ranked last. * * @param node the node to compute the rank for * @return the rank of the node with respect to the invocation offset */ private int rank(ASTNode node) { int relativeRank = node.getStartPosition() + node.getLength() - pos; if (relativeRank < 0) return Integer.MAX_VALUE + relativeRank; else return relativeRank; } }); for (int i = 0; i < sameNodes.length; i++) { ASTNode elem = sameNodes[i]; LinkedPosition linkedPosition = new LinkedPosition(document, elem.getStartPosition(), elem.getLength(), i); if (i == 0) fNamePosition = linkedPosition; fLinkedPositionGroup.addPosition(linkedPosition); } fLinkedModeModel = new LinkedModeModel(); fLinkedModeModel.addGroup(fLinkedPositionGroup); fLinkedModeModel.forceInstall(); fLinkedModeModel.addLinkingListener(new EditorHighlightingSynchronizer(fEditor)); fLinkedModeModel.addLinkingListener(new EditorSynchronizer()); LinkedModeUI ui = new EditorLinkedModeUI(fLinkedModeModel, viewer); ui.setExitPosition(viewer, offset, 0, Integer.MAX_VALUE); ui.setExitPolicy(new ExitPolicy(document)); ui.enter(); linked_mode_entered_callback.run(); // viewer.setSelectedRange(fOriginalSelection.x, fOriginalSelection.y); // by default, full word is selected; restore original selection if (viewer instanceof IEditingSupportRegistry) { IEditingSupportRegistry registry = (IEditingSupportRegistry) viewer; registry.register(fFocusEditingSupport); } openSecondaryPopup(); // startAnimation(); fgActiveLinkedMode = this; } catch (BadLocationException e) { JavaPlugin.log(e); } }