List of usage examples for org.eclipse.jdt.core.compiler IScanner resetTo
void resetTo(int startPosition, int endPosition);
From source file:ca.uvic.chisel.diver.sequencediagrams.sc.java.model.NodeFinder.java
License:Open Source License
/** * A visitor that maps a selection to a given ASTNode. The result node is * determined as follows:/* w w w .j ava 2 s . c o m*/ * <ul> * <li>first the visitor tries to find a node that is covered by <code>start</code> and * <code>length</code> where either <code>start</code> and <code>length</code> exactly * matches the node or where the text covered before and after the node only consists * of white spaces or comments.</li> * <li>if no such node exists than the node that encloses the range defined by * start and end is returned.</li> * <li>if the length is zero than also nodes are considered where the node's * start or end position matches <code>start</code>.</li> * <li>otherwise <code>null</code> is returned.</li> * </ul> * * @param root the root node from which the search starts * @param start the start offset * @param length the length * @param source the source of the compilation unit * * @return the result node * @throws JavaModelException if an error occurs in the Java model * * @since 3.0 */ public static ASTNode perform(ASTNode root, int start, int length, ITypeRoot source) throws JavaModelException { NodeFinder finder = new NodeFinder(start, length); root.accept(finder); ASTNode result = finder.getCoveredNode(); if (result == null) return null; Selection selection = Selection.createFromStartLength(start, length); if (selection.covers(result)) { IBuffer buffer = source.getBuffer(); if (buffer != null) { IScanner scanner = ToolFactory.createScanner(false, false, false, false); scanner.setSource(buffer.getText(start, length).toCharArray()); try { int token = scanner.getNextToken(); if (token != ITerminalSymbols.TokenNameEOF) { int tStart = scanner.getCurrentTokenStartPosition(); if (tStart == result.getStartPosition() - start) { scanner.resetTo(tStart + result.getLength(), length - 1); token = scanner.getNextToken(); if (token == ITerminalSymbols.TokenNameEOF) return result; } } } catch (InvalidInputException e) { } } } return finder.getCoveringNode(); }
From source file:ca.uvic.chisel.javasketch.internal.ast.NodeFinder.java
License:Open Source License
/** * Maps a selection to a given ASTNode, where the selection is given by a start and a length. * The result node is determined as follows: * <ul>//from ww w. j a v a2 s .c o m * <li>first the visitor tries to find a node that is covered by <code>start</code> and * <code>length</code> where either <code>start</code> and <code>length</code> exactly * matches the node or where the text covered before and after the node only consists * of white spaces or comments.</li> * <li>if no such node exists then the node that encloses the range defined by * <code>start</code> and <code>length</code> is returned.</li> * <li>if the length is zero then also nodes are considered where the node's * start or end position matches <code>start</code>.</li> * <li>otherwise <code>null</code> is returned.</li> * </ul> * * @param root the root node from which the search starts * @param start the given start * @param length the given length * @param source the source of the compilation unit * * @return the result node * @throws JavaModelException if an error occurs in the Java model */ public static ASTNode perform(ASTNode root, int start, int length, ITypeRoot source) throws JavaModelException { NodeFinder finder = new NodeFinder(root, start, length); ASTNode result = finder.getCoveredNode(); if (result == null) return null; int nodeStart = result.getStartPosition(); if (start <= nodeStart && ((nodeStart + result.getLength()) <= (start + length))) { IBuffer buffer = source.getBuffer(); if (buffer != null) { IScanner scanner = ToolFactory.createScanner(false, false, false, false); try { scanner.setSource(buffer.getText(start, length).toCharArray()); int token = scanner.getNextToken(); if (token != ITerminalSymbols.TokenNameEOF) { int tStart = scanner.getCurrentTokenStartPosition(); if (tStart == result.getStartPosition() - start) { scanner.resetTo(tStart + result.getLength(), length - 1); token = scanner.getNextToken(); if (token == ITerminalSymbols.TokenNameEOF) return result; } } } catch (InvalidInputException e) { // ignore } catch (IndexOutOfBoundsException e) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=305001 return null; } } } return finder.getCoveringNode(); }
From source file:com.github.elucash.lambda4jdt.FoldingStructureProvider.java
License:Open Source License
/** * Computes the projection ranges for a given <code>ISourceReference</code>. More than one range * or none at all may be returned. If there are no foldable regions, an empty array is returned. * <p>//from w w w. j av a2 s .c om * The last region in the returned array (if not empty) describes the region for the java element * that implements the source reference. Any preceding regions describe javadoc comments of that * java element. * </p> * @param reference a java element that is a source reference * @param ctx the folding context * @return the regions to be folded */ protected final IRegion[] computeProjectionRanges(ISourceReference reference, FoldingStructureComputationContext ctx) { try { ISourceRange range = reference.getSourceRange(); if (!SourceRange.isAvailable(range)) return new IRegion[0]; String contents = reference.getSource(); if (contents == null) return new IRegion[0]; List<IRegion> regions = new ArrayList<IRegion>(); if (!ctx.hasFirstType() && reference instanceof IType) { ctx.setFirstType((IType) reference); IRegion headerComment = computeHeaderComment(ctx); if (headerComment != null) { regions.add(headerComment); ctx.setHasHeaderComment(); } } final int shift = range.getOffset(); IScanner scanner = ctx.getScanner(); scanner.resetTo(shift, shift + range.getLength()); int start = shift; while (true) { int token = scanner.getNextToken(); start = scanner.getCurrentTokenStartPosition(); switch (token) { case ITerminalSymbols.TokenNameCOMMENT_JAVADOC: case ITerminalSymbols.TokenNameCOMMENT_BLOCK: { int end = scanner.getCurrentTokenEndPosition() + 1; regions.add(new Region(start, end - start)); continue; } case ITerminalSymbols.TokenNameCOMMENT_LINE: continue; } break; } regions.add(new Region(start, shift + range.getLength() - start)); return regions.toArray(new IRegion[regions.size()]); } catch (JavaModelException e) { } catch (InvalidInputException e) { } return new IRegion[0]; }
From source file:com.github.elucash.lambda4jdt.FoldingStructureProvider.java
License:Open Source License
private IRegion computeHeaderComment(FoldingStructureComputationContext ctx) throws JavaModelException { // search at most up to the first type ISourceRange range = ctx.getFirstType().getSourceRange(); if (range == null) return null; int start = 0; int end = range.getOffset(); /* code adapted from CommentFormattingStrategy: * scan the header content up to the first type. Once a comment is * found, accumulate any additional comments up to the stop condition. * The stop condition is reaching a package declaration, import container, * or the end of the input./*from ww w .j a v a 2s . co m*/ */ IScanner scanner = ctx.getScanner(); scanner.resetTo(start, end); int headerStart = -1; int headerEnd = -1; try { boolean foundComment = false; int terminal = scanner.getNextToken(); while (terminal != ITerminalSymbols.TokenNameEOF && !(terminal == ITerminalSymbols.TokenNameclass || terminal == ITerminalSymbols.TokenNameinterface || terminal == ITerminalSymbols.TokenNameenum || (foundComment && (terminal == ITerminalSymbols.TokenNameimport || terminal == ITerminalSymbols.TokenNamepackage)))) { if (terminal == ITerminalSymbols.TokenNameCOMMENT_JAVADOC || terminal == ITerminalSymbols.TokenNameCOMMENT_BLOCK || terminal == ITerminalSymbols.TokenNameCOMMENT_LINE) { if (!foundComment) headerStart = scanner.getCurrentTokenStartPosition(); headerEnd = scanner.getCurrentTokenEndPosition(); foundComment = true; } terminal = scanner.getNextToken(); } } catch (InvalidInputException ex) { return null; } if (headerEnd != -1) { return new Region(headerStart, headerEnd - headerStart); } return null; }
From source file:org.eclipse.wb.internal.core.utils.jdt.core.JavadocContentAccess.java
License:Open Source License
/** * @return the {@link Reader} for an {@link IMember}'s Javadoc comment content from the source * attachment.//from ww w . java 2 s. co m */ public static Reader getContentReader(IMember member, boolean allowInherited) throws Exception { // check current type { IBuffer buffer = member.isBinary() ? member.getClassFile().getBuffer() : member.getCompilationUnit().getBuffer(); // no source attachment found if (buffer == null) { return null; } // ISourceRange range = member.getSourceRange(); int start = range.getOffset(); int length = range.getLength(); if (length > 0 && buffer.getChar(start) == '/') { // prepare scanner IScanner scanner; { scanner = ToolFactory.createScanner(true, false, false, false); scanner.setSource(buffer.getCharacters()); scanner.resetTo(start, start + length - 1); } // find last JavaDoc comment { int docOffset = -1; int docEnd = -1; { int terminal = scanner.getNextToken(); while (org.eclipse.jdt.internal.corext.dom.TokenScanner.isComment(terminal)) { if (terminal == ITerminalSymbols.TokenNameCOMMENT_JAVADOC) { docOffset = scanner.getCurrentTokenStartPosition(); docEnd = scanner.getCurrentTokenEndPosition() + 1; } terminal = scanner.getNextToken(); } } // if comment found, return it if (docOffset != -1) { return new JavaDocCommentReader(buffer, docOffset, docEnd); } } } } // check inherited if (allowInherited && member.getElementType() == IJavaElement.METHOD) { IMethod method = (IMethod) member; IMethod superMethod = CodeUtils.findSuperMethod(method); if (superMethod != null) { return getContentReader(superMethod, allowInherited); } } // not found return null; }
From source file:org.j2eespider.util.AnnotationUtil.java
License:Open Source License
/** * Return an array of annotations found in method *//*from www . ja va 2s . co m*/ public static String[] getAnnotationsInMethod(IMethod imethod, List<ValidatorType> annotations) { String[] annotationsInMethod = new String[annotations.size()]; try { IBuffer buffer = imethod.getOpenable().getBuffer(); ISourceRange sourceRange = imethod.getSourceRange(); ISourceRange nameRange = imethod.getNameRange(); IScanner scanner = null; // delay initialization if (sourceRange != null && nameRange != null) { if (scanner == null) { scanner = ToolFactory.createScanner(false, false, true, false); scanner.setSource(buffer.getCharacters()); } scanner.resetTo(sourceRange.getOffset(), nameRange.getOffset()); } else { return annotationsInMethod; } int i = 0; for (ValidatorType annotationType : annotations) { if (findAnnotation(scanner, annotationType.getClassName()) || findAnnotation(scanner, annotationType.getImplementationClass())) { annotationsInMethod[i] = annotationType.getClassName(); i++; } } } catch (JavaModelException e) { } catch (InvalidInputException e) { } return annotationsInMethod; }
From source file:org.j2eespider.util.AnnotationUtil.java
License:Open Source License
/** * Replace annotations in method./*w ww .j a va 2 s . co m*/ */ public static void replaceAnnotationsInMethod(IMethod imethod, List<ValidatorType> annotations, String textNewAnnotations) { try { //monta o scanner do metodo IBuffer methodBuffer = imethod.getOpenable().getBuffer(); ISourceRange sourceRange = imethod.getSourceRange(); ISourceRange javadocRange = null;//imethod.getJavadocRange(); ISourceRange nameRange = imethod.getNameRange(); IScanner scanner = null; // delay initialization if (sourceRange != null && nameRange != null) { if (scanner == null) { scanner = ToolFactory.createScanner(false, false, true, false); scanner.setSource(methodBuffer.getCharacters()); } scanner.resetTo(sourceRange.getOffset(), nameRange.getOffset()); } //apaga todas as annotations que esto em annotationsType e adiciona textNewAnnotations StringBuffer sourceMethod = new StringBuffer(); int tok = scanner.getNextToken(); while (tok != ITerminalSymbols.TokenNameprivate && tok != ITerminalSymbols.TokenNameprotected && tok != ITerminalSymbols.TokenNamepublic) { //loop nas annotations if (tok == ITerminalSymbols.TokenNameAT) { //encontrou o inicio de uma annotation StringBuffer thisAnnotation = new StringBuffer("@"); tok = scanner.getNextToken(); //trabalha todo o contedo da annotation while (tok != ITerminalSymbols.TokenNameAT && tok != ITerminalSymbols.TokenNameprivate && tok != ITerminalSymbols.TokenNameprotected && tok != ITerminalSymbols.TokenNamepublic) { //pega todo o conteudo desta annotation thisAnnotation.append(scanner.getCurrentTokenSource()); //pega o nome dessa annotation tok = scanner.getNextToken(); } //verifica se para apagar essa annotation (s joga no novo sourceMethod se ela no tiver na lista que para apagar) if (!ValidatorUtil.containsValidator(annotations, thisAnnotation.toString())) { sourceMethod.append(thisAnnotation); } } } //grava o resto do metodo int posStartMethod = scanner.getCurrentTokenStartPosition(); int lengthRemoved = posStartMethod - sourceRange.getOffset(); //conta quantos caracteres foram removidos desse metodo (as annotations) String codeRemain = String.valueOf(scanner.getSource()).substring(posStartMethod, posStartMethod + sourceRange.getLength() - lengthRemoved); if (!sourceMethod.toString().equals("") && sourceMethod.toString().lastIndexOf("\n") != sourceMethod.toString().length() - 1) { //se j tem alguma annotation, ve se precisa de quebra de linha sourceMethod.append("\n\t"); } sourceMethod.append(textNewAnnotations); //adiciona as novas annotations antes do resto do mtodo sourceMethod.append(codeRemain); if (javadocRange != null) { //se tiver javadoc, no altera ele... methodBuffer.replace(sourceRange.getOffset() + javadocRange.getLength(), sourceRange.getLength() - javadocRange.getLength(), "\t" + sourceMethod.toString()); //altera o cdigo do mtodo } else { methodBuffer.replace(sourceRange.getOffset(), sourceRange.getLength(), sourceMethod.toString()); //altera o cdigo do mtodo } imethod.getOpenable().save(null, true); } catch (JavaModelException e) { } catch (InvalidInputException e) { } }