aboutsummaryrefslogtreecommitdiff
path: root/javatests/com/google/turbine/lower/IntegrationTestSupport.java
blob: f20962b18fae094e8f069f23eefe9d5f58199f46 (plain)
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
/*
 * Copyright 2016 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.lower;

import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.io.MoreFiles.getFileExtension;
import static com.google.turbine.testing.TestClassPaths.TURBINE_BOOTCLASSPATH;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import static org.junit.Assert.fail;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.io.MoreFiles;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import com.google.turbine.binder.Binder;
import com.google.turbine.binder.Binder.BindingResult;
import com.google.turbine.binder.ClassPath;
import com.google.turbine.binder.ClassPathBinder;
import com.google.turbine.diag.SourceFile;
import com.google.turbine.options.LanguageVersion;
import com.google.turbine.parse.Parser;
import com.google.turbine.testing.AsmUtils;
import com.google.turbine.tree.Tree.CompUnit;
import com.sun.source.util.JavacTask;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.util.Context;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.file.FileSystem;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
import javax.tools.StandardLocation;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.signature.SignatureReader;
import org.objectweb.asm.signature.SignatureVisitor;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.InnerClassNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.RecordComponentNode;
import org.objectweb.asm.tree.TypeAnnotationNode;

/** Support for bytecode diffing-integration tests. */
public final class IntegrationTestSupport {

  /**
   * Normalizes order of members, attributes, and constant pool entries, to allow diffing bytecode.
   */
  public static Map<String, byte[]> sortMembers(Map<String, byte[]> in) {
    List<ClassNode> classes = toClassNodes(in);
    for (ClassNode n : classes) {
      sortAttributes(n);
    }
    return toByteCode(classes);
  }

  /**
   * Canonicalizes bytecode produced by javac to match the expected output of turbine. Includes the
   * same normalization as {@link #sortMembers}, as well as removing everything not produced by the
   * header compiler (code, debug info, etc.)
   */
  public static Map<String, byte[]> canonicalize(Map<String, byte[]> in) {
    List<ClassNode> classes = toClassNodes(in);

    // drop local and anonymous classes
    classes =
        classes.stream()
            .filter(n -> !isAnonymous(n) && !isLocal(n))
            .collect(toCollection(ArrayList::new));

    // collect all inner classes attributes
    Map<String, InnerClassNode> infos = new HashMap<>();
    for (ClassNode n : classes) {
      for (InnerClassNode innerClassNode : n.innerClasses) {
        infos.put(innerClassNode.name, innerClassNode);
      }
    }

    HashSet<String> all = classes.stream().map(n -> n.name).collect(toCollection(HashSet::new));
    for (ClassNode n : classes) {
      removeImplementation(n);
      removeUnusedInnerClassAttributes(infos, n);
      makeEnumsFinal(all, n);
      sortAttributes(n);
      undeprecate(n);
    }

    return toByteCode(classes);
  }

  private static boolean isLocal(ClassNode n) {
    return n.outerMethod != null;
  }

  private static boolean isAnonymous(ClassNode n) {
    // JVMS 4.7.6: if C is anonymous, the value of the inner_name_index item must be zero
    return n.innerClasses.stream().anyMatch(i -> i.name.equals(n.name) && i.innerName == null);
  }

  // ASM sets ACC_DEPRECATED for elements with the Deprecated attribute;
  // unset it if the @Deprecated annotation is not also present.
  // This can happen if the @deprecated javadoc tag was present but the
  // annotation wasn't.
  private static void undeprecate(ClassNode n) {
    if (!isDeprecated(n.visibleAnnotations)) {
      n.access &= ~Opcodes.ACC_DEPRECATED;
    }
    n.methods.stream()
        .filter(m -> !isDeprecated(m.visibleAnnotations))
        .forEach(m -> m.access &= ~Opcodes.ACC_DEPRECATED);
    n.fields.stream()
        .filter(f -> !isDeprecated(f.visibleAnnotations))
        .forEach(f -> f.access &= ~Opcodes.ACC_DEPRECATED);
  }

