Java Code Examples for com.sun.source.util.SourcePositions#getStartPosition()
The following examples show how to use
com.sun.source.util.SourcePositions#getStartPosition() .
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: AddPropertyCodeGenerator.java From netbeans with Apache License 2.0 | 6 votes |
@Override public Void visitClass(ClassTree node, Void p) { final SourcePositions sourcePositions = wc.getTrees().getSourcePositions(); final TreeMaker make = wc.getTreeMaker(); List<Tree> members = new LinkedList<Tree>(); ClassTree classTree = node; for (Tree member : node.getMembers()) { int s = (int) sourcePositions.getStartPosition(wc.getCompilationUnit(), member); int e = (int) sourcePositions.getEndPosition(wc.getCompilationUnit(), member); if (s >= start && e <= end) { classTree = make.removeClassMember(classTree, member); members.add(member); } } classTree = GeneratorUtils.insertClassMembers(wc, classTree, members, start); wc.rewrite(node, classTree); return super.visitClass(classTree, p); }
Example 2
Source File: MoveMembersTransformer.java From netbeans with Apache License 2.0 | 5 votes |
private void changeMemberRefer(Element el, final MemberReferenceTree node, TreePath currentPath, final Element target) { if (el.getModifiers().contains(Modifier.STATIC)) { Tree oldT = node.getQualifierExpression(); Tree newT = make.QualIdent(make.setLabel(make.QualIdent(target), target.getSimpleName()).toString()); rewrite(oldT, newT); } else { SourcePositions positions = workingCopy.getTrees().getSourcePositions(); long startPosition = positions.getStartPosition(workingCopy.getCompilationUnit(), node); long lineNumber = workingCopy.getCompilationUnit().getLineMap().getLineNumber(startPosition); String source = FileUtil.getFileDisplayName(workingCopy.getFileObject()) + ':' + lineNumber; problem = JavaPluginUtils.chainProblems(problem, new Problem(false, NbBundle.getMessage(MoveMembersRefactoringPlugin.class, "WRN_NoAccessor", source))); //NOI18N } }
Example 3
Source File: Utilities.java From netbeans with Apache License 2.0 | 5 votes |
private static Token<JavaTokenId> findIdentifierSpanImplForBindingPattern(CompilationInfo info, Tree tree, CompilationUnitTree cu, SourcePositions positions) { int start = (int)positions.getStartPosition(cu, tree); int endPosition = (int)positions.getEndPosition(cu, tree); if (start == (-1) || endPosition == (-1)) return null; String member = TreeShims.getBinding(tree).toString(); TokenHierarchy<?> th = info.getTokenHierarchy(); TokenSequence<JavaTokenId> ts = th.tokenSequence(JavaTokenId.language()); if (ts.move(endPosition) == Integer.MAX_VALUE) { return null; } if (ts.moveNext()) { while (ts.offset() >= start) { Token<JavaTokenId> t = ts.token(); if (t.id() == JavaTokenId.IDENTIFIER && member.equals(info.getTreeUtilities().decodeIdentifier(t.text()).toString())) { return t; } if (!ts.movePrevious()) break; } } return null; }
Example 4
Source File: Utilities.java From netbeans with Apache License 2.0 | 5 votes |
public static Collection<? extends Element> getForwardReferences(TreePath path, int pos, SourcePositions sourcePositions, Trees trees) { HashSet<Element> refs = new HashSet<Element>(); while(path != null) { switch(path.getLeaf().getKind()) { case BLOCK: if (path.getParentPath().getLeaf().getKind() == Tree.Kind.LAMBDA_EXPRESSION) break; case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: return refs; case VARIABLE: refs.add(trees.getElement(path)); TreePath parent = path.getParentPath(); if (TreeUtilities.CLASS_TREE_KINDS.contains(parent.getLeaf().getKind())) { boolean isStatic = ((VariableTree)path.getLeaf()).getModifiers().getFlags().contains(Modifier.STATIC); for(Tree member : ((ClassTree)parent.getLeaf()).getMembers()) { if (member.getKind() == Tree.Kind.VARIABLE && sourcePositions.getStartPosition(path.getCompilationUnit(), member) >= pos && (isStatic || !((VariableTree)member).getModifiers().getFlags().contains(Modifier.STATIC))) refs.add(trees.getElement(new TreePath(parent, member))); } } return refs; case ENHANCED_FOR_LOOP: EnhancedForLoopTree efl = (EnhancedForLoopTree)path.getLeaf(); if (sourcePositions.getEndPosition(path.getCompilationUnit(), efl.getExpression()) >= pos) refs.add(trees.getElement(new TreePath(path, efl.getVariable()))); } path = path.getParentPath(); } return refs; }
Example 5
Source File: JavadocUtilities.java From netbeans with Apache License 2.0 | 5 votes |
private static boolean isInHeader(CompilationInfo info, ClassTree tree, int offset) { CompilationUnitTree cut = info.getCompilationUnit(); SourcePositions sp = info.getTrees().getSourcePositions(); long lastKnownOffsetInHeader = sp.getStartPosition(cut, tree); List<? extends Tree> impls = tree.getImplementsClause(); List<? extends TypeParameterTree> typeparams; if (impls != null && !impls.isEmpty()) { lastKnownOffsetInHeader= sp.getEndPosition(cut, impls.get(impls.size() - 1)); } else if ((typeparams = tree.getTypeParameters()) != null && !typeparams.isEmpty()) { lastKnownOffsetInHeader= sp.getEndPosition(cut, typeparams.get(typeparams.size() - 1)); } else if (tree.getExtendsClause() != null) { lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getExtendsClause()); } else if (tree.getModifiers() != null) { lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getModifiers()); } TokenSequence<JavaTokenId> ts = info.getTreeUtilities().tokensFor(tree); ts.move((int) lastKnownOffsetInHeader); while (ts.moveNext()) { if (ts.token().id() == JavaTokenId.LBRACE) { return offset < ts.offset(); } } return false; }
Example 6
Source File: SourceUtils.java From netbeans with Apache License 2.0 | 5 votes |
/** * Returns all elements of the given scope that are declared after given position in a source. * @param path to the given search scope * @param pos position in the source * @param sourcePositions * @param trees * @return collection of forward references * * @since 0.136 */ public static Collection<? extends Element> getForwardReferences(TreePath path, int pos, SourcePositions sourcePositions, Trees trees) { HashSet<Element> refs = new HashSet<>(); Element el; while(path != null) { switch(path.getLeaf().getKind()) { case VARIABLE: el = trees.getElement(path); if (el != null) { refs.add(el); } TreePath parent = path.getParentPath(); if (TreeUtilities.CLASS_TREE_KINDS.contains(parent.getLeaf().getKind())) { boolean isStatic = ((VariableTree)path.getLeaf()).getModifiers().getFlags().contains(Modifier.STATIC); for(Tree member : ((ClassTree)parent.getLeaf()).getMembers()) { if (member.getKind() == Tree.Kind.VARIABLE && sourcePositions.getStartPosition(path.getCompilationUnit(), member) >= pos && (isStatic || !((VariableTree)member).getModifiers().getFlags().contains(Modifier.STATIC))) { el = trees.getElement(new TreePath(parent, member)); if (el != null) { refs.add(el); } } } } break; case ENHANCED_FOR_LOOP: EnhancedForLoopTree efl = (EnhancedForLoopTree)path.getLeaf(); if (sourcePositions.getEndPosition(path.getCompilationUnit(), efl.getExpression()) >= pos) { el = trees.getElement(new TreePath(path, efl.getVariable())); if (el != null) { refs.add(el); } } } path = path.getParentPath(); } return refs; }
Example 7
Source File: GeneratorUtils.java From netbeans with Apache License 2.0 | 5 votes |
public static ClassTree insertClassMembers(WorkingCopy wc, ClassTree clazz, List<? extends Tree> members, int offset) throws IllegalStateException { if (offset < 0 || getCodeStyle(wc).getClassMemberInsertionPoint() != CodeStyle.InsertionPoint.CARET_LOCATION) { return GeneratorUtilities.get(wc).insertClassMembers(clazz, members); } int index = 0; SourcePositions sp = wc.getTrees().getSourcePositions(); GuardedDocument gdoc = null; try { Document doc = wc.getDocument(); if (doc != null && doc instanceof GuardedDocument) { gdoc = (GuardedDocument)doc; } } catch (IOException ioe) {} Tree lastMember = null; for (Tree tree : clazz.getMembers()) { if (offset <= sp.getStartPosition(wc.getCompilationUnit(), tree)) { if (gdoc == null) { break; } int pos = (int)(lastMember != null ? sp.getEndPosition(wc.getCompilationUnit(), lastMember) : sp.getStartPosition(wc.getCompilationUnit(), clazz)); pos = gdoc.getGuardedBlockChain().adjustToBlockEnd(pos); if (pos <= sp.getStartPosition(wc.getCompilationUnit(), tree)) { break; } } index++; lastMember = tree; } TreeMaker tm = wc.getTreeMaker(); for (int i = members.size() - 1; i >= 0; i--) { clazz = tm.insertClassMember(clazz, index, members.get(i)); } return clazz; }
Example 8
Source File: Utilities.java From netbeans with Apache License 2.0 | 5 votes |
private static int findLastBracketImpl(Tree tree, CompilationUnitTree cu, SourcePositions positions, Document doc) { int start = (int)positions.getStartPosition(cu, tree); int end = (int)positions.getEndPosition(cu, tree); if (start == (-1) || end == (-1)) { return -1; } if (start > doc.getLength() || end > doc.getLength()) { if (DEBUG) { System.err.println("Log: position outside document: "); System.err.println("decl = " + tree); System.err.println("startOffset = " + start); System.err.println("endOffset = " + end); Thread.dumpStack(); } return (-1); } try { String text = doc.getText(end - 1, 1); if (text.charAt(0) == '}') return end - 1; } catch (BadLocationException e) { LOG.log(Level.INFO, null, e); } return (-1); }
Example 9
Source File: JSEmbeddingProvider.java From netbeans with Apache License 2.0 | 5 votes |
public static void colorizeJSB(final CompilationInfo ci) { final CompilationUnitTree cu = ci.getCompilationUnit(); final Trees trees = ci.getTrees(); final SourcePositions sp = trees.getSourcePositions(); final Finder f = new Finder(trees); final List<LiteralTree> result = new ArrayList<>(); f.scan(cu, result); if (!result.isEmpty()) { try { final TokenHierarchy<Document> tk = TokenHierarchy.get(ci.getDocument()); final Language<?> java = Language.find(JAVA_MIME_TYPE); final Language<?> javaScript = Language.find(JAVASCRIPT_MIME_TYPE); if (java != null && javaScript != null) { final TokenSequence<?> seq = tk.tokenSequence(java); if (seq != null) { for (LiteralTree lt : result) { final int start = (int) sp.getStartPosition(cu, lt); final int end = (int) sp.getEndPosition(cu, lt); seq.move(start); while (seq.moveNext() && seq.offset() < end) { if ( seq.embedded() != null && seq.embedded().language() != null && "text/x-java-string".equals(seq.embedded().language().mimeType()) ) { seq.removeEmbedding(seq.embedded().language()); } seq.createEmbedding(javaScript, 1, 1, true); } } } } } catch (IOException ioe) { LOG.log(Level.WARNING, null, ioe); } } }
Example 10
Source File: ClassMetrics.java From netbeans with Apache License 2.0 | 4 votes |
private static ErrorDescription checkTooManyMethods(HintContext ctx, TreePath path, int limit, boolean anon) { ClassTree clazz = (ClassTree)path.getLeaf(); boolean ignoreAccessors = ctx.getPreferences().getBoolean(OPTION_CLASS_METHODS_IGNORE_ACCESSORS, DEFAULT_CLASS_METHODS_IGNORE_ACCESSORS); boolean ignoreAbstract = ctx.getPreferences().getBoolean(OPTION_CLASS_METHODS_IGNORE_ABSTRACT, DEFAULT_CLASS_METHODS_IGNORE_ABSTRACT); int methodCount = 0; for (Tree member : clazz.getMembers()) { if (member.getKind() != Tree.Kind.METHOD) { continue; } MethodTree method = (MethodTree)member; if (method.getReturnType() == null) { // a constructor ? continue; } TreePath methodPath = new TreePath(path, method); if (ignoreAccessors && (isSimpleGetter(ctx.getInfo(), methodPath) || isSimpleSetter(ctx.getInfo(), methodPath))) { continue; } if (ignoreAbstract) { ExecutableElement mel = (ExecutableElement)ctx.getInfo().getTrees().getElement(methodPath); ExecutableElement overriden = ctx.getInfo().getElementUtilities().getOverriddenMethod(mel); if (overriden != null && overriden.getModifiers().contains(Modifier.ABSTRACT)) { continue; } } methodCount++; } if (methodCount <= limit) { return null; } if (anon) { CompilationInfo info = ctx.getInfo(); SourcePositions pos = info.getTrees().getSourcePositions(); long start = pos.getStartPosition(info.getCompilationUnit(), path.getParentPath().getLeaf()); long mstart = pos.getStartPosition(info.getCompilationUnit(), path.getLeaf()); return ErrorDescriptionFactory.forSpan(ctx, (int)start, (int)mstart, TEXT_AnonClassManyMethods(methodCount)); } else { return ErrorDescriptionFactory.forName(ctx, path, TEXT_ClassManyMethods(clazz.getSimpleName().toString(), methodCount)); } }
Example 11
Source File: PositionEstimator.java From netbeans with Apache License 2.0 | 4 votes |
@Override() public void initialize() { int size = oldL.size(); data = new ArrayList<int[]>(size); SourcePositions positions = diffContext.trees.getSourcePositions(); CompilationUnitTree compilationUnit = diffContext.origUnit; for (Tree item : oldL) { int treeStart = (int) positions.getStartPosition(compilationUnit, item); int treeEnd = (int) positions.getEndPosition(compilationUnit, item); seq.move(treeStart); seq.moveNext(); if (null != moveToSrcRelevant(seq, Direction.BACKWARD)) { seq.moveNext(); } int previousEnd = seq.offset(); Token<JavaTokenId> token; while (nonRelevant.contains((token = seq.token()).id())) { int localResult = -1; switch (token.id()) { case WHITESPACE: int indexOf = token.text().toString().indexOf('\n'); if (indexOf > -1) { localResult = seq.offset() + indexOf; } break; case LINE_COMMENT: previousEnd = seq.offset() + token.text().length(); break; } if (localResult > 0) { previousEnd = localResult; break; } if (!seq.moveNext()) break; } data.add(new int[] { previousEnd, treeEnd, previousEnd }); } initialized = true; }
Example 12
Source File: Utilities.java From netbeans with Apache License 2.0 | 4 votes |
/** * This method returns the part of the syntax tree to be highlighted. * It will be usually the class/method/variable identifier. */ public static TextSpan getUnderlineSpan(CompilationInfo info, Tree tree) { SourcePositions srcPos = info.getTrees().getSourcePositions(); int startOffset = (int) srcPos.getStartPosition(info.getCompilationUnit(), tree); int endOffset = (int) srcPos.getEndPosition(info.getCompilationUnit(), tree); Tree startSearchingForNameIndentifierBehindThisTree = null; if (TreeUtilities.CLASS_TREE_KINDS.contains(tree.getKind())) { startSearchingForNameIndentifierBehindThisTree = ((ClassTree) tree).getModifiers(); } else if (tree.getKind() == Tree.Kind.METHOD) { startSearchingForNameIndentifierBehindThisTree = ((MethodTree) tree).getReturnType(); } else if (tree.getKind() == Tree.Kind.VARIABLE) { startSearchingForNameIndentifierBehindThisTree = ((VariableTree) tree).getType(); } if (startSearchingForNameIndentifierBehindThisTree != null) { int searchStart = (int) srcPos.getEndPosition(info.getCompilationUnit(), startSearchingForNameIndentifierBehindThisTree); TokenSequence<JavaTokenId> tokenSequence = info.getTreeUtilities().tokensFor(tree); if (tokenSequence != null) { boolean eob = false; tokenSequence.move(searchStart); do { eob = !tokenSequence.moveNext(); } while (!eob && tokenSequence.token().id() != JavaTokenId.IDENTIFIER); if (!eob) { Token<JavaTokenId> identifier = tokenSequence.token(); startOffset = identifier.offset(info.getTokenHierarchy()); endOffset = startOffset + identifier.length(); } } } return new TextSpan(startOffset, endOffset); }
Example 13
Source File: TreeUtilities.java From netbeans with Apache License 2.0 | 4 votes |
private TokenSequence<JavaTokenId> tokensFor(Tree tree, SourcePositions sourcePositions, int farEnd) { int start = (int)sourcePositions.getStartPosition(info.getCompilationUnit(), tree); int end = (int)sourcePositions.getEndPosition(info.getCompilationUnit(), tree); return info.getTokenHierarchy().tokenSequence(JavaTokenId.language()).subSequence(start, Math.max(end, farEnd)); }
Example 14
Source File: TutorialTest.java From netbeans with Apache License 2.0 | 4 votes |
public void testForJean() throws FileStateInvalidException, IOException { File tutorialFile = getFile(getSourceDir(), "/org/netbeans/test/codegen/Tutorial2.java"); JavaSource tutorialSource = JavaSource.forFileObject(FileUtil.toFileObject(tutorialFile)); Task task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws java.io.IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); // we know there is exactly one class, named Tutorial2. // (ommiting test for kind corectness!) ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0); // get the method, there is a default constructor and // exactly one method, named demoMethod(). MethodTree method = (MethodTree) clazz.getMembers().get(1); BlockTree body = method.getBody(); // get SourcePositions instance for your working copy and // fetch out start and end position. SourcePositions sp = workingCopy.getTrees().getSourcePositions(); int start = (int) sp.getStartPosition(cut, body); int end = (int) sp.getEndPosition(cut, body); // get body text from source text String bodyText = workingCopy.getText().substring(start, end); MethodTree modified = make.Method( method.getModifiers(), // copy original values method.getName(), method.getReturnType(), method.getTypeParameters(), method.getParameters(), method.getThrows(), bodyText.replace("{0}", "-tag-replace-"), // replace body with the new text null // not applicable here ); // rewrite the original modifiers with the new one: workingCopy.rewrite(method, modified); } }; tutorialSource.runModificationTask(task).commit(); // print the result to the System.err to see the changes in console. BufferedReader in = new BufferedReader(new FileReader(tutorialFile)); PrintStream out = System.out; String str; while ((str = in.readLine()) != null) { out.println(str); } in.close(); }
Example 15
Source File: CreateTestClassHint.java From netbeans with Apache License 2.0 | 4 votes |
@TriggerTreeKind(Tree.Kind.CLASS) @Messages("ERR_CreateTestClassHint=Create Test Class") public static ErrorDescription computeWarning(HintContext context) { TreePath tp = context.getPath(); ClassTree cls = (ClassTree) tp.getLeaf(); CompilationInfo info = context.getInfo(); SourcePositions sourcePositions = info.getTrees().getSourcePositions(); int startPos = (int) sourcePositions.getStartPosition(tp.getCompilationUnit(), cls); int caret = context.getCaretLocation(); String code = context.getInfo().getText(); if (startPos < 0 || caret < 0 || caret < startPos || caret >= code.length()) { return null; } String headerText = code.substring(startPos, caret); int idx = headerText.indexOf('{'); //NOI18N if (idx >= 0) { return null; } ClassPath cp = info.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.SOURCE); FileObject fileObject = info.getFileObject(); if(!fileObject.isValid()) { //File is probably deleted return null; } FileObject root = cp.findOwnerRoot(fileObject); if (root == null) { //File not part of any project return null; } Collection<? extends TestCreatorProvider> providers = Lookup.getDefault().lookupAll(TestCreatorProvider.class); Map<Object, List<String>> validCombinations = Utils.getValidCombinations(info, null); if (validCombinations == null) { // no TestCreatorProvider found return null; } for (TestCreatorProvider provider : providers) { if (provider.enable(new FileObject[]{fileObject}) && !validCombinations.isEmpty()) { List<Fix> fixes = new ArrayList<Fix>(); Fix fix; for (Entry<Object, List<String>> entrySet : validCombinations.entrySet()) { Object location = entrySet.getKey(); for (String testingFramework : entrySet.getValue()) { fix = new CreateTestClassFix(new FileObject[]{fileObject}, location, testingFramework); fixes.add(fix); } } validCombinations.clear(); return ErrorDescriptionFactory.forTree(context, context.getPath(), Bundle.ERR_CreateTestClassHint(), fixes.toArray(new Fix[fixes.size()])); } } validCombinations.clear(); return null; }
Example 16
Source File: CreateTestMethodsHint.java From netbeans with Apache License 2.0 | 4 votes |
@TriggerTreeKind(Tree.Kind.METHOD) @Messages("ERR_CreateTestMethodsHint=Generate All Test Methods") public static ErrorDescription computeWarning(HintContext context) { final TreePath tp = context.getPath(); final MethodTree method = (MethodTree) tp.getLeaf(); if (method.getModifiers().getFlags().contains(Modifier.PRIVATE)) { return null; } String methodName = method.getName().toString(); CompilationInfo info = context.getInfo(); SourcePositions sourcePositions = info.getTrees().getSourcePositions(); int startPos = (int) sourcePositions.getStartPosition(tp.getCompilationUnit(), method); int caret = context.getCaretLocation(); String code = context.getInfo().getText(); if (startPos < 0 || caret < 0 || caret < startPos || caret >= code.length()) { return null; } String headerText = code.substring(startPos, caret); int idx = headerText.indexOf('{'); //NOI18N if (idx >= 0) { return null; } ClassPath cp = info.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.SOURCE); FileObject fileObject = info.getFileObject(); if(!fileObject.isValid()) { //File is probably deleted return null; } FileObject root = cp.findOwnerRoot(fileObject); if (root == null) { //File not part of any project return null; } Collection<? extends TestCreatorProvider> providers = Lookup.getDefault().lookupAll(TestCreatorProvider.class); Map<Object, List<String>> validCombinations = Utils.getValidCombinations(info, methodName); if (validCombinations == null) { // no TestCreatorProvider found return null; } for (TestCreatorProvider provider : providers) { if (provider.enable(new FileObject[]{fileObject}) && !validCombinations.isEmpty()) { List<Fix> fixes = new ArrayList<Fix>(); Fix fix; for (Entry<Object, List<String>> entrySet : validCombinations.entrySet()) { Object location = entrySet.getKey(); for (String testingFramework : entrySet.getValue()) { fix = new CreateTestMethodsFix(new FileObject[]{fileObject}, location, testingFramework); fixes.add(fix); } } validCombinations.clear(); return ErrorDescriptionFactory.forTree(context, context.getPath(), Bundle.ERR_CreateTestMethodsHint(), fixes.toArray(new Fix[fixes.size()])); } } validCombinations.clear(); return null; }
Example 17
Source File: Utilities.java From netbeans with Apache License 2.0 | 4 votes |
/** * This method returns the part of the syntax tree to be highlighted. * It will be usually the class/method/variable identifier. */ public static TextSpan getUnderlineSpan(CompilationInfo info, Tree tree){ SourcePositions srcPos = info.getTrees().getSourcePositions(); int startOffset = (int) srcPos.getStartPosition(info.getCompilationUnit(), tree); int endOffset = (int) srcPos.getEndPosition(info.getCompilationUnit(), tree); Tree startSearchingForNameIndentifierBehindThisTree = null; if(tree != null) { if (TreeUtilities.CLASS_TREE_KINDS.contains(tree.getKind())){ startSearchingForNameIndentifierBehindThisTree = ((ClassTree)tree).getModifiers(); } else if (tree.getKind() == Tree.Kind.METHOD){ startSearchingForNameIndentifierBehindThisTree = ((MethodTree)tree).getReturnType(); } else if (tree.getKind() == Tree.Kind.VARIABLE){ startSearchingForNameIndentifierBehindThisTree = ((VariableTree)tree).getType(); } if (startSearchingForNameIndentifierBehindThisTree != null){ int searchStart = (int) srcPos.getEndPosition(info.getCompilationUnit(), startSearchingForNameIndentifierBehindThisTree); TokenSequence tokenSequence = info.getTreeUtilities().tokensFor(tree); if (tokenSequence != null){ boolean eob = false; tokenSequence.move(searchStart); do{ eob = !tokenSequence.moveNext(); } while (!eob && tokenSequence.token().id() != JavaTokenId.IDENTIFIER); if (!eob){ Token identifier = tokenSequence.token(); startOffset = identifier.offset(info.getTokenHierarchy()); endOffset = startOffset + identifier.length(); } } } } return new TextSpan(startOffset, endOffset); }
Example 18
Source File: ExpectedTypeResolver.java From netbeans with Apache License 2.0 | 4 votes |
/** * Handles subexpression in conditional expr. If the expression is the condition, the expected * type is boolean. Otherwise the parent expression is evaluated for expected types. It is expected * that the 'expression' will be eventually casted to the desired type, while the other branch' * expression should remain as it is. Types, that theExpression cannot be casted to, or the other * branch' expression can't be assigned to (must be casted as well) are rejected. * * @param node the conditional node * @param p dummy * @return list of possible types for the expression */ @Override public List<? extends TypeMirror> visitConditionalExpression(ConditionalExpressionTree node, Object p) { if (theExpression == null) { // cannot determine return null; } if (theExpression.getLeaf() == node.getCondition()) { return booleanType(); } Tree otherExpression; if (theExpression.getLeaf() == node.getFalseExpression()) { otherExpression = node.getTrueExpression(); } else { otherExpression = node.getFalseExpression(); } TypeMirror otherType = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), otherExpression)); TypeMirror thisType = info.getTrees().getTypeMirror(getExpressionWithoutCasts()); if (!(Utilities.isValidType(otherType) && Utilities.isValidType(thisType))) { return null; } ExpectedTypeResolver subResolver = new ExpectedTypeResolver(getCurrentPath(), getCurrentPath(), info); subResolver.typeCastDepth++; List<? extends TypeMirror> pp = subResolver.scan(getCurrentPath().getParentPath(), null); if (pp == null) { return null; } List<? extends TypeMirror> parentTypes = new ArrayList<TypeMirror>(pp); for (Iterator<? extends TypeMirror> it = parentTypes.iterator(); it.hasNext(); ) { TypeMirror m = it.next(); if (!info.getTypeUtilities().isCastable(thisType, m)) { Scope s = info.getTrees().getScope(getCurrentPath()); SourcePositions pos = info.getTrees().getSourcePositions(); StringBuilder sb = new StringBuilder(); int posFirst = (int)pos.getStartPosition(info.getCompilationUnit(), theExpression.getLeaf()); int posSecond = (int)pos.getStartPosition(info.getCompilationUnit(), otherExpression); if (posFirst < 0 || posSecond < 0) { // LOMBOK return null; } String first = info.getText().substring(posFirst, (int)pos.getEndPosition(info.getCompilationUnit(), theExpression.getLeaf())); String second = info.getText().substring(posSecond, (int)pos.getEndPosition(info.getCompilationUnit(), otherExpression)); sb.append(first).append("+").append(second); ExpressionTree expr = info.getTreeUtilities().parseExpression(sb.toString(), new SourcePositions[1]); TypeMirror targetType = purify(info, info.getTreeUtilities().attributeTree(expr, s)); if (targetType == null || !info.getTypes().isAssignable(targetType, m)) { it.remove(); } } } return parentTypes.isEmpty() ? Collections.singletonList(otherType) : parentTypes; }
Example 19
Source File: RemoveSurroundingCodeAction.java From netbeans with Apache License 2.0 | 4 votes |
private int getStart(TreeUtilities tu, SourcePositions sp, CompilationUnitTree cut, Tree tree) { List<Comment> comments = tu.getComments(tree, true); return comments.isEmpty() ? (int) sp.getStartPosition(cut, tree) : comments.get(0).pos(); }
Example 20
Source File: Utilities.java From netbeans with Apache License 2.0 | 4 votes |
private static int findBodyStartImpl(CompilationInfo info, Tree cltree, CompilationUnitTree cu, SourcePositions positions, Document doc) { int start = (int)positions.getStartPosition(cu, cltree); int end = (int)positions.getEndPosition(cu, cltree); if (start == (-1) || end == (-1)) { return -1; } int startPos = -1; switch (cltree.getKind()) { case CLASS: case INTERFACE: case ENUM: { ClassTree ct = (ClassTree)cltree; startPos = findSubtreeEnd(cu, positions, ct.getImplementsClause(), ct.getExtendsClause(), ct.getTypeParameters(), ct.getModifiers() ); break; } case METHOD: { // if the method contains some parameters, skip to the end of the parameter list MethodTree mt = (MethodTree)cltree; startPos = findSubtreeEnd(cu, positions, mt.getDefaultValue(), mt.getThrows(), mt.getParameters(), mt.getModifiers()); break; } } if (startPos > start) { start = startPos; } if (start > doc.getLength() || end > doc.getLength()) { if (DEBUG) { System.err.println("Log: position outside document: "); System.err.println("decl = " + cltree); System.err.println("startOffset = " + start); System.err.println("endOffset = " + end); Thread.dumpStack(); } return (-1); } TokenHierarchy<JavaTokenId> th = (TokenHierarchy<JavaTokenId>)info.getTokenHierarchy(); TokenSequence<JavaTokenId> seq = (TokenSequence<JavaTokenId>)th.tokenSequence(); seq.move(start); while (seq.moveNext()) { if (seq.token().id() == JavaTokenId.LBRACE) { return seq.offset(); } } return (-1); }