本文整理汇总了Java中javax.tools.Diagnostic.getStartPosition方法的典型用法代码示例。如果您正苦于以下问题:Java Diagnostic.getStartPosition方法的具体用法?Java Diagnostic.getStartPosition怎么用?Java Diagnostic.getStartPosition使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.tools.Diagnostic
的用法示例。
在下文中一共展示了Diagnostic.getStartPosition方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: highlightErrorInArea
import javax.tools.Diagnostic; //导入方法依赖的package包/类
private static void highlightErrorInArea(Diagnostic diagnostic) {
int start = (int) diagnostic.getStartPosition();
int end = (int) diagnostic.getEndPosition();
int areaSize = customCodeArea.getText().length() - 1;
if (start == end) {
if (start > 0) {
start--;
}
if (end < areaSize) {
end++;
}
} else if (end < start) {
end = start + 1;
start--;
if (end == areaSize) {
end--;
}
}
customCodeArea.getCodeAreaCSS().setStyleClass(start, end, "error");
}
示例2: click
import javax.tools.Diagnostic; //导入方法依赖的package包/类
@Override
public void click(Diagnostic diagnostic) {
Log.d(TAG, "click() called with: diagnostic = [" + diagnostic + "]");
mMainActivity.closeDrawer(GravityCompat.START);
Object source = diagnostic.getSource();
if (source instanceof JavaFileObject && diagnostic.getKind() == Diagnostic.Kind.ERROR) {
String path = ((JavaFileObject) source).getName();
int i = mPagePresenter.gotoPage(path);
if (i == -1) {
mPagePresenter.addPage(path, true);
}
EditPageContract.SourceView editor = mPagePresenter.getCurrentPage();
if (editor == null) {
Log.d(TAG, "click: editor null");
return;
}
int startPosition = (int) diagnostic.getStartPosition();
int endPosition = (int) diagnostic.getEndPosition();
editor.highlightError(startPosition, endPosition);
editor.setCursorPosition(endPosition);
} else {
// TODO: 19/07/2017 implement other
}
}
示例3: compute
import javax.tools.Diagnostic; //导入方法依赖的package包/类
@TriggerPatterns({
@TriggerPattern("new $clazz<$tparams$>($params$)")
})
public static ErrorDescription compute(HintContext ctx) {
if (ctx.getMultiVariables().get("$tparams$").isEmpty()) return null;
TreePath clazz = ctx.getVariables().get("$clazz");
long start = ctx.getInfo().getTrees().getSourcePositions().getStartPosition(clazz.getCompilationUnit(), clazz.getLeaf());
ctx.getVariables().put("$init", ctx.getPath());
OUTER: for (Diagnostic<?> d : ctx.getInfo().getDiagnostics()) {
if (start != d.getStartPosition()) continue;
if (!CODES.contains(d.getCode())) continue;
FOUND: for (Entry<String, Collection<String>> e : key2Pattern.entrySet()) {
for (String p : e.getValue()) {
if (p == null || MatcherUtilities.matches(ctx, ctx.getPath().getParentPath(), p)) {
boolean enabled = isEnabled(ctx, e.getKey());
if (!enabled) {
continue OUTER;
} else {
break FOUND;
}
}
}
}
// check that the resolved symbol has no overloads, which would
// take parametrized supertypes of the arguments
if (checkAmbiguousOverload(ctx.getInfo(), ctx.getPath())) {
return null;
}
return ErrorDescriptionFactory.forTree(ctx, clazz.getParentPath(), d.getMessage(null), new FixImpl(ctx.getInfo(), ctx.getPath()).toEditorFix());
}
return null;
}
示例4: getPrefferedPosition
import javax.tools.Diagnostic; //导入方法依赖的package包/类
public static long getPrefferedPosition(CompilationInfo info, Diagnostic d) throws IOException {
if ("compiler.err.doesnt.exist".equals(d.getCode()) || "compiler.err.try.with.resources.expr.needs.var".equals(d.getCode())) {
return d.getStartPosition();
}
if ("compiler.err.cant.resolve.location".equals(d.getCode()) || "compiler.err.cant.resolve.location.args".equals(d.getCode())) {
int[] span = findUnresolvedElementSpan(info, (int) d.getPosition());
if (span != null) {
return span[0];
} else {
return d.getPosition();
}
}
if ("compiler.err.not.stmt".equals(d.getCode())) {
//check for "Collections.":
TreePath path = findUnresolvedElement(info, (int) d.getStartPosition() - 1);
Element el = path != null ? info.getTrees().getElement(path) : null;
if (el == null || el.asType().getKind() == TypeKind.ERROR) {
return d.getStartPosition() - 1;
}
/*
if (el.asType().getKind() == TypeKind.PACKAGE) {
//check if the package does actually exist:
String s = ((PackageElement) el).getQualifiedName().toString();
if (info.getElements().getPackageElement(s) == null) {
//it does not:
return d.getStartPosition() - 1;
}
}
*/
return d.getStartPosition();
}
return d.getPosition();
}
示例5: getDiagnostic
import javax.tools.Diagnostic; //导入方法依赖的package包/类
/**
* Returns the diagnostics entry
* @param compilationInfo
* @param start
* @param codes
* @return
*/
private Diagnostic getDiagnostic(CompilationInfo compilationInfo, long start, Set<String> errorCodes) {
Diagnostic result = null;
for (Diagnostic d : compilationInfo.getDiagnostics()) {
if (start != d.getStartPosition()) {
continue;
}
if (!errorCodes.contains(d.getCode())) {
continue;
}
result=d;
}
return result;
}
示例6: isCurrArea
import javax.tools.Diagnostic; //导入方法依赖的package包/类
private static boolean isCurrArea(Diagnostic<? extends JavaFileObject> diagnostic) {
String name = diagnostic.getSource().getName();
int lastSlash = name.lastIndexOf(File.separator);
String shortName = name.substring(lastSlash + 1);
String areaName = customCodeArea.getName();
long startPosError = diagnostic.getStartPosition();
return isCurrArea(shortName, areaName, startPosError);
}
示例7: getErrorDetails
import javax.tools.Diagnostic; //导入方法依赖的package包/类
private String getErrorDetails(Diagnostic diagnostic) {
String sourceErrorDetails = "";
CharSequence sourceCode = getSourceContent(diagnostic);
if (sourceCode != null) {
String source = sourceCode.toString();
int startPosition = (int) diagnostic.getStartPosition();
int endPosition = (int) diagnostic.getEndPosition();
if (endPosition < 0 && startPosition < 0) {
return "";
}
if (startPosition < 0) {
startPosition = endPosition;
} else if (endPosition < 0) {
endPosition = startPosition;
}
final int snippetStart = getSnippetStart(source, startPosition);
final int snippetEnd = getSnippetEnd(source, endPosition);
final String errorLine = source.substring(snippetStart, snippetEnd).replaceAll("\n", " ");;
startPosition -= snippetStart;
endPosition -= snippetStart;
StringBuilder signStringBuilder = getSpacesStringBuilder(errorLine.length());
signStringBuilder.insert(startPosition, POSITION_CHARACTER);
if (startPosition != endPosition) {
signStringBuilder.insert(endPosition, POSITION_CHARACTER);
}
sourceErrorDetails = errorLine + "\n" + signStringBuilder.toString() + "\n\n";
}
return sourceErrorDetails;
}
示例8: diag
import javax.tools.Diagnostic; //导入方法依赖的package包/类
@Override
public Diag diag(final Diagnostic<? extends JavaFileObject> d) {
return new Diag() {
@Override
public boolean isError() {
return d.getKind() == Diagnostic.Kind.ERROR;
}
@Override
public long getPosition() {
return d.getPosition();
}
@Override
public long getStartPosition() {
return d.getStartPosition();
}
@Override
public long getEndPosition() {
return d.getEndPosition();
}
@Override
public String getCode() {
return d.getCode();
}
@Override
public String getMessage(Locale locale) {
return expunge(d.getMessage(locale));
}
};
}
示例9: main
import javax.tools.Diagnostic; //导入方法依赖的package包/类
public static void main(String... args) throws IOException {
class MyFileObject extends SimpleJavaFileObject {
MyFileObject() {
super(URI.create("myfo:///Test.java"), SOURCE);
}
@Override
public String getCharContent(boolean ignoreEncodingErrors) {
// 0 1 2 3
// 012345678901234567890123456789012345
return "class Test { String s = 1234; }";
}
}
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
List<JavaFileObject> compilationUnits =
Collections.<JavaFileObject>singletonList(new MyFileObject());
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
List<String> options = Arrays.asList("-processor", EndPositions.class.getCanonicalName());
JavacTask task = (JavacTask)javac.getTask(null, null, diagnostics, options, null, compilationUnits);
boolean valid = task.call();
if (valid)
throw new AssertionError("Expected one error, but found none.");
List<Diagnostic<? extends JavaFileObject>> errors = diagnostics.getDiagnostics();
if (errors.size() != 1)
throw new AssertionError("Expected one error only, but found " + errors.size() + "; errors: " + errors);
Diagnostic<?> error = errors.get(0);
if (error.getStartPosition() >= error.getEndPosition())
throw new AssertionError("Expected start to be less than end position: start [" +
error.getStartPosition() + "], end [" + error.getEndPosition() +"]" +
"; diagnostics code: " + error.getCode());
System.out.println("All is good!");
}
示例10: compile
import javax.tools.Diagnostic; //导入方法依赖的package包/类
static void compile(JavaSource src) throws IOException {
ByteArrayOutputStream ba = new ByteArrayOutputStream();
PrintWriter writer = new PrintWriter(ba);
File tempDir = new File(".");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector dc = new DiagnosticCollector();
try (JavaFileManager javaFileManager = getJavaFileManager(compiler, dc)) {
List<String> options = new ArrayList<>();
options.add("-cp");
options.add(tempDir.getPath());
options.add("-d");
options.add(tempDir.getPath());
options.add("--should-stop:at=GENERATE");
List<JavaFileObject> sources = new ArrayList<>();
sources.add(src);
JavaCompiler.CompilationTask task =
compiler.getTask(writer, javaFileManager,
dc, options, null,
sources);
task.call();
for (Diagnostic diagnostic : (List<Diagnostic>) dc.getDiagnostics()) {
long actualStart = diagnostic.getStartPosition();
long actualEnd = diagnostic.getEndPosition();
System.out.println("Source: " + src.source);
System.out.println("Diagnostic: " + diagnostic);
System.out.print("Start position: Expected: " + src.startPos);
System.out.println(", Actual: " + actualStart);
System.out.print("End position: Expected: " + src.endPos);
System.out.println(", Actual: " + actualEnd);
if (src.startPos != actualStart || src.endPos != actualEnd) {
throw new RuntimeException("error: trees don't match");
}
}
}
}
示例11: brokenPlatform
import javax.tools.Diagnostic; //导入方法依赖的package包/类
public static void brokenPlatform(
@NonNull final Context ctx,
@NonNull final Iterable<? extends CompileTuple> files,
@NullAllowed final Diagnostic<JavaFileObject> diagnostic) {
if (diagnostic == null) {
return;
}
final Diagnostic<JavaFileObject> error = new Diagnostic<JavaFileObject>() {
@Override
public Kind getKind() {
return Kind.ERROR;
}
@Override
public JavaFileObject getSource() {
return diagnostic.getSource();
}
@Override
public long getPosition() {
return diagnostic.getPosition();
}
@Override
public long getStartPosition() {
return diagnostic.getStartPosition();
}
@Override
public long getEndPosition() {
return diagnostic.getEndPosition();
}
@Override
public long getLineNumber() {
return diagnostic.getLineNumber();
}
@Override
public long getColumnNumber() {
return diagnostic.getColumnNumber();
}
@Override
public String getCode() {
return diagnostic.getCode();
}
@Override
public String getMessage(Locale locale) {
return diagnostic.getMessage(locale);
}
};
for (CompileTuple file : files) {
if (!file.virtual) {
ErrorsCache.setErrors(
ctx.getRootURI(),
file.indexable,
Collections.<Diagnostic<JavaFileObject>>singleton(error),
ERROR_CONVERTOR);
}
}
}
示例12: check
import javax.tools.Diagnostic; //导入方法依赖的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
}
示例13: isStartPosMoreThanMinusOne
import javax.tools.Diagnostic; //导入方法依赖的package包/类
private static boolean isStartPosMoreThanMinusOne(Diagnostic diagnostic) {
return diagnostic.getStartPosition() > -1;
}
示例14: annotate
import javax.tools.Diagnostic; //导入方法依赖的package包/类
@Override
public void annotate( PsiElement element, AnnotationHolder holder )
{
PsiClass psiClass = ResourceToManifoldUtil.findPsiClass( element.getContainingFile() );
if( psiClass == null )
{
return;
}
if( PsiErrorClassUtil.isErrorClass( psiClass ) && element instanceof PsiFileSystemItem )
{
holder.createErrorAnnotation( new TextRange( 0, element.getContainingFile().getTextLength() ), PsiErrorClassUtil.getErrorFrom( psiClass ).getMessage() );
return;
}
if( !(psiClass instanceof ManifoldPsiClass) )
{
return;
}
DiagnosticCollector issues = ((ManifoldPsiClass)psiClass).getIssues();
if( issues == null )
{
return;
}
for( Object obj : issues.getDiagnostics() )
{
Diagnostic issue = (Diagnostic)obj;
if( element.getTextOffset() > issue.getStartPosition() ||
element.getTextOffset() + element.getTextLength() <= issue.getStartPosition() )
{
continue;
}
PsiElement deepestElement = element.getContainingFile().findElementAt( (int)issue.getStartPosition() );
if( deepestElement != element )
{
continue;
}
switch( issue.getKind() )
{
case ERROR:
holder.createErrorAnnotation( deepestElement, issue.getMessage( Locale.getDefault() ) );
break;
case WARNING:
case MANDATORY_WARNING:
holder.createWarningAnnotation( deepestElement, issue.getMessage( Locale.getDefault() ) );
break;
case NOTE:
case OTHER:
holder.createInfoAnnotation( deepestElement, issue.getMessage( Locale.getDefault() ) );
break;
}
}
}