  private static boolean isDeprecated(List<AnnotationNode> visibleAnnotations) {
    return visibleAnnotations != null
        && visibleAnnotations.stream().anyMatch(a -> a.desc.equals("Ljava/lang/Deprecated;"));
  }

  private static void makeEnumsFinal(Set<String> all, ClassNode n) {
    n.innerClasses.forEach(
        x -> {
          if (all.contains(x.name) && (x.access & Opcodes.ACC_ENUM) == Opcodes.ACC_ENUM) {
            x.access &= ~Opcodes.ACC_ABSTRACT;
            x.access |= Opcodes.ACC_FINAL;
          }
        });
    if ((n.access & Opcodes.ACC_ENUM) == Opcodes.ACC_ENUM) {
      n.access &= ~Opcodes.ACC_ABSTRACT;
      n.access |= Opcodes.ACC_FINAL;
    }
  }

  private static Map<String, byte[]> toByteCode(List<ClassNode> classes) {
    Map<String, byte[]> out = new LinkedHashMap<>();
    for (ClassNode n : classes) {
      ClassWriter cw = new ClassWriter(0);
      n.accept(cw);
      out.put(n.name, cw.toByteArray());
    }
    return out;
  }

  private static List<ClassNode> toClassNodes(Map<String, byte[]> in) {
    List<ClassNode> classes = new ArrayList<>();
    for (byte[] f : in.values()) {
      ClassNode n = new ClassNode();
      new ClassReader(f).accept(n, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);

      classes.add(n);
    }
    return classes;
  }

  /** Remove elements that are omitted by turbine, e.g. private and synthetic members. */
  private static void removeImplementation(ClassNode n) {
    n.innerClasses =
        n.innerClasses.stream()
            .filter(x -> (x.access & Opcodes.ACC_SYNTHETIC) == 0 && x.innerName != null)
            .collect(toList());

    n.methods =
        n.methods.stream()
            .filter(x -> (x.access & (Opcodes.ACC_SYNTHETIC | Opcodes.ACC_PRIVATE)) == 0)
            .filter(x -> !x.name.equals("<clinit>"))
            .collect(toList());

    n.fields =
        n.fields.stream()
            .filter(x -> (x.access & (Opcodes.ACC_SYNTHETIC | Opcodes.ACC_PRIVATE)) == 0)
            .collect(toList());
  }

  /** Apply a standard sort order to attributes. */
  private static void sortAttributes(ClassNode n) {

    n.innerClasses.sort(
        Comparator.comparing((InnerClassNode x) -> x.name)
            .thenComparing(x -> x.outerName)
            .thenComparing(x -> x.innerName)
            .thenComparing(x -> x.access));

    sortAnnotations(n.visibleAnnotations);
    sortAnnotations(n.invisibleAnnotations);
    sortTypeAnnotations(n.visibleTypeAnnotations);
    sortTypeAnnotations(n.invisibleTypeAnnotations);

    for (MethodNode m : n.methods) {
      sortParameterAnnotations(m.visibleParameterAnnotations);
      sortParameterAnnotations(m.invisibleParameterAnnotations);

      sortAnnotations(m.visibleAnnotations);
      sortAnnotations(m.invisibleAnnotations);
      sortTypeAnnotations(m.visibleTypeAnnotations);
      sortTypeAnnotations(m.invisibleTypeAnnotations);
    }

    for (FieldNode f : n.fields) {
      sortAnnotations(f.visibleAnnotations);
      sortAnnotations(f.invisibleAnnotations);
      sortTypeAnnotations(f.visibleTypeAnnotations);
      sortTypeAnnotations(f.invisibleTypeAnnotations);
    }

    if (n.recordComponents != null) {
      for (RecordComponentNode r : n.recordComponents) {
        sortAnnotations(r.visibleAnnotations);
        sortAnnotations(r.invisibleAnnotations);
        sortTypeAnnotations(r.visibleTypeAnnotations);
        sortTypeAnnotations(r.invisibleTypeAnnotations);
      }
    }

    if (n.nestMembers != null) {
      Collections.sort(n.nestMembers);
    }
  }

