1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
|
/*
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.turbine.processing;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.MoreCollectors.onlyElement;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.joining;
import static javax.lang.model.util.ElementFilter.methodsIn;
import static javax.lang.model.util.ElementFilter.typesIn;
import static org.junit.Assert.assertThrows;
import static org.junit.Assume.assumeTrue;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.turbine.binder.Binder;
import com.google.turbine.binder.Binder.BindingResult;
import com.google.turbine.binder.ClassPathBinder;
import com.google.turbine.binder.Processing;
import com.google.turbine.binder.Processing.ProcessorInfo;
import com.google.turbine.diag.SourceFile;
import com.google.turbine.diag.TurbineDiagnostic;
import com.google.turbine.diag.TurbineError;
import com.google.turbine.lower.IntegrationTestSupport;
import com.google.turbine.parse.Parser;
import com.google.turbine.testing.TestClassPaths;
import com.google.turbine.tree.Tree;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
import java.io.Writer;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.ExecutableType;
import javax.tools.Diagnostic;
import javax.tools.FileObject;
import javax.tools.JavaFileObject;
import javax.tools.StandardLocation;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class ProcessingIntegrationTest {
@SupportedAnnotationTypes("*")
public static class CrashingProcessor extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
throw new RuntimeException("crash!");
}
}
@Test
public void crash() throws IOException {
ImmutableList<Tree.CompUnit> units =
parseUnit(
"=== Test.java ===", //
"@Deprecated",
"class Test extends NoSuch {",
"}");
TurbineError e =
assertThrows(
TurbineError.class,
() ->
Binder.bind(
units,
ClassPathBinder.bindClasspath(ImmutableList.of()),
Processing.ProcessorInfo.create(
ImmutableList.of(new CrashingProcessor()),
getClass().getClassLoader(),
ImmutableMap.of(),
SourceVersion.latestSupported()),
TestClassPaths.TURBINE_BOOTCLASSPATH,
Optional.empty()));
ImmutableList<String> messages =
e.diagnostics().stream().map(TurbineDiagnostic::message).collect(toImmutableList());
assertThat(messages).hasSize(2);
assertThat(messages.get(0)).contains("could not resolve NoSuch");
assertThat(messages.get(1)).contains("crash!");
}
@SupportedAnnotationTypes("*")
public static class WarningProcessor extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
private boolean first = true;
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (first) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "proc warning");
try {
JavaFileObject file = processingEnv.getFiler().createSourceFile("Gen.java");
try (Writer writer = file.openWriter()) {
writer.write("class Gen {}");
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
first = false;
}
if (roundEnv.processingOver()) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "proc error");
}
return false;
}
}
@Test
public void warnings() throws IOException {
ImmutableList<Tree.CompUnit> units =
parseUnit(
"=== Test.java ===", //
"@Deprecated",
"class Test {",
"}");
TurbineError e =
assertThrows(
TurbineError.class,
() ->
Binder.bind(
units,
ClassPathBinder.bindClasspath(ImmutableList.of()),
Processing.ProcessorInfo.create(
ImmutableList.of(new WarningProcessor()),
getClass().getClassLoader(),
ImmutableMap.of(),
SourceVersion.latestSupported()),
TestClassPaths.TURBINE_BOOTCLASSPATH,
Optional.empty()));
ImmutableList<String> diags =
e.diagnostics().stream().map(d -> d.message()).collect(toImmutableList());
assertThat(diags).hasSize(2);
assertThat(diags.get(0)).contains("proc warning");
assertThat(diags.get(1)).contains("proc error");
}
@SupportedAnnotationTypes("*")
public static class ResourceProcessor extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
private boolean first = true;
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (first) {
try {
try (Writer writer = processingEnv.getFiler().createSourceFile("Gen").openWriter()) {
writer.write("class Gen {}");
}
try (Writer writer =
processingEnv
.getFiler()
.createResource(StandardLocation.SOURCE_OUTPUT, "", "source.txt")
.openWriter()) {
writer.write("hello source output");
}
try (Writer writer =
processingEnv
.getFiler()
.createResource(StandardLocation.CLASS_OUTPUT, "", "class.txt")
.openWriter()) {
writer.write("hello class output");
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
first = false;
}
return false;
}
}
@Test
public void resources() throws IOException {
ImmutableList<Tree.CompUnit> units =
parseUnit(
"=== Test.java ===", //
"@Deprecated",
"class Test {",
"}");
BindingResult bound =
Binder.bind(
units,
ClassPathBinder.bindClasspath(ImmutableList.of()),
ProcessorInfo.create(
ImmutableList.of(new ResourceProcessor()),
getClass().getClassLoader(),
ImmutableMap.of(),
SourceVersion.latestSupported()),
TestClassPaths.TURBINE_BOOTCLASSPATH,
Optional.empty());
assertThat(bound.generatedSources().keySet()).containsExactly("Gen.java", "source.txt");
assertThat(bound.generatedClasses().keySet()).containsExactly("class.txt");
// The requireNonNull calls are safe because of the keySet checks above.
assertThat(requireNonNull(bound.generatedSources().get("source.txt")).source())
.isEqualTo("hello source output");
assertThat(new String(requireNonNull(bound.generatedClasses().get("class.txt")), UTF_8))
.isEqualTo("hello class output");
}
@Test
public void getAllAnnotations() throws IOException {
ImmutableList<Tree.CompUnit> units =
parseUnit(
"=== A.java ===", //
"import java.lang.annotation.Inherited;",
"@Inherited",
"@interface A {}",
"=== B.java ===", //
"@interface B {}",
"=== One.java ===", //
"@A @B class One {}",
"=== Two.java ===", //
"class Two extends One {}");
BindingResult bound =
Binder.bind(
units,
ClassPathBinder.bindClasspath(ImmutableList.of()),
ProcessorInfo.create(
ImmutableList.of(new ElementsAnnotatedWithProcessor()),
getClass().getClassLoader(),
ImmutableMap.of(),
SourceVersion.latestSupported()),
TestClassPaths.TURBINE_BOOTCLASSPATH,
Optional.empty());
assertThat(
Splitter.on(System.lineSeparator())
.omitEmptyStrings()
.split(
new String(
bound.generatedClasses().entrySet().stream()
.filter(s -> s.getKey().equals("output.txt"))
.collect(onlyElement())
.getValue(),
UTF_8)))
.containsExactly("A: One, Two", "B: One");
}
@SupportedAnnotationTypes("*")
private static class ElementsAnnotatedWithProcessor extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
private boolean first = true;
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (first) {
try (PrintWriter writer =
new PrintWriter(
processingEnv
.getFiler()
.createResource(StandardLocation.CLASS_OUTPUT, "", "output.txt")
.openWriter(),
/* autoFlush= */ true)) {
printAnnotatedElements(roundEnv, writer, "A");
printAnnotatedElements(roundEnv, writer, "B");
} catch (IOException e) {
throw new UncheckedIOException(e);
}
first = false;
}
return false;
}
private void printAnnotatedElements(
RoundEnvironment roundEnv, PrintWriter writer, String annotation) {
writer.println(
annotation
+ ": "
+ roundEnv
.getElementsAnnotatedWith(
processingEnv.getElementUtils().getTypeElement(annotation))
.stream()
.map(e -> e.getSimpleName().toString())
.collect(joining(", ")));
}
}
private static void logError(
ProcessingEnvironment processingEnv,
RoundEnvironment roundEnv,
Class<?> processorClass,
int round) {
processingEnv
.getMessager()
.printMessage(
Diagnostic.Kind.ERROR,
String.format(
"%d: %s {errorRaised=%s, processingOver=%s}",
round,
processorClass.getSimpleName(),
roundEnv.errorRaised(),
roundEnv.processingOver()));
}
@SupportedAnnotationTypes("*")
public static class ErrorProcessor extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
int round = 0;
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
int round = ++this.round;
logError(processingEnv, roundEnv, getClass(), round);
String name = "Gen" + round;
try (Writer writer = processingEnv.getFiler().createSourceFile(name).openWriter()) {
writer.write(String.format("class %s {}", name));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return false;
}
}
@SupportedAnnotationTypes("*")
public static class FinalRoundErrorProcessor extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
int round = 0;
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
int round = ++this.round;
if (roundEnv.processingOver()) {
logError(processingEnv, roundEnv, getClass(), round);
}
return false;
}
}
@Test
public void errorsAndFinalRound() throws IOException {
ImmutableList<Tree.CompUnit> units =
parseUnit(
"=== Test.java ===", //
"@Deprecated",
"class Test {",
"}");
TurbineError e =
assertThrows(
TurbineError.class,
() ->
Binder.bind(
units,
ClassPathBinder.bindClasspath(ImmutableList.of()),
Processing.ProcessorInfo.create(
ImmutableList.of(new ErrorProcessor(), new FinalRoundErrorProcessor()),
getClass().getClassLoader(),
ImmutableMap.of(),
SourceVersion.latestSupported()),
TestClassPaths.TURBINE_BOOTCLASSPATH,
Optional.empty()));
ImmutableList<String> diags =
e.diagnostics().stream().map(d -> d.message()).collect(toImmutableList());
assertThat(diags)
.containsExactly(
"1: ErrorProcessor {errorRaised=false, processingOver=false}",
"2: ErrorProcessor {errorRaised=true, processingOver=true}",
"2: FinalRoundErrorProcessor {errorRaised=true, processingOver=true}")
.inOrder();
}
@SupportedAnnotationTypes("*")
public static class SuperTypeProcessor extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
TypeElement typeElement = processingEnv.getElementUtils().getTypeElement("T");
processingEnv
.getMessager()
.printMessage(
Diagnostic.Kind.ERROR,
typeElement.getSuperclass()
+ " "
+ processingEnv.getTypeUtils().directSupertypes(typeElement.asType()));
return false;
}
}
@Test
public void superType() throws IOException {
ImmutableList<Tree.CompUnit> units =
parseUnit(
"=== T.java ===", //
"@Deprecated",
"class T extends S {",
"}");
TurbineError e =
assertThrows(
TurbineError.class,
() ->
Binder.bind(
units,
ClassPathBinder.bindClasspath(ImmutableList.of()),
Processing.ProcessorInfo.create(
ImmutableList.of(new SuperTypeProcessor()),
getClass().getClassLoader(),
ImmutableMap.of(),
SourceVersion.latestSupported()),
TestClassPaths.TURBINE_BOOTCLASSPATH,
Optional.empty()));
ImmutableList<String> diags =
e.diagnostics().stream().map(d -> d.message()).collect(toImmutableList());
assertThat(diags).containsExactly("could not resolve S", "S [S]").inOrder();
}
@SupportedAnnotationTypes("*")
public static class GenerateAnnotationProcessor extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
private boolean first = true;
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (first) {
try {
JavaFileObject file = processingEnv.getFiler().createSourceFile("A");
try (Writer writer = file.openWriter()) {
writer.write("@interface A {}");
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
first = false;
}
return false;
}
}
@Test
public void generatedAnnotationDefinition() throws IOException {
ImmutableList<Tree.CompUnit> units =
parseUnit(
"=== T.java ===", //
"@interface B {",
" A value() default @A;",
"}",
"@B(value = @A)",
"class T {",
"}");
BindingResult bound =
Binder.bind(
units,
ClassPathBinder.bindClasspath(ImmutableList.of()),
ProcessorInfo.create(
ImmutableList.of(new GenerateAnnotationProcessor()),
getClass().getClassLoader(),
ImmutableMap.of(),
SourceVersion.latestSupported()),
TestClassPaths.TURBINE_BOOTCLASSPATH,
Optional.empty());
assertThat(bound.generatedSources()).containsKey("A.java");
}
@SupportedAnnotationTypes("*")
public static class GenerateQualifiedProcessor extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
String superType =
processingEnv.getElementUtils().getTypeElement("T").getSuperclass().toString();
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, superType);
return false;
}
}
@Test
public void qualifiedErrorType() throws IOException {
ImmutableList<Tree.CompUnit> units =
parseUnit(
"=== T.java ===", //
"class T extends G.I {",
"}");
TurbineError e =
assertThrows(
TurbineError.class,
() ->
Binder.bind(
units,
ClassPathBinder.bindClasspath(ImmutableList.of()),
ProcessorInfo.create(
ImmutableList.of(new GenerateQualifiedProcessor()),
getClass().getClassLoader(),
ImmutableMap.of(),
SourceVersion.latestSupported()),
TestClassPaths.TURBINE_BOOTCLASSPATH,
Optional.empty()));
assertThat(
e.diagnostics().stream()
.filter(d -> d.severity().equals(Diagnostic.Kind.NOTE))
.map(d -> d.message()))
.containsExactly("G.I");
}
@SupportedAnnotationTypes("*")
public static class ElementValueInspector extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
TypeElement element = processingEnv.getElementUtils().getTypeElement("T");
for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) {
processingEnv
.getMessager()
.printMessage(
Diagnostic.Kind.NOTE,
String.format("@Deprecated(%s)", annotationMirror.getElementValues()),
element,
annotationMirror);
}
return false;
}
}
@Test
public void badElementValue() throws IOException {
ImmutableList<Tree.CompUnit> units =
parseUnit(
"=== T.java ===", //
"@Deprecated(noSuch = 42) class T {}");
TurbineError e =
assertThrows(
TurbineError.class,
() ->
Binder.bind(
units,
ClassPathBinder.bindClasspath(ImmutableList.of()),
ProcessorInfo.create(
ImmutableList.of(new ElementValueInspector()),
getClass().getClassLoader(),
ImmutableMap.of(),
SourceVersion.latestSupported()),
TestClassPaths.TURBINE_BOOTCLASSPATH,
Optional.empty()));
assertThat(
e.diagnostics().stream()
.filter(d -> d.severity().equals(Diagnostic.Kind.ERROR))
.map(d -> d.message()))
.containsExactly("could not resolve element noSuch() in java.lang.Deprecated");
assertThat(
e.diagnostics().stream()
.filter(d -> d.severity().equals(Diagnostic.Kind.NOTE))
.map(d -> d.message()))
.containsExactly("@Deprecated({})");
}
@SupportedAnnotationTypes("*")
public static class RecordProcessor extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (Element e : roundEnv.getRootElements()) {
processingEnv
.getMessager()
.printMessage(
Diagnostic.Kind.ERROR,
e.getKind() + " " + e + " " + ((TypeElement) e).getSuperclass());
for (Element m : e.getEnclosedElements()) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, m.getKind() + " " + m);
}
}
return false;
}
}
@Test
public void recordProcessing() throws IOException {
assumeTrue(Runtime.version().feature() >= 15);
ImmutableList<Tree.CompUnit> units =
parseUnit(
"=== R.java ===", //
"record R<T>(@Deprecated T x, int... y) {}");
TurbineError e =
assertThrows(
TurbineError.class,
() ->
Binder.bind(
units,
ClassPathBinder.bindClasspath(ImmutableList.of()),
ProcessorInfo.create(
ImmutableList.of(new RecordProcessor()),
getClass().getClassLoader(),
ImmutableMap.of(),
SourceVersion.latestSupported()),
TestClassPaths.TURBINE_BOOTCLASSPATH,
Optional.empty()));
assertThat(
e.diagnostics().stream()
.filter(d -> d.severity().equals(Diagnostic.Kind.ERROR))
.map(d -> d.message()))
.containsExactly(
"RECORD R java.lang.Record",
"RECORD_COMPONENT x",
"RECORD_COMPONENT y",
"CONSTRUCTOR R(T,int[])",
"METHOD toString()",
"METHOD hashCode()",
"METHOD equals(java.lang.Object)",
"METHOD x()",
"METHOD y()");
}
@Test
public void missingElementValue() {
ImmutableList<Tree.CompUnit> units =
parseUnit(
"=== T.java ===", //
"import java.lang.annotation.Retention;",
"@Retention() @interface T {}");
TurbineError e =
assertThrows(
TurbineError.class,
() ->
Binder.bind(
units,
ClassPathBinder.bindClasspath(ImmutableList.of()),
ProcessorInfo.create(
// missing annotation arguments are not a recoverable error, annotation
// processing shouldn't happen
ImmutableList.of(new CrashingProcessor()),
getClass().getClassLoader(),
ImmutableMap.of(),
SourceVersion.latestSupported()),
TestClassPaths.TURBINE_BOOTCLASSPATH,
Optional.empty()));
assertThat(e.diagnostics().stream().map(d -> d.message()))
.containsExactly("missing required annotation argument: value");
}
private static ImmutableList<Tree.CompUnit> parseUnit(String... lines) {
return IntegrationTestSupport.TestInput.parse(Joiner.on('\n').join(lines))
.sources
.entrySet()
.stream()
.map(e -> new SourceFile(e.getKey(), e.getValue()))
.map(Parser::parse)
.collect(toImmutableList());
}
@SupportedAnnotationTypes("*")
public static class AllMethodsProcessor extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
ImmutableList<ExecutableElement> methods =
typesIn(roundEnv.getRootElements()).stream()
.flatMap(t -> methodsIn(t.getEnclosedElements()).stream())
.collect(toImmutableList());
for (ExecutableElement a : methods) {
for (ExecutableElement b : methods) {
if (a.equals(b)) {
continue;
}
ExecutableType ta = (ExecutableType) a.asType();
ExecutableType tb = (ExecutableType) b.asType();
boolean r = processingEnv.getTypeUtils().isSubsignature(ta, tb);
processingEnv
.getMessager()
.printMessage(
Diagnostic.Kind.ERROR,
String.format(
"%s#%s%s <: %s#%s%s ? %s",
a.getEnclosingElement(),
a.getSimpleName(),
ta,
b.getEnclosingElement(),
b.getSimpleName(),
tb,
r));
}
}
return false;
}
}
@Test
public void bound() {
ImmutableList<Tree.CompUnit> units =
parseUnit(
"=== A.java ===", //
"import java.util.List;",
"class A<T> {",
" <U extends T> U f(List<U> list) {",
" return list.get(0);",
" }",
"}",
"class B extends A<String> {",
" @Override",
" <U extends String> U f(List<U> list) {",
" return super.f(list);",
" }",
"}",
"class C extends A<Object> {",
" @Override",
" <U> U f(List<U> list) {",
" return super.f(list);",
" }",
"}");
TurbineError e =
assertThrows(
TurbineError.class,
() ->
Binder.bind(
units,
ClassPathBinder.bindClasspath(ImmutableList.of()),
ProcessorInfo.create(
ImmutableList.of(new AllMethodsProcessor()),
getClass().getClassLoader(),
ImmutableMap.of(),
SourceVersion.latestSupported()),
TestClassPaths.TURBINE_BOOTCLASSPATH,
Optional.empty()));
assertThat(e.diagnostics().stream().map(d -> d.message()))
.containsExactly(
"A#f<U>(java.util.List<U>)U <: B#f<U>(java.util.List<U>)U ? false",
"A#f<U>(java.util.List<U>)U <: C#f<U>(java.util.List<U>)U ? false",
"B#f<U>(java.util.List<U>)U <: A#f<U>(java.util.List<U>)U ? false",
"B#f<U>(java.util.List<U>)U <: C#f<U>(java.util.List<U>)U ? false",
"C#f<U>(java.util.List<U>)U <: A#f<U>(java.util.List<U>)U ? false",
"C#f<U>(java.util.List<U>)U <: B#f<U>(java.util.List<U>)U ? false");
}
@SupportedAnnotationTypes("*")
public static class URIProcessor extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
private boolean first = true;
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (!first) {
return false;
}
first = false;
try {
FileObject output =
processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "foo", "Bar");
Path path = Paths.get(output.toUri());
processingEnv
.getMessager()
.printMessage(Diagnostic.Kind.ERROR, output.toUri() + " - " + path);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return false;
}
}
@Test
public void uriProcessing() throws IOException {
ImmutableList<Tree.CompUnit> units =
parseUnit(
"=== T.java ===", //
"class T {}");
TurbineError e =
assertThrows(
TurbineError.class,
() ->
Binder.bind(
units,
ClassPathBinder.bindClasspath(ImmutableList.of()),
ProcessorInfo.create(
ImmutableList.of(new URIProcessor()),
getClass().getClassLoader(),
ImmutableMap.of(),
SourceVersion.latestSupported()),
TestClassPaths.TURBINE_BOOTCLASSPATH,
Optional.empty()));
assertThat(
e.diagnostics().stream()
.filter(d -> d.severity().equals(Diagnostic.Kind.ERROR))
.map(d -> d.message()))
.containsExactly("file:///foo/Bar - " + Paths.get(URI.create("file:///foo/Bar")));
}
}
|