File: TestClientCodeWrapper.java

package info (click to toggle)
libnb-javaparser-java 9%2B2018-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 65,320 kB
  • sloc: java: 440,096; xml: 6,359; sh: 865; makefile: 314
file content (646 lines) | stat: -rw-r--r-- 23,595 bytes parent folder | download | duplicates (12)
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
/*
 * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * @test
 * @bug 6437138 6482554
 * @summary JSR 199: Compiler doesn't diagnose crash in user code
 * @library ../lib
 * @modules jdk.compiler/com.sun.tools.javac.api
 * @build JavacTestingAbstractProcessor TestClientCodeWrapper
 * @run main TestClientCodeWrapper
 */

import java.io.*;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.*;
import javax.annotation.processing.*;
import javax.lang.model.*;
import javax.lang.model.element.*;
import javax.tools.*;
import javax.tools.JavaFileObject.Kind;

import com.sun.source.util.*;
import com.sun.tools.javac.api.*;

public class TestClientCodeWrapper extends JavacTestingAbstractProcessor {
    public static void main(String... args) throws Exception {
        new TestClientCodeWrapper().run();
    }

    /**
     * Run a series of compilations, each with a different user-provided object
     * configured to throw an exception when a specific method is invoked.
     * Then, verify the exception is thrown as expected.
     *
     * Some methods are not invoked from the compiler, and are excluded from the test.
     */
    void run() throws Exception {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
            defaultFileManager = fm;

            for (Method m: getMethodsExcept(JavaFileManager.class,
                        "close", "getJavaFileForInput", "getLocationForModule", "getServiceLoader", "contains")) {
                test(m);
            }

            for (Method m: getMethodsExcept(FileObject.class, "delete")) {
                test(m);
            }

            for (Method m: getMethods(JavaFileObject.class)) {
                test(m);
            }

            for (Method m: getMethodsExcept(Processor.class, "getCompletions")) {
                test(m);
            }

            for (Method m: DiagnosticListener.class.getDeclaredMethods()) {
                test(m);
            }

            for (Method m: TaskListener.class.getDeclaredMethods()) {
                test(m);
            }

            if (errors > 0)
                throw new Exception(errors + " errors occurred");
        }
    }

    /** Get a sorted set of the methods declared on a class. */
    Set<Method> getMethods(Class<?> clazz) {
        return getMethodsExcept(clazz, new String[0]);
    }

    /** Get a sorted set of the methods declared on a class, excluding
     *  specified methods by name. */
    Set<Method> getMethodsExcept(Class<?> clazz, String... exclude) {
        Set<Method> methods = new TreeSet<Method>(new Comparator<Method>() {
            public int compare(Method m1, Method m2) {
                return m1.toString().compareTo(m2.toString());
            }
        });
        Set<String> e = new HashSet<String>(Arrays.asList(exclude));
        for (Method m: clazz.getDeclaredMethods()) {
            if (!e.contains(m.getName()))
                methods.add(m);
        }
        return methods;
    }

    /**
     * Test a method in a user supplied component, to verify javac's handling
     * of any exceptions thrown by that method.
     */
    void test(Method m) throws Exception {
        testNum++;

        File extDirs = new File("empty-extdirs");
        extDirs.mkdirs();

        File testClasses = new File("test" + testNum);
        testClasses.mkdirs();
        defaultFileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(testClasses));

        System.err.println("test " + testNum + ": "
                + m.getDeclaringClass().getSimpleName() + "." + m.getName());

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);

        List<String> javacOptions = Arrays.asList(
                "--add-exports", "jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED",
                "-extdirs", extDirs.getPath(), // for use by filemanager handleOption
                "-processor", TestClientCodeWrapper.class.getName()
                );

        List<String> classes = Collections.emptyList();

        JavacTool tool = JavacTool.create();
        try {
            JavacTask task = tool.getTask(pw,
                    getFileManager(m, defaultFileManager),
                    getDiagnosticListener(m, pw),
                    javacOptions,
                    classes,
                    getCompilationUnits(m));

            if (isDeclaredIn(m, Processor.class))
                task.setProcessors(getProcessors(m));

            if (isDeclaredIn(m, TaskListener.class))
                task.setTaskListener(getTaskListener(m, pw));

            boolean ok = task.call();
            error("compilation " + (ok ? "succeeded" : "failed") + " unexpectedly");
        } catch (RuntimeException e) {
            System.err.println("caught " + e);
            if (e.getClass() == RuntimeException.class) {
                Throwable cause = e.getCause();
                if (cause instanceof UserError) {
                    String expect = m.getName();
                    String found = cause.getMessage();
                    checkEqual("exception messaqe", expect, found);
                } else {
                    cause.printStackTrace(System.err);
                    error("Unexpected exception: " + cause);
                }
            } else {
                e.printStackTrace(System.err);
                error("Unexpected exception: " + e);
            }
        }

        pw.close();
        String out = sw.toString();
        System.err.println(out);
    }

    /** Get a file manager to use for the test compilation. */
    JavaFileManager getFileManager(Method m, JavaFileManager defaultFileManager) {
        return isDeclaredIn(m, JavaFileManager.class, FileObject.class, JavaFileObject.class)
                ? new UserFileManager(m, defaultFileManager)
                : defaultFileManager;
    }

    /** Get a diagnostic listener to use for the test compilation. */
    DiagnosticListener<JavaFileObject> getDiagnosticListener(Method m, PrintWriter out) {
        return isDeclaredIn(m, DiagnosticListener.class)
                ? new UserDiagnosticListener(m, out)
                : null;
    }

    /** Get a set of file objects to use for the test compilation. */
    Iterable<? extends JavaFileObject> getCompilationUnits(Method m) {
        File testSrc = new File(System.getProperty("test.src"));
        File thisSrc = new File(testSrc, TestClientCodeWrapper.class.getName() + ".java");
        Iterable<? extends JavaFileObject> files = defaultFileManager.getJavaFileObjects(thisSrc);
        if (isDeclaredIn(m, FileObject.class, JavaFileObject.class))
            return Arrays.asList(new UserFileObject(m, files.iterator().next()));
        else
            return files;
    }

    /** Get a set of annotation processors to use for the test compilation. */
    Iterable<? extends Processor> getProcessors(Method m) {
        return Arrays.asList(new UserProcessor(m));
    }

    /** Get a task listener to use for the test compilation. */
    TaskListener getTaskListener(Method m, PrintWriter out) {
        return new UserTaskListener(m, out);
    }

    /** Check if two values are .equal, and report an error if not. */
    <T> void checkEqual(String label, T expect, T found) {
        if (!expect.equals(found))
            error("Unexpected value for " + label + ": " + found + "; expected: " + expect);
    }

    /** Report an error. */
    void error(String msg) {
        System.err.println("Error: " + msg);
        errors++;
    }

    /** Check if a method is declared in any of a set of classes */
    static boolean isDeclaredIn(Method m, Class<?>... classes) {
        Class<?> dc = m.getDeclaringClass();
        for (Class<?> c: classes) {
            if (c == dc) return true;
        }
        return false;
    }

    /** Throw an intentional error if the method has a given name. */
    static void throwUserExceptionIfNeeded(Method m, String name) {
        if (m != null && m.getName().equals(name))
            throw new UserError(name);
    }

    StandardJavaFileManager defaultFileManager;
    int testNum;
    int errors;

    //--------------------------------------------------------------------------

    /**
     * Processor used to trigger use of methods not normally used by javac.
     */
    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        boolean firstRound = false;
        for (Element e: roundEnv.getRootElements()) {
            if (e.getSimpleName().contentEquals(TestClientCodeWrapper.class.getSimpleName()))
                firstRound = true;
        }
        if (firstRound) {
            try {
                FileObject f1 = filer.getResource(StandardLocation.CLASS_PATH, "",
                    TestClientCodeWrapper.class.getName() + ".java");
                f1.openInputStream().close();
                f1.openReader(false).close();

                FileObject f2 = filer.createResource(
                        StandardLocation.CLASS_OUTPUT, "", "f2.txt", (Element[]) null);
                f2.openOutputStream().close();

                FileObject f3 = filer.createResource(
                        StandardLocation.CLASS_OUTPUT, "", "f3.txt", (Element[]) null);
                f3.openWriter().close();

                JavaFileObject f4 = filer.createSourceFile("f4", (Element[]) null);
                f4.openWriter().close();
                f4.getNestingKind();
                f4.getAccessLevel();

                messager.printMessage(Diagnostic.Kind.NOTE, "informational note",
                        roundEnv.getRootElements().iterator().next());

            } catch (IOException e) {
                throw new UserError(e);
            }
        }
        return true;
    }

    //--------------------------------------------------------------------------

    // <editor-fold defaultstate="collapsed" desc="User classes">

    static class UserError extends Error {
        private static final long serialVersionUID = 1L;
        UserError(String msg) {
            super(msg);
        }
        UserError(Throwable t) {
            super(t);
        }
    }

    static class UserFileManager extends ForwardingJavaFileManager<JavaFileManager> {
        Method fileManagerMethod;
        Method fileObjectMethod;

        UserFileManager(Method m, JavaFileManager delegate) {
            super(delegate);
            if (isDeclaredIn(m, JavaFileManager.class)) {
                fileManagerMethod = m;
            } else if (isDeclaredIn(m, FileObject.class, JavaFileObject.class)) {
                fileObjectMethod = m;
            } else
                assert false;
        }

        @Override
        public ClassLoader getClassLoader(Location location) {
            throwUserExceptionIfNeeded(fileManagerMethod, "getClassLoader");
            return super.getClassLoader(location);
        }

        @Override
        public <S> ServiceLoader getServiceLoader(Location location, Class<S> service) throws IOException {
            throwUserExceptionIfNeeded(fileManagerMethod, "getServiceLoader");
            return super.getServiceLoader(location, service);
        }

        @Override
        public Iterable<JavaFileObject> list(Location location, String packageName, Set<Kind> kinds, boolean recurse) throws IOException {
            throwUserExceptionIfNeeded(fileManagerMethod, "list");
            return wrap(super.list(location, packageName, kinds, recurse));
        }

        @Override
        public String inferBinaryName(Location location, JavaFileObject file) {
            throwUserExceptionIfNeeded(fileManagerMethod, "inferBinaryName");
            return super.inferBinaryName(location, unwrap(file));
        }

        @Override
        public boolean isSameFile(FileObject a, FileObject b) {
            throwUserExceptionIfNeeded(fileManagerMethod, "isSameFile");
            return super.isSameFile(unwrap(a), unwrap(b));
        }

        @Override
        public boolean handleOption(String current, Iterator<String> remaining) {
            throwUserExceptionIfNeeded(fileManagerMethod, "handleOption");
            return super.handleOption(current, remaining);
        }

        @Override
        public boolean hasLocation(Location location) {
            throwUserExceptionIfNeeded(fileManagerMethod, "hasLocation");
            return super.hasLocation(location);
        }

        @Override
        public JavaFileObject getJavaFileForInput(Location location, String className, Kind kind) throws IOException {
            throwUserExceptionIfNeeded(fileManagerMethod, "getJavaFileForInput");
            return wrap(super.getJavaFileForInput(location, className, kind));
        }

        @Override
        public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException {
            throwUserExceptionIfNeeded(fileManagerMethod, "getJavaFileForOutput");
            return wrap(super.getJavaFileForOutput(location, className, kind, sibling));
        }

        @Override
        public FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException {
            throwUserExceptionIfNeeded(fileManagerMethod, "getFileForInput");
            return wrap(super.getFileForInput(location, packageName, relativeName));
        }

        @Override
        public FileObject getFileForOutput(Location location, String packageName, String relativeName, FileObject sibling) throws IOException {
            throwUserExceptionIfNeeded(fileManagerMethod, "getFileForOutput");
            return wrap(super.getFileForOutput(location, packageName, relativeName, sibling));
        }

        @Override
        public void flush() throws IOException {
            throwUserExceptionIfNeeded(fileManagerMethod, "flush");
            super.flush();
        }

        @Override
        public void close() throws IOException {
            throwUserExceptionIfNeeded(fileManagerMethod, "close");
            super.close();
        }

        @Override
        public int isSupportedOption(String option) {
            throwUserExceptionIfNeeded(fileManagerMethod, "isSupportedOption");
            return super.isSupportedOption(option);
        }

        @Override
        public Location getLocationForModule(Location location, String moduleName) throws IOException {
            throwUserExceptionIfNeeded(fileManagerMethod, "getLocationForModule");
            return super.getLocationForModule(location, moduleName);
        }

        @Override
        public Location getLocationForModule(Location location, JavaFileObject fo) throws IOException {
            throwUserExceptionIfNeeded(fileManagerMethod, "getLocationForModule");
            return super.getLocationForModule(location, fo);
        }

        @Override
        public String inferModuleName(Location location) throws IOException {
            throwUserExceptionIfNeeded(fileManagerMethod, "inferModuleName");
            return super.inferModuleName(location);
        }

        @Override
        public Iterable<Set<Location>> listLocationsForModules(Location location) throws IOException {
            throwUserExceptionIfNeeded(fileManagerMethod, "listLocationsForModules");
            return super.listLocationsForModules(location);
        }

        @Override
        public boolean contains(Location location, FileObject fo) throws IOException {
            throwUserExceptionIfNeeded(fileManagerMethod, "contains");
            return super.contains(location, fo);
        }

        public FileObject wrap(FileObject fo) {
            if (fileObjectMethod == null || fo == null)
                return fo;
            return new UserFileObject(fileObjectMethod, (JavaFileObject)fo);
        }

        FileObject unwrap(FileObject fo) {
            if (fo instanceof UserFileObject)
                return ((UserFileObject) fo).unwrap();
            else
                return fo;
        }

        public JavaFileObject wrap(JavaFileObject fo) {
            if (fileObjectMethod == null || fo == null)
                return fo;
            return new UserFileObject(fileObjectMethod, fo);
        }

        public Iterable<JavaFileObject> wrap(Iterable<? extends JavaFileObject> list) {
            List<JavaFileObject> wrapped = new ArrayList<JavaFileObject>();
            for (JavaFileObject fo : list)
                wrapped.add(wrap(fo));
            return Collections.unmodifiableList(wrapped);
        }

        JavaFileObject unwrap(JavaFileObject fo) {
            if (fo instanceof UserFileObject)
                return ((UserFileObject) fo).unwrap();
            else
                return fo;
        }
    }

    static class UserFileObject extends ForwardingJavaFileObject<JavaFileObject> {
        Method method;

        UserFileObject(Method m, JavaFileObject delegate) {
            super(delegate);
            assert isDeclaredIn(m, FileObject.class, JavaFileObject.class);
            this.method = m;
        }

        JavaFileObject unwrap() {
            return fileObject;
        }

        @Override
        public Kind getKind() {
            throwUserExceptionIfNeeded(method, "getKind");
            return super.getKind();
        }

        @Override
        public boolean isNameCompatible(String simpleName, Kind kind) {
            throwUserExceptionIfNeeded(method, "isNameCompatible");
            return super.isNameCompatible(simpleName, kind);
        }

        @Override
        public NestingKind getNestingKind() {
            throwUserExceptionIfNeeded(method, "getNestingKind");
            return super.getNestingKind();
        }

        @Override
        public Modifier getAccessLevel() {
            throwUserExceptionIfNeeded(method, "getAccessLevel");
            return super.getAccessLevel();
        }

        @Override
        public URI toUri() {
            throwUserExceptionIfNeeded(method, "toUri");
            return super.toUri();
        }

        @Override
        public String getName() {
            throwUserExceptionIfNeeded(method, "getName");
            return super.getName();
        }

        @Override
        public InputStream openInputStream() throws IOException {
            throwUserExceptionIfNeeded(method, "openInputStream");
            return super.openInputStream();
        }

        @Override
        public OutputStream openOutputStream() throws IOException {
            throwUserExceptionIfNeeded(method, "openOutputStream");
            return super.openOutputStream();
        }

        @Override
        public Reader openReader(boolean ignoreEncodingErrors) throws IOException {
            throwUserExceptionIfNeeded(method, "openReader");
            return super.openReader(ignoreEncodingErrors);
        }

        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            throwUserExceptionIfNeeded(method, "getCharContent");
            return super.getCharContent(ignoreEncodingErrors);
        }

        @Override
        public Writer openWriter() throws IOException {
            throwUserExceptionIfNeeded(method, "openWriter");
            return super.openWriter();
        }

        @Override
        public long getLastModified() {
            throwUserExceptionIfNeeded(method, "getLastModified");
            return super.getLastModified();
        }

        @Override
        public boolean delete() {
            throwUserExceptionIfNeeded(method, "delete");
            return super.delete();
        }

    }

    static class UserProcessor extends JavacTestingAbstractProcessor {
        Method method;

        UserProcessor(Method m) {
            assert isDeclaredIn(m, Processor.class);
            method = m;
        }

        @Override
        public Set<String> getSupportedOptions() {
            throwUserExceptionIfNeeded(method, "getSupportedOptions");
            return super.getSupportedOptions();
        }

        @Override
        public Set<String> getSupportedAnnotationTypes() {
            throwUserExceptionIfNeeded(method, "getSupportedAnnotationTypes");
            return super.getSupportedAnnotationTypes();
        }

        @Override
        public SourceVersion getSupportedSourceVersion() {
            throwUserExceptionIfNeeded(method, "getSupportedSourceVersion");
            return super.getSupportedSourceVersion();
        }

        @Override
        public void init(ProcessingEnvironment processingEnv) {
            throwUserExceptionIfNeeded(method, "init");
            super.init(processingEnv);
        }

        @Override
        public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
            throwUserExceptionIfNeeded(method, "process");
            return true;
        }

        @Override
        public Iterable<? extends Completion> getCompletions(Element element, AnnotationMirror annotation, ExecutableElement member, String userText) {
            throwUserExceptionIfNeeded(method, "getCompletions");
            return super.getCompletions(element, annotation, member, userText);
        }
    }

    static class UserDiagnosticListener implements DiagnosticListener<JavaFileObject> {
        Method method;
        PrintWriter out;

        UserDiagnosticListener(Method m, PrintWriter out) {
            assert isDeclaredIn(m, DiagnosticListener.class);
            this.method = m;
            this.out = out;
        }

        @Override
        public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
            throwUserExceptionIfNeeded(method, "report");
            out.println("report: " + diagnostic);
        }
    }

    static class UserTaskListener implements TaskListener {
        Method method;
        PrintWriter out;

        UserTaskListener(Method m, PrintWriter out) {
            assert isDeclaredIn(m, TaskListener.class);
            this.method = m;
            this.out = out;
        }

        @Override
        public void started(TaskEvent e) {
            throwUserExceptionIfNeeded(method, "started");
            out.println("started: " + e);
        }

        @Override
        public void finished(TaskEvent e) {
            throwUserExceptionIfNeeded(method, "finished");
            out.println("finished: " + e);
        }
    }

    // </editor-fold>
}