  private static void sortParameterAnnotations(List<AnnotationNode>[] parameters) {
    if (parameters == null) {
      return;
    }
    for (List<AnnotationNode> annos : parameters) {
      sortAnnotations(annos);
    }
  }

  private static void sortTypeAnnotations(List<TypeAnnotationNode> annos) {
    if (annos == null) {
      return;
    }
    annos.sort(
        Comparator.comparing((TypeAnnotationNode a) -> a.desc)
            .thenComparing(a -> String.valueOf(a.typeRef))
            .thenComparing(a -> String.valueOf(a.typePath))
            .thenComparing(a -> String.valueOf(a.values)));
  }

  private static void sortAnnotations(List<AnnotationNode> annos) {
    if (annos == null) {
      return;
    }
    annos.sort(
        Comparator.comparing((AnnotationNode a) -> a.desc)
            .thenComparing(a -> String.valueOf(a.values)));
  }

  /**
   * Remove InnerClass attributes that are no longer needed after member pruning. This requires
   * visiting all descriptors and signatures in the bytecode to find references to inner classes.
   */
  private static void removeUnusedInnerClassAttributes(
      Map<String, InnerClassNode> infos, ClassNode n) {
    Set<String> types = new HashSet<>();
    {
      types.add(n.name);
      collectTypesFromSignature(types, n.signature);
      if (n.superName != null) {
        types.add(n.superName);
      }
      types.addAll(n.interfaces);

      addTypesInAnnotations(types, n.visibleAnnotations);
      addTypesInAnnotations(types, n.invisibleAnnotations);
      addTypesInTypeAnnotations(types, n.visibleTypeAnnotations);
      addTypesInTypeAnnotations(types, n.invisibleTypeAnnotations);
    }
    for (MethodNode m : n.methods) {
      collectTypesFromSignature(types, m.desc);
      collectTypesFromSignature(types, m.signature);
      types.addAll(m.exceptions);

      addTypesInAnnotations(types, m.visibleAnnotations);
      addTypesInAnnotations(types, m.invisibleAnnotations);
      addTypesInTypeAnnotations(types, m.visibleTypeAnnotations);
      addTypesInTypeAnnotations(types, m.invisibleTypeAnnotations);

      addTypesFromParameterAnnotations(types, m.visibleParameterAnnotations);
      addTypesFromParameterAnnotations(types, m.invisibleParameterAnnotations);

      collectTypesFromAnnotationValue(types, m.annotationDefault);
    }
    for (FieldNode f : n.fields) {
      collectTypesFromSignature(types, f.desc);
      collectTypesFromSignature(types, f.signature);

      addTypesInAnnotations(types, f.visibleAnnotations);
      addTypesInAnnotations(types, f.invisibleAnnotations);
      addTypesInTypeAnnotations(types, f.visibleTypeAnnotations);
      addTypesInTypeAnnotations(types, f.invisibleTypeAnnotations);
    }
    if (n.recordComponents != null) {
      for (RecordComponentNode r : n.recordComponents) {
        collectTypesFromSignature(types, r.descriptor);
        collectTypesFromSignature(types, r.signature);

        addTypesInAnnotations(types, r.visibleAnnotations);
        addTypesInAnnotations(types, r.invisibleAnnotations);
        addTypesInTypeAnnotations(types, r.visibleTypeAnnotations);
        addTypesInTypeAnnotations(types, r.invisibleTypeAnnotations);
      }
    }

    if (n.nestMembers != null) {
      for (String member : n.nestMembers) {
        InnerClassNode i = infos.get(member);
        if (i.outerName != null) {
          types.add(member);
        }
      }
    }

    List<InnerClassNode> used = new ArrayList<>();
    for (InnerClassNode i : n.innerClasses) {
      if (i.outerName != null && i.outerName.equals(n.name)) {
        // keep InnerClass attributes for any member classes
        used.add(i);
      } else if (types.contains(i.name)) {
        // otherwise, keep InnerClass attributes that were referenced in class or member signatures
        addInnerChain(infos, used, i.name);
      }
    }
    addInnerChain(infos, used, n.name);
    n.innerClasses = used;

    if (n.nestMembers != null) {
      Set<String> members = used.stream().map(i -> i.name).collect(toSet());
      n.nestMembers = n.nestMembers.stream().filter(members::contains).collect(toList());
    }
  }

