Java Code Examples for org.eclipse.jdt.core.compiler.IScanner#getNextToken()
The following examples show how to use
org.eclipse.jdt.core.compiler.IScanner#getNextToken() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Util.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
private static boolean isJustWhitespaceOrComment(int start, int end, IBuffer buffer) { if (start == end) { return true; } Assert.isTrue(start <= end); String trimmedText = buffer.getText(start, end - start).trim(); if (0 == trimmedText.length()) { return true; } else { IScanner scanner = ToolFactory.createScanner(false, false, false, null); scanner.setSource(trimmedText.toCharArray()); try { return scanner.getNextToken() == ITerminalSymbols.TokenNameEOF; } catch (InvalidInputException e) { return false; } } }
Example 2
Source File: Util.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private static boolean isJustWhitespaceOrComment(int start, int end, IBuffer buffer) { if (start == end) return true; Assert.isTrue(start <= end); String trimmedText= buffer.getText(start, end - start).trim(); if (0 == trimmedText.length()) { return true; } else { IScanner scanner= ToolFactory.createScanner(false, false, false, null); scanner.setSource(trimmedText.toCharArray()); try { return scanner.getNextToken() == ITerminalSymbols.TokenNameEOF; } catch (InvalidInputException e) { return false; } } }
Example 3
Source File: MarkerUtil.java From spotbugs with GNU Lesser General Public License v2.1 | 6 votes |
/** * @param source * must be not null * @param range * can be null * @return may return null, otherwise an initialized scanner which may * answer which source offset index belongs to which source line * @throws JavaModelException */ private static IScanner initScanner(IType source, ISourceRange range) throws JavaModelException { if (range == null) { return null; } char[] charContent = getContent(source); if (charContent == null) { return null; } IScanner scanner = ToolFactory.createScanner(false, false, false, true); scanner.setSource(charContent); int offset = range.getOffset(); try { while (scanner.getNextToken() != ITerminalSymbols.TokenNameEOF) { // do nothing, just wait for the end of stream if (offset <= scanner.getCurrentTokenEndPosition()) { break; } } } catch (InvalidInputException e) { FindbugsPlugin.getDefault().logException(e, "Could not init scanner for type: " + source); } return scanner; }
Example 4
Source File: CommentAnalyzer.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
/** * Removes comments and whitespace * @param reference the type reference * @return the reference only consisting of dots and java identifier characters */ public static String normalizeReference(String reference) { IScanner scanner= ToolFactory.createScanner(false, false, false, false); scanner.setSource(reference.toCharArray()); StringBuffer sb= new StringBuffer(); try { int tokenType= scanner.getNextToken(); while (tokenType != ITerminalSymbols.TokenNameEOF) { sb.append(scanner.getRawTokenSource()); tokenType= scanner.getNextToken(); } } catch (InvalidInputException e) { Assert.isTrue(false, reference); } reference= sb.toString(); return reference; }
Example 5
Source File: TaskMarkerProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private int getSurroundingComment(IScanner scanner) { try { int start= fLocation.getOffset(); int end= start + fLocation.getLength(); int token= scanner.getNextToken(); while (token != ITerminalSymbols.TokenNameEOF) { if (TokenScanner.isComment(token)) { int currStart= scanner.getCurrentTokenStartPosition(); int currEnd= scanner.getCurrentTokenEndPosition() + 1; if (currStart <= start && end <= currEnd) { return token; } } token= scanner.getNextToken(); } } catch (InvalidInputException e) { // ignore } return ITerminalSymbols.TokenNameEOF; }
Example 6
Source File: JavaTokenComparator.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * Creates a token comparator for the given string. * * @param text the text to be tokenized */ public JavaTokenComparator(String text) { Assert.isLegal(text != null); fText= text; int length= fText.length(); fStarts= new int[length]; fLengths= new int[length]; fCount= 0; IScanner scanner= ToolFactory.createScanner(true, true, false, false); // returns comments & whitespace scanner.setSource(fText.toCharArray()); int endPos= 0; try { int tokenType; while ((tokenType= scanner.getNextToken()) != ITerminalSymbols.TokenNameEOF) { int start= scanner.getCurrentTokenStartPosition(); int end= scanner.getCurrentTokenEndPosition()+1; // Comments and strings should not be treated as a single token, see https://bugs.eclipse.org/78063 if (TokenScanner.isComment(tokenType) || tokenType == ITerminalSymbols.TokenNameStringLiteral) { // Line comments are often commented code, so lets treat them as code. See https://bugs.eclipse.org/216707 boolean parseAsJava= tokenType == ITerminalSymbols.TokenNameCOMMENT_LINE; int dl= parseAsJava ? getCommentStartTokenLength(tokenType) : 0; if (dl > 0) recordTokenRange(start, dl); parseSubrange(start + dl, text.substring(start + dl, end), parseAsJava); } else { recordTokenRange(start, end - start); } endPos= end; } } catch (InvalidInputException ex) { // We couldn't parse part of the input. Fall through and make the rest a single token } // Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=13907 if (endPos < length) { recordTokenRange(endPos, length - endPos); } }
Example 7
Source File: NewTypeWizardPage.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private boolean isValidComment(String template) { IScanner scanner= ToolFactory.createScanner(true, false, false, false); scanner.setSource(template.toCharArray()); try { int next= scanner.getNextToken(); while (TokenScanner.isComment(next)) { next= scanner.getNextToken(); } return next == ITerminalSymbols.TokenNameEOF; } catch (InvalidInputException e) { } return false; }
Example 8
Source File: CodeTemplateContextType.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private boolean isValidComment(String template) { IScanner scanner= ToolFactory.createScanner(true, false, false, false); scanner.setSource(template.toCharArray()); try { int next= scanner.getNextToken(); while (TokenScanner.isComment(next)) { next= scanner.getNextToken(); } return next == ITerminalSymbols.TokenNameEOF; } catch (InvalidInputException e) { } return false; }
Example 9
Source File: NodeFinder.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * A visitor that maps a selection to a given ASTNode. The result node is * determined as follows: * <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(); }
Example 10
Source File: CommentAnalyzer.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private void check(RefactoringStatus result, Selection selection, IScanner scanner, int start, int end) { char[] characters= scanner.getSource(); selection= adjustSelection(characters, selection, end); scanner.resetTo(start, end); int token= 0; try { loop: while (token != ITerminalSymbols.TokenNameEOF) { token= scanner.getNextToken(); switch(token) { case ITerminalSymbols.TokenNameCOMMENT_LINE: case ITerminalSymbols.TokenNameCOMMENT_BLOCK: case ITerminalSymbols.TokenNameCOMMENT_JAVADOC: if (checkStart(scanner, selection.getOffset())) { result.addFatalError(RefactoringCoreMessages.CommentAnalyzer_starts_inside_comment); break loop; } if (checkEnd(scanner, selection.getInclusiveEnd())) { result.addFatalError(RefactoringCoreMessages.CommentAnalyzer_ends_inside_comment); break loop; } break; } } } catch (InvalidInputException e) { result.addFatalError(RefactoringCoreMessages.CommentAnalyzer_internal_error); } }
Example 11
Source File: TypeCreator.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 5 votes |
private boolean isValidComment(String template) { IScanner scanner = ToolFactory.createScanner(true, false, false, false); scanner.setSource(template.toCharArray()); try { int next = scanner.getNextToken(); while (TokenScanner.isComment(next)) { next = scanner.getNextToken(); } return next == ITerminalSymbols.TokenNameEOF; } catch (InvalidInputException e) { // If there are lexical errors, the comment is invalid } return false; }
Example 12
Source File: SJavaTokenComparator.java From coming with MIT License | 5 votes |
/** * Creates a token comparator for the given string. * * @param text the text to be tokenized * @param textTokenComparatorFactory a factory to create text token comparators */ public SJavaTokenComparator(String text) { fText= text; int length= fText.length(); fStarts= new int[length]; fLengths= new int[length]; fTokens= new String[length]; fCount= 0; IScanner scanner= ToolFactory.createScanner(true, false, false, false); // returns comments & whitespace scanner.setSource(fText.toCharArray()); int endPos= 0; try { int tokenType; while ((tokenType= scanner.getNextToken()) != ITerminalSymbols.TokenNameEOF) { int start= scanner.getCurrentTokenStartPosition(); int end= scanner.getCurrentTokenEndPosition()+1; // Comments are treated as a single token (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=78063) if (!TokenScanner.isComment(tokenType)) { recordTokenRange(start, end - start); } endPos= end; } } catch (InvalidInputException ex) { // We couldn't parse part of the input. Fall through and make the rest a single token } // Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=13907 if (endPos < length) { recordTokenRange(endPos, length - endPos); } }
Example 13
Source File: FoldingRangeHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private int getNextToken(IScanner scanner) { int token = 0; while (token == 0) { try { token = scanner.getNextToken(); } catch (InvalidInputException e) { // ignore // JavaLanguageServerPlugin.logException("Problem with folding range", e); } } return token; }
Example 14
Source File: TypeOccurrenceCollector.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
public SearchMatch acceptSearchMatch2(ICompilationUnit unit, SearchMatch match) throws CoreException { int start= match.getOffset(); int length= match.getLength(); //unqualified: String matchText= unit.getBuffer().getText(start, length); if (fOldName.equals(matchText)) { return match; } //(partially) qualified: if (fOldQualifiedName.endsWith(matchText)) { //e.g. rename B and p.A.B ends with match A.B int simpleNameLenght= fOldName.length(); match.setOffset(start + length - simpleNameLenght); match.setLength(simpleNameLenght); return match; } //Not a standard reference -- use scanner to find last identifier token: IScanner scanner= getScanner(unit); scanner.setSource(matchText.toCharArray()); int simpleNameStart= -1; int simpleNameEnd= -1; try { int token = scanner.getNextToken(); while (token != ITerminalSymbols.TokenNameEOF) { if (token == ITerminalSymbols.TokenNameIdentifier) { simpleNameStart= scanner.getCurrentTokenStartPosition(); simpleNameEnd= scanner.getCurrentTokenEndPosition(); } token = scanner.getNextToken(); } } catch (InvalidInputException e){ //ignore } if (simpleNameStart != -1) { match.setOffset(start + simpleNameStart); match.setLength(simpleNameEnd + 1 - simpleNameStart); } return match; }
Example 15
Source File: MethodOccurenceCollector.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
@Override public void acceptSearchMatch(ICompilationUnit unit, SearchMatch match) throws CoreException { if (match instanceof MethodReferenceMatch && ((MethodReferenceMatch) match).isSuperInvocation() && match.getAccuracy() == SearchMatch.A_INACCURATE) { return; // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=156491 } if (match.isImplicit()) { // see bug 94062 collectMatch(match); return; } int start= match.getOffset(); int length= match.getLength(); String matchText= unit.getBuffer().getText(start, length); //direct match: if (fName.equals(matchText)) { collectMatch(match); return; } // lambda expression if (match instanceof MethodDeclarationMatch && match.getElement() instanceof IMethod && ((IMethod) match.getElement()).isLambdaMethod()) { // don't touch the lambda return; } //Not a standard reference -- use scanner to find last identifier token before left parenthesis: IScanner scanner= getScanner(unit); scanner.setSource(matchText.toCharArray()); int simpleNameStart= -1; int simpleNameEnd= -1; try { int token = scanner.getNextToken(); while (token != ITerminalSymbols.TokenNameEOF && token != ITerminalSymbols.TokenNameLPAREN) { // reference in code includes arguments in parentheses if (token == ITerminalSymbols.TokenNameIdentifier) { simpleNameStart= scanner.getCurrentTokenStartPosition(); simpleNameEnd= scanner.getCurrentTokenEndPosition(); } token = scanner.getNextToken(); } } catch (InvalidInputException e){ //ignore } if (simpleNameStart != -1) { match.setOffset(start + simpleNameStart); match.setLength(simpleNameEnd + 1 - simpleNameStart); } collectMatch(match); }
Example 16
Source File: Member.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
public ISourceRange getJavadocRange() throws JavaModelException { ISourceRange range= getSourceRange(); if (range == null) return null; IBuffer buf= null; if (isBinary()) { buf = getClassFile().getBuffer(); } else { ICompilationUnit compilationUnit = getCompilationUnit(); if (!compilationUnit.isConsistent()) { return null; } buf = compilationUnit.getBuffer(); } final int start= range.getOffset(); final int length= range.getLength(); if (length > 0 && buf.getChar(start) == '/') { IScanner scanner= ToolFactory.createScanner(true, false, false, false); try { scanner.setSource(buf.getText(start, length).toCharArray()); int docOffset= -1; int docEnd= -1; int terminal= scanner.getNextToken(); loop: while (true) { switch(terminal) { case ITerminalSymbols.TokenNameCOMMENT_JAVADOC : docOffset= scanner.getCurrentTokenStartPosition(); docEnd= scanner.getCurrentTokenEndPosition() + 1; terminal= scanner.getNextToken(); break; case ITerminalSymbols.TokenNameCOMMENT_LINE : case ITerminalSymbols.TokenNameCOMMENT_BLOCK : terminal= scanner.getNextToken(); continue loop; default : break loop; } } if (docOffset != -1) { return new SourceRange(docOffset + start, docEnd - docOffset); } } catch (InvalidInputException ex) { // try if there is inherited Javadoc } catch (IndexOutOfBoundsException e) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=305001 } } return null; }
Example 17
Source File: TypeOccurrenceCollector.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
public SearchMatch acceptSearchMatch2(ICompilationUnit unit, SearchMatch match) throws CoreException { int start= match.getOffset(); int length= match.getLength(); //unqualified: String matchText= unit.getBuffer().getText(start, length); if (fOldName.equals(matchText)) { return match; } //(partially) qualified: if (fOldQualifiedName.endsWith(matchText)) { //e.g. rename B and p.A.B ends with match A.B int simpleNameLenght= fOldName.length(); match.setOffset(start + length - simpleNameLenght); match.setLength(simpleNameLenght); return match; } //Not a standard reference -- use scanner to find last identifier token: IScanner scanner= getScanner(unit); scanner.setSource(matchText.toCharArray()); int simpleNameStart= -1; int simpleNameEnd= -1; try { int token = scanner.getNextToken(); while (token != ITerminalSymbols.TokenNameEOF) { if (token == ITerminalSymbols.TokenNameIdentifier) { // type reference can occur in module-info.java and collide with a restricted keyword. simpleNameStart= scanner.getCurrentTokenStartPosition(); simpleNameEnd= scanner.getCurrentTokenEndPosition(); } token = scanner.getNextToken(); } } catch (InvalidInputException e){ //ignore } if (simpleNameStart != -1) { match.setOffset(start + simpleNameStart); match.setLength(simpleNameEnd + 1 - simpleNameStart); } return match; }
Example 18
Source File: DefaultJavaFoldingStructureProvider.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
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. */ 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; }
Example 19
Source File: MethodOccurenceCollector.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
@Override public void acceptSearchMatch(ICompilationUnit unit, SearchMatch match) throws CoreException { if (match instanceof MethodReferenceMatch && ((MethodReferenceMatch) match).isSuperInvocation() && match.getAccuracy() == SearchMatch.A_INACCURATE) { return; // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=156491 } if (match.isImplicit()) { // see bug 94062 collectMatch(match); return; } int start= match.getOffset(); int length= match.getLength(); String matchText= unit.getBuffer().getText(start, length); //direct match: if (fName.equals(matchText)) { collectMatch(match); return; } // lambda expression if (match instanceof MethodDeclarationMatch && match.getElement() instanceof IMethod && ((IMethod) match.getElement()).isLambdaMethod()) { // don't touch the lambda return; } //Not a standard reference -- use scanner to find last identifier token before left parenthesis: IScanner scanner= getScanner(unit); scanner.setSource(matchText.toCharArray()); int simpleNameStart= -1; int simpleNameEnd= -1; try { int token = scanner.getNextToken(); while (token != ITerminalSymbols.TokenNameEOF && token != ITerminalSymbols.TokenNameLPAREN) { // reference in code includes arguments in parentheses if (token == InternalTokenNameIdentifier) { simpleNameStart= scanner.getCurrentTokenStartPosition(); simpleNameEnd= scanner.getCurrentTokenEndPosition(); } token = scanner.getNextToken(); } } catch (InvalidInputException e){ //ignore } if (simpleNameStart != -1) { match.setOffset(start + simpleNameStart); match.setLength(simpleNameEnd + 1 - simpleNameStart); } collectMatch(match); }
Example 20
Source File: JavaLexer.java From SLP-Core with MIT License | 4 votes |
public List<List<String>> tokenizeLines(String text) { IScanner scanner = ToolFactory.createScanner(false, false, true, "1.8"); scanner.setSource(text.toCharArray()); List<List<String>> lineTokens = new ArrayList<>(); List<String> tokens = new ArrayList<>(); lineTokens.add(new ArrayList<>()); int nextToken = 0; int line = 1; while (true) { try { nextToken = scanner.getNextToken(); int ln = scanner.getLineNumber(scanner.getCurrentTokenStartPosition()); if (ln > line) { for (int i = line + 1; i <= ln; i++) lineTokens.add(new ArrayList<>()); line = ln; } if (nextToken == ITerminalSymbols.TokenNameEOF) break; } catch (InvalidInputException e) { continue; } String val = new String(scanner.getCurrentTokenSource()); if (val.startsWith("\"") && val.endsWith("\"") && val.length() > 2) { if (val.length() >= 15) { val = "\"\""; } else { String body = val.substring(1, val.length() - 1); body = body.replaceAll("\\\\", "\\\\\\\\"); body = body.replaceAll("\"", "\\\\\""); body = body.replaceAll("\n", "\\n"); body = body.replaceAll("\r", "\\r"); body = body.replaceAll("\t", "\\t"); val = "\"" + body + "\""; } } else if (val.startsWith("\'") && val.endsWith("\'")) { val = val.replaceAll("\n", "\\n"); val = val.replaceAll("\r", "\\r"); val = val.replaceAll("\t", "\\t"); } // For Java, we have to add heuristic check regarding breaking up >> else if (val.matches(">>+")) { boolean split = false; for (int i = tokens.size() - 1; i >= 0; i--) { String token = tokens.get(i); if (token.matches("[,\\.\\?\\[\\]]") || Character.isUpperCase(token.charAt(0)) || token.equals("extends") || token.equals("super") || token.matches("(byte|short|int|long|float|double)")) { continue; } else if (token.matches("(<|>)+")) { split = true; break; } else { break; } } if (split) { for (int i = 0; i < val.length(); i++) { tokens.add(">"); lineTokens.get(lineTokens.size() - 1).add(">"); } continue; } } tokens.add(val); lineTokens.get(lineTokens.size() - 1).add(val); } return lineTokens; }