本文整理汇总了Java中com.sun.source.util.SourcePositions.getStartPosition方法的典型用法代码示例。如果您正苦于以下问题:Java SourcePositions.getStartPosition方法的具体用法?Java SourcePositions.getStartPosition怎么用?Java SourcePositions.getStartPosition使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.sun.source.util.SourcePositions
的用法示例。
在下文中一共展示了SourcePositions.getStartPosition方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: findExactStatement
import com.sun.source.util.SourcePositions; //导入方法依赖的package包/类
private StatementTree findExactStatement(CompilationInfo info, BlockTree block, int offset, boolean start) {
if (offset == (-1)) return null;
SourcePositions sp = info.getTrees().getSourcePositions();
CompilationUnitTree cut = info.getCompilationUnit();
for (StatementTree t : block.getStatements()) {
long pos = start ? sp.getStartPosition(info.getCompilationUnit(), t) : sp.getEndPosition( cut, t);
if (offset == pos) {
return t;
}
}
return null;
}
示例2: run
import com.sun.source.util.SourcePositions; //导入方法依赖的package包/类
public boolean run(DocletEnvironment root) {
DocTrees trees = root.getDocTrees();
SourcePositions sourcePositions = trees.getSourcePositions();
for (TypeElement klass : ElementFilter.typesIn(root.getIncludedElements())) {
for (ExecutableElement method : getMethods(klass)) {
if (method.getSimpleName().toString().equals("tabbedMethod")) {
TreePath path = trees.getPath(method);
CompilationUnitTree cu = path.getCompilationUnit();
long pos = sourcePositions.getStartPosition(cu, path.getLeaf());
LineMap lineMap = cu.getLineMap();
long columnNumber = lineMap.getColumnNumber(pos);
if (columnNumber == 9) {
System.out.println(columnNumber + ": OK!");
return true;
} else {
System.err.println(columnNumber + ": wrong tab expansion");
return false;
}
}
}
}
return false;
}
示例3: if
import com.sun.source.util.SourcePositions; //导入方法依赖的package包/类
@Hint(displayName="#DN_ToOrIf", description="#DESC_ToOrIf", category="suggestions", hintKind=Hint.Kind.ACTION)
@TriggerPattern("if ($cond1) $then; else if ($cond2) $then; else $else$;")
@Messages({"ERR_ToOrIf=",
"FIX_ToOrIf=Join ifs using ||"})
public static ErrorDescription toOrIf(HintContext ctx) {
SourcePositions sp = ctx.getInfo().getTrees().getSourcePositions();
CompilationUnitTree cut = ctx.getInfo().getCompilationUnit();
boolean caretAccepted = ctx.getCaretLocation() <= sp.getStartPosition(cut, ctx.getPath().getLeaf()) + 2 || caretInsideToLevelElseKeyword(ctx);
if (!caretAccepted) return null;
return ErrorDescriptionFactory.forSpan(ctx, ctx.getCaretLocation(), ctx.getCaretLocation(), Bundle.ERR_ToOrIf(), JavaFixUtilities.rewriteFix(ctx, Bundle.FIX_ToOrIf(), ctx.getPath(), "if ($cond1 || $cond2) $then; else $else$;"));
}
示例4: initialize
import com.sun.source.util.SourcePositions; //导入方法依赖的package包/类
public void initialize() {
int size = oldL.size();
matrix = new int[size+1][5];
matrix[size] = new int[] { -1, -1, -1, -1, -1 };
SourcePositions positions = diffContext.trees.getSourcePositions();
CompilationUnitTree compilationUnit = diffContext.origUnit;
int i = 0;
for (Tree item : oldL) {
int treeStart = (int) positions.getStartPosition(compilationUnit, item);
int treeEnd = (int) positions.getEndPosition(compilationUnit, item);
// stupid hack, we have to remove syntetic constructors --
// should be filtered before and shouldn't be part of this
// collection (oldL)
if (treeEnd < 0) continue;
seq.move(treeStart);
int startIndex = seq.index();
// go back to opening/closing curly, semicolon or other
// token java-compiler important token.
moveToSrcRelevant(seq, Direction.BACKWARD);
seq.moveNext();
int veryBeg = seq.index();
seq.move(treeEnd);
matrix[i++] = new int[] { veryBeg, veryBeg, veryBeg, startIndex, seq.index() };
if (i == size) {
seq.move(treeEnd);
matrix[i][2] = seq.index();
}
}
initialized = true;
}
示例5: getPosition
import com.sun.source.util.SourcePositions; //导入方法依赖的package包/类
private long[] getPosition( Element e ) {
Trees trees = cc.getTrees();
CompilationUnitTree cut = cc.getCompilationUnit();
Tree t = trees.getTree(e);
if ( t == null ) {
return new long[]{-1,-1};
}
SourcePositions sourcePositions = trees.getSourcePositions();
return new long[] {sourcePositions.getStartPosition(cut, t),sourcePositions.getEndPosition(cut, t)};
}
示例6: getForwardReferences
import com.sun.source.util.SourcePositions; //导入方法依赖的package包/类
/**
* 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;
}
示例7: tokensFor
import com.sun.source.util.SourcePositions; //导入方法依赖的package包/类
/**Returns tokens for a given tree. Uses specified {@link SourcePositions}.
*/
public TokenSequence<JavaTokenId> tokensFor(Tree tree, SourcePositions sourcePositions) {
int start = (int)sourcePositions.getStartPosition(info.getCompilationUnit(), tree);
int end = (int)sourcePositions.getEndPosition(info.getCompilationUnit(), tree);
return info.getTokenHierarchy().tokenSequence(JavaTokenId.language()).subSequence(start, end);
}
示例8: findIdentifierSpanImpl
import com.sun.source.util.SourcePositions; //导入方法依赖的package包/类
private static Token<JavaTokenId> findIdentifierSpanImpl(CompilationInfo info, Tree decl, Tree lastLeft, List<? extends Tree> firstRight, String name, CompilationUnitTree cu, SourcePositions positions) {
int declStart = (int) positions.getStartPosition(cu, decl);
lastLeft = normalizeLastLeftTree(lastLeft);
int start = lastLeft != null ? (int)positions.getEndPosition(cu, lastLeft) : declStart;
if (start == (-1)) {
start = declStart;
if (start == (-1)) {
return null;
}
}
int end = (int)positions.getEndPosition(cu, decl);
for (Tree t : firstRight) {
if (t == null)
continue;
int proposedEnd = (int)positions.getStartPosition(cu, t);
if (proposedEnd != (-1) && proposedEnd < end)
end = proposedEnd;
}
if (end == (-1)) {
return null;
}
if (start > end) {
//may happend in case:
//public static String s() [] {}
//(meaning: method returning array of Strings)
//use a conservative start value:
start = (int) positions.getStartPosition(cu, decl);
}
return findTokenWithText(info, name, start, end);
}
示例9: createHighlightImpl
import com.sun.source.util.SourcePositions; //导入方法依赖的package包/类
private static Token<JavaTokenId> createHighlightImpl(CompilationInfo info, Document doc, TreePath tree) {
Tree leaf = tree.getLeaf();
SourcePositions positions = info.getTrees().getSourcePositions();
CompilationUnitTree cu = info.getCompilationUnit();
//XXX: do not use instanceof:
if (leaf instanceof MethodTree || leaf instanceof VariableTree || leaf instanceof ClassTree
|| leaf instanceof MemberSelectTree || leaf instanceof AnnotatedTypeTree || leaf instanceof MemberReferenceTree) {
return findIdentifierSpan(info, doc, tree);
}
int start = (int) positions.getStartPosition(cu, leaf);
int end = (int) positions.getEndPosition(cu, leaf);
if (start == Diagnostic.NOPOS || end == Diagnostic.NOPOS) {
return null;
}
TokenHierarchy<?> th = info.getTokenHierarchy();
TokenSequence<JavaTokenId> ts = th.tokenSequence(JavaTokenId.language());
if (ts.move(start) == Integer.MAX_VALUE) {
return null;
}
if (ts.moveNext()) {
Token<JavaTokenId> token = ts.token();
if (ts.offset() == start && token != null) {
final JavaTokenId id = token.id();
if (id == JavaTokenId.IDENTIFIER) {
return token;
}
if (id == JavaTokenId.THIS || id == JavaTokenId.SUPER) {
return ts.offsetToken();
}
}
}
return null;
}
示例10: doPerformTest
import com.sun.source.util.SourcePositions; //导入方法依赖的package包/类
protected void doPerformTest(String code, int start, int end, int testIndex, boolean verify, int... duplicates) throws Exception {
prepareTest(code, testIndex);
TreePath path = info.getTreeUtilities().pathFor((start + end) / 2 + 1);
while (path != null) {
Tree t = path.getLeaf();
SourcePositions sp = info.getTrees().getSourcePositions();
if ( start == sp.getStartPosition(info.getCompilationUnit(), t)
&& end == sp.getEndPosition(info.getCompilationUnit(), t)) {
break;
}
path = path.getParentPath();
}
assertNotNull(path);
Collection<TreePath> result = computeDuplicates(path);
// assertEquals(f.result.toString(), duplicates.length / 2, f.result.size());
if (verify) {
int[] dupes = new int[result.size() * 2];
int index = 0;
for (TreePath tp : result) {
dupes[index++] = (int) info.getTrees().getSourcePositions().getStartPosition(info.getCompilationUnit(), tp.getLeaf());
dupes[index++] = (int) info.getTrees().getSourcePositions().getEndPosition(info.getCompilationUnit(), tp.getLeaf());
}
assertTrue("Was: " + Arrays.toString(dupes) + " should have been: " + Arrays.toString(duplicates), Arrays.equals(duplicates, dupes));
}
}
示例11: computeWarning
import com.sun.source.util.SourcePositions; //导入方法依赖的package包/类
@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;
}
示例12: checkTooManyMethods
import com.sun.source.util.SourcePositions; //导入方法依赖的package包/类
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));
}
}
示例13: visitConditionalExpression
import com.sun.source.util.SourcePositions; //导入方法依赖的package包/类
/**
* 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;
}
示例14: check
import com.sun.source.util.SourcePositions; //导入方法依赖的package包/类
@TriggerTreeKind({Tree.Kind.CLASS, Tree.Kind.INTERFACE})
public static ErrorDescription check(HintContext context) {
TreePath tp = context.getPath();
ClassTree cls = (ClassTree) tp.getLeaf();
CompilationInfo info = context.getInfo();
SourcePositions sourcePositions = info.getTrees().getSourcePositions();
long startPos = sourcePositions.getStartPosition(tp.getCompilationUnit(), cls);
if (startPos > Integer.MAX_VALUE) {
return null;
}
int[] bodySpan = info.getTreeUtilities().findBodySpan(cls);
if (bodySpan == null || bodySpan[0] <= startPos) {
return null;
}
int caret = context.getCaretLocation();
if (startPos < 0 || caret < 0 || caret < startPos || caret >= bodySpan[0]) {
return null;
}
// #222487
// If there is a compile-time error on the class, then don't offer to
// create a subclass.
List<Diagnostic> errors = info.getDiagnostics();
if (!errors.isEmpty()) {
for (Diagnostic d : errors) {
if (d.getKind() != Diagnostic.Kind.ERROR) {
continue;
}
// Check that the error's start position is within the class header
// Note: d.getEndPosition() is not used because, for example,
// a "compiler.err.does.not.override.abstract" error ends at
// the end of the class tree.
if (startPos <= d.getStartPosition() && d.getStartPosition() <= bodySpan[0]) {
return null;
}
}
}
TypeElement typeElement = (TypeElement) info.getTrees().getElement(tp);
if (typeElement == null || typeElement.getModifiers().contains(Modifier.FINAL)) return null;
Element outer = typeElement.getEnclosingElement();
// do not offer the hint for non-static inner classes. Permit for classes nested into itnerface - no enclosing instance
if (outer != null && outer.getKind() != ElementKind.PACKAGE && outer.getKind() != ElementKind.INTERFACE) {
if (outer.getKind() != ElementKind.CLASS && outer.getKind() != ElementKind.ENUM) {
return null;
}
if (!typeElement.getModifiers().contains(Modifier.STATIC)) {
return null;
}
}
ClassPath cp = info.getClasspathInfo().getClassPath(PathKind.SOURCE);
FileObject root = cp.findOwnerRoot(info.getFileObject());
if (root == null) { //File not part of any project
return null;
}
PackageElement packageElement = (PackageElement) info.getElementUtilities().outermostTypeElement(typeElement).getEnclosingElement();
CreateSubclassFix fix = new CreateSubclassFix(info, root, packageElement.getQualifiedName().toString(), typeElement.getSimpleName().toString() + "Impl", typeElement); //NOI18N
return ErrorDescriptionFactory.forTree(context, context.getPath(), NbBundle.getMessage(CreateSubclass.class, typeElement.getKind() == ElementKind.CLASS
? typeElement.getModifiers().contains(Modifier.ABSTRACT) ? "ERR_ImplementAbstractClass" : "ERR_CreateSubclass" : "ERR_ImplementInterface"), fix); //NOI18N
}
示例15: isIn
import com.sun.source.util.SourcePositions; //导入方法依赖的package包/类
private boolean isIn(CompilationUnitTree cu, SourcePositions sp, Tree tree, int position) {
return sp.getStartPosition(cu, tree) <= position && position <= sp.getEndPosition(cu, tree);
}