  private static void addTypesFromParameterAnnotations(
      Set<String> types, List<AnnotationNode>[] parameterAnnotations) {
    if (parameterAnnotations == null) {
      return;
    }
    for (List<AnnotationNode> annos : parameterAnnotations) {
      addTypesInAnnotations(types, annos);
    }
  }

  private static void addTypesInTypeAnnotations(Set<String> types, List<TypeAnnotationNode> annos) {
    if (annos == null) {
      return;
    }
    annos.forEach(a -> collectTypesFromAnnotation(types, a));
  }

  private static void addTypesInAnnotations(Set<String> types, List<AnnotationNode> annos) {
    if (annos == null) {
      return;
    }
    annos.forEach(a -> collectTypesFromAnnotation(types, a));
  }

  private static void collectTypesFromAnnotation(Set<String> types, AnnotationNode a) {
    collectTypesFromSignature(types, a.desc);
    collectTypesFromAnnotationValues(types, a.values);
  }

  private static void collectTypesFromAnnotationValues(Set<String> types, List<?> values) {
    if (values == null) {
      return;
    }
    for (Object v : values) {
      collectTypesFromAnnotationValue(types, v);
    }
  }

  private static void collectTypesFromAnnotationValue(Set<String> types, Object v) {
    if (v instanceof List) {
      collectTypesFromAnnotationValues(types, (List<?>) v);
    } else if (v instanceof Type) {
      collectTypesFromSignature(types, ((Type) v).getDescriptor());
    } else if (v instanceof AnnotationNode) {
      collectTypesFromAnnotation(types, (AnnotationNode) v);
    } else if (v instanceof String[]) {
      String[] enumValue = (String[]) v;
      collectTypesFromSignature(types, enumValue[0]);
    }
  }

  /**
   * For each preserved InnerClass attribute, keep any information about transitive enclosing
   * classes of the inner class.
   */
  private static void addInnerChain(
      Map<String, InnerClassNode> infos, List<InnerClassNode> used, String i) {
    while (infos.containsKey(i)) {
      InnerClassNode info = infos.get(i);
      used.add(info);
      i = info.outerName;
    }
  }

  /** Save all class types referenced in a signature. */
  private static void collectTypesFromSignature(Set<String> classes, String signature) {
    if (signature == null) {
      return;
    }
    // signatures for qualified generic class types are visited as name and type argument pieces,
    // so stitch them back together into a binary class name
    final Set<String> classes1 = classes;
    new SignatureReader(signature)
        .accept(
            new SignatureVisitor(Opcodes.ASM9) {
              private final Set<String> classes = classes1;
              // class signatures may contain type arguments that contain class signatures
              Deque<List<String>> pieces = new ArrayDeque<>();

              @Override
              public void visitInnerClassType(String name) {
                pieces.element().add(name);
              }

              @Override
              public void visitClassType(String name) {
                List<String> classType = new ArrayList<>();
                classType.add(name);
                pieces.push(classType);
              }

              @Override
              public void visitEnd() {
                classes.add(Joiner.on('$').join(pieces.pop()));
                super.visitEnd();
              }
            });
  }

  public static Map<String, byte[]> runTurbine(
      Map<String, String> input, ImmutableList<Path> classpath) throws IOException {
    return runTurbine(input, classpath, ImmutableList.of());
  }

  public static Map<String, byte[]> runTurbine(
      Map<String, String> input, ImmutableList<Path> classpath, ImmutableList<String> javacopts)
      throws IOException {
    return runTurbine(
        input, classpath, TURBINE_BOOTCLASSPATH, /* moduleVersion= */ Optional.empty(), javacopts);
  }

  static Map<String, byte[]> runTurbine(
      Map<String, String> input,
      ImmutableList<Path> classpath,
      ClassPath bootClassPath,
      Optional<String> moduleVersion,
      ImmutableList<String> javacopts)
      throws IOException {
    BindingResult bound = turbineAnalysis(input, classpath, bootClassPath, moduleVersion);
    return Lower.lowerAll(
            LanguageVersion.fromJavacopts(javacopts),
            bound.units(),
            bound.modules(),
            bound.classPathEnv())
        .bytes();
  }

  public static BindingResult turbineAnalysis(
      Map<String, String> input,
      ImmutableList<Path> classpath,
      ClassPath bootClassPath,
      Optional<String> moduleVersion)
      throws IOException {
    ImmutableList<CompUnit> units =
        input.entrySet().stream()
            .map(e -> new SourceFile(e.getKey(), e.getValue()))
            .map(Parser::parse)
            .collect(toImmutableList());

    return Binder.bind(
        units, ClassPathBinder.bindClasspath(classpath), bootClassPath, moduleVersion);
  }

  public static JavacTask runJavacAnalysis(
      Map<String, String> sources, Collection<Path> classpath, ImmutableList<String> options)
      throws Exception {
    return runJavacAnalysis(sources, classpath, options, new DiagnosticCollector<>());
  }

  public static JavacTask runJavacAnalysis(
      Map<String, String> sources,
      Collection<Path> classpath,
      ImmutableList<String> options,
      DiagnosticCollector<JavaFileObject> collector)
      throws Exception {
    FileSystem fs = Jimfs.newFileSystem(Configuration.unix());
    Path out = fs.getPath("out");
    return setupJavac(sources, classpath, options, collector, fs, out);
  }

  public static Map<String, byte[]> runJavac(
      Map<String, String> sources, Collection<Path> classpath) throws Exception {
    return runJavac(
        sources, classpath, ImmutableList.of("-parameters", "-source", "8", "-target", "8"));
  }

  public static Map<String, byte[]> runJavac(
      Map<String, String> sources, Collection<Path> classpath, ImmutableList<String> options)
      throws Exception {

    DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<>();
    FileSystem fs = Jimfs.newFileSystem(Configuration.unix());
    Path out = fs.getPath("out");

    JavacTask task = setupJavac(sources, classpath, options, collector, fs, out);

    if (!task.call()) {
      fail(collector.getDiagnostics().stream().map(d -> d.toString()).collect(joining("\n")));
    }

    List<Path> classes = new ArrayList<>();
    Files.walkFileTree(
        out,
        new SimpleFileVisitor<Path>() {
          @Override
          public FileVisitResult visitFile(Path path, BasicFileAttributes attrs)
              throws IOException {
            if (getFileExtension(path).equals("class")) {
              classes.add(path);
            }
            return FileVisitResult.CONTINUE;
          }
        });
    Map<String, byte[]> result = new LinkedHashMap<>();
    for (Path path : classes) {
      String r = out.relativize(path).toString();
      result.put(r.substring(0, r.length() - ".class".length()), Files.readAllBytes(path));
    }
    return result;
  }

  private static JavacTask setupJavac(
      Map<String, String> sources,
      Collection<Path> classpath,
      ImmutableList<String> options,
      DiagnosticCollector<JavaFileObject> collector,
      FileSystem fs,
      Path out)
      throws IOException {
    Path srcs = fs.getPath("srcs");

    Files.createDirectories(out);

    ArrayList<Path> inputs = new ArrayList<>();
    for (Map.Entry<String, String> entry : sources.entrySet()) {
      Path path = srcs.resolve(entry.getKey());
      if (path.getParent() != null) {
        Files.createDirectories(path.getParent());
      }
      MoreFiles.asCharSink(path, UTF_8).write(entry.getValue());
      inputs.add(path);
    }

    JavacTool compiler = JavacTool.create();
    JavacFileManager fileManager = new JavacFileManager(new Context(), true, UTF_8);
    fileManager.setLocationFromPaths(StandardLocation.CLASS_OUTPUT, ImmutableList.of(out));
    fileManager.setLocationFromPaths(StandardLocation.CLASS_PATH, classpath);
    fileManager.setLocationFromPaths(StandardLocation.locationFor("MODULE_PATH"), classpath);
    if (inputs.stream()
            .filter(i -> requireNonNull(i.getFileName()).toString().equals("module-info.java"))
            .count()
        > 1) {
      // multi-module mode
      fileManager.setLocationFromPaths(
          StandardLocation.locationFor("MODULE_SOURCE_PATH"), ImmutableList.of(srcs));
    }

    return compiler.getTask(
        new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.err, UTF_8)), true),
        fileManager,
        collector,
        options,
        ImmutableList.of(),
        fileManager.getJavaFileObjectsFromPaths(inputs));
  }

  /** Normalizes and stringifies a collection of class files. */
  public static String dump(Map<String, byte[]> compiled) throws Exception {
    StringBuilder sb = new StringBuilder();
    List<String> keys = new ArrayList<>(compiled.keySet());
    Collections.sort(keys);
    for (String key : keys) {
      String na = key;
      if (na.startsWith("/")) {
        na = na.substring(1);
      }
      sb.append(String.format("=== %s ===\n", na));
      sb.append(AsmUtils.textify(compiled.get(key), /* skipDebug= */ true));
    }
    return sb.toString();
  }

  public static class TestInput {

    public final Map<String, String> sources;
    public final Map<String, String> classes;

    public TestInput(Map<String, String> sources, Map<String, String> classes) {
      this.sources = sources;
      this.classes = classes;
    }

    public static TestInput parse(String text) {
      Map<String, String> sources = new LinkedHashMap<>();
      Map<String, String> classes = new LinkedHashMap<>();
      String className = null;
      String sourceName = null;
      List<String> lines = new ArrayList<>();
      for (String line : Splitter.on('\n').split(text)) {
        if (line.startsWith("===")) {
          if (sourceName != null) {
            sources.put(sourceName, Joiner.on('\n').join(lines) + "\n");
          }
          if (className != null) {
            classes.put(className, Joiner.on('\n').join(lines) + "\n");
          }
          lines.clear();
          sourceName = line.substring(3, line.length() - 3).trim();
          className = null;
        } else if (line.startsWith("%%%")) {
          if (className != null) {
            classes.put(className, Joiner.on('\n').join(lines) + "\n");
          }
          if (sourceName != null) {
            sources.put(sourceName, Joiner.on('\n').join(lines) + "\n");
          }
          className = line.substring(3, line.length() - 3).trim();
          lines.clear();
          sourceName = null;
        } else {
          lines.add(line);
        }
      }
      if (sourceName != null) {
        sources.put(sourceName, Joiner.on('\n').join(lines) + "\n");
      }
      if (className != null) {
        classes.put(className, Joiner.on('\n').join(lines) + "\n");
      }
      lines.clear();
      return new TestInput(sources, classes);
    }
  }

  public static int getMajor() {
    return Runtime.version().feature();
  }

  private IntegrationTestSupport() {}
}