changeset 4452:cdb8c9dd402f

Merge
author jjg
date Thu, 10 Nov 2016 15:58:49 -0800
parents b3e533ec494a 6afd59d40256
children 1520a026cd3e
files make/build.xml src/jdk.compiler/share/classes/com/sun/tools/javac/api/JavacTaskImpl.java src/jdk.compiler/share/classes/com/sun/tools/javac/code/Scope.java src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Modules.java src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TypeEnter.java src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassReader.java src/jdk.compiler/share/classes/com/sun/tools/javac/main/Arguments.java src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties src/jdk.compiler/share/classes/com/sun/tools/javac/resources/javac.properties src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/Start.java src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/ToolOption.java src/jdk.jshell/share/classes/jdk/internal/jshell/tool/EditPad.java src/jdk.jshell/share/classes/jdk/internal/jshell/tool/ExternalEditor.java src/jdk.jshell/share/classes/jdk/jshell/execution/JDIDefaultExecutionControl.java src/jdk.jshell/share/classes/jdk/jshell/execution/JDIEventHandler.java src/jdk.jshell/share/classes/jdk/jshell/execution/JDIExecutionControl.java src/jdk.jshell/share/classes/jdk/jshell/execution/JDIInitiator.java src/jdk.jshell/share/classes/module-info.java test/jdk/javadoc/tool/modules/Modules.java test/jdk/jshell/EditorPadTest.java test/jdk/jshell/JDILaunchingExecutionControlTest.java test/jdk/jshell/JDIListeningExecutionControlTest.java test/jdk/jshell/JDIListeningLocalhostExecutionControlTest.java test/jdk/jshell/ToolFormatTest.java test/jdk/jshell/UserJDIUserRemoteTest.java test/tools/javac/T6403466.java test/tools/javac/diags/Example.java test/tools/javac/diags/examples/CantFindModule/CantFindModule.java test/tools/javac/diags/examples/ServiceDefinitionInner/ServiceDefinitionInner.java test/tools/javac/diags/examples/ServiceDefinitionInner/modulesourcepath/m/module-info.java test/tools/javac/diags/examples/ServiceDefinitionInner/modulesourcepath/m/p1/C1.java test/tools/javac/diags/examples/ServiceDefinitionInner/modulesourcepath/m/p2/C2.java test/tools/javac/diags/examples/XaddexportsMalformedEntry.java test/tools/javac/diags/examples/XaddexportsTooMany.java test/tools/javac/diags/examples/XaddreadsMalformedEntry.java test/tools/javac/diags/examples/XaddreadsTooMany.java test/tools/javac/modules/AddLimitMods.java test/tools/javac/modules/AddReadsTest.java test/tools/javac/modules/AnnotationProcessorsInModulesTest.java test/tools/javac/modules/AutomaticModules.java test/tools/javac/modules/EdgeCases.java test/tools/javac/modules/GraphsTest.java test/tools/javac/modules/ModuleTestBase.java test/tools/javac/modules/PackageMultipleModules.java test/tools/javac/modules/PatchModulesTest.java test/tools/javac/modules/ProvidesTest.java test/tools/javac/modules/RequiresTransitiveTest.java test/tools/javac/modules/ResolveTest.java test/tools/javac/modules/T8168854/pack1/Outer.java test/tools/javac/modules/T8168854/pack1/Outer1.java test/tools/javac/modules/UsesTest.java test/tools/javac/modules/XModuleTest.java test/tools/javac/processing/model/LocalClasses/LocalClassesModel.java
diffstat 93 files changed, 4230 insertions(+), 2430 deletions(-) [+]
line wrap: on
line diff
--- a/make/build.xml	Wed Nov 09 21:20:20 2016 +0100
+++ b/make/build.xml	Thu Nov 10 15:58:49 2016 -0800
@@ -84,17 +84,21 @@
     <property name="build.prevsrc" location="${build.dir}/prevsrc"/>
 
     <pathconvert property="modules.names" pathsep=",">
-        <globmapper from="${src.dir}/*" to="*" />
+        <globmapper from="${src.dir}/*" to="*" handledirsep="yes"/>
         <dirset dir="${src.dir}" includes="*.*"/>
     </pathconvert>
 
     <pathconvert property="xpatch.rest" pathsep=" --patch-module=">
-        <regexpmapper from="${file.separator}([^${file.separator}]+)$" to='\1="${build.modules}${file.separator}\1"' />
+        <regexpmapper from="/([^$/]+)$"
+                      to='\1="${build.modules}/\1"'
+                      handledirsep="yes"/>
         <dirset dir="${src.dir}" includes="*.*"/>
     </pathconvert>
 
     <pathconvert property="xpatch.noquotes.rest" pathsep=" --patch-module=">
-        <regexpmapper from="${file.separator}([^${file.separator}]+)$" to="\1=${build.modules}${file.separator}\1" />
+        <regexpmapper from="/([^$/]+)$"
+                      to="\1=${build.modules}/\1"
+                      handledirsep="yes"/>
         <dirset dir="${src.dir}" includes="*.*"/>
     </pathconvert>
 
@@ -207,7 +211,9 @@
             <arg line="-source ${javac.source} -target ${javac.target}" />
             <arg value="-d" />
             <arg value="${build.modules}" />
-            <arg line="${javac.opts} --module-source-path ${src.dir}${file.separator}*${file.separator}share${file.separator}classes:${build.gensrc} -m ${modules.names}" />
+            <arg line="${javac.opts}" />
+            <arg line="--module-source-path ${src.dir}${file.separator}*${file.separator}share${file.separator}classes${path.separator}${build.gensrc}" />
+            <arg line="-m ${modules.names}" />
         </exec>
         <delete>
             <fileset dir="${build.modules}" includes="**/module-info.class"/>
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/api/JavacTaskImpl.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/api/JavacTaskImpl.java	Thu Nov 10 15:58:49 2016 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, 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
@@ -101,6 +101,8 @@
                 @Override
                 public Main.Result call() throws Exception {
                     prepareCompiler(false);
+                    if (compiler.errorCount() > 0)
+                        return Main.Result.ERROR;
                     compiler.compile(args.getFileObjects(), args.getClassNames(), processors);
                     return (compiler.errorCount() > 0) ? Main.Result.ERROR : Main.Result.OK; // FIXME?
                 }
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Scope.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Scope.java	Thu Nov 10 15:58:49 2016 -0800
@@ -137,12 +137,18 @@
     /** Returns true iff the given Symbol is in this scope or any outward scope.
      */
     public boolean includes(final Symbol sym) {
+        return includes(sym, RECURSIVE);
+    }
+
+    /** Returns true iff the given Symbol is in this scope, optionally checking outward scopes.
+     */
+    public boolean includes(final Symbol sym, LookupKind lookupKind) {
         return getSymbolsByName(sym.name, new Filter<Symbol>() {
             @Override
             public boolean accepts(Symbol t) {
                 return t == sym;
             }
-        }).iterator().hasNext();
+        }, lookupKind).iterator().hasNext();
     }
 
     /** Returns true iff this scope does not contain any Symbol. Does not inspect outward scopes.
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Modules.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Modules.java	Thu Nov 10 15:58:49 2016 -0800
@@ -36,7 +36,6 @@
 import java.util.LinkedHashMap;
 import java.util.LinkedHashSet;
 import java.util.Map;
-import java.util.Map.Entry;
 import java.util.Set;
 import java.util.function.Consumer;
 import java.util.function.Predicate;
@@ -63,6 +62,7 @@
 import com.sun.tools.javac.code.Directive.UsesDirective;
 import com.sun.tools.javac.code.Flags;
 import com.sun.tools.javac.code.Kinds;
+import com.sun.tools.javac.code.Lint.LintCategory;
 import com.sun.tools.javac.code.ModuleFinder;
 import com.sun.tools.javac.code.Source;
 import com.sun.tools.javac.code.Symbol;
@@ -138,6 +138,7 @@
     private final Types types;
     private final JavaFileManager fileManager;
     private final ModuleFinder moduleFinder;
+    private final Source source;
     private final boolean allowModules;
 
     public final boolean multiModuleMode;
@@ -158,6 +159,8 @@
     private final String limitModsOpt;
     private final Set<String> extraLimitMods = new HashSet<>();
 
+    private final boolean lintOptions;
+
     private Set<ModuleSymbol> rootModules = null;
 
     public static Modules instance(Context context) {
@@ -179,9 +182,12 @@
         moduleFinder = ModuleFinder.instance(context);
         types = Types.instance(context);
         fileManager = context.get(JavaFileManager.class);
-        allowModules = Source.instance(context).allowModules();
+        source = Source.instance(context);
+        allowModules = source.allowModules();
         Options options = Options.instance(context);
 
+        lintOptions = options.isUnset(Option.XLINT_CUSTOM, "-" + LintCategory.OPTIONS.option);
+
         moduleOverride = options.get(Option.XMODULE);
 
         multiModuleMode = fileManager.hasLocation(StandardLocation.MODULE_SOURCE_PATH);
@@ -497,7 +503,7 @@
             ModuleSymbol msym = moduleFinder.findModule((ModuleSymbol) sym);
 
             if (msym.kind == Kinds.Kind.ERR) {
-                log.error(Errors.CantFindModule(msym));
+                log.error(Errors.ModuleNotFound(msym));
                 //make sure the module is initialized:
                 msym.directives = List.nil();
                 msym.exports = List.nil();
@@ -867,8 +873,6 @@
                         log.error(implName.pos(), Errors.ServiceImplementationIsAbstract(impl));
                     } else if (impl.isInner()) {
                         log.error(implName.pos(), Errors.ServiceImplementationIsInner(impl));
-                    } else if (service.isInner()) {
-                        log.error(tree.serviceName.pos(), Errors.ServiceDefinitionIsInner(service));
                     } else {
                         MethodSymbol constr = noArgsConstructor(impl);
                         if (constr == null) {
@@ -989,6 +993,8 @@
             Set<ModuleSymbol> limitMods = new HashSet<>();
             if (limitModsOpt != null) {
                 for (String limit : limitModsOpt.split(",")) {
+                    if (!isValidName(limit))
+                        continue;
                     limitMods.add(syms.enterModule(names.fromString(limit)));
                 }
             }
@@ -997,6 +1003,14 @@
             }
             observable = computeTransitiveClosure(limitMods, null);
             observable.addAll(rootModules);
+            if (lintOptions) {
+                for (ModuleSymbol msym : limitMods) {
+                    if (!observable.contains(msym)) {
+                        log.warning(LintCategory.OPTIONS,
+                                Warnings.ModuleForOptionNotFound(Option.LIMIT_MODULES, msym));
+                    }
+                }
+            }
         }
 
         Predicate<ModuleSymbol> observablePred = sym -> observable == null || observable.contains(sym);
@@ -1049,6 +1063,8 @@
                                       .filter(systemModulePred.negate().and(observablePred));
                         break;
                     default:
+                        if (!isValidName(added))
+                            continue;
                         modules = Stream.of(syms.enterModule(names.fromString(added)));
                         break;
                 }
@@ -1253,8 +1269,9 @@
             addVisiblePackages(msym, seen, rm, rm.exports);
         }
 
-        for (Entry<ModuleSymbol, Set<ExportsDirective>> addExportsEntry : addExports.entrySet())
-            addVisiblePackages(msym, seen, addExportsEntry.getKey(), addExportsEntry.getValue());
+        addExports.forEach((exportsFrom, exports) -> {
+            addVisiblePackages(msym, seen, exportsFrom, exports);
+        });
     }
 
     private void addVisiblePackages(ModuleSymbol msym,
@@ -1292,12 +1309,11 @@
             return;
 
         addExports = new LinkedHashMap<>();
+        Set<ModuleSymbol> unknownModules = new HashSet<>();
 
         if (addExportsOpt == null)
             return;
 
-//        System.err.println("Modules.addExports:\n   " + addExportsOpt.replace("\0", "\n   "));
-
         Pattern ep = Pattern.compile("([^/]+)/([^=]+)=(.*)");
         for (String s: addExportsOpt.split("\0+")) {
             if (s.isEmpty())
@@ -1315,7 +1331,15 @@
             String packageName = em.group(2);
             String targetNames = em.group(3);
 
+            if (!isValidName(moduleName))
+                continue;
+
             ModuleSymbol msym = syms.enterModule(names.fromString(moduleName));
+            if (!isKnownModule(msym, unknownModules))
+                continue;
+
+            if (!isValidName(packageName))
+                continue;
             PackageSymbol p = syms.enterPackage(msym, names.fromString(packageName));
             p.modle = msym;  // TODO: do we need this?
 
@@ -1325,11 +1349,11 @@
                 if (toModule.equals("ALL-UNNAMED")) {
                     m = syms.unnamedModule;
                 } else {
-                    if (!SourceVersion.isName(toModule)) {
-                        // TODO: error: invalid module name
+                    if (!isValidName(toModule))
                         continue;
-                    }
                     m = syms.enterModule(names.fromString(toModule));
+                    if (!isKnownModule(m, unknownModules))
+                        continue;
                 }
                 targetModules = targetModules.prepend(m);
             }
@@ -1340,6 +1364,21 @@
         }
     }
 
+    private boolean isKnownModule(ModuleSymbol msym, Set<ModuleSymbol> unknownModules) {
+        if (allModules.contains(msym)) {
+            return true;
+        }
+
+        if (!unknownModules.contains(msym)) {
+            if (lintOptions) {
+                log.warning(LintCategory.OPTIONS,
+                        Warnings.ModuleForOptionNotFound(Option.ADD_EXPORTS, msym));
+            }
+            unknownModules.add(msym);
+        }
+        return false;
+    }
+
     private void initAddReads() {
         if (addReads != null)
             return;
@@ -1349,8 +1388,6 @@
         if (addReadsOpt == null)
             return;
 
-//        System.err.println("Modules.addReads:\n   " + addReadsOpt.replace("\0", "\n   "));
-
         Pattern rp = Pattern.compile("([^=]+)=(.*)");
         for (String s : addReadsOpt.split("\0+")) {
             if (s.isEmpty())
@@ -1361,26 +1398,40 @@
             }
 
             // Terminology comes from
-            //  --add-reads target-module=source-module,...
+            //  --add-reads source-module=target-module,...
             // Compare to
-            //  module target-module { requires source-module; ... }
-            String targetName = rm.group(1);
-            String sources = rm.group(2);
+            //  module source-module { requires target-module; ... }
+            String sourceName = rm.group(1);
+            String targetNames = rm.group(2);
 
-            ModuleSymbol msym = syms.enterModule(names.fromString(targetName));
-            for (String source : sources.split("[ ,]+")) {
-                ModuleSymbol sourceModule;
-                if (source.equals("ALL-UNNAMED")) {
-                    sourceModule = syms.unnamedModule;
+            if (!isValidName(sourceName))
+                continue;
+
+            ModuleSymbol msym = syms.enterModule(names.fromString(sourceName));
+            if (!allModules.contains(msym)) {
+                if (lintOptions) {
+                    log.warning(Warnings.ModuleForOptionNotFound(Option.ADD_READS, msym));
+                }
+                continue;
+            }
+
+            for (String targetName : targetNames.split("[ ,]+", -1)) {
+                ModuleSymbol targetModule;
+                if (targetName.equals("ALL-UNNAMED")) {
+                    targetModule = syms.unnamedModule;
                 } else {
-                    if (!SourceVersion.isName(source)) {
-                        // TODO: error: invalid module name
+                    if (!isValidName(targetName))
+                        continue;
+                    targetModule = syms.enterModule(names.fromString(targetName));
+                    if (!allModules.contains(targetModule)) {
+                        if (lintOptions) {
+                            log.warning(LintCategory.OPTIONS, Warnings.ModuleForOptionNotFound(Option.ADD_READS, targetModule));
+                        }
                         continue;
                     }
-                    sourceModule = syms.enterModule(names.fromString(source));
                 }
                 addReads.computeIfAbsent(msym, m -> new HashSet<>())
-                        .add(new RequiresDirective(sourceModule, EnumSet.of(RequiresFlag.EXTRA)));
+                        .add(new RequiresDirective(targetModule, EnumSet.of(RequiresFlag.EXTRA)));
             }
         }
     }
@@ -1413,6 +1464,10 @@
         }
     }
 
+    private boolean isValidName(CharSequence name) {
+        return SourceVersion.isName(name, Source.toSourceVersion(source));
+    }
+
     // DEBUG
     private String toString(ModuleSymbol msym) {
         return msym.name + "["
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java	Thu Nov 10 15:58:49 2016 -0800
@@ -554,7 +554,8 @@
         } else if (mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
             ForAll pmt = (ForAll) mt;
             if (typeargtypes.length() != pmt.tvars.length())
-                throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
+                 // not enough args
+                throw inapplicableMethodException.setMessage("wrong.number.type.args", Integer.toString(pmt.tvars.length()));
             // Check type arguments are within bounds
             List<Type> formals = pmt.tvars;
             List<Type> actuals = typeargtypes;
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassReader.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassReader.java	Thu Nov 10 15:58:49 2016 -0800
@@ -63,6 +63,7 @@
 
 import static com.sun.tools.javac.code.Flags.*;
 import static com.sun.tools.javac.code.Kinds.Kind.*;
+import com.sun.tools.javac.code.Scope.LookupKind;
 import static com.sun.tools.javac.code.TypeTag.ARRAY;
 import static com.sun.tools.javac.code.TypeTag.CLASS;
 import static com.sun.tools.javac.code.TypeTag.TYPEVAR;
@@ -1380,7 +1381,7 @@
         } else {
             ((ClassType)sym.type).setEnclosingType(Type.noType);
         }
-        enterTypevars(self);
+        enterTypevars(self, self.type);
         if (!missingTypeVariables.isEmpty()) {
             ListBuffer<Type> typeVars =  new ListBuffer<>();
             for (Type typevar : missingTypeVariables) {
@@ -2293,7 +2294,11 @@
             // Sometimes anonymous classes don't have an outer
             // instance, however, there is no reliable way to tell so
             // we never strip this$n
-            if (!currentOwner.name.isEmpty())
+            // ditto for local classes. Local classes that have an enclosing method set
+            // won't pass the "hasOuterInstance" check above, but those that don't have an
+            // enclosing method (i.e. from initializers) will pass that check.
+            boolean local = !currentOwner.owner.members().includes(currentOwner, LookupKind.NON_RECURSIVE);
+            if (!currentOwner.name.isEmpty() && !local)
                 type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()),
                                       type.getReturnType(),
                                       type.getThrownTypes(),
@@ -2460,19 +2465,17 @@
     /** Enter type variables of this classtype and all enclosing ones in
      *  `typevars'.
      */
-    protected void enterTypevars(Type t) {
-        if (t.getEnclosingType() != null && t.getEnclosingType().hasTag(CLASS))
-            enterTypevars(t.getEnclosingType());
-        for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail)
+    protected void enterTypevars(Symbol sym, Type t) {
+        if (t.getEnclosingType() != null) {
+            if (!t.getEnclosingType().hasTag(TypeTag.NONE)) {
+                enterTypevars(sym.owner, t.getEnclosingType());
+            }
+        } else if (sym.kind == MTH && !sym.isStatic()) {
+            enterTypevars(sym.owner, sym.owner.type);
+        }
+        for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail) {
             typevars.enter(xs.head.tsym);
-    }
-
-    protected void enterTypevars(Symbol sym) {
-        if (sym.owner.kind == MTH) {
-            enterTypevars(sym.owner);
-            enterTypevars(sym.owner.owner);
         }
-        enterTypevars(sym.type);
     }
 
     protected ClassSymbol enterClass(Name name) {
@@ -2495,7 +2498,7 @@
         // prepare type variable table
         typevars = typevars.dup(currentOwner);
         if (ct.getEnclosingType().hasTag(CLASS))
-            enterTypevars(ct.getEnclosingType());
+            enterTypevars(c.owner, ct.getEnclosingType());
 
         // read flags, or skip if this is an inner class
         long f = nextChar();
@@ -2654,6 +2657,11 @@
                     types.subst(ct.supertype_field, missing, found);
                 ct.interfaces_field =
                     types.subst(ct.interfaces_field, missing, found);
+                ct.typarams_field =
+                    types.substBounds(ct.typarams_field, missing, found);
+                for (List<Type> types = ct.typarams_field; types.nonEmpty(); types = types.tail) {
+                    types.head.tsym.type = types.head;
+                }
             } else if (missingTypeVariables.isEmpty() !=
                        foundTypeVariables.isEmpty()) {
                 Name name = missingTypeVariables.head.tsym.name;
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Arguments.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Arguments.java	Thu Nov 10 15:58:49 2016 -0800
@@ -43,6 +43,7 @@
 import java.util.regex.Pattern;
 import java.util.stream.Stream;
 
+import javax.lang.model.SourceVersion;
 import javax.tools.JavaFileManager;
 import javax.tools.JavaFileManager.Location;
 import javax.tools.JavaFileObject;
@@ -400,7 +401,7 @@
     /**
      * Validates the overall consistency of the options and operands
      * processed by processOptions.
-     * @return true if all args are successfully validating; false otherwise.
+     * @return true if all args are successfully validated; false otherwise.
      * @throws IllegalStateException if a problem is found and errorMode is set to
      *      ILLEGAL_STATE
      */
@@ -611,65 +612,147 @@
             log.warning(LintCategory.OPTIONS, "option.obsolete.suppression");
         }
 
-        String addExports = options.get(Option.ADD_EXPORTS);
-        if (addExports != null) {
-            // Each entry must be of the form module/package=target-list where target-list is a
-            // comma-separated list of module or ALL-UNNAMED.
-            // All module/package pairs must be unique.
-            Pattern p = Pattern.compile("([^/]+)/([^=]+)=(.*)");
-            Map<String,List<String>> map = new LinkedHashMap<>();
-            for (String e: addExports.split("\0")) {
-                Matcher m = p.matcher(e);
-                if (!m.matches()) {
-                    log.error(Errors.XaddexportsMalformedEntry(e));
-                    continue;
-                }
-                String eModule = m.group(1);  // TODO: check a valid dotted identifier
-                String ePackage = m.group(2); // TODO: check a valid dotted identifier
-                String eTargets = m.group(3);  // TODO: check a valid list of dotted identifier or ALL-UNNAMED
-                String eModPkg = eModule + '/' + ePackage;
-                List<String> l = map.get(eModPkg);
-                map.put(eModPkg, (l == null) ? List.of(eTargets) : l.prepend(eTargets));
-            }
-            map.forEach((key, value) -> {
-                if (value.size() > 1) {
-                    log.error(Errors.XaddexportsTooMany(key));
-                    // TODO: consider adding diag fragments for the entries
-                }
-            });
-        }
-
-        String addReads = options.get(Option.ADD_READS);
-        if (addReads != null) {
-            // Each entry must be of the form module=source-list where source-list is a
-            // comma separated list of module or ALL-UNNAMED.
-            // All target modules (i.e. on left of '=')  must be unique.
-            Pattern p = Pattern.compile("([^=]+)=(.*)");
-            Map<String,List<String>> map = new LinkedHashMap<>();
-            for (String e: addReads.split("\0")) {
-                Matcher m = p.matcher(e);
-                if (!m.matches()) {
-                    log.error(Errors.XaddreadsMalformedEntry(e));
-                    continue;
-                }
-                String eModule = m.group(1);  // TODO: check a valid dotted identifier
-                String eSources = m.group(2);  // TODO: check a valid list of dotted identifier or ALL-UNNAMED
-                List<String> l = map.get(eModule);
-                map.put(eModule, (l == null) ? List.of(eSources) : l.prepend(eSources));
-            }
-            map.forEach((key, value) -> {
-                if (value.size() > 1) {
-                    log.error(Errors.XaddreadsTooMany(key));
-                    // TODO: consider adding diag fragments for the entries
-                }
-            });
-        }
+        SourceVersion sv = Source.toSourceVersion(source);
+        validateAddExports(sv);
+        validateAddModules(sv);
+        validateAddReads(sv);
+        validateLimitModules(sv);
 
         if (lintOptions && options.isSet(Option.ADD_OPENS)) {
             log.warning(LintCategory.OPTIONS, Warnings.AddopensIgnored);
         }
 
-        return !errors;
+        return !errors && (log.nerrors == 0);
+    }
+
+    private void validateAddExports(SourceVersion sv) {
+        String addExports = options.get(Option.ADD_EXPORTS);
+        if (addExports != null) {
+            // Each entry must be of the form sourceModule/sourcePackage=target-list where
+            // target-list is a comma separated list of module or ALL-UNNAMED.
+            // Empty items in the target-list are ignored.
+            // There must be at least one item in the list; this is handled in Option.ADD_EXPORTS.
+            Pattern p = Option.ADD_EXPORTS.getPattern();
+            for (String e : addExports.split("\0")) {
+                Matcher m = p.matcher(e);
+                if (m.matches()) {
+                    String sourceModuleName = m.group(1);
+                    if (!SourceVersion.isName(sourceModuleName, sv)) {
+                        // syntactically invalid source name:  e.g. --add-exports m!/p1=m2
+                        log.warning(Warnings.BadNameForOption(Option.ADD_EXPORTS, sourceModuleName));
+                    }
+                    String sourcePackageName = m.group(2);
+                    if (!SourceVersion.isName(sourcePackageName, sv)) {
+                        // syntactically invalid source name:  e.g. --add-exports m1/p!=m2
+                        log.warning(Warnings.BadNameForOption(Option.ADD_EXPORTS, sourcePackageName));
+                    }
+
+                    String targetNames = m.group(3);
+                    for (String targetName : targetNames.split(",")) {
+                        switch (targetName) {
+                            case "":
+                            case "ALL-UNNAMED":
+                                break;
+
+                            default:
+                                if (!SourceVersion.isName(targetName, sv)) {
+                                    // syntactically invalid target name:  e.g. --add-exports m1/p1=m!
+                                    log.warning(Warnings.BadNameForOption(Option.ADD_EXPORTS, targetName));
+                                }
+                                break;
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    private void validateAddReads(SourceVersion sv) {
+        String addReads = options.get(Option.ADD_READS);
+        if (addReads != null) {
+            // Each entry must be of the form source=target-list where target-list is a
+            // comma-separated list of module or ALL-UNNAMED.
+            // Empty items in the target list are ignored.
+            // There must be at least one item in the list; this is handled in Option.ADD_READS.
+            Pattern p = Option.ADD_READS.getPattern();
+            for (String e : addReads.split("\0")) {
+                Matcher m = p.matcher(e);
+                if (m.matches()) {
+                    String sourceName = m.group(1);
+                    if (!SourceVersion.isName(sourceName, sv)) {
+                        // syntactically invalid source name:  e.g. --add-reads m!=m2
+                        log.warning(Warnings.BadNameForOption(Option.ADD_READS, sourceName));
+                    }
+
+                    String targetNames = m.group(2);
+                    for (String targetName : targetNames.split(",", -1)) {
+                        switch (targetName) {
+                            case "":
+                            case "ALL-UNNAMED":
+                                break;
+
+                            default:
+                                if (!SourceVersion.isName(targetName, sv)) {
+                                    // syntactically invalid target name:  e.g. --add-reads m1=m!
+                                    log.warning(Warnings.BadNameForOption(Option.ADD_READS, targetName));
+                                }
+                                break;
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    private void validateAddModules(SourceVersion sv) {
+        String addModules = options.get(Option.ADD_MODULES);
+        if (addModules != null) {
+            // Each entry must be of the form target-list where target-list is a
+            // comma separated list of module names, or ALL-DEFAULT, ALL-SYSTEM,
+            // or ALL-MODULE_PATH.
+            // Empty items in the target list are ignored.
+            // There must be at least one item in the list; this is handled in Option.ADD_MODULES.
+            for (String moduleName : addModules.split(",")) {
+                switch (moduleName) {
+                    case "":
+                    case "ALL-DEFAULT":
+                    case "ALL-SYSTEM":
+                    case "ALL-MODULE-PATH":
+                        break;
+
+                    default:
+                        if (!SourceVersion.isName(moduleName, sv)) {
+                            // syntactically invalid module name:  e.g. --add-modules m1,m!
+                            log.warning(Warnings.BadNameForOption(Option.ADD_MODULES, moduleName));
+                        }
+                        break;
+                }
+            }
+        }
+    }
+
+    private void validateLimitModules(SourceVersion sv) {
+        String limitModules = options.get(Option.LIMIT_MODULES);
+        if (limitModules != null) {
+            // Each entry must be of the form target-list where target-list is a
+            // comma separated list of module names, or ALL-DEFAULT, ALL-SYSTEM,
+            // or ALL-MODULE_PATH.
+            // Empty items in the target list are ignored.
+            // There must be at least one item in the list; this is handled in Option.LIMIT_EXPORTS.
+            for (String moduleName : limitModules.split(",")) {
+                switch (moduleName) {
+                    case "":
+                        break;
+
+                    default:
+                        if (!SourceVersion.isName(moduleName, sv)) {
+                            // syntactically invalid module name:  e.g. --limit-modules m1,m!
+                            log.warning(Warnings.BadNameForOption(Option.LIMIT_MODULES, moduleName));
+                        }
+                        break;
+                }
+            }
+        }
     }
 
     /**
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java	Thu Nov 10 15:58:49 2016 -0800
@@ -35,6 +35,7 @@
 import java.util.Collections;
 import java.util.Comparator;
 import java.util.EnumSet;
+import java.util.HashSet;
 import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.LinkedHashSet;
@@ -43,6 +44,8 @@
 import java.util.ServiceLoader;
 import java.util.Set;
 import java.util.TreeSet;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 import java.util.stream.Collectors;
 import java.util.stream.StreamSupport;
 
@@ -199,31 +202,37 @@
         // The standard file manager code knows to split apart the NULL-separated components.
         @Override
         public boolean process(OptionHelper helper, String option, String arg) {
-            if (!arg.contains("=")) { // could be more strict regeex, e.g. "(?i)[a-z0-9_.]+=.*"
-                helper.error(Errors.LocnInvalidArgForXpatch(arg));
+            if (arg.isEmpty()) {
+                helper.error("err.no.value.for.option", option);
+                return true;
+            } else if (getPattern().matcher(arg).matches()) {
+                String prev = helper.get(PATCH_MODULE);
+                if (prev == null) {
+                    super.process(helper, option, arg);
+                    return false;
+                } else {
+                    String argModulePackage = arg.substring(0, arg.indexOf('='));
+                    boolean isRepeated = Arrays.stream(prev.split("\0"))
+                            .map(s -> s.substring(0, s.indexOf('=')))
+                            .collect(Collectors.toSet())
+                            .contains(argModulePackage);
+                    if (isRepeated) {
+                        helper.error("err.repeated.value.for.patch.module", argModulePackage);
+                        return true;
+                    } else {
+                        super.process(helper, option, prev + '\0' + arg);
+                        return false;
+                    }
+                }
+            } else {
+                helper.error("err.bad.value.for.option", option, arg);
+                return true;
             }
+        }
 
-            String previous = helper.get(this);
-            if (previous == null) {
-                return super.process(helper, option, arg);
-            }
-
-            Map<String,String> map = new LinkedHashMap<>();
-            for (String s : previous.split("\0")) {
-                int sep = s.indexOf('=');
-                map.put(s.substring(0, sep), s.substring(sep + 1));
-            }
-
-            int sep = arg.indexOf('=');
-            map.put(arg.substring(0, sep), arg.substring(sep + 1));
-
-            StringBuilder sb = new StringBuilder();
-            map.forEach((m, p) -> {
-                if (sb.length() > 0)
-                    sb.append('\0');
-                sb.append(m).append('=').append(p);
-            });
-            return super.process(helper, option, sb.toString());
+        @Override
+        public Pattern getPattern() {
+            return Pattern.compile("([^/]+)=(,*[^,].*)");
         }
     },
 
@@ -556,9 +565,22 @@
     ADD_EXPORTS("--add-exports", "opt.arg.addExports", "opt.addExports", EXTENDED, BASIC) {
         @Override
         public boolean process(OptionHelper helper, String option, String arg) {
-            String prev = helper.get(ADD_EXPORTS);
-            helper.put(ADD_EXPORTS.primaryName, (prev == null) ? arg : prev + '\0' + arg);
-            return false;
+            if (arg.isEmpty()) {
+                helper.error("err.no.value.for.option", option);
+                return true;
+            } else if (getPattern().matcher(arg).matches()) {
+                String prev = helper.get(ADD_EXPORTS);
+                helper.put(ADD_EXPORTS.primaryName, (prev == null) ? arg : prev + '\0' + arg);
+                return false;
+            } else {
+                helper.error("err.bad.value.for.option", option, arg);
+                return true;
+            }
+        }
+
+        @Override
+        public Pattern getPattern() {
+            return Pattern.compile("([^/]+)/([^=]+)=(,*[^,].*)");
         }
     },
 
@@ -567,9 +589,22 @@
     ADD_READS("--add-reads", "opt.arg.addReads", "opt.addReads", EXTENDED, BASIC) {
         @Override
         public boolean process(OptionHelper helper, String option, String arg) {
-            String prev = helper.get(ADD_READS);
-            helper.put(ADD_READS.primaryName, (prev == null) ? arg : prev + '\0' + arg);
-            return false;
+            if (arg.isEmpty()) {
+                helper.error("err.no.value.for.option", option);
+                return true;
+            } else if (getPattern().matcher(arg).matches()) {
+                String prev = helper.get(ADD_READS);
+                helper.put(ADD_READS.primaryName, (prev == null) ? arg : prev + '\0' + arg);
+                return false;
+            } else {
+                helper.error("err.bad.value.for.option", option, arg);
+                return true;
+            }
+        }
+
+        @Override
+        public Pattern getPattern() {
+            return Pattern.compile("([^=]+)=(,*[^,].*)");
         }
     },
 
@@ -579,6 +614,7 @@
             String prev = helper.get(XMODULE);
             if (prev != null) {
                 helper.error("err.option.too.many", XMODULE.primaryName);
+                return true;
             }
             helper.put(XMODULE.primaryName, arg);
             return false;
@@ -587,9 +623,50 @@
 
     MODULE("--module -m", "opt.arg.m", "opt.m", STANDARD, BASIC),
 
-    ADD_MODULES("--add-modules", "opt.arg.addmods", "opt.addmods", STANDARD, BASIC),
+    ADD_MODULES("--add-modules", "opt.arg.addmods", "opt.addmods", STANDARD, BASIC) {
+        @Override
+        public boolean process(OptionHelper helper, String option, String arg) {
+            if (arg.isEmpty()) {
+                helper.error("err.no.value.for.option", option);
+                return true;
+            } else if (getPattern().matcher(arg).matches()) {
+                String prev = helper.get(ADD_MODULES);
+                // since the individual values are simple names, we can simply join the
+                // values of multiple --add-modules options with ','
+                helper.put(ADD_MODULES.primaryName, (prev == null) ? arg : prev + ',' + arg);
+                return false;
+            } else {
+                helper.error("err.bad.value.for.option", option, arg);
+                return true;
+            }
+        }
 
-    LIMIT_MODULES("--limit-modules", "opt.arg.limitmods", "opt.limitmods", STANDARD, BASIC),
+        @Override
+        public Pattern getPattern() {
+            return Pattern.compile(",*[^,].*");
+        }
+    },
+
+    LIMIT_MODULES("--limit-modules", "opt.arg.limitmods", "opt.limitmods", STANDARD, BASIC) {
+        @Override
+        public boolean process(OptionHelper helper, String option, String arg) {
+            if (arg.isEmpty()) {
+                helper.error("err.no.value.for.option", option);
+                return true;
+            } else if (getPattern().matcher(arg).matches()) {
+                helper.put(LIMIT_MODULES.primaryName, arg); // last one wins
+                return false;
+            } else {
+                helper.error("err.bad.value.for.option", option, arg);
+                return true;
+            }
+        }
+
+        @Override
+        public Pattern getPattern() {
+            return Pattern.compile(",*[^,].*");
+        }
+    },
 
     // This option exists only for the purpose of documenting itself.
     // It's actually implemented by the CommandLine class.
@@ -965,20 +1042,24 @@
      */
     public boolean handleOption(OptionHelper helper, String arg, Iterator<String> rest) {
         if (hasArg()) {
+            String option;
             String operand;
             int sep = findSeparator(arg);
             if (getArgKind() == Option.ArgKind.ADJACENT) {
+                option = primaryName; // aliases not supported
                 operand = arg.substring(primaryName.length());
             } else if (sep > 0) {
+                option = arg.substring(0, sep);
                 operand = arg.substring(sep + 1);
             } else {
                 if (!rest.hasNext()) {
                     helper.error("err.req.arg", arg);
                     return false;
                 }
+                option = arg;
                 operand = rest.next();
             }
-            return !process(helper, arg, operand);
+            return !process(helper, option, operand);
         } else {
             return !process(helper, arg);
         }
@@ -1035,6 +1116,15 @@
     }
 
     /**
+     * Returns a pattern to analyze the value for an option.
+     * @return the pattern
+     * @throws UnsupportedOperationException if an option does not provide a pattern.
+     */
+    public Pattern getPattern() {
+        throw new UnsupportedOperationException();
+    }
+
+    /**
      * Scans a word to find the first separator character, either colon or equals.
      * @param word the word to be scanned
      * @return the position of the first':' or '=' character in the word,
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties	Thu Nov 10 15:58:49 2016 -0800
@@ -2138,6 +2138,10 @@
 compiler.misc.arg.length.mismatch=\
     actual and formal argument lists differ in length
 
+# 0: string
+compiler.misc.wrong.number.type.args=\
+    wrong number of type arguments; required {0}
+
 # 0: message segment
 compiler.misc.no.conforming.assignment.exists=\
     argument mismatch; {0}
@@ -2791,10 +2795,6 @@
     the service implementation is an inner class: {0}
 
 # 0: symbol
-compiler.err.service.definition.is.inner=\
-    the service definition is an inner class: {0}
-
-# 0: symbol
 compiler.err.service.definition.is.enum=\
     the service definition is an enum: {0}
 
@@ -2869,21 +2869,13 @@
 compiler.err.duplicate.module.on.path=\
     duplicate module on {0}\nmodule in {1}
 
-# 0:  string
-compiler.err.xaddexports.malformed.entry=\
-    bad value for --add-exports {0}
-
-# 0: string
-compiler.err.xaddexports.too.many=\
-    multiple --add-exports options for {0}
-
-# 0:  string
-compiler.err.xaddreads.malformed.entry=\
-    bad value for --add-reads {0}
-
-# 0: string
-compiler.err.xaddreads.too.many=\
-    multiple --add-reads options for {0}
+# 0: option name, 1: string
+compiler.warn.bad.name.for.option=\
+    bad name in value for {0} option: ''{1}''
+
+# 0: option name, 1: symbol
+compiler.warn.module.for.option.not.found=\
+    module name in {0} option not found: {1}
 
 compiler.err.addmods.all.module.path.invalid=\
     --add-modules ALL-MODULE-PATH can only be used when compiling the unnamed module
@@ -2906,10 +2898,6 @@
 compiler.misc.cant.resolve.modules=\
     cannot resolve modules
 
-# 0: symbol
-compiler.err.cant.find.module=\
-    cannot find module: {0}
-
 # 0: string
 compiler.err.invalid.module.specifier=\
     module specifier not allowed: {0}
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/javac.properties	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/javac.properties	Thu Nov 10 15:58:49 2016 -0800
@@ -357,6 +357,12 @@
     not a file: {0}
 javac.err.cannot.access.runtime.env=\
     cannot access runtime environment
+javac.err.bad.value.for.option=\
+    bad value for {0} option: ''{1}''
+javac.err.no.value.for.option=\
+    no value for {0} option
+javac.err.repeated.value.for.patch.module=\
+    --patch-module specified more than once for {0}
 
 ## messages
 
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/util/AbstractDiagnosticFormatter.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/util/AbstractDiagnosticFormatter.java	Thu Nov 10 15:58:49 2016 -0800
@@ -48,6 +48,7 @@
 import com.sun.tools.javac.code.Type.CapturedType;
 import com.sun.tools.javac.file.PathFileObject;
 import com.sun.tools.javac.jvm.Profile;
+import com.sun.tools.javac.main.Option;
 import com.sun.tools.javac.tree.JCTree.*;
 import com.sun.tools.javac.tree.Pretty;
 
@@ -204,6 +205,9 @@
         else if (arg instanceof Profile) {
             return ((Profile)arg).name;
         }
+        else if (arg instanceof Option) {
+            return ((Option)arg).primaryName;
+        }
         else if (arg instanceof Formattable) {
             return ((Formattable)arg).toString(l, messages);
         }
--- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/Start.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/Start.java	Thu Nov 10 15:58:49 2016 -0800
@@ -939,6 +939,17 @@
             public void put(String name, String value) {
                 compOpts.put(name, value);
             }
+
+            @Override
+            public void remove(String name) {
+                compOpts.remove(name);
+            }
+
+            @Override
+            public boolean handleFileManagerOption(com.sun.tools.javac.main.Option option, String value) {
+                fileManagerOpts.put(option, value);
+                return true;
+            }
         };
     }
 
--- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/ToolOption.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/ToolOption.java	Thu Nov 10 15:58:49 2016 -0800
@@ -57,63 +57,56 @@
     BOOTCLASSPATH("-bootclasspath", STANDARD, true) {
         @Override
         public void process(Helper helper, String arg) {
-            helper.setFileManagerOpt(Option.BOOT_CLASS_PATH, arg);
+            Option.BOOT_CLASS_PATH.process(helper.getOptionHelper(), primaryName, arg);
         }
     },
 
     CLASS_PATH("--class-path -classpath -cp", STANDARD, true) {
         @Override
         public void process(Helper helper, String arg) {
-            helper.setFileManagerOpt(Option.CLASS_PATH, arg);
+            Option.CLASS_PATH.process(helper.getOptionHelper(), primaryName, arg);
         }
     },
 
     EXTDIRS("-extdirs", STANDARD, true) {
         @Override
         public void process(Helper helper, String arg) {
-            helper.setFileManagerOpt(Option.EXTDIRS, arg);
+            Option.EXTDIRS.process(helper.getOptionHelper(), primaryName, arg);
         }
     },
 
     SOURCE_PATH("--source-path -sourcepath", STANDARD, true) {
         @Override
         public void process(Helper helper, String arg) {
-            helper.setFileManagerOpt(Option.SOURCE_PATH, arg);
-        }
-    },
-
-    SYSCLASSPATH("-sysclasspath", HIDDEN, true) {
-        @Override
-        public void process(Helper helper, String arg) {
-            helper.setFileManagerOpt(Option.BOOT_CLASS_PATH, arg);
+            Option.SOURCE_PATH.process(helper.getOptionHelper(), primaryName, arg);
         }
     },
 
     MODULE_SOURCE_PATH("--module-source-path", STANDARD, true) {
         @Override
         public void process(Helper helper, String arg) {
-            helper.setFileManagerOpt(Option.MODULE_SOURCE_PATH, arg);
+            Option.MODULE_SOURCE_PATH.process(helper.getOptionHelper(), primaryName, arg);
         }
     },
 
     UPGRADE_MODULE_PATH("--upgrade-module-path", STANDARD, true) {
         @Override
         public void process(Helper helper, String arg) {
-            helper.setFileManagerOpt(Option.UPGRADE_MODULE_PATH, arg);
+            Option.UPGRADE_MODULE_PATH.process(helper.getOptionHelper(), primaryName, arg);
         }
     },
 
     SYSTEM("--system", STANDARD, true) {
         @Override
         public void process(Helper helper, String arg) {
-            helper.setFileManagerOpt(Option.SYSTEM, arg);
+            Option.SYSTEM.process(helper.getOptionHelper(), primaryName, arg);
         }
     },
 
     MODULE_PATH("--module-path -p", STANDARD, true) {
         @Override
         public void process(Helper helper, String arg) {
-            helper.setFileManagerOpt(Option.MODULE_PATH, arg);
+            Option.MODULE_PATH.process(helper.getOptionHelper(), primaryName, arg);
         }
     },
 
@@ -141,7 +134,7 @@
     ENCODING("-encoding", STANDARD, true) {
         @Override
         public void process(Helper helper, String arg) {
-            helper.setFileManagerOpt(Option.ENCODING, arg);
+            Option.ENCODING.process(helper.getOptionHelper(), primaryName, arg);
         }
     },
 
@@ -290,14 +283,6 @@
 
     // ----- output control options -----
 
-    PROMPT("-prompt", HIDDEN) {
-        @Override
-        public void process(Helper helper) {
-            helper.compOpts.put("-prompt", "-prompt");
-            helper.promptOnError = true;
-        }
-    },
-
     QUIET("-quiet", STANDARD) {
         @Override
         public void process(Helper helper) {
--- a/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/ConsoleIOContext.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/ConsoleIOContext.java	Thu Nov 10 15:58:49 2016 -0800
@@ -29,7 +29,6 @@
 import jdk.jshell.SourceCodeAnalysis.QualifiedNames;
 import jdk.jshell.SourceCodeAnalysis.Suggestion;
 
-import java.awt.event.ActionListener;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InterruptedIOException;
@@ -171,10 +170,10 @@
                 return anchor[0];
             }
         });
-        bind(DOCUMENTATION_SHORTCUT, (ActionListener) evt -> documentation(repl));
+        bind(DOCUMENTATION_SHORTCUT, (Runnable) () -> documentation(repl));
         for (FixComputer computer : FIX_COMPUTERS) {
             for (String shortcuts : SHORTCUT_FIXES) {
-                bind(shortcuts + computer.shortcut, (ActionListener) evt -> fixes(computer));
+                bind(shortcuts + computer.shortcut, (Runnable) () -> fixes(computer));
             }
         }
         try {
--- a/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/EditPad.java	Wed Nov 09 21:20:20 2016 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,129 +0,0 @@
-/*
- * Copyright (c) 2015, 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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * 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.
- */
-
-package jdk.internal.jshell.tool;
-
-import java.awt.BorderLayout;
-import java.awt.FlowLayout;
-import java.awt.event.KeyEvent;
-import java.awt.event.WindowAdapter;
-import java.awt.event.WindowEvent;
-import java.util.concurrent.CountDownLatch;
-import java.util.function.Consumer;
-import javax.swing.JButton;
-import javax.swing.JFrame;
-import javax.swing.JPanel;
-import javax.swing.JScrollPane;
-import javax.swing.JTextArea;
-import javax.swing.SwingUtilities;
-
-/**
- * A minimal Swing editor as a fallback when the user does not specify an
- * external editor.
- */
-@SuppressWarnings("serial")             // serialVersionUID intentionally omitted
-public class EditPad extends JFrame implements Runnable {
-    private final Consumer<String> errorHandler; // For possible future error handling
-    private final String initialText;
-    private final CountDownLatch closeLock;
-    private final Consumer<String> saveHandler;
-
-    EditPad(Consumer<String> errorHandler, String initialText,
-            CountDownLatch closeLock, Consumer<String> saveHandler) {
-        super("JShell Edit Pad");
-        this.errorHandler = errorHandler;
-        this.initialText = initialText;
-        this.closeLock = closeLock;
-        this.saveHandler = saveHandler;
-    }
-
-    @Override
-    public void run() {
-        addWindowListener(new WindowAdapter() {
-            @Override
-            public void windowClosing(WindowEvent e) {
-                EditPad.this.dispose();
-                closeLock.countDown();
-            }
-        });
-        setLocationRelativeTo(null);
-        setLayout(new BorderLayout());
-        JTextArea textArea = new JTextArea(initialText);
-        add(new JScrollPane(textArea), BorderLayout.CENTER);
-        add(buttons(textArea), BorderLayout.SOUTH);
-
-        setSize(800, 600);
-        setVisible(true);
-    }
-
-    private JPanel buttons(JTextArea textArea) {
-        FlowLayout flow = new FlowLayout();
-        flow.setHgap(35);
-        JPanel buttons = new JPanel(flow);
-        JButton cancel = new JButton("Cancel");
-        cancel.setMnemonic(KeyEvent.VK_C);
-        JButton accept = new JButton("Accept");
-        accept.setMnemonic(KeyEvent.VK_A);
-        JButton exit = new JButton("Exit");
-        exit.setMnemonic(KeyEvent.VK_X);
-        buttons.add(cancel);
-        buttons.add(accept);
-        buttons.add(exit);
-
-        cancel.addActionListener(e -> {
-            close();
-        });
-        accept.addActionListener(e -> {
-            saveHandler.accept(textArea.getText());
-        });
-        exit.addActionListener(e -> {
-            saveHandler.accept(textArea.getText());
-            close();
-        });
-
-        return buttons;
-    }
-
-    private void close() {
-        setVisible(false);
-        dispose();
-        closeLock.countDown();
-    }
-
-    public static void edit(Consumer<String> errorHandler, String initialText,
-            Consumer<String> saveHandler) {
-        CountDownLatch closeLock = new CountDownLatch(1);
-        SwingUtilities.invokeLater(
-                new EditPad(errorHandler, initialText, closeLock, saveHandler));
-        do {
-            try {
-                closeLock.await();
-                break;
-            } catch (InterruptedException ex) {
-                // ignore and loop
-            }
-        } while (true);
-    }
-}
--- a/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/ExternalEditor.java	Wed Nov 09 21:20:20 2016 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,170 +0,0 @@
-/*
- * Copyright (c) 2015, 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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * 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.
- */
-
-package jdk.internal.jshell.tool;
-
-import java.io.IOException;
-import java.nio.charset.Charset;
-import java.nio.file.ClosedWatchServiceException;
-import java.nio.file.FileSystems;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.WatchKey;
-import java.nio.file.WatchService;
-import java.util.Arrays;
-import java.util.Scanner;
-import java.util.function.Consumer;
-import java.util.stream.Collectors;
-import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
-import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
-import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
-
-/**
- * Wrapper for controlling an external editor.
- */
-public class ExternalEditor {
-    private final Consumer<String> errorHandler;
-    private final Consumer<String> saveHandler;
-    private final Consumer<String> printHandler;
-    private final IOContext input;
-    private final boolean wait;
-
-    private WatchService watcher;
-    private Thread watchedThread;
-    private Path dir;
-    private Path tmpfile;
-
-    ExternalEditor(Consumer<String> errorHandler, Consumer<String> saveHandler,
-            IOContext input, boolean wait, Consumer<String> printHandler) {
-        this.errorHandler = errorHandler;
-        this.saveHandler = saveHandler;
-        this.printHandler = printHandler;
-        this.input = input;
-        this.wait = wait;
-    }
-
-    private void edit(String[] cmd, String initialText) {
-        try {
-            setupWatch(initialText);
-            launch(cmd);
-        } catch (IOException ex) {
-            errorHandler.accept(ex.getMessage());
-        }
-    }
-
-    /**
-     * Creates a WatchService and registers the given directory
-     */
-    private void setupWatch(String initialText) throws IOException {
-        this.watcher = FileSystems.getDefault().newWatchService();
-        this.dir = Files.createTempDirectory("jshelltemp");
-        this.tmpfile = Files.createTempFile(dir, null, ".java");
-        Files.write(tmpfile, initialText.getBytes(Charset.forName("UTF-8")));
-        dir.register(watcher,
-                ENTRY_CREATE,
-                ENTRY_DELETE,
-                ENTRY_MODIFY);
-        watchedThread = new Thread(() -> {
-            for (;;) {
-                WatchKey key;
-                try {
-                    key = watcher.take();
-                } catch (ClosedWatchServiceException ex) {
-                    // The watch service has been closed, we are done
-                    break;
-                } catch (InterruptedException ex) {
-                    // tolerate an interrupt
-                    continue;
-                }
-
-                if (!key.pollEvents().isEmpty()) {
-                    // Changes have occurred in temp edit directory,
-                    // transfer the new sources to JShell (unless the editor is
-                    // running directly in JShell's window -- don't make a mess)
-                    if (!input.terminalEditorRunning()) {
-                        saveFile();
-                    }
-                }
-
-                boolean valid = key.reset();
-                if (!valid) {
-                    // The watch service has been closed, we are done
-                    break;
-                }
-            }
-        });
-        watchedThread.start();
-    }
-
-    private void launch(String[] cmd) throws IOException {
-        String[] params = Arrays.copyOf(cmd, cmd.length + 1);
-        params[cmd.length] = tmpfile.toString();
-        ProcessBuilder pb = new ProcessBuilder(params);
-        pb = pb.inheritIO();
-
-        try {
-            input.suspend();
-            Process process = pb.start();
-            // wait to exit edit mode in one of these ways...
-            if (wait) {
-                // -wait option -- ignore process exit, wait for carriage-return
-                Scanner scanner = new Scanner(System.in);
-                printHandler.accept("jshell.msg.press.return.to.leave.edit.mode");
-                scanner.nextLine();
-            } else {
-                // wait for process to exit
-                process.waitFor();
-            }
-        } catch (IOException ex) {
-            errorHandler.accept("process IO failure: " + ex.getMessage());
-        } catch (InterruptedException ex) {
-            errorHandler.accept("process interrupt: " + ex.getMessage());
-        } finally {
-            try {
-                watcher.close();
-                watchedThread.join(); //so that saveFile() is finished.
-                saveFile();
-            } catch (InterruptedException ex) {
-                errorHandler.accept("process interrupt: " + ex.getMessage());
-            } finally {
-                input.resume();
-            }
-        }
-    }
-
-    private void saveFile() {
-        try {
-            saveHandler.accept(Files.lines(tmpfile).collect(Collectors.joining("\n", "", "\n")));
-        } catch (IOException ex) {
-            errorHandler.accept("Failure in read edit file: " + ex.getMessage());
-        }
-    }
-
-    static void edit(String[] cmd, Consumer<String> errorHandler, String initialText,
-            Consumer<String> saveHandler, IOContext input, boolean wait, Consumer<String> printHandler) {
-        ExternalEditor ed = new ExternalEditor(errorHandler, saveHandler, input, wait, printHandler);
-        ed.edit(cmd, initialText);
-    }
-}
--- a/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/Feedback.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/Feedback.java	Thu Nov 10 15:58:49 2016 -0800
@@ -116,6 +116,10 @@
                 name, type, value, unresolved, errorLines);
     }
 
+    public String truncateVarValue(String value) {
+        return mode.truncateVarValue(value);
+    }
+
     public String getPrompt(String nextId) {
         return mode.getPrompt(nextId);
     }
@@ -416,6 +420,45 @@
             return sb.toString();
         }
 
+        String truncateVarValue(String value) {
+            return truncateValue(value,
+                    bits(FormatCase.VARVALUE, FormatAction.ADDED,
+                            FormatWhen.PRIMARY, FormatResolve.OK,
+                            FormatUnresolved.UNRESOLVED0, FormatErrors.ERROR0));
+        }
+
+        String truncateValue(String value, long bits) {
+            if (value==null) {
+                return "";
+            } else {
+                // Retrieve the truncation length
+                String truncField = format(TRUNCATION_FIELD, bits);
+                if (truncField.isEmpty()) {
+                    // No truncation set, use whole value
+                    return value;
+                } else {
+                    // Convert truncation length to int
+                    // this is safe since it has been tested before it is set
+                    int trunc = Integer.parseUnsignedInt(truncField);
+                    int len = value.length();
+                    if (len > trunc) {
+                        if (trunc <= 13) {
+                            // Very short truncations have no room for "..."
+                            return value.substring(0, trunc);
+                        } else {
+                            // Normal truncation, make total length equal truncation length
+                            int endLen = trunc / 3;
+                            int startLen = trunc - 5 - endLen;
+                            return value.substring(0, startLen) + " ... " + value.substring(len -endLen);
+                        }
+                    } else {
+                        // Within truncation length, use whole value
+                        return value;
+                    }
+                }
+            }
+        }
+
         // Compute the display output given full context and values
         String format(FormatCase fc, FormatAction fa, FormatWhen fw,
                     FormatResolve fr, FormatUnresolved fu, FormatErrors fe,
@@ -425,33 +468,7 @@
             String fname = name==null? "" : name;
             String ftype = type==null? "" : type;
             // Compute the representation of value
-            String fvalue;
-            if (value==null) {
-                fvalue = "";
-            } else {
-                // Retrieve the truncation length
-                String truncField = format(TRUNCATION_FIELD, bits);
-                if (truncField.isEmpty()) {
-                    // No truncation set, use whole value
-                    fvalue = value;
-                } else {
-                    // Convert truncation length to int
-                    // this is safe since it has been tested before it is set
-                    int trunc = Integer.parseUnsignedInt(truncField);
-                    if (value.length() > trunc) {
-                        if (trunc <= 5) {
-                            // Very short truncations have no room for "..."
-                            fvalue = value.substring(0, trunc);
-                        } else {
-                            // Normal truncation, make total length equal truncation length
-                            fvalue = value.substring(0, trunc - 4) + " ...";
-                        }
-                    } else {
-                        // Within truncation length, use whole value
-                        fvalue = value;
-                    }
-                }
-            }
+            String fvalue = truncateValue(value, bits);
             String funresolved = unresolved==null? "" : unresolved;
             String errors = errorLines.stream()
                     .map(el -> String.format(
--- a/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java	Thu Nov 10 15:58:49 2016 -0800
@@ -89,6 +89,7 @@
 import java.util.MissingResourceException;
 import java.util.Optional;
 import java.util.ResourceBundle;
+import java.util.ServiceLoader;
 import java.util.Spliterators;
 import java.util.function.Function;
 import java.util.function.Supplier;
@@ -99,6 +100,8 @@
 import jdk.internal.jshell.tool.Feedback.FormatResolve;
 import jdk.internal.jshell.tool.Feedback.FormatUnresolved;
 import jdk.internal.jshell.tool.Feedback.FormatWhen;
+import jdk.internal.editor.spi.BuildInEditorProvider;
+import jdk.internal.editor.external.ExternalEditor;
 import static java.util.Arrays.asList;
 import static java.util.Arrays.stream;
 import static java.util.stream.Collectors.joining;
@@ -323,7 +326,7 @@
     }
 
     /**
-     * Print using resource bundle look-up and adding prefix and postfix
+     * Resource bundle look-up
      *
      * @param key the resource key
      */
@@ -523,7 +526,7 @@
             runFile(loadFile, "jshell");
         }
 
-        if (regenerateOnDeath) {
+        if (regenerateOnDeath && feedback.shouldDisplayCommandFluff()) {
             hardmsg("jshell.msg.welcome", version());
         }
 
@@ -1978,20 +1981,59 @@
         Consumer<String> saveHandler = new SaveHandler(src, srcSet);
         Consumer<String> errorHandler = s -> hard("Edit Error: %s", s);
         if (editor == BUILT_IN_EDITOR) {
-            try {
-                EditPad.edit(errorHandler, src, saveHandler);
-            } catch (RuntimeException ex) {
-                errormsg("jshell.err.cant.launch.editor", ex);
-                fluffmsg("jshell.msg.try.set.editor");
-                return false;
+            return builtInEdit(src, saveHandler, errorHandler);
+        } else {
+            // Changes have occurred in temp edit directory,
+            // transfer the new sources to JShell (unless the editor is
+            // running directly in JShell's window -- don't make a mess)
+            String[] buffer = new String[1];
+            Consumer<String> extSaveHandler = s -> {
+                if (input.terminalEditorRunning()) {
+                    buffer[0] = s;
+                } else {
+                    saveHandler.accept(s);
+                }
+            };
+            ExternalEditor.edit(editor.cmd, src,
+                    errorHandler, extSaveHandler,
+                    () -> input.suspend(),
+                    () -> input.resume(),
+                    editor.wait,
+                    () -> hardrb("jshell.msg.press.return.to.leave.edit.mode"));
+            if (buffer[0] != null) {
+                saveHandler.accept(buffer[0]);
             }
-        } else {
-            ExternalEditor.edit(editor.cmd, errorHandler, src, saveHandler, input,
-                    editor.wait, this::hardrb);
         }
         return true;
     }
     //where
+    // start the built-in editor
+    private boolean builtInEdit(String initialText,
+            Consumer<String> saveHandler, Consumer<String> errorHandler) {
+        try {
+            ServiceLoader<BuildInEditorProvider> sl
+                    = ServiceLoader.load(BuildInEditorProvider.class);
+            // Find the highest ranking provider
+            BuildInEditorProvider provider = null;
+            for (BuildInEditorProvider p : sl) {
+                if (provider == null || p.rank() > provider.rank()) {
+                    provider = p;
+                }
+            }
+            if (provider != null) {
+                provider.edit(getResourceString("jshell.label.editpad"),
+                        initialText, saveHandler, errorHandler);
+                return true;
+            } else {
+                errormsg("jshell.err.no.builtin.editor");
+            }
+        } catch (RuntimeException ex) {
+            errormsg("jshell.err.cant.launch.editor", ex);
+        }
+        fluffmsg("jshell.msg.try.set.editor");
+        return false;
+    }
+    //where
     // receives editor requests to save
     private class SaveHandler implements Consumer<String> {
 
@@ -2198,7 +2240,7 @@
         stream.forEachOrdered(vk ->
         {
             String val = state.status(vk) == Status.VALID
-                    ? state.varValue(vk)
+                    ? feedback.truncateVarValue(state.varValue(vk))
                     : getResourceString("jshell.msg.vars.not.active");
             hard("  %s %s = %s", vk.typeName(), vk.name(), val);
         });
--- a/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/resources/l10n.properties	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/resources/l10n.properties	Thu Nov 10 15:58:49 2016 -0800
@@ -54,10 +54,12 @@
 jshell.err.command.ambiguous = Command: ''{0}'' is ambiguous: {1}
 jshell.msg.set.editor.set = Editor set to: {0}
 jshell.msg.set.editor.retain = Editor setting retained: {0}
-jshell.err.cant.launch.editor = Cannot launch editor -- unexpected exception: {0}
-jshell.msg.try.set.editor = Try /set editor to use external editor.
+jshell.err.no.builtin.editor = Built-in editor not available.
+jshell.err.cant.launch.editor = Cannot launch built-in editor -- unexpected exception: {0}
+jshell.msg.try.set.editor = See ''/help /set editor'' to use external editor.
 jshell.msg.press.return.to.leave.edit.mode = Press return to leave edit mode.
 jshell.err.wait.applies.to.external.editor = -wait applies to external editors
+jshell.label.editpad = JShell Edit Pad
 
 jshell.err.setting.to.retain.must.be.specified = The setting to retain must be specified -- {0}
 jshell.msg.set.show.mode.settings = \nTo show mode settings use ''/set prompt'', ''/set truncation'', ...\n\
@@ -336,7 +338,7 @@
      Reset and replay the valid history between the previous and most\n\t\
      recent time that jshell was entered, or a /reset, or /reload\n\t\
      command was executed. This can thus be used to restore a previous\n\t\
-     jshell tool sesson.\n\n\
+     jshell tool session.\n\n\
 /reload [-restore] -quiet\n\t\
      With the '-quiet' argument the replay is not shown.  Errors will display.
 
--- a/src/jdk.jshell/share/classes/jdk/jshell/JShell.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.jshell/share/classes/jdk/jshell/JShell.java	Thu Nov 10 15:58:49 2016 -0800
@@ -47,7 +47,7 @@
 import java.util.stream.Stream;
 import jdk.internal.jshell.debug.InternalDebugControl;
 import jdk.jshell.Snippet.Status;
-import jdk.jshell.execution.JDIDefaultExecutionControl;
+import jdk.jshell.execution.JdiDefaultExecutionControl;
 import jdk.jshell.spi.ExecutionControl.EngineTerminationException;
 import jdk.jshell.spi.ExecutionControl.ExecutionControlException;
 import jdk.jshell.spi.ExecutionEnv;
@@ -117,10 +117,9 @@
         this.extraRemoteVMOptions = b.extraRemoteVMOptions;
         this.extraCompilerOptions = b.extraCompilerOptions;
         this.executionControlGenerator = b.executionControlGenerator==null
-                ? failOverExecutionControlGenerator(
-                        JDIDefaultExecutionControl.launch(),
-                        JDIDefaultExecutionControl.listen("localhost"),
-                        JDIDefaultExecutionControl.listen(null))
+                ? failOverExecutionControlGenerator(JdiDefaultExecutionControl.launch(),
+                        JdiDefaultExecutionControl.listen("localhost"),
+                        JdiDefaultExecutionControl.listen(null))
                 : b.executionControlGenerator;
 
         this.maps = new SnippetMaps(this);
--- a/src/jdk.jshell/share/classes/jdk/jshell/MaskCommentsAndModifiers.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.jshell/share/classes/jdk/jshell/MaskCommentsAndModifiers.java	Thu Nov 10 15:58:49 2016 -0800
@@ -36,10 +36,14 @@
  */
 class MaskCommentsAndModifiers {
 
-    private final static Set<String> IGNORED_MODIFERS =
+    private final static Set<String> IGNORED_MODIFIERS =
             Stream.of( "public", "protected", "private", "static", "final" )
                     .collect( Collectors.toSet() );
 
+    private final static Set<String> OTHER_MODIFIERS =
+            Stream.of( "abstract", "strictfp", "transient", "volatile", "synchronized", "native", "default" )
+                    .collect( Collectors.toSet() );
+
     // Builder to accumulate non-masked characters
     private final StringBuilder sbCleared = new StringBuilder();
 
@@ -52,24 +56,28 @@
     // Entire input string length
     private final int length;
 
-    // Should leading modifiers be masked away
-    private final boolean maskModifiers;
-
-    // The next character
+    // The next character position
     private int next = 0;
 
-    // We have past any point where a top-level modifier could be
-    private boolean inside = false;
+    // The current character
+    private int c;
+
+    // Do we mask-off ignored modifiers?  Set by parameter and turned off after
+    // initial modifier section
+    private boolean maskModifiers;
 
     // Does the string end with an unclosed '/*' style comment?
     private boolean openComment = false;
 
-    @SuppressWarnings("empty-statement")
     MaskCommentsAndModifiers(String s, boolean maskModifiers) {
         this.str = s;
         this.length = s.length();
         this.maskModifiers = maskModifiers;
-        do { } while (next());
+        read();
+        while (c >= 0) {
+            next();
+            read();
+        }
     }
 
     String cleared() {
@@ -90,24 +98,33 @@
      * Read the next character
      */
     private int read() {
-        if (next >= length) {
-            return -1;
-        }
-        return str.charAt(next++);
+        return c = (next >= length)
+                ? -1
+                : str.charAt(next++);
     }
 
-    private void write(StringBuilder sb, int ch) {
+    private void unread() {
+        if (c >= 0) {
+            --next;
+        }
+    }
+
+    private void writeTo(StringBuilder sb, int ch) {
         sb.append((char)ch);
     }
 
     private void write(int ch) {
-        write(sbCleared, ch);
-        write(sbMask, Character.isWhitespace(ch) ? ch : ' ');
+        if (ch != -1) {
+            writeTo(sbCleared, ch);
+            writeTo(sbMask, Character.isWhitespace(ch) ? ch : ' ');
+        }
     }
 
     private void writeMask(int ch) {
-        write(sbMask, ch);
-        write(sbCleared, Character.isWhitespace(ch) ? ch : ' ');
+        if (ch != -1) {
+            writeTo(sbMask, ch);
+            writeTo(sbCleared, Character.isWhitespace(ch) ? ch : ' ');
+        }
     }
 
     private void write(CharSequence s) {
@@ -122,99 +139,105 @@
         }
     }
 
-    private boolean next() {
-        return next(read());
-    }
-
-    private boolean next(int c) {
-        if (c < 0) {
-            return false;
-        }
-
-        if (c == '\'' || c == '"') {
-            inside = true;
-            write(c);
-            int match = c;
-            c = read();
-            while (c != match) {
-                if (c < 0) {
-                    return false;
-                }
-                if (c == '\n' || c == '\r') {
+    private void next() {
+        switch (c) {
+            case '\'':
+            case '"':
+                maskModifiers = false;
+                write(c);
+                int match = c;
+                while (read() >= 0 && c != match && c != '\n' && c != '\r') {
                     write(c);
-                    return true;
-                }
-                if (c == '\\') {
-                    write(c);
-                    c = read();
-                }
-                write(c);
-                c = read();
-            }
-            write(c);
-            return true;
-        }
-
-        if (c == '/') {
-            c = read();
-            if (c == '*') {
-                writeMask('/');
-                writeMask(c);
-                int prevc = 0;
-                while ((c = read()) != '/' || prevc != '*') {
-                    if (c < 0) {
-                        openComment = true;
-                        return false;
-                    }
-                    writeMask(c);
-                    prevc = c;
-                }
-                writeMask(c);
-                return true;
-            } else if (c == '/') {
-                writeMask('/');
-                writeMask(c);
-                while ((c = read()) != '\n' && c != '\r') {
-                    if (c < 0) {
-                        return false;
-                    }
-                    writeMask(c);
-                }
-                writeMask(c);
-                return true;
-            } else {
-                inside = true;
-                write('/');
-                // read character falls through
-            }
-        }
-
-        if (Character.isJavaIdentifierStart(c)) {
-            if (maskModifiers && !inside) {
-                StringBuilder sb = new StringBuilder();
-                do {
-                    write(sb, c);
-                    c = read();
-                } while (Character.isJavaIdentifierPart(c));
-                String id = sb.toString();
-                if (IGNORED_MODIFERS.contains(id)) {
-                    writeMask(sb);
-                } else {
-                    write(sb);
-                    if (id.equals("import")) {
-                        inside = true;
+                    if (c == '\\') {
+                        write(read());
                     }
                 }
-                return next(c); // recurse to handle left-over character
-            }
-        } else if (!Character.isWhitespace(c)) {
-            inside = true;
+                write(c); // write match // line-end
+                break;
+            case '/':
+                read();
+                switch (c) {
+                    case '*':
+                        writeMask('/');
+                        writeMask(c);
+                        int prevc = 0;
+                        while (read() >= 0 && (c != '/' || prevc != '*')) {
+                            writeMask(c);
+                            prevc = c;
+                        }
+                        writeMask(c);
+                        openComment = c < 0;
+                        break;
+                    case '/':
+                        writeMask('/');
+                        writeMask(c);
+                        while (read() >= 0 && c != '\n' && c != '\r') {
+                            writeMask(c);
+                        }
+                        writeMask(c);
+                        break;
+                    default:
+                        maskModifiers = false;
+                        write('/');
+                        unread();
+                        break;
+                }
+                break;
+            case '@':
+                do {
+                    write(c);
+                    read();
+                } while (Character.isJavaIdentifierPart(c));
+                while (Character.isWhitespace(c)) {
+                    write(c);
+                    read();
+                }
+                // if this is an annotation with arguments, process those recursively
+                if (c == '(') {
+                    write(c);
+                    boolean prevMaskModifiers = maskModifiers;
+                    int parenCnt = 1;
+                    while (read() >= 0) {
+                        if (c == ')') {
+                            if (--parenCnt == 0) {
+                                break;
+                            }
+                        } else if (c == '(') {
+                            ++parenCnt;
+                        }
+                        next(); // recurse to handle quotes and comments
+                    }
+                    write(c);
+                    // stuff in annotation arguments doesn't effect inside determination
+                    maskModifiers = prevMaskModifiers;
+                } else {
+                    unread();
+                }
+                break;
+            default:
+                if (Character.isJavaIdentifierStart(c)) {
+                    StringBuilder sb = new StringBuilder();
+                    do {
+                        writeTo(sb, c);
+                        read();
+                    } while (Character.isJavaIdentifierPart(c));
+                    unread();
+                    String id = sb.toString();
+                    if (maskModifiers && IGNORED_MODIFIERS.contains(id)) {
+                        writeMask(sb);
+                    } else {
+                        write(sb);
+                        if (maskModifiers && !OTHER_MODIFIERS.contains(id)) {
+                            maskModifiers = false;
+                        }
+                    }
+                } else {
+                    if (!Character.isWhitespace(c)) {
+                        maskModifiers = false;
+                    }
+                    write(c);
+                }
+                break;
         }
-
-        if (c < 0) {
-            return false;
-        }
-        write(c);
-        return true;
     }
 }
--- a/src/jdk.jshell/share/classes/jdk/jshell/execution/JDIDefaultExecutionControl.java	Wed Nov 09 21:20:20 2016 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,282 +0,0 @@
-/*
- * Copyright (c) 2016, 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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * 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.
- */
-package jdk.jshell.execution;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.io.OutputStream;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Consumer;
-import com.sun.jdi.BooleanValue;
-import com.sun.jdi.ClassNotLoadedException;
-import com.sun.jdi.Field;
-import com.sun.jdi.IncompatibleThreadStateException;
-import com.sun.jdi.InvalidTypeException;
-import com.sun.jdi.ObjectReference;
-import com.sun.jdi.StackFrame;
-import com.sun.jdi.ThreadReference;
-import com.sun.jdi.VMDisconnectedException;
-import com.sun.jdi.VirtualMachine;
-import jdk.jshell.spi.ExecutionControl;
-import jdk.jshell.spi.ExecutionEnv;
-import static jdk.jshell.execution.Util.remoteInputOutput;
-
-/**
- * The implementation of {@link jdk.jshell.spi.ExecutionControl} that the
- * JShell-core uses by default.
- * Launches a remote process -- the "remote agent".
- * Interfaces to the remote agent over a socket and via JDI.
- * Designed to work with {@link RemoteExecutionControl}.
- *
- * @author Robert Field
- * @author Jan Lahoda
- */
-public class JDIDefaultExecutionControl extends JDIExecutionControl {
-
-    private static final String REMOTE_AGENT = RemoteExecutionControl.class.getName();
-
-    private VirtualMachine vm;
-    private Process process;
-
-    private final Object STOP_LOCK = new Object();
-    private boolean userCodeRunning = false;
-
-    /**
-     * Creates an ExecutionControl instance based on a JDI
-     * {@code LaunchingConnector}.
-     *
-     * @return the generator
-     */
-    public static ExecutionControl.Generator launch() {
-        return env -> create(env, true, null);
-    }
-
-    /**
-     * Creates an ExecutionControl instance based on a JDI
-     * {@code ListeningConnector}.
-     *
-     * @param host explicit hostname to use, if null use discovered
-     * hostname, applies to listening only (!isLaunch)
-     * @return the generator
-     */
-    public static ExecutionControl.Generator listen(String host) {
-        return env -> create(env, false, host);
-    }
-
-    /**
-     * Creates an ExecutionControl instance based on a JDI
-     * {@code ListeningConnector} or {@code LaunchingConnector}.
-     *
-     * Initialize JDI and use it to launch the remote JVM. Set-up a socket for
-     * commands and results. This socket also transports the user
-     * input/output/error.
-     *
-     * @param env the context passed by
-     * {@link jdk.jshell.spi.ExecutionControl#start(jdk.jshell.spi.ExecutionEnv) }
-     * @param isLaunch does JDI do the launch? That is, LaunchingConnector,
-     * otherwise we start explicitly and use ListeningConnector
-     * @param host explicit hostname to use, if null use discovered
-     * hostname, applies to listening only (!isLaunch)
-     * @return the channel
-     * @throws IOException if there are errors in set-up
-     */
-    private static ExecutionControl create(ExecutionEnv env,
-            boolean isLaunch, String host) throws IOException {
-        try (final ServerSocket listener = new ServerSocket(0)) {
-            // timeout after 60 seconds
-            listener.setSoTimeout(60000);
-            int port = listener.getLocalPort();
-
-            // Set-up the JDI connection
-            JDIInitiator jdii = new JDIInitiator(port,
-                    env.extraRemoteVMOptions(), REMOTE_AGENT, isLaunch, host);
-            VirtualMachine vm = jdii.vm();
-            Process process = jdii.process();
-
-            List<Consumer<String>> deathListeners = new ArrayList<>();
-            deathListeners.add(s -> env.closeDown());
-            Util.detectJDIExitEvent(vm, s -> {
-                for (Consumer<String> h : deathListeners) {
-                    h.accept(s);
-                }
-            });
-
-            // Set-up the commands/reslts on the socket.  Piggy-back snippet
-            // output.
-            Socket socket = listener.accept();
-            // out before in -- match remote creation so we don't hang
-            OutputStream out = socket.getOutputStream();
-            Map<String, OutputStream> outputs = new HashMap<>();
-            outputs.put("out", env.userOut());
-            outputs.put("err", env.userErr());
-            Map<String, InputStream> input = new HashMap<>();
-            input.put("in", env.userIn());
-            return remoteInputOutput(socket.getInputStream(), out, outputs, input, (objIn, objOut) -> new JDIDefaultExecutionControl(objOut, objIn, vm, process, deathListeners));
-        }
-    }
-
-    /**
-     * Create an instance.
-     *
-     * @param cmdout the output for commands
-     * @param cmdin the input for responses
-     */
-    private JDIDefaultExecutionControl(ObjectOutput cmdout, ObjectInput cmdin,
-            VirtualMachine vm, Process process, List<Consumer<String>> deathListeners) {
-        super(cmdout, cmdin);
-        this.vm = vm;
-        this.process = process;
-        deathListeners.add(s -> disposeVM());
-    }
-
-    @Override
-    public String invoke(String classname, String methodname)
-            throws RunException,
-            EngineTerminationException, InternalException {
-        String res;
-        synchronized (STOP_LOCK) {
-            userCodeRunning = true;
-        }
-        try {
-            res = super.invoke(classname, methodname);
-        } finally {
-            synchronized (STOP_LOCK) {
-                userCodeRunning = false;
-            }
-        }
-        return res;
-    }
-
-    /**
-     * Interrupts a running remote invoke by manipulating remote variables
-     * and sending a stop via JDI.
-     *
-     * @throws EngineTerminationException the execution engine has terminated
-     * @throws InternalException an internal problem occurred
-     */
-    @Override
-    public void stop() throws EngineTerminationException, InternalException {
-        synchronized (STOP_LOCK) {
-            if (!userCodeRunning) {
-                return;
-            }
-
-            vm().suspend();
-            try {
-                OUTER:
-                for (ThreadReference thread : vm().allThreads()) {
-                    // could also tag the thread (e.g. using name), to find it easier
-                    for (StackFrame frame : thread.frames()) {
-                        if (REMOTE_AGENT.equals(frame.location().declaringType().name()) &&
-                                (    "invoke".equals(frame.location().method().name())
-                                || "varValue".equals(frame.location().method().name()))) {
-                            ObjectReference thiz = frame.thisObject();
-                            Field inClientCode = thiz.referenceType().fieldByName("inClientCode");
-                            Field expectingStop = thiz.referenceType().fieldByName("expectingStop");
-                            Field stopException = thiz.referenceType().fieldByName("stopException");
-                            if (((BooleanValue) thiz.getValue(inClientCode)).value()) {
-                                thiz.setValue(expectingStop, vm().mirrorOf(true));
-                                ObjectReference stopInstance = (ObjectReference) thiz.getValue(stopException);
-
-                                vm().resume();
-                                debug("Attempting to stop the client code...\n");
-                                thread.stop(stopInstance);
-                                thiz.setValue(expectingStop, vm().mirrorOf(false));
-                            }
-
-                            break OUTER;
-                        }
-                    }
-                }
-            } catch (ClassNotLoadedException | IncompatibleThreadStateException | InvalidTypeException ex) {
-                throw new InternalException("Exception on remote stop: " + ex);
-            } finally {
-                vm().resume();
-            }
-        }
-    }
-
-    @Override
-    public void close() {
-        super.close();
-        disposeVM();
-    }
-
-    private synchronized void disposeVM() {
-        try {
-            if (vm != null) {
-                vm.dispose(); // This could NPE, so it is caught below
-                vm = null;
-            }
-        } catch (VMDisconnectedException ex) {
-            // Ignore if already closed
-        } catch (Throwable ex) {
-            debug(ex, "disposeVM");
-        } finally {
-            if (process != null) {
-                process.destroy();
-                process = null;
-            }
-        }
-    }
-
-    @Override
-    protected synchronized VirtualMachine vm() throws EngineTerminationException {
-        if (vm == null) {
-            throw new EngineTerminationException("VM closed");
-        } else {
-            return vm;
-        }
-    }
-
-    /**
-     * Log debugging information. Arguments as for {@code printf}.
-     *
-     * @param format a format string as described in Format string syntax
-     * @param args arguments referenced by the format specifiers in the format
-     * string.
-     */
-    private static void debug(String format, Object... args) {
-        // Reserved for future logging
-    }
-
-    /**
-     * Log a serious unexpected internal exception.
-     *
-     * @param ex the exception
-     * @param where a description of the context of the exception
-     */
-    private static void debug(Throwable ex, String where) {
-        // Reserved for future logging
-    }
-
-}
--- a/src/jdk.jshell/share/classes/jdk/jshell/execution/JDIEventHandler.java	Wed Nov 09 21:20:20 2016 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,140 +0,0 @@
-/*
- * Copyright (c) 1998, 2014, 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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * 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.
- */
-
-package jdk.jshell.execution;
-
-import java.util.function.Consumer;
-import com.sun.jdi.*;
-import com.sun.jdi.event.*;
-
-/**
- * Handler of Java Debug Interface events.
- * Adapted from jdb EventHandler.
- * Only exit and disconnect events processed.
- */
-class JDIEventHandler implements Runnable {
-
-    private final Thread thread;
-    private volatile boolean connected = true;
-    private boolean completed = false;
-    private final VirtualMachine vm;
-    private final Consumer<String> reportVMExit;
-
-    /**
-     * Creates an event handler. Start with {@code start()}.
-     *
-     * @param vm the virtual machine for which to handle events
-     * @param reportVMExit callback to report exit/disconnect
-     * (passed true if the VM has died)
-     */
-    JDIEventHandler(VirtualMachine vm, Consumer<String> reportVMExit) {
-        this.vm = vm;
-        this.reportVMExit = reportVMExit;
-        this.thread = new Thread(this, "event-handler");
-        this.thread.setDaemon(true);
-    }
-
-    /**
-     * Starts the event handler.
-     */
-    void start() {
-        thread.start();
-    }
-
-    synchronized void shutdown() {
-        connected = false;  // force run() loop termination
-        thread.interrupt();
-        while (!completed) {
-            try {wait();} catch (InterruptedException exc) {}
-        }
-    }
-
-    @Override
-    public void run() {
-        EventQueue queue = vm.eventQueue();
-        while (connected) {
-            try {
-                EventSet eventSet = queue.remove();
-                boolean resumeStoppedApp = false;
-                EventIterator it = eventSet.eventIterator();
-                while (it.hasNext()) {
-                    resumeStoppedApp |= handleEvent(it.nextEvent());
-                }
-
-                if (resumeStoppedApp) {
-                    eventSet.resume();
-                }
-            } catch (InterruptedException exc) {
-                // Do nothing. Any changes will be seen at top of loop.
-            } catch (VMDisconnectedException discExc) {
-                handleDisconnectedException();
-                break;
-            }
-        }
-        synchronized (this) {
-            completed = true;
-            notifyAll();
-        }
-    }
-
-    private boolean handleEvent(Event event) {
-        handleExitEvent(event);
-        return true;
-    }
-
-    private void handleExitEvent(Event event) {
-        if (event instanceof VMDeathEvent) {
-            reportVMExit.accept("VM Died");
-        } else if (event instanceof VMDisconnectEvent) {
-            connected = false;
-            reportVMExit.accept("VM Disconnected");
-        } else {
-            // ignore everything else
-        }
-    }
-
-    private synchronized void handleDisconnectedException() {
-        /*
-         * A VMDisconnectedException has happened while dealing with
-         * another event. We need to flush the event queue, dealing only
-         * with exit events (VMDeath, VMDisconnect) so that we terminate
-         * correctly.
-         */
-        EventQueue queue = vm.eventQueue();
-        while (connected) {
-            try {
-                EventSet eventSet = queue.remove();
-                EventIterator iter = eventSet.eventIterator();
-                while (iter.hasNext()) {
-                    handleExitEvent(iter.next());
-                }
-            } catch (InterruptedException exc) {
-                // ignore
-            } catch (InternalError exc) {
-                // ignore
-            }
-        }
-    }
-}
--- a/src/jdk.jshell/share/classes/jdk/jshell/execution/JDIExecutionControl.java	Wed Nov 09 21:20:20 2016 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,117 +0,0 @@
-/*
- * Copyright (c) 2014, 2016, 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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * 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.
- */
-
-package jdk.jshell.execution;
-
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Stream;
-import com.sun.jdi.ReferenceType;
-import com.sun.jdi.VirtualMachine;
-import jdk.jshell.spi.ExecutionControl;
-import static java.util.stream.Collectors.toMap;
-
-/**
- * Abstract JDI implementation of {@link jdk.jshell.spi.ExecutionControl}
- */
-public abstract class JDIExecutionControl extends StreamingExecutionControl implements ExecutionControl {
-
-    /**
-     * Mapping from class names to JDI {@link ReferenceType}.
-     */
-    private final Map<String, ReferenceType> toReferenceType = new HashMap<>();
-
-    /**
-     * Create an instance.
-     * @param out the output from the remote agent
-     * @param in the input to the remote agent
-     */
-    protected JDIExecutionControl(ObjectOutput out, ObjectInput in) {
-        super(out, in);
-    }
-
-    /**
-     * Returns the JDI {@link VirtualMachine} instance.
-     *
-     * @return the virtual machine
-     * @throws EngineTerminationException if the VM is dead/disconnected
-     */
-    protected abstract VirtualMachine vm() throws EngineTerminationException;
-
-    /**
-     * Redefine the specified classes. Where 'redefine' is, as in JDI and JVMTI,
-     * an in-place replacement of the classes (preserving class identity) --
-     * that is, existing references to the class do not need to be recompiled.
-     * This implementation uses JDI
-     * {@link com.sun.jdi.VirtualMachine#redefineClasses(java.util.Map) }.
-     * It will be unsuccessful if
-     * the signature of the class has changed (see the JDI spec). The
-     * JShell-core is designed to adapt to unsuccessful redefine.
-     */
-    @Override
-    public void redefine(ClassBytecodes[] cbcs)
-            throws ClassInstallException, EngineTerminationException {
-        try {
-            // Convert to the JDI ReferenceType to class bytes map form needed
-            // by JDI.
-            VirtualMachine vm = vm();
-            Map<ReferenceType, byte[]> rmp = Stream.of(cbcs)
-                    .collect(toMap(
-                            cbc -> referenceType(vm, cbc.name()),
-                            cbc -> cbc.bytecodes()));
-            // Attempt redefine.  Throws exceptions on failure.
-            vm().redefineClasses(rmp);
-        } catch (EngineTerminationException ex) {
-            throw ex;
-        } catch (Exception ex) {
-            throw new ClassInstallException("redefine: " + ex.getMessage(), new boolean[cbcs.length]);
-        }
-    }
-
-    /**
-     * Returns the JDI {@link ReferenceType} corresponding to the specified
-     * class name.
-     *
-     * @param vm the current JDI {@link VirtualMachine} as returned by
-     * {@code vm()}
-     * @param name the class name to look-up
-     * @return the corresponding {@link ReferenceType}
-     */
-    protected ReferenceType referenceType(VirtualMachine vm, String name) {
-        return toReferenceType.computeIfAbsent(name, n -> nameToRef(vm, n));
-    }
-
-    private static ReferenceType nameToRef(VirtualMachine vm, String name) {
-        List<ReferenceType> rtl = vm.classesByName(name);
-        if (rtl.size() != 1) {
-            return null;
-        }
-        return rtl.get(0);
-    }
-
-}
--- a/src/jdk.jshell/share/classes/jdk/jshell/execution/JDIInitiator.java	Wed Nov 09 21:20:20 2016 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,223 +0,0 @@
-/*
- * Copyright (c) 2016, 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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * 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.
- */
-package jdk.jshell.execution;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import com.sun.jdi.Bootstrap;
-import com.sun.jdi.VirtualMachine;
-import com.sun.jdi.connect.Connector;
-import com.sun.jdi.connect.LaunchingConnector;
-import com.sun.jdi.connect.ListeningConnector;
-
-/**
- * Sets up a JDI connection, providing the resulting JDI {@link VirtualMachine}
- * and the {@link Process} the remote agent is running in.
- */
-public class JDIInitiator {
-
-    private VirtualMachine vm;
-    private Process process = null;
-    private final Connector connector;
-    private final String remoteAgent;
-    private final Map<String, com.sun.jdi.connect.Connector.Argument> connectorArgs;
-
-    /**
-     * Start the remote agent and establish a JDI connection to it.
-     *
-     * @param port the socket port for (non-JDI) commands
-     * @param remoteVMOptions any user requested VM options
-     * @param remoteAgent full class name of remote agent to launch
-     * @param isLaunch does JDI do the launch? That is, LaunchingConnector,
-     * otherwise we start explicitly and use ListeningConnector
-     * @param host explicit hostname to use, if null use discovered
-     * hostname, applies to listening only (!isLaunch)
-     */
-    public JDIInitiator(int port, List<String> remoteVMOptions, String remoteAgent,
-            boolean isLaunch, String host) {
-        this.remoteAgent = remoteAgent;
-        String connectorName
-                = isLaunch
-                        ? "com.sun.jdi.CommandLineLaunch"
-                        : "com.sun.jdi.SocketListen";
-        this.connector = findConnector(connectorName);
-        if (connector == null) {
-            throw new IllegalArgumentException("No connector named: " + connectorName);
-        }
-        Map<String, String> argumentName2Value
-                = isLaunch
-                        ? launchArgs(port, String.join(" ", remoteVMOptions))
-                        : new HashMap<>();
-        if (host != null && !isLaunch) {
-            argumentName2Value.put("localAddress", host);
-        }
-        this.connectorArgs = mergeConnectorArgs(connector, argumentName2Value);
-        this.vm = isLaunch
-                ? launchTarget()
-                : listenTarget(port, remoteVMOptions);
-
-    }
-
-    /**
-     * Returns the resulting {@code VirtualMachine} instance.
-     *
-     * @return the virtual machine
-     */
-    public VirtualMachine vm() {
-        return vm;
-    }
-
-    /**
-     * Returns the launched process.
-     *
-     * @return the remote agent process
-     */
-    public Process process() {
-        return process;
-    }
-
-    /* launch child target vm */
-    private VirtualMachine launchTarget() {
-        LaunchingConnector launcher = (LaunchingConnector) connector;
-        try {
-            VirtualMachine new_vm = launcher.launch(connectorArgs);
-            process = new_vm.process();
-            return new_vm;
-        } catch (Exception ex) {
-            reportLaunchFail(ex, "launch");
-        }
-        return null;
-    }
-
-    /**
-     * Directly launch the remote agent and connect JDI to it with a
-     * ListeningConnector.
-     */
-    private VirtualMachine listenTarget(int port, List<String> remoteVMOptions) {
-        ListeningConnector listener = (ListeningConnector) connector;
-        try {
-            // Start listening, get the JDI connection address
-            String addr = listener.startListening(connectorArgs);
-            debug("Listening at address: " + addr);
-
-            // Launch the RemoteAgent requesting a connection on that address
-            String javaHome = System.getProperty("java.home");
-            List<String> args = new ArrayList<>();
-            args.add(javaHome == null
-                    ? "java"
-                    : javaHome + File.separator + "bin" + File.separator + "java");
-            args.add("-agentlib:jdwp=transport=" + connector.transport().name() +
-                    ",address=" + addr);
-            args.addAll(remoteVMOptions);
-            args.add(remoteAgent);
-            args.add("" + port);
-            ProcessBuilder pb = new ProcessBuilder(args);
-            process = pb.start();
-
-            // Forward out, err, and in
-            // Accept the connection from the remote agent
-            vm = listener.accept(connectorArgs);
-            listener.stopListening(connectorArgs);
-            return vm;
-        } catch (Exception ex) {
-            reportLaunchFail(ex, "listen");
-        }
-        return null;
-    }
-
-    private Connector findConnector(String name) {
-        for (Connector cntor
-                : Bootstrap.virtualMachineManager().allConnectors()) {
-            if (cntor.name().equals(name)) {
-                return cntor;
-            }
-        }
-        return null;
-    }
-
-    private Map<String, Connector.Argument> mergeConnectorArgs(Connector connector, Map<String, String> argumentName2Value) {
-        Map<String, Connector.Argument> arguments = connector.defaultArguments();
-
-        for (Entry<String, String> argumentEntry : argumentName2Value.entrySet()) {
-            String name = argumentEntry.getKey();
-            String value = argumentEntry.getValue();
-            Connector.Argument argument = arguments.get(name);
-
-            if (argument == null) {
-                throw new IllegalArgumentException("Argument is not defined for connector:" +
-                        name + " -- " + connector.name());
-            }
-
-            argument.setValue(value);
-        }
-
-        return arguments;
-    }
-
-    /**
-     * The JShell specific Connector args for the LaunchingConnector.
-     *
-     * @param portthe socket port for (non-JDI) commands
-     * @param remoteVMOptions any user requested VM options
-     * @return the argument map
-     */
-    private Map<String, String> launchArgs(int port, String remoteVMOptions) {
-        Map<String, String> argumentName2Value = new HashMap<>();
-        argumentName2Value.put("main", remoteAgent + " " + port);
-        argumentName2Value.put("options", remoteVMOptions);
-        return argumentName2Value;
-    }
-
-    private void reportLaunchFail(Exception ex, String context) {
-        throw new InternalError("Failed remote " + context + ": " + connector +
-                " -- " + connectorArgs, ex);
-    }
-
-    /**
-     * Log debugging information. Arguments as for {@code printf}.
-     *
-     * @param format a format string as described in Format string syntax
-     * @param args arguments referenced by the format specifiers in the format
-     * string.
-     */
-    private void debug(String format, Object... args) {
-        // Reserved for future logging
-    }
-
-    /**
-     * Log a serious unexpected internal exception.
-     *
-     * @param ex the exception
-     * @param where a description of the context of the exception
-     */
-    private void debug(Throwable ex, String where) {
-        // Reserved for future logging
-    }
-
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiDefaultExecutionControl.java	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,282 @@
+/*
+ * Copyright (c) 2016, 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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.
+ */
+package jdk.jshell.execution;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.io.OutputStream;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Consumer;
+import com.sun.jdi.BooleanValue;
+import com.sun.jdi.ClassNotLoadedException;
+import com.sun.jdi.Field;
+import com.sun.jdi.IncompatibleThreadStateException;
+import com.sun.jdi.InvalidTypeException;
+import com.sun.jdi.ObjectReference;
+import com.sun.jdi.StackFrame;
+import com.sun.jdi.ThreadReference;
+import com.sun.jdi.VMDisconnectedException;
+import com.sun.jdi.VirtualMachine;
+import jdk.jshell.spi.ExecutionControl;
+import jdk.jshell.spi.ExecutionEnv;
+import static jdk.jshell.execution.Util.remoteInputOutput;
+
+/**
+ * The implementation of {@link jdk.jshell.spi.ExecutionControl} that the
+ * JShell-core uses by default.
+ * Launches a remote process -- the "remote agent".
+ * Interfaces to the remote agent over a socket and via JDI.
+ * Designed to work with {@link RemoteExecutionControl}.
+ *
+ * @author Robert Field
+ * @author Jan Lahoda
+ */
+public class JdiDefaultExecutionControl extends JdiExecutionControl {
+
+    private static final String REMOTE_AGENT = RemoteExecutionControl.class.getName();
+
+    private VirtualMachine vm;
+    private Process process;
+
+    private final Object STOP_LOCK = new Object();
+    private boolean userCodeRunning = false;
+
+    /**
+     * Creates an ExecutionControl instance based on a JDI
+     * {@code LaunchingConnector}.
+     *
+     * @return the generator
+     */
+    public static ExecutionControl.Generator launch() {
+        return env -> create(env, true, null);
+    }
+
+    /**
+     * Creates an ExecutionControl instance based on a JDI
+     * {@code ListeningConnector}.
+     *
+     * @param host explicit hostname to use, if null use discovered
+     * hostname, applies to listening only (!isLaunch)
+     * @return the generator
+     */
+    public static ExecutionControl.Generator listen(String host) {
+        return env -> create(env, false, host);
+    }
+
+    /**
+     * Creates an ExecutionControl instance based on a JDI
+     * {@code ListeningConnector} or {@code LaunchingConnector}.
+     *
+     * Initialize JDI and use it to launch the remote JVM. Set-up a socket for
+     * commands and results. This socket also transports the user
+     * input/output/error.
+     *
+     * @param env the context passed by
+     * {@link jdk.jshell.spi.ExecutionControl#start(jdk.jshell.spi.ExecutionEnv) }
+     * @param isLaunch does JDI do the launch? That is, LaunchingConnector,
+     * otherwise we start explicitly and use ListeningConnector
+     * @param host explicit hostname to use, if null use discovered
+     * hostname, applies to listening only (!isLaunch)
+     * @return the channel
+     * @throws IOException if there are errors in set-up
+     */
+    private static ExecutionControl create(ExecutionEnv env,
+            boolean isLaunch, String host) throws IOException {
+        try (final ServerSocket listener = new ServerSocket(0)) {
+            // timeout after 60 seconds
+            listener.setSoTimeout(60000);
+            int port = listener.getLocalPort();
+
+            // Set-up the JDI connection
+            JdiInitiator jdii = new JdiInitiator(port,
+                    env.extraRemoteVMOptions(), REMOTE_AGENT, isLaunch, host);
+            VirtualMachine vm = jdii.vm();
+            Process process = jdii.process();
+
+            List<Consumer<String>> deathListeners = new ArrayList<>();
+            deathListeners.add(s -> env.closeDown());
+            Util.detectJdiExitEvent(vm, s -> {
+                for (Consumer<String> h : deathListeners) {
+                    h.accept(s);
+                }
+            });
+
+            // Set-up the commands/reslts on the socket.  Piggy-back snippet
+            // output.
+            Socket socket = listener.accept();
+            // out before in -- match remote creation so we don't hang
+            OutputStream out = socket.getOutputStream();
+            Map<String, OutputStream> outputs = new HashMap<>();
+            outputs.put("out", env.userOut());
+            outputs.put("err", env.userErr());
+            Map<String, InputStream> input = new HashMap<>();
+            input.put("in", env.userIn());
+            return remoteInputOutput(socket.getInputStream(), out, outputs, input, (objIn, objOut) -> new JdiDefaultExecutionControl(objOut, objIn, vm, process, deathListeners));
+        }
+    }
+
+    /**
+     * Create an instance.
+     *
+     * @param cmdout the output for commands
+     * @param cmdin the input for responses
+     */
+    private JdiDefaultExecutionControl(ObjectOutput cmdout, ObjectInput cmdin,
+            VirtualMachine vm, Process process, List<Consumer<String>> deathListeners) {
+        super(cmdout, cmdin);
+        this.vm = vm;
+        this.process = process;
+        deathListeners.add(s -> disposeVM());
+    }
+
+    @Override
+    public String invoke(String classname, String methodname)
+            throws RunException,
+            EngineTerminationException, InternalException {
+        String res;
+        synchronized (STOP_LOCK) {
+            userCodeRunning = true;
+        }
+        try {
+            res = super.invoke(classname, methodname);
+        } finally {
+            synchronized (STOP_LOCK) {
+                userCodeRunning = false;
+            }
+        }
+        return res;
+    }
+
+    /**
+     * Interrupts a running remote invoke by manipulating remote variables
+     * and sending a stop via JDI.
+     *
+     * @throws EngineTerminationException the execution engine has terminated
+     * @throws InternalException an internal problem occurred
+     */
+    @Override
+    public void stop() throws EngineTerminationException, InternalException {
+        synchronized (STOP_LOCK) {
+            if (!userCodeRunning) {
+                return;
+            }
+
+            vm().suspend();
+            try {
+                OUTER:
+                for (ThreadReference thread : vm().allThreads()) {
+                    // could also tag the thread (e.g. using name), to find it easier
+                    for (StackFrame frame : thread.frames()) {
+                        if (REMOTE_AGENT.equals(frame.location().declaringType().name()) &&
+                                (    "invoke".equals(frame.location().method().name())
+                                || "varValue".equals(frame.location().method().name()))) {
+                            ObjectReference thiz = frame.thisObject();
+                            Field inClientCode = thiz.referenceType().fieldByName("inClientCode");
+                            Field expectingStop = thiz.referenceType().fieldByName("expectingStop");
+                            Field stopException = thiz.referenceType().fieldByName("stopException");
+                            if (((BooleanValue) thiz.getValue(inClientCode)).value()) {
+                                thiz.setValue(expectingStop, vm().mirrorOf(true));
+                                ObjectReference stopInstance = (ObjectReference) thiz.getValue(stopException);
+
+                                vm().resume();
+                                debug("Attempting to stop the client code...\n");
+                                thread.stop(stopInstance);
+                                thiz.setValue(expectingStop, vm().mirrorOf(false));
+                            }
+
+                            break OUTER;
+                        }
+                    }
+                }
+            } catch (ClassNotLoadedException | IncompatibleThreadStateException | InvalidTypeException ex) {
+                throw new InternalException("Exception on remote stop: " + ex);
+            } finally {
+                vm().resume();
+            }
+        }
+    }
+
+    @Override
+    public void close() {
+        super.close();
+        disposeVM();
+    }
+
+    private synchronized void disposeVM() {
+        try {
+            if (vm != null) {
+                vm.dispose(); // This could NPE, so it is caught below
+                vm = null;
+            }
+        } catch (VMDisconnectedException ex) {
+            // Ignore if already closed
+        } catch (Throwable ex) {
+            debug(ex, "disposeVM");
+        } finally {
+            if (process != null) {
+                process.destroy();
+                process = null;
+            }
+        }
+    }
+
+    @Override
+    protected synchronized VirtualMachine vm() throws EngineTerminationException {
+        if (vm == null) {
+            throw new EngineTerminationException("VM closed");
+        } else {
+            return vm;
+        }
+    }
+
+    /**
+     * Log debugging information. Arguments as for {@code printf}.
+     *
+     * @param format a format string as described in Format string syntax
+     * @param args arguments referenced by the format specifiers in the format
+     * string.
+     */
+    private static void debug(String format, Object... args) {
+        // Reserved for future logging
+    }
+
+    /**
+     * Log a serious unexpected internal exception.
+     *
+     * @param ex the exception
+     * @param where a description of the context of the exception
+     */
+    private static void debug(Throwable ex, String where) {
+        // Reserved for future logging
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiEventHandler.java	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,140 @@
+/*
+ * Copyright (c) 1998, 2014, 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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.
+ */
+
+package jdk.jshell.execution;
+
+import java.util.function.Consumer;
+import com.sun.jdi.*;
+import com.sun.jdi.event.*;
+
+/**
+ * Handler of Java Debug Interface events.
+ * Adapted from jdb EventHandler.
+ * Only exit and disconnect events processed.
+ */
+class JdiEventHandler implements Runnable {
+
+    private final Thread thread;
+    private volatile boolean connected = true;
+    private boolean completed = false;
+    private final VirtualMachine vm;
+    private final Consumer<String> reportVMExit;
+
+    /**
+     * Creates an event handler. Start with {@code start()}.
+     *
+     * @param vm the virtual machine for which to handle events
+     * @param reportVMExit callback to report exit/disconnect
+     * (passed true if the VM has died)
+     */
+    JdiEventHandler(VirtualMachine vm, Consumer<String> reportVMExit) {
+        this.vm = vm;
+        this.reportVMExit = reportVMExit;
+        this.thread = new Thread(this, "event-handler");
+        this.thread.setDaemon(true);
+    }
+
+    /**
+     * Starts the event handler.
+     */
+    void start() {
+        thread.start();
+    }
+
+    synchronized void shutdown() {
+        connected = false;  // force run() loop termination
+        thread.interrupt();
+        while (!completed) {
+            try {wait();} catch (InterruptedException exc) {}
+        }
+    }
+
+    @Override
+    public void run() {
+        EventQueue queue = vm.eventQueue();
+        while (connected) {
+            try {
+                EventSet eventSet = queue.remove();
+                boolean resumeStoppedApp = false;
+                EventIterator it = eventSet.eventIterator();
+                while (it.hasNext()) {
+                    resumeStoppedApp |= handleEvent(it.nextEvent());
+                }
+
+                if (resumeStoppedApp) {
+                    eventSet.resume();
+                }
+            } catch (InterruptedException exc) {
+                // Do nothing. Any changes will be seen at top of loop.
+            } catch (VMDisconnectedException discExc) {
+                handleDisconnectedException();
+                break;
+            }
+        }
+        synchronized (this) {
+            completed = true;
+            notifyAll();
+        }
+    }
+
+    private boolean handleEvent(Event event) {
+        handleExitEvent(event);
+        return true;
+    }
+
+    private void handleExitEvent(Event event) {
+        if (event instanceof VMDeathEvent) {
+            reportVMExit.accept("VM Died");
+        } else if (event instanceof VMDisconnectEvent) {
+            connected = false;
+            reportVMExit.accept("VM Disconnected");
+        } else {
+            // ignore everything else
+        }
+    }
+
+    private synchronized void handleDisconnectedException() {
+        /*
+         * A VMDisconnectedException has happened while dealing with
+         * another event. We need to flush the event queue, dealing only
+         * with exit events (VMDeath, VMDisconnect) so that we terminate
+         * correctly.
+         */
+        EventQueue queue = vm.eventQueue();
+        while (connected) {
+            try {
+                EventSet eventSet = queue.remove();
+                EventIterator iter = eventSet.eventIterator();
+                while (iter.hasNext()) {
+                    handleExitEvent(iter.next());
+                }
+            } catch (InterruptedException exc) {
+                // ignore
+            } catch (InternalError exc) {
+                // ignore
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiExecutionControl.java	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 2014, 2016, 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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.
+ */
+
+package jdk.jshell.execution;
+
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Stream;
+import com.sun.jdi.ReferenceType;
+import com.sun.jdi.VirtualMachine;
+import jdk.jshell.spi.ExecutionControl;
+import static java.util.stream.Collectors.toMap;
+
+/**
+ * Abstract JDI implementation of {@link jdk.jshell.spi.ExecutionControl}
+ */
+public abstract class JdiExecutionControl extends StreamingExecutionControl implements ExecutionControl {
+
+    /**
+     * Mapping from class names to JDI {@link ReferenceType}.
+     */
+    private final Map<String, ReferenceType> toReferenceType = new HashMap<>();
+
+    /**
+     * Create an instance.
+     * @param out the output from the remote agent
+     * @param in the input to the remote agent
+     */
+    protected JdiExecutionControl(ObjectOutput out, ObjectInput in) {
+        super(out, in);
+    }
+
+    /**
+     * Returns the JDI {@link VirtualMachine} instance.
+     *
+     * @return the virtual machine
+     * @throws EngineTerminationException if the VM is dead/disconnected
+     */
+    protected abstract VirtualMachine vm() throws EngineTerminationException;
+
+    /**
+     * Redefine the specified classes. Where 'redefine' is, as in JDI and JVMTI,
+     * an in-place replacement of the classes (preserving class identity) --
+     * that is, existing references to the class do not need to be recompiled.
+     * This implementation uses JDI
+     * {@link com.sun.jdi.VirtualMachine#redefineClasses(java.util.Map) }.
+     * It will be unsuccessful if
+     * the signature of the class has changed (see the JDI spec). The
+     * JShell-core is designed to adapt to unsuccessful redefine.
+     */
+    @Override
+    public void redefine(ClassBytecodes[] cbcs)
+            throws ClassInstallException, EngineTerminationException {
+        try {
+            // Convert to the JDI ReferenceType to class bytes map form needed
+            // by JDI.
+            VirtualMachine vm = vm();
+            Map<ReferenceType, byte[]> rmp = Stream.of(cbcs)
+                    .collect(toMap(
+                            cbc -> referenceType(vm, cbc.name()),
+                            cbc -> cbc.bytecodes()));
+            // Attempt redefine.  Throws exceptions on failure.
+            vm().redefineClasses(rmp);
+        } catch (EngineTerminationException ex) {
+            throw ex;
+        } catch (Exception ex) {
+            throw new ClassInstallException("redefine: " + ex.getMessage(), new boolean[cbcs.length]);
+        }
+    }
+
+    /**
+     * Returns the JDI {@link ReferenceType} corresponding to the specified
+     * class name.
+     *
+     * @param vm the current JDI {@link VirtualMachine} as returned by
+     * {@code vm()}
+     * @param name the class name to look-up
+     * @return the corresponding {@link ReferenceType}
+     */
+    protected ReferenceType referenceType(VirtualMachine vm, String name) {
+        return toReferenceType.computeIfAbsent(name, n -> nameToRef(vm, n));
+    }
+
+    private static ReferenceType nameToRef(VirtualMachine vm, String name) {
+        List<ReferenceType> rtl = vm.classesByName(name);
+        if (rtl.size() != 1) {
+            return null;
+        }
+        return rtl.get(0);
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiInitiator.java	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,223 @@
+/*
+ * Copyright (c) 2016, 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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.
+ */
+package jdk.jshell.execution;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import com.sun.jdi.Bootstrap;
+import com.sun.jdi.VirtualMachine;
+import com.sun.jdi.connect.Connector;
+import com.sun.jdi.connect.LaunchingConnector;
+import com.sun.jdi.connect.ListeningConnector;
+
+/**
+ * Sets up a JDI connection, providing the resulting JDI {@link VirtualMachine}
+ * and the {@link Process} the remote agent is running in.
+ */
+public class JdiInitiator {
+
+    private VirtualMachine vm;
+    private Process process = null;
+    private final Connector connector;
+    private final String remoteAgent;
+    private final Map<String, com.sun.jdi.connect.Connector.Argument> connectorArgs;
+
+    /**
+     * Start the remote agent and establish a JDI connection to it.
+     *
+     * @param port the socket port for (non-JDI) commands
+     * @param remoteVMOptions any user requested VM options
+     * @param remoteAgent full class name of remote agent to launch
+     * @param isLaunch does JDI do the launch? That is, LaunchingConnector,
+     * otherwise we start explicitly and use ListeningConnector
+     * @param host explicit hostname to use, if null use discovered
+     * hostname, applies to listening only (!isLaunch)
+     */
+    public JdiInitiator(int port, List<String> remoteVMOptions, String remoteAgent,
+            boolean isLaunch, String host) {
+        this.remoteAgent = remoteAgent;
+        String connectorName
+                = isLaunch
+                        ? "com.sun.jdi.CommandLineLaunch"
+                        : "com.sun.jdi.SocketListen";
+        this.connector = findConnector(connectorName);
+        if (connector == null) {
+            throw new IllegalArgumentException("No connector named: " + connectorName);
+        }
+        Map<String, String> argumentName2Value
+                = isLaunch
+                        ? launchArgs(port, String.join(" ", remoteVMOptions))
+                        : new HashMap<>();
+        if (host != null && !isLaunch) {
+            argumentName2Value.put("localAddress", host);
+        }
+        this.connectorArgs = mergeConnectorArgs(connector, argumentName2Value);
+        this.vm = isLaunch
+                ? launchTarget()
+                : listenTarget(port, remoteVMOptions);
+
+    }
+
+    /**
+     * Returns the resulting {@code VirtualMachine} instance.
+     *
+     * @return the virtual machine
+     */
+    public VirtualMachine vm() {
+        return vm;
+    }
+
+    /**
+     * Returns the launched process.
+     *
+     * @return the remote agent process
+     */
+    public Process process() {
+        return process;
+    }
+
+    /* launch child target vm */
+    private VirtualMachine launchTarget() {
+        LaunchingConnector launcher = (LaunchingConnector) connector;
+        try {
+            VirtualMachine new_vm = launcher.launch(connectorArgs);
+            process = new_vm.process();
+            return new_vm;
+        } catch (Exception ex) {
+            reportLaunchFail(ex, "launch");
+        }
+        return null;
+    }
+
+    /**
+     * Directly launch the remote agent and connect JDI to it with a
+     * ListeningConnector.
+     */
+    private VirtualMachine listenTarget(int port, List<String> remoteVMOptions) {
+        ListeningConnector listener = (ListeningConnector) connector;
+        try {
+            // Start listening, get the JDI connection address
+            String addr = listener.startListening(connectorArgs);
+            debug("Listening at address: " + addr);
+
+            // Launch the RemoteAgent requesting a connection on that address
+            String javaHome = System.getProperty("java.home");
+            List<String> args = new ArrayList<>();
+            args.add(javaHome == null
+                    ? "java"
+                    : javaHome + File.separator + "bin" + File.separator + "java");
+            args.add("-agentlib:jdwp=transport=" + connector.transport().name() +
+                    ",address=" + addr);
+            args.addAll(remoteVMOptions);
+            args.add(remoteAgent);
+            args.add("" + port);
+            ProcessBuilder pb = new ProcessBuilder(args);
+            process = pb.start();
+
+            // Forward out, err, and in
+            // Accept the connection from the remote agent
+            vm = listener.accept(connectorArgs);
+            listener.stopListening(connectorArgs);
+            return vm;
+        } catch (Exception ex) {
+            reportLaunchFail(ex, "listen");
+        }
+        return null;
+    }
+
+    private Connector findConnector(String name) {
+        for (Connector cntor
+                : Bootstrap.virtualMachineManager().allConnectors()) {
+            if (cntor.name().equals(name)) {
+                return cntor;
+            }
+        }
+        return null;
+    }
+
+    private Map<String, Connector.Argument> mergeConnectorArgs(Connector connector, Map<String, String> argumentName2Value) {
+        Map<String, Connector.Argument> arguments = connector.defaultArguments();
+
+        for (Entry<String, String> argumentEntry : argumentName2Value.entrySet()) {
+            String name = argumentEntry.getKey();
+            String value = argumentEntry.getValue();
+            Connector.Argument argument = arguments.get(name);
+
+            if (argument == null) {
+                throw new IllegalArgumentException("Argument is not defined for connector:" +
+                        name + " -- " + connector.name());
+            }
+
+            argument.setValue(value);
+        }
+
+        return arguments;
+    }
+
+    /**
+     * The JShell specific Connector args for the LaunchingConnector.
+     *
+     * @param portthe socket port for (non-JDI) commands
+     * @param remoteVMOptions any user requested VM options
+     * @return the argument map
+     */
+    private Map<String, String> launchArgs(int port, String remoteVMOptions) {
+        Map<String, String> argumentName2Value = new HashMap<>();
+        argumentName2Value.put("main", remoteAgent + " " + port);
+        argumentName2Value.put("options", remoteVMOptions);
+        return argumentName2Value;
+    }
+
+    private void reportLaunchFail(Exception ex, String context) {
+        throw new InternalError("Failed remote " + context + ": " + connector +
+                " -- " + connectorArgs, ex);
+    }
+
+    /**
+     * Log debugging information. Arguments as for {@code printf}.
+     *
+     * @param format a format string as described in Format string syntax
+     * @param args arguments referenced by the format specifiers in the format
+     * string.
+     */
+    private void debug(String format, Object... args) {
+        // Reserved for future logging
+    }
+
+    /**
+     * Log a serious unexpected internal exception.
+     *
+     * @param ex the exception
+     * @param where a description of the context of the exception
+     */
+    private void debug(Throwable ex, String where) {
+        // Reserved for future logging
+    }
+
+}
--- a/src/jdk.jshell/share/classes/jdk/jshell/execution/RemoteExecutionControl.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.jshell/share/classes/jdk/jshell/execution/RemoteExecutionControl.java	Thu Nov 10 15:58:49 2016 -0800
@@ -41,7 +41,7 @@
  * process). This agent loads code over a socket from the main JShell process,
  * executes the code, and other misc, Specialization of
  * {@link DirectExecutionControl} which adds stop support controlled by
- * an external process. Designed to work with {@link JDIDefaultExecutionControl}.
+ * an external process. Designed to work with {@link JdiDefaultExecutionControl}.
  *
  * @author Jan Lahoda
  * @author Robert Field
--- a/src/jdk.jshell/share/classes/jdk/jshell/execution/Util.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.jshell/share/classes/jdk/jshell/execution/Util.java	Thu Nov 10 15:58:49 2016 -0800
@@ -239,9 +239,9 @@
      * @param unbiddenExitHandler the handler, which will accept the exit
      * information
      */
-    public static void detectJDIExitEvent(VirtualMachine vm, Consumer<String> unbiddenExitHandler) {
+    public static void detectJdiExitEvent(VirtualMachine vm, Consumer<String> unbiddenExitHandler) {
         if (vm.canBeModified()) {
-            new JDIEventHandler(vm, unbiddenExitHandler).start();
+            new JdiEventHandler(vm, unbiddenExitHandler).start();
         }
     }
 
--- a/src/jdk.jshell/share/classes/jdk/jshell/spi/ExecutionControl.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.jshell/share/classes/jdk/jshell/spi/ExecutionControl.java	Thu Nov 10 15:58:49 2016 -0800
@@ -44,12 +44,13 @@
  * To install an {@code ExecutionControl}, its {@code Generator} is passed to
  * {@link jdk.jshell.JShell.Builder#executionEngine(ExecutionControl.Generator)  }.
  */
-public interface ExecutionControl {
+public interface ExecutionControl extends AutoCloseable {
 
     /**
      * Defines a functional interface for creating {@link ExecutionControl}
      * instances.
      */
+    @FunctionalInterface
     public interface Generator {
 
         /**
--- a/src/jdk.jshell/share/classes/module-info.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/src/jdk.jshell/share/classes/module-info.java	Thu Nov 10 15:58:49 2016 -0800
@@ -30,14 +30,16 @@
  */
 module jdk.jshell {
     requires transitive java.compiler;
-    requires java.desktop;
     requires java.prefs;
     requires jdk.compiler;
     requires jdk.internal.le;
+    requires jdk.internal.ed;
     requires jdk.internal.opt;
     requires jdk.jdi;
 
     exports jdk.jshell;
     exports jdk.jshell.spi;
     exports jdk.jshell.execution;
+
+    uses jdk.internal.editor.spi.BuildInEditorProvider;
 }
--- a/test/jdk/javadoc/tool/modules/Modules.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/jdk/javadoc/tool/modules/Modules.java	Thu Nov 10 15:58:49 2016 -0800
@@ -296,7 +296,7 @@
         checkMembersSelected("pkg2.B.f");
     }
 
-//    @Test @ignore JDK-8166379
+    @Test
     public void testPatchModuleOption(Path base) throws Exception {
         Path src = base.resolve("src");
         Path modulePath = base.resolve("modules");
--- a/test/jdk/jshell/ClassMembersTest.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/jdk/jshell/ClassMembersTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -38,6 +38,9 @@
 import jdk.jshell.SourceCodeAnalysis;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
+import jdk.jshell.TypeDeclSnippet;
+import static jdk.jshell.Snippet.Status.OVERWRITTEN;
+import static jdk.jshell.Snippet.Status.VALID;
 
 public class ClassMembersTest extends KullaTesting {
 
@@ -141,29 +144,36 @@
                 new ExpectedDiagnostic("compiler.err.non-static.cant.be.ref", 0, 8, 1, -1, -1, Diagnostic.Kind.ERROR));
     }
 
-    @Test(enabled = false) // TODO 8080354
-    public void annotationTest() {
+    @Test(dataProvider = "retentionPolicyTestCase")
+    public void annotationTest(RetentionPolicy policy) {
         assertEval("import java.lang.annotation.*;");
+        String annotationSource =
+                "@Retention(RetentionPolicy." + policy.toString() + ")\n" +
+                "@interface A {}";
+        assertEval(annotationSource);
+        String classSource =
+                "@A class C {\n" +
+                "   @A C() {}\n" +
+                "   @A void f() {}\n" +
+                "   @A int f;\n" +
+                "   @A class Inner {}\n" +
+                "}";
+        assertEval(classSource);
+        String isRuntimeVisible = policy == RetentionPolicy.RUNTIME ? "true" : "false";
+        assertEval("C.class.getAnnotationsByType(A.class).length > 0;", isRuntimeVisible);
+        assertEval("C.class.getDeclaredConstructor().getAnnotationsByType(A.class).length > 0;", isRuntimeVisible);
+        assertEval("C.class.getDeclaredMethod(\"f\").getAnnotationsByType(A.class).length > 0;", isRuntimeVisible);
+        assertEval("C.class.getDeclaredField(\"f\").getAnnotationsByType(A.class).length > 0;", isRuntimeVisible);
+        assertEval("C.Inner.class.getAnnotationsByType(A.class).length > 0;", isRuntimeVisible);
+    }
+
+    @DataProvider(name = "retentionPolicyTestCase")
+    public Object[][] retentionPolicyTestCaseGenerator() {
+        List<Object[]> list = new ArrayList<>();
         for (RetentionPolicy policy : RetentionPolicy.values()) {
-            String annotationSource =
-                    "@Retention(RetentionPolicy." + policy.toString() + ")\n" +
-                    "@interface A {}";
-            assertEval(annotationSource);
-            String classSource =
-                    "@A class C {\n" +
-                    "   @A C() {}\n" +
-                    "   @A void f() {}\n" +
-                    "   @A int f;\n" +
-                    "   @A class Inner {}\n" +
-                    "}";
-            assertEval(classSource);
-            String isRuntimeVisible = policy == RetentionPolicy.RUNTIME ? "true" : "false";
-            assertEval("C.class.getAnnotationsByType(A.class).length > 0;", isRuntimeVisible);
-            assertEval("C.class.getDeclaredConstructor().getAnnotationsByType(A.class).length > 0;", isRuntimeVisible);
-            assertEval("C.class.getDeclaredMethod(\"f\").getAnnotationsByType(A.class).length > 0;", isRuntimeVisible);
-            assertEval("C.class.getDeclaredField(\"f\").getAnnotationsByType(A.class).length > 0;", isRuntimeVisible);
-            assertEval("C.Inner.class.getAnnotationsByType(A.class).length > 0;", isRuntimeVisible);
+            list.add(new Object[]{policy});
         }
+        return list.toArray(new Object[list.size()][]);
     }
 
     @DataProvider(name = "memberTestCase")
--- a/test/jdk/jshell/ClassesTest.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/jdk/jshell/ClassesTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8145239
+ * @bug 8145239 8129559 8080354
  * @summary Tests for EvaluationState.classes
  * @build KullaTesting TestingInputStream ExpectedDiagnostic
  * @run testng ClassesTest
@@ -255,6 +255,25 @@
         assertActiveKeys();
     }
 
+    public void classesIgnoredModifiersAnnotation() {
+        assertEval("public @interface X { }");
+        assertEval("@X public interface A { }");
+        assertDeclareWarn1("@X static class B implements A { }",
+                new ExpectedDiagnostic("jdk.eval.warn.illegal.modifiers", 0, 9, 0, -1, -1, Diagnostic.Kind.WARNING));
+        assertDeclareWarn1("@X final interface C extends A { }",
+                new ExpectedDiagnostic("jdk.eval.warn.illegal.modifiers", 0, 8, 0, -1, -1, Diagnostic.Kind.WARNING));
+        assertActiveKeys();
+    }
+
+    public void classesIgnoredModifiersOtherModifiers() {
+        assertEval("strictfp public interface A { }");
+        assertDeclareWarn1("strictfp static class B implements A { }",
+                new ExpectedDiagnostic("jdk.eval.warn.illegal.modifiers", 0, 15, 0, -1, -1, Diagnostic.Kind.WARNING));
+        assertDeclareWarn1("strictfp final interface C extends A { }",
+                new ExpectedDiagnostic("jdk.eval.warn.illegal.modifiers", 0, 14, 0, -1, -1, Diagnostic.Kind.WARNING));
+        assertActiveKeys();
+    }
+
     public void ignoreModifierSpaceIssue() {
         assertEval("interface I { void f(); } ");
         // there should not be a space between 'I' and '{' to reproduce the failure
--- a/test/jdk/jshell/CompletenessTest.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/jdk/jshell/CompletenessTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8149524 8131024 8165211 8080071 8130454 8167343
+ * @bug 8149524 8131024 8165211 8080071 8130454 8167343 8129559
  * @summary Test SourceCodeAnalysis
  * @build KullaTesting TestingInputStream
  * @run testng CompletenessTest
@@ -176,6 +176,7 @@
         "@interface Anno",
         "void f()",
         "void f() throws E",
+        "@A(",
     };
 
     static final String[] unknown = new String[] {
--- a/test/jdk/jshell/EditorPadTest.java	Wed Nov 09 21:20:20 2016 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,246 +0,0 @@
-/*
- * Copyright (c) 2015, 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 8139872
- * @summary Testing built-in editor.
- * @modules java.desktop/java.awt
- *          jdk.jshell/jdk.internal.jshell.tool
- * @build ReplToolTesting EditorTestBase
- * @run testng EditorPadTest
- */
-
-import java.awt.AWTException;
-import java.awt.Component;
-import java.awt.Container;
-import java.awt.Dimension;
-import java.awt.Frame;
-import java.awt.GraphicsEnvironment;
-import java.awt.Point;
-import java.awt.Robot;
-import java.awt.event.InputEvent;
-import java.awt.event.WindowEvent;
-import java.lang.reflect.InvocationTargetException;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
-import java.util.function.Consumer;
-
-import javax.swing.JButton;
-import javax.swing.JFrame;
-import javax.swing.JPanel;
-import javax.swing.JScrollPane;
-import javax.swing.JTextArea;
-import javax.swing.JViewport;
-import javax.swing.SwingUtilities;
-
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-
-public class EditorPadTest extends EditorTestBase {
-
-    private static final int DELAY = 500;
-
-    private static Robot robot;
-    private static JFrame frame = null;
-    private static JTextArea area = null;
-    private static JButton cancel = null;
-    private static JButton accept = null;
-    private static JButton exit = null;
-
-    // Do not actually run if we are headless
-    @Override
-    public void testEditor(boolean defaultStartup, String[] args, ReplTest... tests) {
-        if (!GraphicsEnvironment.isHeadless()) {
-            test(defaultStartup, args, tests);
-        }
-    }
-
-    @BeforeClass
-    public static void setUpEditorPadTest() {
-        if (!GraphicsEnvironment.isHeadless()) {
-            try {
-                robot = new Robot();
-                robot.setAutoWaitForIdle(true);
-                robot.setAutoDelay(DELAY);
-            } catch (AWTException e) {
-                throw new ExceptionInInitializerError(e);
-            }
-        }
-    }
-
-    @AfterClass
-    public static void shutdown() {
-        executorShutdown();
-    }
-
-    @Override
-    public void writeSource(String s) {
-        SwingUtilities.invokeLater(() -> area.setText(s));
-    }
-
-    @Override
-    public String getSource() {
-        try {
-            String[] s = new String[1];
-            SwingUtilities.invokeAndWait(() -> s[0] = area.getText());
-            return s[0];
-        } catch (InvocationTargetException | InterruptedException e) {
-            throw new RuntimeException(e);
-        }
-    }
-
-    @Override
-    public void accept() {
-        clickOn(accept);
-    }
-
-    @Override
-    public void exit() {
-        clickOn(exit);
-    }
-
-    @Override
-    public void cancel() {
-        clickOn(cancel);
-    }
-
-    @Override
-    public void shutdownEditor() {
-        SwingUtilities.invokeLater(this::clearElements);
-        waitForIdle();
-    }
-
-    @Test
-    public void testShuttingDown() {
-        testEditor(
-                (a) -> assertEditOutput(a, "/ed", "", this::shutdownEditor)
-        );
-    }
-
-    private void waitForIdle() {
-        robot.waitForIdle();
-        robot.delay(DELAY);
-    }
-
-    private Future<?> task;
-    @Override
-    public void assertEdit(boolean after, String cmd,
-                           Consumer<String> checkInput, Consumer<String> checkOutput, Action action) {
-        if (!after) {
-            setCommandInput(cmd + "\n");
-            task = getExecutor().submit(() -> {
-                try {
-                    waitForIdle();
-                    SwingUtilities.invokeLater(this::seekElements);
-                    waitForIdle();
-                    checkInput.accept(getSource());
-                    action.accept();
-                } catch (Throwable e) {
-                    shutdownEditor();
-                    if (e instanceof AssertionError) {
-                        throw (AssertionError) e;
-                    }
-                    throw new RuntimeException(e);
-                }
-            });
-        } else {
-            try {
-                task.get();
-                waitForIdle();
-                checkOutput.accept(getCommandOutput());
-            } catch (ExecutionException e) {
-                if (e.getCause() instanceof AssertionError) {
-                    throw (AssertionError) e.getCause();
-                }
-                throw new RuntimeException(e);
-            } catch (Exception e) {
-                throw new RuntimeException(e);
-            } finally {
-                shutdownEditor();
-            }
-        }
-    }
-
-    private void seekElements() {
-        for (Frame f : Frame.getFrames()) {
-            if (f.getTitle().contains("Edit Pad")) {
-                frame = (JFrame) f;
-                // workaround
-                frame.setLocation(0, 0);
-                Container root = frame.getContentPane();
-                for (Component c : root.getComponents()) {
-                    if (c instanceof JScrollPane) {
-                        JScrollPane scrollPane = (JScrollPane) c;
-                        for (Component comp : scrollPane.getComponents()) {
-                            if (comp instanceof JViewport) {
-                                JViewport view = (JViewport) comp;
-                                area = (JTextArea) view.getComponent(0);
-                            }
-                        }
-                    }
-                    if (c instanceof JPanel) {
-                        JPanel p = (JPanel) c;
-                        for (Component comp : p.getComponents()) {
-                            if (comp instanceof JButton) {
-                                JButton b = (JButton) comp;
-                                switch (b.getText()) {
-                                    case "Cancel":
-                                        cancel = b;
-                                        break;
-                                    case "Exit":
-                                        exit = b;
-                                        break;
-                                    case "Accept":
-                                        accept = b;
-                                        break;
-                                }
-                            }
-                        }
-                    }
-                }
-            }
-        }
-    }
-
-    private void clearElements() {
-        if (frame != null) {
-            frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
-            frame = null;
-        }
-        area = null;
-        accept = null;
-        cancel = null;
-        exit = null;
-    }
-
-    private void clickOn(JButton button) {
-        waitForIdle();
-        Point p = button.getLocationOnScreen();
-        Dimension d = button.getSize();
-        robot.mouseMove(p.x + d.width / 2, p.y + d.height / 2);
-        robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
-        robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
-    }
-}
--- a/test/jdk/jshell/FailOverExecutionControlTest.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/jdk/jshell/FailOverExecutionControlTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -33,7 +33,7 @@
 
 import org.testng.annotations.Test;
 import org.testng.annotations.BeforeMethod;
-import jdk.jshell.execution.JDIDefaultExecutionControl;
+import jdk.jshell.execution.JdiDefaultExecutionControl;
 import jdk.jshell.spi.ExecutionControl;
 import jdk.jshell.spi.ExecutionEnv;
 import static jdk.jshell.execution.Util.failOverExecutionControlGenerator;
@@ -47,7 +47,7 @@
         setUp(builder -> builder.executionEngine(failOverExecutionControlGenerator(
                 new AlwaysFailingGenerator(),
                 new AlwaysFailingGenerator(),
-                JDIDefaultExecutionControl.launch())));
+                JdiDefaultExecutionControl.launch())));
     }
 
     class AlwaysFailingGenerator implements ExecutionControl.Generator {
--- a/test/jdk/jshell/IgnoreTest.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/jdk/jshell/IgnoreTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -22,7 +22,7 @@
  */
 
 /*
- * @test
+ * @test 8129559
  * @summary Test the ignoring of comments and certain modifiers
  * @build KullaTesting TestingInputStream
  * @run testng IgnoreTest
@@ -70,6 +70,39 @@
         assertVariableDeclSnippet(x5, "x5", "int", VALID, VAR_DECLARATION_SUBKIND, 0, 1);
     }
 
+    public void testVarModifierAnnotation() {
+        assertEval("@interface A { int value() default 0; }");
+        VarSnippet x1 = varKey(assertEval("@A public int x1;"));
+        assertVariableDeclSnippet(x1, "x1", "int", VALID, VAR_DECLARATION_SUBKIND, 0, 0);
+        VarSnippet x2 = varKey(assertEval("@A(14) protected int x2;"));
+        assertVariableDeclSnippet(x2, "x2", "int", VALID, VAR_DECLARATION_SUBKIND, 0, 0);
+        VarSnippet x3 = varKey(assertEval("@A(value=111)private int x3;"));
+        assertVariableDeclSnippet(x3, "x3", "int", VALID, VAR_DECLARATION_SUBKIND, 0, 0);
+        VarSnippet x4 = (VarSnippet) assertDeclareWarn1("@A static int x4;", "jdk.eval.warn.illegal.modifiers");
+        assertVariableDeclSnippet(x4, "x4", "int", VALID, VAR_DECLARATION_SUBKIND, 0, 1);
+        VarSnippet x5 = (VarSnippet) assertDeclareWarn1("@A(1111) final int x5;", "jdk.eval.warn.illegal.modifiers");
+        assertVariableDeclSnippet(x5, "x5", "int", VALID, VAR_DECLARATION_SUBKIND, 0, 1);
+    }
+
+    public void testVarModifierOtherModifier() {
+        VarSnippet x1 = varKey(assertEval("volatile public int x1;"));
+        assertVariableDeclSnippet(x1, "x1", "int", VALID, VAR_DECLARATION_SUBKIND, 0, 0);
+        VarSnippet x2 = varKey(assertEval("transient protected int x2;"));
+        assertVariableDeclSnippet(x2, "x2", "int", VALID, VAR_DECLARATION_SUBKIND, 0, 0);
+        VarSnippet x3 = varKey(assertEval("transient private int x3;"));
+        assertVariableDeclSnippet(x3, "x3", "int", VALID, VAR_DECLARATION_SUBKIND, 0, 0);
+        VarSnippet x4 = (VarSnippet) assertDeclareWarn1("volatile static int x4;", "jdk.eval.warn.illegal.modifiers");
+        assertVariableDeclSnippet(x4, "x4", "int", VALID, VAR_DECLARATION_SUBKIND, 0, 1);
+        VarSnippet x5 = (VarSnippet) assertDeclareWarn1("transient final int x5;", "jdk.eval.warn.illegal.modifiers");
+        assertVariableDeclSnippet(x5, "x5", "int", VALID, VAR_DECLARATION_SUBKIND, 0, 1);
+    }
+
+    public void testMisplacedIgnoredModifier() {
+        assertEvalFail("int public y;");
+        assertEvalFail("String private x;");
+        assertEvalFail("(protected 34);");
+    }
+
     public void testMethodModifier() {
         MethodSnippet m4 = (MethodSnippet) assertDeclareWarn1("static void m4() {}", "jdk.eval.warn.illegal.modifiers");
         assertMethodDeclSnippet(m4, "m4", "()void", VALID, 0, 1);
@@ -77,6 +110,14 @@
         assertMethodDeclSnippet(m5, "m5", "()void", VALID, 0, 1);
     }
 
+    public void testMethodModifierAnnotation() {
+        assertEval("@interface A { int value() default 0; }");
+        MethodSnippet m4 = (MethodSnippet) assertDeclareWarn1("@A static void m4() {}", "jdk.eval.warn.illegal.modifiers");
+        assertMethodDeclSnippet(m4, "m4", "()void", VALID, 0, 1);
+        MethodSnippet m5 = (MethodSnippet) assertDeclareWarn1("@A(value=66)final void m5() {}", "jdk.eval.warn.illegal.modifiers");
+        assertMethodDeclSnippet(m5, "m5", "()void", VALID, 0, 1);
+    }
+
     public void testClassModifier() {
         TypeDeclSnippet c4 = (TypeDeclSnippet) assertDeclareWarn1("static class C4 {}", "jdk.eval.warn.illegal.modifiers");
         assertTypeDeclSnippet(c4, "C4", VALID, CLASS_SUBKIND, 0, 1);
--- a/test/jdk/jshell/JDILaunchingExecutionControlTest.java	Wed Nov 09 21:20:20 2016 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 2016, 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 8164518
- * @summary Tests for standard JDI connector (without failover) -- launching
- * @modules jdk.jshell/jdk.jshell.execution
- * @build KullaTesting ExecutionControlTestBase
- * @run testng JDILaunchingExecutionControlTest
- */
-
-
-import org.testng.annotations.Test;
-import org.testng.annotations.BeforeMethod;
-import jdk.jshell.execution.JDIDefaultExecutionControl;
-
-@Test
-public class JDILaunchingExecutionControlTest extends ExecutionControlTestBase {
-
-    @BeforeMethod
-    @Override
-    public void setUp() {
-        setUp(builder -> builder.executionEngine(JDIDefaultExecutionControl.launch()));
-    }
-}
--- a/test/jdk/jshell/JDIListeningExecutionControlTest.java	Wed Nov 09 21:20:20 2016 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 2016, 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 8131029 8159935 8160127 8164518
- * @summary Tests for alternate JDI connector -- listening
- * @modules jdk.jshell/jdk.jshell.execution
- * @build KullaTesting ExecutionControlTestBase
- * @run testng JDIListeningExecutionControlTest
- */
-
-
-import org.testng.annotations.Test;
-import org.testng.annotations.BeforeMethod;
-import jdk.jshell.execution.JDIDefaultExecutionControl;
-
-@Test
-public class JDIListeningExecutionControlTest extends ExecutionControlTestBase {
-
-    @BeforeMethod
-    @Override
-    public void setUp() {
-        setUp(builder -> builder.executionEngine(JDIDefaultExecutionControl.listen(null)));
-    }
-}
--- a/test/jdk/jshell/JDIListeningLocalhostExecutionControlTest.java	Wed Nov 09 21:20:20 2016 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 2016, 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 8164518
- * @summary Tests for alternate JDI connector -- listening to "localhost"
- * @modules jdk.jshell/jdk.jshell.execution
- * @build KullaTesting ExecutionControlTestBase
- * @run testng JDIListeningLocalhostExecutionControlTest
- */
-
-
-import org.testng.annotations.Test;
-import org.testng.annotations.BeforeMethod;
-import jdk.jshell.execution.JDIDefaultExecutionControl;
-
-@Test
-public class JDIListeningLocalhostExecutionControlTest extends ExecutionControlTestBase {
-
-    @BeforeMethod
-    @Override
-    public void setUp() {
-        setUp(builder -> builder.executionEngine(JDIDefaultExecutionControl.listen("localhost")));
-    }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/jshell/JdiLaunchingExecutionControlTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2016, 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 8164518
+ * @summary Tests for standard JDI connector (without failover) -- launching
+ * @modules jdk.jshell/jdk.jshell.execution
+ * @build KullaTesting ExecutionControlTestBase
+ * @run testng JdiLaunchingExecutionControlTest
+ */
+
+
+import org.testng.annotations.Test;
+import org.testng.annotations.BeforeMethod;
+import jdk.jshell.execution.JdiDefaultExecutionControl;
+
+@Test
+public class JdiLaunchingExecutionControlTest extends ExecutionControlTestBase {
+
+    @BeforeMethod
+    @Override
+    public void setUp() {
+        setUp(builder -> builder.executionEngine(JdiDefaultExecutionControl.launch()));
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/jshell/JdiListeningExecutionControlTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2016, 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 8131029 8159935 8160127 8164518
+ * @summary Tests for alternate JDI connector -- listening
+ * @modules jdk.jshell/jdk.jshell.execution
+ * @build KullaTesting ExecutionControlTestBase
+ * @run testng JdiListeningExecutionControlTest
+ */
+
+
+import org.testng.annotations.Test;
+import org.testng.annotations.BeforeMethod;
+import jdk.jshell.execution.JdiDefaultExecutionControl;
+
+@Test
+public class JdiListeningExecutionControlTest extends ExecutionControlTestBase {
+
+    @BeforeMethod
+    @Override
+    public void setUp() {
+        setUp(builder -> builder.executionEngine(JdiDefaultExecutionControl.listen(null)));
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/jshell/JdiListeningLocalhostExecutionControlTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2016, 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 8164518
+ * @summary Tests for alternate JDI connector -- listening to "localhost"
+ * @modules jdk.jshell/jdk.jshell.execution
+ * @build KullaTesting ExecutionControlTestBase
+ * @run testng JdiListeningLocalhostExecutionControlTest
+ */
+
+
+import org.testng.annotations.Test;
+import org.testng.annotations.BeforeMethod;
+import jdk.jshell.execution.JdiDefaultExecutionControl;
+
+@Test
+public class JdiListeningLocalhostExecutionControlTest extends ExecutionControlTestBase {
+
+    @BeforeMethod
+    @Override
+    public void setUp() {
+        setUp(builder -> builder.executionEngine(JdiDefaultExecutionControl.listen("localhost")));
+    }
+}
--- a/test/jdk/jshell/ModifiersTest.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/jdk/jshell/ModifiersTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -22,7 +22,7 @@
  */
 
 /*
- * @test 8167643
+ * @test 8167643 8129559
  * @summary Tests for modifiers
  * @build KullaTesting TestingInputStream ExpectedDiagnostic
  * @run testng ModifiersTest
@@ -31,6 +31,7 @@
 import java.util.ArrayList;
 import java.util.List;
 
+import java.util.function.Consumer;
 import javax.tools.Diagnostic;
 
 import org.testng.annotations.DataProvider;
@@ -45,42 +46,53 @@
         String[] ignoredModifiers = new String[] {
             "static", "final"
         };
+        String[] silentlyIgnoredModifiers = new String[] {
+            "public", "protected", "private"
+        };
+        String[] before = new String[] {
+            "strictfp", "abstract", "@X", "@X(value=9)"
+        };
+        String context = "@interface X { int value() default 0; }";
+        Consumer<String> eval = this::assertEval;
+        Consumer<String> evalWarn = s -> assertDeclareWarn1(s, "jdk.eval.warn.illegal.modifiers");
         for (String ignoredModifier : ignoredModifiers) {
             for (ClassType classType : ClassType.values()) {
-                testCases.add(new Object[] { ignoredModifier, classType });
+                testCases.add(new Object[] { ignoredModifier, classType, evalWarn, "", null });
+            }
+        }
+        for (String ignoredModifier : ignoredModifiers) {
+            for (String preface : before) {
+                testCases.add(new Object[] { ignoredModifier, ClassType.CLASS, evalWarn, preface, context});
+            }
+        }
+        for (String ignoredModifier : silentlyIgnoredModifiers) {
+            for (ClassType classType : ClassType.values()) {
+                testCases.add(new Object[] { ignoredModifier, classType, eval, "", null });
+            }
+        }
+        for (String ignoredModifier : silentlyIgnoredModifiers) {
+            for (String preface : before) {
+                testCases.add(new Object[] { ignoredModifier, ClassType.CLASS, eval, preface, context});
             }
         }
         return testCases.toArray(new Object[testCases.size()][]);
     }
 
     @Test(dataProvider = "ignoredModifiers")
-    public void ignoredModifiers(String modifier, ClassType classType) {
-        assertDeclareWarn1(
-                String.format("%s %s A {}", modifier, classType), "jdk.eval.warn.illegal.modifiers");
-        assertNumberOfActiveClasses(1);
-        assertClasses(clazz(classType, "A"));
-        assertActiveKeys();
-    }
-
-    @DataProvider(name = "silentlyIgnoredModifiers")
-    public Object[][] getSilentTestCases() {
-        List<Object[]> testCases = new ArrayList<>();
-        String[] ignoredModifiers = new String[] {
-            "public", "protected", "private"
-        };
-        for (String ignoredModifier : ignoredModifiers) {
-            for (ClassType classType : ClassType.values()) {
-                testCases.add(new Object[] { ignoredModifier, classType });
-            }
+    public void ignoredModifiers(String modifier, ClassType classType,
+            Consumer<String> eval, String preface, String context) {
+        if (context != null) {
+            assertEval(context);
         }
-        return testCases.toArray(new Object[testCases.size()][]);
-    }
-
-    @Test(dataProvider = "silentlyIgnoredModifiers")
-    public void silentlyIgnoredModifiers(String modifier, ClassType classType) {
-        assertEval(String.format("%s %s A {}", modifier, classType));
-        assertNumberOfActiveClasses(1);
-        assertClasses(clazz(classType, "A"));
+        String decl = String.format("%s %s %s A {}", preface, modifier, classType);
+        eval.accept(decl);
+        if (context != null) {
+            assertNumberOfActiveClasses(2);
+            assertClasses(clazz(ClassType.ANNOTATION, "X"), clazz(classType, "A"));
+        } else {
+            assertNumberOfActiveClasses(1);
+            assertClasses(clazz(classType, "A"));
+        }
         assertActiveKeys();
     }
 
--- a/test/jdk/jshell/ToolFormatTest.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/jdk/jshell/ToolFormatTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8148316 8148317 8151755 8152246 8153551 8154812 8157261 8163840
+ * @bug 8148316 8148317 8151755 8152246 8153551 8154812 8157261 8163840 8166637 8161969
  * @summary Tests for output customization
  * @library /tools/lib
  * @modules jdk.compiler/com.sun.tools.javac.api
@@ -220,8 +220,8 @@
             test(
                     (a) -> assertCommandOutputStartsWith(a, "/set feedback normal", ""),
                     (a) -> assertCommand(a, "String s = java.util.stream.IntStream.range(65, 74)"+
-                            ".mapToObj(i -> \"\"+(char)i).reduce((a,b) -> a + b + a).get()",
-                            "s ==> \"ABACABADABACABAEABACABADABACABAFABACABADABACABAEABACABADABACABAGABACABADABA ..."),
+                            ".mapToObj(i -> \"\"+(char)i).reduce((a,b) -> a + b + a).get() + \"XYZ\"",
+                            "s ==> \"ABACABADABACABAEABACABADABACABAFABACABADABACABAE ... BACABAEABACABADABACABAXYZ\""),
                     (a) -> assertCommandOutputStartsWith(a, "/set mode test -quiet", ""),
                     (a) -> assertCommandOutputStartsWith(a, "/set feedback test", ""),
                     (a) -> assertCommand(a, "/set format test display '{type}:{value}' primary", ""),
@@ -234,8 +234,9 @@
                             "/set truncation test 10 varvalue"),
                     (a) -> assertCommandOutputContains(a, "/set truncation test",
                             "/set truncation test 10 varvalue"),
-                    (a) -> assertCommand(a, "String r = s", "String:\"ABACABADABACABA ..."),
-                    (a) -> assertCommand(a, "r", "String:\"ABACA ..."),
+                    (a) -> assertCommand(a, "/var", "|    String s = \"ABACABADA"),
+                    (a) -> assertCommand(a, "String r = s", "String:\"ABACABAD ... BAXYZ\""),
+                    (a) -> assertCommand(a, "r", "String:\"ABACABADA"),
                     (a) -> assertCommand(a, "r=s", "String:\"AB")
             );
         } finally {
--- a/test/jdk/jshell/ToolRetainTest.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/jdk/jshell/ToolRetainTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -23,13 +23,14 @@
 
 /*
  * @test
- * @bug 8157200 8163840
+ * @bug 8157200 8163840 8154513
  * @summary Tests of what information is retained across jshell tool runs
  * @modules jdk.jshell/jdk.internal.jshell.tool
  * @build ToolRetainTest ReplToolTesting
  * @run testng ToolRetainTest
  */
 
+import java.util.Locale;
 import org.testng.annotations.Test;
 
 @Test
@@ -62,14 +63,14 @@
                 (a) -> assertCommand(a, "/set mode -retain trm1", ""),
                 (a) -> assertCommand(a, "/exit", "")
         );
-        test(
+        test(Locale.ROOT, true, new String[0], "",
                 (a) -> assertCommand(a, "/set mode trm2 -quiet", ""),
                 (a) -> assertCommand(a, "/set format trm2 display '{name}={value}'", ""),
                 (a) -> assertCommand(a, "int x = 45", "x:45"),
                 (a) -> assertCommand(a, "/set mode -retain trm2", ""),
                 (a) -> assertCommand(a, "/exit", "")
         );
-        test(
+        test(Locale.ROOT, true, new String[0], "",
                 (a) -> assertCommandOutputContains(a, "/set mode trm1",
                         "/set format trm1 display \"{name}:{value}\""),
                 (a) -> assertCommand(a, "/set format trm2 display",
--- a/test/jdk/jshell/ToolSimpleTest.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/jdk/jshell/ToolSimpleTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8153716 8143955 8151754 8150382 8153920 8156910 8131024 8160089 8153897 8167128
+ * @bug 8153716 8143955 8151754 8150382 8153920 8156910 8131024 8160089 8153897 8167128 8154513
  * @summary Simple jshell tool tests
  * @modules jdk.compiler/com.sun.tools.javac.api
  *          jdk.compiler/com.sun.tools.javac.main
@@ -35,6 +35,7 @@
 import java.util.Arrays;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Locale;
 import java.util.function.Consumer;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
@@ -465,14 +466,14 @@
     }
 
     public void testOptionQ() {
-        test(new String[]{"-q", "--no-startup"},
+        test(Locale.ROOT, false, new String[]{"-q", "--no-startup"}, "",
                 (a) -> assertCommand(a, "1+1", "$1 ==> 2"),
                 (a) -> assertCommand(a, "int x = 5", "")
         );
     }
 
     public void testOptionS() {
-        test(new String[]{"-s", "--no-startup"},
+        test(Locale.ROOT, false, new String[]{"-s", "--no-startup"}, "",
                 (a) -> assertCommand(a, "1+1", "")
         );
     }
@@ -486,7 +487,7 @@
     }
 
     public void testOptionFeedback() {
-        test(new String[]{"--feedback", "concise", "--no-startup"},
+        test(Locale.ROOT, false, new String[]{"--feedback", "concise", "--no-startup"}, "",
                 (a) -> assertCommand(a, "1+1", "$1 ==> 2"),
                 (a) -> assertCommand(a, "int x = 5", "")
         );
@@ -498,17 +499,17 @@
                             .filter(l -> !l.isEmpty())
                             .count(), "Expected no lines: " + s);
                 };
-        test(new String[]{"-nq"},
+        test(Locale.ROOT, false, new String[]{"-nq"}, "",
                 (a) -> assertCommandCheckOutput(a, "/list -all", confirmNoStartup),
                 (a) -> assertCommand(a, "1+1", "$1 ==> 2"),
                 (a) -> assertCommand(a, "int x = 5", "")
         );
-        test(new String[]{"-qn"},
+        test(Locale.ROOT, false, new String[]{"-qn"}, "",
                 (a) -> assertCommandCheckOutput(a, "/list -all", confirmNoStartup),
                 (a) -> assertCommand(a, "1+1", "$1 ==> 2"),
                 (a) -> assertCommand(a, "int x = 5", "")
         );
-        test(new String[]{"-ns"},
+        test(Locale.ROOT, false, new String[]{"-ns"}, "",
                 (a) -> assertCommandCheckOutput(a, "/list -all", confirmNoStartup),
                 (a) -> assertCommand(a, "1+1", "")
         );
--- a/test/jdk/jshell/UserJDIUserRemoteTest.java	Wed Nov 09 21:20:20 2016 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,286 +0,0 @@
-/*
- * Copyright (c) 2016, 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 8160128 8159935
- * @summary Tests for Aux channel, custom remote agents, custom JDI implementations.
- * @build KullaTesting ExecutionControlTestBase
- * @run testng UserJDIUserRemoteTest
- */
-import java.io.ByteArrayOutputStream;
-import org.testng.annotations.Test;
-import org.testng.annotations.BeforeMethod;
-import jdk.jshell.Snippet;
-import static jdk.jshell.Snippet.Status.OVERWRITTEN;
-import static jdk.jshell.Snippet.Status.VALID;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.net.ServerSocket;
-import java.util.ArrayList;
-import java.util.List;
-import com.sun.jdi.VMDisconnectedException;
-import com.sun.jdi.VirtualMachine;
-import jdk.jshell.VarSnippet;
-import jdk.jshell.execution.DirectExecutionControl;
-import jdk.jshell.execution.JDIExecutionControl;
-import jdk.jshell.execution.JDIInitiator;
-import jdk.jshell.execution.Util;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.net.Socket;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.function.Consumer;
-import jdk.jshell.spi.ExecutionControl;
-import jdk.jshell.spi.ExecutionControl.ExecutionControlException;
-import jdk.jshell.spi.ExecutionEnv;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.fail;
-import static jdk.jshell.execution.Util.forwardExecutionControlAndIO;
-import static jdk.jshell.execution.Util.remoteInputOutput;
-
-@Test
-public class UserJDIUserRemoteTest extends ExecutionControlTestBase {
-
-    ExecutionControl currentEC;
-    ByteArrayOutputStream auxStream;
-
-    @BeforeMethod
-    @Override
-    public void setUp() {
-        auxStream = new ByteArrayOutputStream();
-        setUp(builder -> builder.executionEngine(MyExecutionControl.create(this)));
-    }
-
-    public void testVarValue() {
-        VarSnippet dv = varKey(assertEval("double aDouble = 1.5;"));
-        String vd = getState().varValue(dv);
-        assertEquals(vd, "1.5");
-        assertEquals(auxStream.toString(), "aDouble");
-    }
-
-    public void testExtension() throws ExecutionControlException {
-        assertEval("42;");
-        Object res = currentEC.extensionCommand("FROG", "test");
-        assertEquals(res, "ribbit");
-    }
-
-    public void testRedefine() {
-        Snippet vx = varKey(assertEval("int x;"));
-        Snippet mu = methodKey(assertEval("int mu() { return x * 4; }"));
-        Snippet c = classKey(assertEval("class C { String v() { return \"#\" + mu(); } }"));
-        assertEval("C c0  = new C();");
-        assertEval("c0.v();", "\"#0\"");
-        assertEval("int x = 10;", "10",
-                ste(MAIN_SNIPPET, VALID, VALID, false, null),
-                ste(vx, VALID, OVERWRITTEN, false, MAIN_SNIPPET));
-        assertEval("c0.v();", "\"#40\"");
-        assertEval("C c = new C();");
-        assertEval("c.v();", "\"#40\"");
-        assertEval("int mu() { return x * 3; }",
-                ste(MAIN_SNIPPET, VALID, VALID, false, null),
-                ste(mu, VALID, OVERWRITTEN, false, MAIN_SNIPPET));
-        assertEval("c.v();", "\"#30\"");
-        assertEval("class C { String v() { return \"@\" + mu(); } }",
-                ste(MAIN_SNIPPET, VALID, VALID, false, null),
-                ste(c, VALID, OVERWRITTEN, false, MAIN_SNIPPET));
-        assertEval("c0.v();", "\"@30\"");
-        assertEval("c = new C();");
-        assertEval("c.v();", "\"@30\"");
-        assertActiveKeys();
-    }
-}
-
-class MyExecutionControl extends JDIExecutionControl {
-
-    private static final String REMOTE_AGENT = MyRemoteExecutionControl.class.getName();
-
-    private VirtualMachine vm;
-    private Process process;
-
-    /**
-     * Creates an ExecutionControl instance based on a JDI
-     * {@code LaunchingConnector}.
-     *
-     * @return the generator
-     */
-    public static ExecutionControl.Generator create(UserJDIUserRemoteTest test) {
-        return env -> make(env, test);
-    }
-
-    /**
-     * Creates an ExecutionControl instance based on a JDI
-     * {@code ListeningConnector} or {@code LaunchingConnector}.
-     *
-     * Initialize JDI and use it to launch the remote JVM. Set-up a socket for
-     * commands and results. This socket also transports the user
-     * input/output/error.
-     *
-     * @param env the context passed by
-         * {@link jdk.jshell.spi.ExecutionControl#start(jdk.jshell.spi.ExecutionEnv) }
-     * @return the channel
-     * @throws IOException if there are errors in set-up
-     */
-    static ExecutionControl make(ExecutionEnv env, UserJDIUserRemoteTest test) throws IOException {
-        try (final ServerSocket listener = new ServerSocket(0)) {
-            // timeout after 60 seconds
-            listener.setSoTimeout(60000);
-            int port = listener.getLocalPort();
-
-            // Set-up the JDI connection
-            List<String> opts = new ArrayList<>(env.extraRemoteVMOptions());
-            opts.add("-classpath");
-            opts.add(System.getProperty("java.class.path")
-                    + System.getProperty("path.separator")
-                    + System.getProperty("user.dir"));
-            JDIInitiator jdii = new JDIInitiator(port,
-                    opts, REMOTE_AGENT, true, null);
-            VirtualMachine vm = jdii.vm();
-            Process process = jdii.process();
-
-            List<Consumer<String>> deathListeners = new ArrayList<>();
-            deathListeners.add(s -> env.closeDown());
-            Util.detectJDIExitEvent(vm, s -> {
-                for (Consumer<String> h : deathListeners) {
-                    h.accept(s);
-                }
-            });
-
-            // Set-up the commands/reslts on the socket.  Piggy-back snippet
-            // output.
-            Socket socket = listener.accept();
-            // out before in -- match remote creation so we don't hang
-            OutputStream out = socket.getOutputStream();
-            Map<String, OutputStream> outputs = new HashMap<>();
-            outputs.put("out", env.userOut());
-            outputs.put("err", env.userErr());
-            outputs.put("aux", test.auxStream);
-            Map<String, InputStream> input = new HashMap<>();
-            input.put("in", env.userIn());
-            ExecutionControl myec = remoteInputOutput(socket.getInputStream(), out, outputs, input, (objIn, objOut) -> new MyExecutionControl(objOut, objIn, vm, process, deathListeners));
-            test.currentEC = myec;
-            return myec;
-        }
-    }
-
-    /**
-     * Create an instance.
-     *
-     * @param out the output for commands
-     * @param in the input for responses
-     */
-    private MyExecutionControl(ObjectOutput out, ObjectInput in,
-            VirtualMachine vm, Process process,
-            List<Consumer<String>> deathListeners) {
-        super(out, in);
-        this.vm = vm;
-        this.process = process;
-        deathListeners.add(s -> disposeVM());
-    }
-
-    @Override
-    public void close() {
-        super.close();
-        disposeVM();
-    }
-
-    private synchronized void disposeVM() {
-        try {
-            if (vm != null) {
-                vm.dispose(); // This could NPE, so it is caught below
-                vm = null;
-            }
-        } catch (VMDisconnectedException ex) {
-            // Ignore if already closed
-        } catch (Throwable e) {
-            fail("disposeVM threw: " + e);
-        } finally {
-            if (process != null) {
-                process.destroy();
-                process = null;
-            }
-        }
-    }
-
-    @Override
-    protected synchronized VirtualMachine vm() throws EngineTerminationException {
-        if (vm == null) {
-            throw new EngineTerminationException("VM closed");
-        } else {
-            return vm;
-        }
-    }
-
-}
-
-class MyRemoteExecutionControl extends DirectExecutionControl implements ExecutionControl {
-
-    static PrintStream auxPrint;
-
-    /**
-     * Launch the agent, connecting to the JShell-core over the socket specified
-     * in the command-line argument.
-     *
-     * @param args standard command-line arguments, expectation is the socket
-     * number is the only argument
-     * @throws Exception any unexpected exception
-     */
-    public static void main(String[] args) throws Exception {
-        try {
-            String loopBack = null;
-            Socket socket = new Socket(loopBack, Integer.parseInt(args[0]));
-            InputStream inStream = socket.getInputStream();
-            OutputStream outStream = socket.getOutputStream();
-            Map<String, Consumer<OutputStream>> outputs = new HashMap<>();
-            outputs.put("out", st -> System.setOut(new PrintStream(st, true)));
-            outputs.put("err", st -> System.setErr(new PrintStream(st, true)));
-            outputs.put("aux", st -> { auxPrint = new PrintStream(st, true); });
-            Map<String, Consumer<InputStream>> input = new HashMap<>();
-            input.put("in", st -> System.setIn(st));
-            forwardExecutionControlAndIO(new MyRemoteExecutionControl(), inStream, outStream, outputs, input);
-        } catch (Throwable ex) {
-            throw ex;
-        }
-    }
-
-    @Override
-    public String varValue(String className, String varName)
-            throws RunException, EngineTerminationException, InternalException {
-        auxPrint.print(varName);
-        return super.varValue(className, varName);
-    }
-
-    @Override
-    public Object extensionCommand(String className, Object arg)
-            throws RunException, EngineTerminationException, InternalException {
-        if (!arg.equals("test")) {
-            throw new InternalException("expected extensionCommand arg to be 'test' got: " + arg);
-        }
-        return "ribbit";
-    }
-
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/jshell/UserJdiUserRemoteTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,286 @@
+/*
+ * Copyright (c) 2016, 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 8160128 8159935
+ * @summary Tests for Aux channel, custom remote agents, custom JDI implementations.
+ * @build KullaTesting ExecutionControlTestBase
+ * @run testng UserJdiUserRemoteTest
+ */
+import java.io.ByteArrayOutputStream;
+import org.testng.annotations.Test;
+import org.testng.annotations.BeforeMethod;
+import jdk.jshell.Snippet;
+import static jdk.jshell.Snippet.Status.OVERWRITTEN;
+import static jdk.jshell.Snippet.Status.VALID;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.net.ServerSocket;
+import java.util.ArrayList;
+import java.util.List;
+import com.sun.jdi.VMDisconnectedException;
+import com.sun.jdi.VirtualMachine;
+import jdk.jshell.VarSnippet;
+import jdk.jshell.execution.DirectExecutionControl;
+import jdk.jshell.execution.JdiExecutionControl;
+import jdk.jshell.execution.JdiInitiator;
+import jdk.jshell.execution.Util;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.net.Socket;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.function.Consumer;
+import jdk.jshell.spi.ExecutionControl;
+import jdk.jshell.spi.ExecutionControl.ExecutionControlException;
+import jdk.jshell.spi.ExecutionEnv;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.fail;
+import static jdk.jshell.execution.Util.forwardExecutionControlAndIO;
+import static jdk.jshell.execution.Util.remoteInputOutput;
+
+@Test
+public class UserJdiUserRemoteTest extends ExecutionControlTestBase {
+
+    ExecutionControl currentEC;
+    ByteArrayOutputStream auxStream;
+
+    @BeforeMethod
+    @Override
+    public void setUp() {
+        auxStream = new ByteArrayOutputStream();
+        setUp(builder -> builder.executionEngine(MyExecutionControl.create(this)));
+    }
+
+    public void testVarValue() {
+        VarSnippet dv = varKey(assertEval("double aDouble = 1.5;"));
+        String vd = getState().varValue(dv);
+        assertEquals(vd, "1.5");
+        assertEquals(auxStream.toString(), "aDouble");
+    }
+
+    public void testExtension() throws ExecutionControlException {
+        assertEval("42;");
+        Object res = currentEC.extensionCommand("FROG", "test");
+        assertEquals(res, "ribbit");
+    }
+
+    public void testRedefine() {
+        Snippet vx = varKey(assertEval("int x;"));
+        Snippet mu = methodKey(assertEval("int mu() { return x * 4; }"));
+        Snippet c = classKey(assertEval("class C { String v() { return \"#\" + mu(); } }"));
+        assertEval("C c0  = new C();");
+        assertEval("c0.v();", "\"#0\"");
+        assertEval("int x = 10;", "10",
+                ste(MAIN_SNIPPET, VALID, VALID, false, null),
+                ste(vx, VALID, OVERWRITTEN, false, MAIN_SNIPPET));
+        assertEval("c0.v();", "\"#40\"");
+        assertEval("C c = new C();");
+        assertEval("c.v();", "\"#40\"");
+        assertEval("int mu() { return x * 3; }",
+                ste(MAIN_SNIPPET, VALID, VALID, false, null),
+                ste(mu, VALID, OVERWRITTEN, false, MAIN_SNIPPET));
+        assertEval("c.v();", "\"#30\"");
+        assertEval("class C { String v() { return \"@\" + mu(); } }",
+                ste(MAIN_SNIPPET, VALID, VALID, false, null),
+                ste(c, VALID, OVERWRITTEN, false, MAIN_SNIPPET));
+        assertEval("c0.v();", "\"@30\"");
+        assertEval("c = new C();");
+        assertEval("c.v();", "\"@30\"");
+        assertActiveKeys();
+    }
+}
+
+class MyExecutionControl extends JdiExecutionControl {
+
+    private static final String REMOTE_AGENT = MyRemoteExecutionControl.class.getName();
+
+    private VirtualMachine vm;
+    private Process process;
+
+    /**
+     * Creates an ExecutionControl instance based on a JDI
+     * {@code LaunchingConnector}.
+     *
+     * @return the generator
+     */
+    public static ExecutionControl.Generator create(UserJdiUserRemoteTest test) {
+        return env -> make(env, test);
+    }
+
+    /**
+     * Creates an ExecutionControl instance based on a JDI
+     * {@code ListeningConnector} or {@code LaunchingConnector}.
+     *
+     * Initialize JDI and use it to launch the remote JVM. Set-up a socket for
+     * commands and results. This socket also transports the user
+     * input/output/error.
+     *
+     * @param env the context passed by
+         * {@link jdk.jshell.spi.ExecutionControl#start(jdk.jshell.spi.ExecutionEnv) }
+     * @return the channel
+     * @throws IOException if there are errors in set-up
+     */
+    static ExecutionControl make(ExecutionEnv env, UserJdiUserRemoteTest test) throws IOException {
+        try (final ServerSocket listener = new ServerSocket(0)) {
+            // timeout after 60 seconds
+            listener.setSoTimeout(60000);
+            int port = listener.getLocalPort();
+
+            // Set-up the JDI connection
+            List<String> opts = new ArrayList<>(env.extraRemoteVMOptions());
+            opts.add("-classpath");
+            opts.add(System.getProperty("java.class.path")
+                    + System.getProperty("path.separator")
+                    + System.getProperty("user.dir"));
+            JdiInitiator jdii = new JdiInitiator(port,
+                    opts, REMOTE_AGENT, true, null);
+            VirtualMachine vm = jdii.vm();
+            Process process = jdii.process();
+
+            List<Consumer<String>> deathListeners = new ArrayList<>();
+            deathListeners.add(s -> env.closeDown());
+            Util.detectJdiExitEvent(vm, s -> {
+                for (Consumer<String> h : deathListeners) {
+                    h.accept(s);
+                }
+            });
+
+            // Set-up the commands/reslts on the socket.  Piggy-back snippet
+            // output.
+            Socket socket = listener.accept();
+            // out before in -- match remote creation so we don't hang
+            OutputStream out = socket.getOutputStream();
+            Map<String, OutputStream> outputs = new HashMap<>();
+            outputs.put("out", env.userOut());
+            outputs.put("err", env.userErr());
+            outputs.put("aux", test.auxStream);
+            Map<String, InputStream> input = new HashMap<>();
+            input.put("in", env.userIn());
+            ExecutionControl myec = remoteInputOutput(socket.getInputStream(), out, outputs, input, (objIn, objOut) -> new MyExecutionControl(objOut, objIn, vm, process, deathListeners));
+            test.currentEC = myec;
+            return myec;
+        }
+    }
+
+    /**
+     * Create an instance.
+     *
+     * @param out the output for commands
+     * @param in the input for responses
+     */
+    private MyExecutionControl(ObjectOutput out, ObjectInput in,
+            VirtualMachine vm, Process process,
+            List<Consumer<String>> deathListeners) {
+        super(out, in);
+        this.vm = vm;
+        this.process = process;
+        deathListeners.add(s -> disposeVM());
+    }
+
+    @Override
+    public void close() {
+        super.close();
+        disposeVM();
+    }
+
+    private synchronized void disposeVM() {
+        try {
+            if (vm != null) {
+                vm.dispose(); // This could NPE, so it is caught below
+                vm = null;
+            }
+        } catch (VMDisconnectedException ex) {
+            // Ignore if already closed
+        } catch (Throwable e) {
+            fail("disposeVM threw: " + e);
+        } finally {
+            if (process != null) {
+                process.destroy();
+                process = null;
+            }
+        }
+    }
+
+    @Override
+    protected synchronized VirtualMachine vm() throws EngineTerminationException {
+        if (vm == null) {
+            throw new EngineTerminationException("VM closed");
+        } else {
+            return vm;
+        }
+    }
+
+}
+
+class MyRemoteExecutionControl extends DirectExecutionControl implements ExecutionControl {
+
+    static PrintStream auxPrint;
+
+    /**
+     * Launch the agent, connecting to the JShell-core over the socket specified
+     * in the command-line argument.
+     *
+     * @param args standard command-line arguments, expectation is the socket
+     * number is the only argument
+     * @throws Exception any unexpected exception
+     */
+    public static void main(String[] args) throws Exception {
+        try {
+            String loopBack = null;
+            Socket socket = new Socket(loopBack, Integer.parseInt(args[0]));
+            InputStream inStream = socket.getInputStream();
+            OutputStream outStream = socket.getOutputStream();
+            Map<String, Consumer<OutputStream>> outputs = new HashMap<>();
+            outputs.put("out", st -> System.setOut(new PrintStream(st, true)));
+            outputs.put("err", st -> System.setErr(new PrintStream(st, true)));
+            outputs.put("aux", st -> { auxPrint = new PrintStream(st, true); });
+            Map<String, Consumer<InputStream>> input = new HashMap<>();
+            input.put("in", st -> System.setIn(st));
+            forwardExecutionControlAndIO(new MyRemoteExecutionControl(), inStream, outStream, outputs, input);
+        } catch (Throwable ex) {
+            throw ex;
+        }
+    }
+
+    @Override
+    public String varValue(String className, String varName)
+            throws RunException, EngineTerminationException, InternalException {
+        auxPrint.print(varName);
+        return super.varValue(className, varName);
+    }
+
+    @Override
+    public Object extensionCommand(String className, Object arg)
+            throws RunException, EngineTerminationException, InternalException {
+        if (!arg.equals("test")) {
+            throw new InternalException("expected extensionCommand arg to be 'test' got: " + arg);
+        }
+        return "ribbit";
+    }
+
+}
--- a/test/tools/doclint/moduleTests/bad/module-info.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/tools/doclint/moduleTests/bad/module-info.java	Thu Nov 10 15:58:49 2016 -0800
@@ -6,7 +6,7 @@
  * @modules jdk.compiler/com.sun.tools.doclint
  * @build DocLintTester
  * @run main DocLintTester -ref module-info.out module-info.java
- * @compile/fail/ref=module-info.javac.out -XDrawDiagnostics -Werror -Xdoclint:all module-info.java
+ * @compile/fail/ref=module-info.javac.out -XDrawDiagnostics -Werror -Xlint:-options -Xdoclint:all module-info.java
  */
 
 // missing doc comment
--- a/test/tools/doclint/moduleTests/good/module-info.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/tools/doclint/moduleTests/good/module-info.java	Thu Nov 10 15:58:49 2016 -0800
@@ -29,7 +29,7 @@
  * @modules jdk.compiler/com.sun.tools.doclint
  * @build DocLintTester
  * @run main DocLintTester module-info.java
- * @compile -Xdoclint:all -Werror module-info.java
+ * @compile -Xdoclint:all -Werror -Xlint:-options module-info.java
  */
 
 /** good module */
--- a/test/tools/javac/T6403466.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/tools/javac/T6403466.java	Thu Nov 10 15:58:49 2016 -0800
@@ -58,9 +58,7 @@
                 fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrcDir, self + ".java")));
 
             Iterable<String> options = Arrays.asList(
-                "--add-exports",
-                    "jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED,"
-                    + "jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED",
+                "--add-exports", "jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED",
                 "--processor-path", testClassDir,
                 "-processor", self,
                 "-s", ".",
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/javac/diags/examples/BadNameForOption.java	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2016, 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.
+ */
+
+// key: compiler.warn.bad.name.for.option
+// options: --add-exports Bad!Name/p=java.base
+
+class BadNameForOption { }
+
--- a/test/tools/javac/diags/examples/CantFindModule/CantFindModule.java	Wed Nov 09 21:20:20 2016 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 2016, 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.
- */
-
-// key: compiler.err.cant.find.module
-// key: compiler.err.doesnt.exist
-
-// options: --add-exports undef/undef=ALL-UNNAMED
-
-import undef.Any;
-
-class Test {}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/javac/diags/examples/ModuleForOptionNotFound.java	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2016, 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.
+ */
+
+// key: compiler.warn.module.for.option.not.found
+// key: compiler.err.doesnt.exist
+
+// options: --add-exports undefModule/undefPackage=ALL-UNNAMED
+
+import undefPackage.Any;
+
+class Test {}
+
--- a/test/tools/javac/diags/examples/ServiceDefinitionInner/ServiceDefinitionInner.java	Wed Nov 09 21:20:20 2016 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,25 +0,0 @@
-/*
- * Copyright (c) 2016, 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.
- */
-
-// key: compiler.err.service.definition.is.inner
-// key: compiler.err.encl.class.required
--- a/test/tools/javac/diags/examples/ServiceDefinitionInner/modulesourcepath/m/module-info.java	Wed Nov 09 21:20:20 2016 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,27 +0,0 @@
-/*
- * Copyright (c) 2016, 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.
- */
-
-module m {
-    provides p1.C1.InnerDefinition with p2.C2;
-    exports p1;
-}
--- a/test/tools/javac/diags/examples/ServiceDefinitionInner/modulesourcepath/m/p1/C1.java	Wed Nov 09 21:20:20 2016 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,28 +0,0 @@
-/*
- * Copyright (c) 2016, 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.
- */
-
-package p1;
-
-public class C1 {
-    public class InnerDefinition {}
-}
--- a/test/tools/javac/diags/examples/ServiceDefinitionInner/modulesourcepath/m/p2/C2.java	Wed Nov 09 21:20:20 2016 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,26 +0,0 @@
-/*
- * Copyright (c) 2016, 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.
- */
-
-package p2;
-
-public class C2 extends p1.C1.InnerDefinition {}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/javac/diags/examples/WrongNumberTypeArgsFragment.java	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2016, 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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.
+ */
+
+// key: compiler.err.cant.apply.symbol
+// key: compiler.misc.wrong.number.type.args
+
+import java.util.*;
+
+class WrongNumberTypeArgsFragment {
+    void test() {
+        Arrays.<String, Integer>asList("");
+    }
+}
--- a/test/tools/javac/diags/examples/XaddexportsMalformedEntry.java	Wed Nov 09 21:20:20 2016 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,28 +0,0 @@
-/*
- * Copyright (c) 2016, 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.
- */
-
-// key: compiler.err.xaddexports.malformed.entry
-// options: --add-exports jdk.compiler/com.sun.tools.javac.util
-
-public class XaddexportsMalformedEntry {
-}
--- a/test/tools/javac/diags/examples/XaddexportsTooMany.java	Wed Nov 09 21:20:20 2016 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,28 +0,0 @@
-/*
- * Copyright (c) 2016, 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.
- */
-
-// key: compiler.err.xaddexports.too.many
-// options: --add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED  --add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED
-
-public class XaddexportsTooMany {
-}
--- a/test/tools/javac/diags/examples/XaddreadsMalformedEntry.java	Wed Nov 09 21:20:20 2016 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,28 +0,0 @@
-/*
- * Copyright (c) 2016, 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.
- */
-
-// key: compiler.err.xaddreads.malformed.entry
-// options: --add-reads jdk.compiler
-
-public class XaddreadsMalformedEntry {
-}
--- a/test/tools/javac/diags/examples/XaddreadsTooMany.java	Wed Nov 09 21:20:20 2016 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,28 +0,0 @@
-/*
- * Copyright (c) 2016, 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.
- */
-
-// key: compiler.err.xaddreads.too.many
-// options: --add-reads jdk.compiler=ALL-UNNAMED  --add-reads jdk.compiler=ALL-UNNAMED
-
-public class XaddreadsTooMany {
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/javac/modules/AddExportsTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,346 @@
+/*
+ * Copyright (c) 2015, 2016, 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
+ * @summary Test the --add-exports option
+ * @library /tools/lib
+ * @modules jdk.compiler/com.sun.tools.javac.api
+ *          jdk.compiler/com.sun.tools.javac.main
+ * @build toolbox.ToolBox toolbox.JavacTask ModuleTestBase
+ * @run main AddExportsTest
+ */
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Set;
+
+import toolbox.JavacTask;
+import toolbox.Task;
+import toolbox.ToolBox;
+
+public class AddExportsTest extends ModuleTestBase {
+
+    public static void main(String... args) throws Exception {
+        new AddExportsTest().runTests();
+    }
+
+    @Test
+    public void testEmpty(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "class Dummy { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+        testEmpty(src, classes, "--add-exports", "");
+        testEmpty(src, classes, "--add-exports=");
+    }
+
+    private void testEmpty(Path src, Path classes, String... options) throws Exception {
+        String log = new JavacTask(tb, Task.Mode.CMDLINE)
+                .options(options)
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        checkOutputContains(log,
+            "javac: no value for --add-exports option");
+    }
+
+    @Test
+    public void testEmptyItem(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { }",
+                          "package p1; public class C1 { }");
+        Path src_m2 = src.resolve("m2");
+        tb.writeJavaFiles(src_m2,
+                          "module m2 { }",
+                          "package p2; class C2 { p1.C1 c1; }");
+        Path src_m3 = src.resolve("m3");
+        tb.writeJavaFiles(src_m3,
+                          "module m3 { }",
+                          "package p3; class C3 { p1.C1 c1; }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        testEmptyItem(src, classes, "m1/p1=,m2,m3");
+        testEmptyItem(src, classes, "m1/p1=m2,,m3");
+        testEmptyItem(src, classes, "m1/p1=m2,m3,");
+    }
+
+    void testEmptyItem(Path src, Path classes, String option) throws Exception {
+        new JavacTask(tb)
+                .options("--module-source-path", src.toString(),
+                         "--add-exports", option)
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+    }
+
+    @Test
+    public void testEmptyList(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { exports p1; }",
+                          "package p1; public class C1 { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        testEmptyList(src, classes, "m1/p1=");
+        testEmptyList(src, classes, "m1/p1=,");
+    }
+
+    void testEmptyList(Path src, Path classes, String option) throws Exception {
+        String log = new JavacTask(tb, Task.Mode.CMDLINE)
+                .options("--module-source-path", src.toString(),
+                         "--add-exports", option)
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        checkOutputContains(log,
+            "javac: bad value for --add-exports option: '" + option + "'");
+    }
+
+    @Test
+    public void testMissingSourceParts(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { exports p1; }",
+                          "package p1; public class C1 { }");
+        Path src_m2 = src.resolve("m2");
+        tb.writeJavaFiles(src_m2,
+                          "module m2 { }",
+                          "package p2; class C2 { p1.C1 c1; }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        testMissingSourcePart(src, classes, "=m2");
+        testMissingSourcePart(src, classes, "/=m2");
+        testMissingSourcePart(src, classes, "m1/=m2");
+        testMissingSourcePart(src, classes, "/p1=m2");
+        testMissingSourcePart(src, classes, "m1p1=m2");
+    }
+
+    private void testMissingSourcePart(Path src, Path classes, String option) throws Exception {
+        String log = new JavacTask(tb, Task.Mode.CMDLINE)
+                .options("--module-source-path", src.toString(),
+                         "--add-exports", option)
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        checkOutputContains(log,
+            "javac: bad value for --add-exports option: '" + option + "'");
+    }
+
+    @Test
+    public void testBadSourceParts(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { exports p1; }",
+                          "package p1; public class C1 { }");
+        Path src_m2 = src.resolve("m2");
+        tb.writeJavaFiles(src_m2,
+                          "module m2 { }",
+                          "package p2; class C2 { p1.C1 c1; }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        testBadSourcePart(src, classes, "m!/p1=m2", "m!");
+        testBadSourcePart(src, classes, "m1/p!=m2", "p!");
+    }
+
+    private void testBadSourcePart(Path src, Path classes, String option, String badName)
+                throws Exception {
+        String log = new JavacTask(tb, Task.Mode.CMDLINE)
+                .options("-XDrawDiagnostics",
+                         "--module-source-path", src.toString(),
+                         "--add-exports", option)
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        checkOutputContains(log,
+            "- compiler.warn.bad.name.for.option: --add-exports, " + badName);
+    }
+
+    @Test
+    public void testBadTarget(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { exports p1; }",
+                          "package p1; public class C1 { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        String log = new JavacTask(tb, Task.Mode.CMDLINE)
+                .options("-XDrawDiagnostics",
+                         "--module-source-path", src.toString(),
+                         "--add-exports", "m1/p1=m!")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        checkOutputContains(log,
+            "- compiler.warn.bad.name.for.option: --add-exports, m!");
+    }
+
+    @Test
+    public void testSourceNotFound(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        String log = new JavacTask(tb, Task.Mode.CMDLINE)
+                .options("-XDrawDiagnostics",
+                         "--module-source-path", src.toString(),
+                         "--add-exports", "DoesNotExist/p=m1")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        checkOutputContains(log,
+            "- compiler.warn.module.for.option.not.found: --add-exports, DoesNotExist");
+    }
+
+    @Test
+    public void testTargetNotFound(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { }",
+                          "package p1; class C1 { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        String log = new JavacTask(tb, Task.Mode.CMDLINE)
+                .options("-XDrawDiagnostics",
+                         "--module-source-path", src.toString(),
+                         "--add-exports", "m1/p1=DoesNotExist")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        checkOutputContains(log,
+            "- compiler.warn.module.for.option.not.found: --add-exports, DoesNotExist");
+    }
+
+    @Test
+    public void testDuplicate(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { }",
+                          "package p1; public class C1 { }");
+        Path src_m2 = src.resolve("m2");
+        tb.writeJavaFiles(src_m2,
+                          "module m2 { }",
+                          "package p2; class C2 { p1.C1 c1; }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        new JavacTask(tb)
+                .options("--module-source-path", src.toString(),
+                         "--add-exports", "m1/p1=m2,m2")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+    }
+
+    @Test
+    public void testRepeated_SameTarget(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { }",
+                          "package p1; public class C1 { }");
+        Path src_m2 = src.resolve("m2");
+        tb.writeJavaFiles(src_m2,
+                          "module m2 { }",
+                          "package p2; class C2 { p1.C1 c1; }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        new JavacTask(tb)
+                .options("--module-source-path", src.toString(),
+                         "--add-exports", "m1/p1=m2",
+                         "--add-exports", "m1/p1=m2")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+    }
+
+    @Test
+    public void testRepeated_DifferentTarget(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { }",
+                          "package p1; public class C1 { }");
+        Path src_m2 = src.resolve("m2");
+        tb.writeJavaFiles(src_m2,
+                          "module m2 { }",
+                          "package p2; class C2 { p1.C1 c1; }");
+        Path src_m3 = src.resolve("m3");
+        tb.writeJavaFiles(src_m3,
+                          "module m3 { }",
+                          "package p3; class C3 { p1.C1 c1; }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        new JavacTask(tb)
+                .options("--module-source-path", src.toString(),
+                         "--add-exports", "m1/p1=m2",
+                         "--add-exports", "m1/p1=m3")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/javac/modules/AddModulesTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,232 @@
+/*
+ * Copyright (c) 2015, 2016, 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
+ * @summary Test the --add-modules option
+ * @library /tools/lib
+ * @modules jdk.compiler/com.sun.tools.javac.api
+ *          jdk.compiler/com.sun.tools.javac.main
+ * @build toolbox.ToolBox toolbox.JavacTask ModuleTestBase
+ * @run main AddModulesTest
+ */
+
+
+import java.nio.file.Path;
+
+import toolbox.JavacTask;
+import toolbox.Task;
+import toolbox.ToolBox;
+
+public class AddModulesTest extends ModuleTestBase {
+    public static void main(String... args) throws Exception {
+        new AddModulesTest().runTests();
+    }
+
+    @Test
+    public void testEmpty(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "class Dummy { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        testEmpty(src, classes, "--add-modules", "");
+        testEmpty(src, classes, "--add-modules=");
+    }
+
+    private void testEmpty(Path src, Path classes, String... options) throws Exception {
+        String log = new JavacTask(tb, Task.Mode.CMDLINE)
+                .options(options)
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        checkOutputContains(log,
+            "javac: no value for --add-modules option");
+    }
+
+    @Test
+    public void testEmptyItem(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { }");
+        Path src_m2 = src.resolve("m2");
+        tb.writeJavaFiles(src_m2,
+                          "module m2 { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        testEmptyItem(src, classes, ",m1");
+        testEmptyItem(src, classes, "m1,,m2");
+        testEmptyItem(src, classes, "m1,");
+    }
+
+    private void testEmptyItem(Path src, Path classes, String option) throws Exception {
+        new JavacTask(tb)
+                .options("--module-source-path", src.toString(),
+                         "--add-modules", option)
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+    }
+
+    @Test
+    public void testEmptyList(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "class Dummy { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        String log = new JavacTask(tb, Task.Mode.CMDLINE)
+                .options("--module-source-path", src.toString(),
+                         "--add-modules", ",")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        checkOutputContains(log,
+            "javac: bad value for --add-modules option");
+    }
+
+    @Test
+    public void testInvalidName(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "class Dummy { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        String log = new JavacTask(tb)
+                .options("-XDrawDiagnostics",
+                         "--add-modules", "BadModule!")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        checkOutputContains(log,
+            "- compiler.warn.bad.name.for.option: --add-modules, BadModule!");
+    }
+
+    @Test
+    public void testUnknownName(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "class Dummy { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        String log = new JavacTask(tb)
+                .options("-XDrawDiagnostics",
+                         "--add-modules", "DoesNotExist")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        checkOutputContains(log,
+            "- compiler.err.module.not.found: DoesNotExist");
+    }
+
+    @Test
+    public void testDuplicate(Path base) throws Exception {
+        Path src = base.resolve("src");
+
+        // setup a utility module
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { exports p1; }",
+                          "package p1; public class C1 { }");
+        Path modules = base.resolve("modules");
+        tb.createDirectories(modules);
+
+        new JavacTask(tb)
+                .options("--module-source-path", src.toString())
+                .outdir(modules)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+
+        // now test access to the module
+        Path src2 = base.resolve("src2");
+        tb.writeJavaFiles(src2,
+                          "class Dummy { p1.C1 c1; }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        new JavacTask(tb)
+                .options("--module-path", modules.toString(),
+                         "--add-modules", "m1,m1")
+                .outdir(classes)
+                .files(findJavaFiles(src2))
+                .run()
+                .writeAll();
+    }
+
+    @Test
+    public void testRepeatable(Path base) throws Exception {
+        Path src = base.resolve("src");
+
+        // setup some utility modules
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { exports p1; }",
+                          "package p1; public class C1 { }");
+        Path src_m2 = src.resolve("m2");
+        tb.writeJavaFiles(src_m2,
+                          "module m2 { exports p2; }",
+                          "package p2; public class C2 { }");
+        Path modules = base.resolve("modules");
+        tb.createDirectories(modules);
+
+        new JavacTask(tb)
+                .options("--module-source-path", src.toString())
+                .outdir(modules)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+
+        // now test access to the modules
+        Path src2 = base.resolve("src2");
+        tb.writeJavaFiles(src2,
+                          "class Dummy { p1.C1 c1; p2.C2 c2; }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        new JavacTask(tb)
+                .options("--module-path", modules.toString(),
+                         "--add-modules", "m1",
+                         "--add-modules", "m2")
+                .outdir(classes)
+                .files(findJavaFiles(src2))
+                .run()
+                .writeAll();
+    }
+}
+
--- a/test/tools/javac/modules/AddReadsTest.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/tools/javac/modules/AddReadsTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -28,6 +28,7 @@
  * @modules jdk.compiler/com.sun.tools.javac.api
  *          jdk.compiler/com.sun.tools.javac.main
  *          jdk.jdeps/com.sun.tools.javap
+ *          java.desktop
  * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask toolbox.JavapTask ModuleTestBase
  * @run main AddReadsTest
  */
@@ -49,7 +50,6 @@
 import toolbox.JavacTask;
 import toolbox.JavapTask;
 import toolbox.Task;
-import toolbox.ToolBox;
 
 public class AddReadsTest extends ModuleTestBase {
 
@@ -80,8 +80,8 @@
                 .writeAll()
                 .getOutput(Task.OutputKind.DIRECT);
 
-        if (!log.contains("Test.java:1:44: compiler.err.not.def.access.package.cant.access: api.Api, api"))
-            throw new Exception("expected output not found");
+        checkOutputContains(log,
+            "Test.java:1:44: compiler.err.not.def.access.package.cant.access: api.Api, api");
 
         //test add dependencies:
         new JavacTask(tb)
@@ -104,7 +104,8 @@
 
         //cyclic dependencies OK when created through addReads:
         new JavacTask(tb)
-                .options("--add-reads", "m2=m1,m1=m2",
+                .options("--add-reads", "m2=m1",
+                         "--add-reads", "m1=m2",
                          "--module-source-path", src.toString())
                 .outdir(classes)
                 .files(findJavaFiles(src))
@@ -233,7 +234,8 @@
                           "package impl; public class Impl { javax.swing.JButton b; }");
 
         new JavacTask(tb)
-          .options("--add-reads", "java.base=java.desktop",
+          .options("--add-modules", "java.desktop",
+                   "--add-reads", "java.base=java.desktop",
                    "-Xmodule:java.base")
           .outdir(classes)
           .files(findJavaFiles(src))
@@ -308,4 +310,356 @@
           .run()
           .writeAll();
     }
+
+    @Test
+    public void testAddSelf(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { exports p1; }",
+                          "package p1; public class C1 { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        new JavacTask(tb)
+                .options("--module-source-path", src.toString(),
+                         "--add-reads", "m1=m1")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+    }
+
+    @Test
+    public void testEmpty(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "class Dummy { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        testEmpty(src, classes, "--add-reads", "");
+        testEmpty(src, classes, "--add-reads=");
+    }
+
+    private void testEmpty(Path src, Path classes, String... options) throws Exception {
+        String log = new JavacTask(tb, Task.Mode.CMDLINE)
+                .options(options)
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        checkOutputContains(log,
+            "javac: no value for --add-reads option");
+    }
+
+    @Test
+    public void testEmptyItem(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { exports p1; }",
+                          "package p1; public class C1 { }");
+        Path src_m2 = src.resolve("m2");
+        tb.writeJavaFiles(src_m2,
+                          "module m2 { }",
+                          "package p2; class C2 { }");
+        Path src_m3 = src.resolve("m3");
+        tb.writeJavaFiles(src_m3,
+                          "module m3 { }",
+                          "package p3; class C3 { p1.C1 c1; }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        testEmptyItem(src, classes, "m3=,m1");
+        testEmptyItem(src, classes, "m3=m1,,m2");
+        testEmptyItem(src, classes, "m3=m1,");
+    }
+
+    private void testEmptyItem(Path src, Path classes, String option) throws Exception {
+        new JavacTask(tb)
+                .options("--module-source-path", src.toString(),
+                         "--add-reads", option)
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+    }
+
+    @Test
+    public void testEmptyList(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { exports p1; }",
+                          "package p1; public class C1 { }");
+        Path src_m2 = src.resolve("m2");
+        tb.writeJavaFiles(src_m2,
+                          "module m2 { }",
+                          "package p2; class C2 { }");
+        Path src_m3 = src.resolve("m3");
+        tb.writeJavaFiles(src_m3,
+                          "module m3 { }",
+                          "package p3; class C3 { p1.C1 c1; }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        testEmptyList(src, classes, "m3=");
+        testEmptyList(src, classes, "m3=,");
+    }
+
+    private void testEmptyList(Path src, Path classes, String option) throws Exception {
+        String log = new JavacTask(tb, Task.Mode.CMDLINE)
+                .options("--module-source-path", src.toString(),
+                         "--add-reads", option)
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        checkOutputContains(log,
+            "javac: bad value for --add-reads option: '" + option + "'");
+    }
+
+    @Test
+    public void testMultipleAddReads_DifferentModules(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { exports p1; }",
+                          "package p1; public class C1 { }");
+        Path src_m2 = src.resolve("m2");
+        tb.writeJavaFiles(src_m2,
+                          "module m2 { }",
+                          "package p2; class C2 { p1.C1 c1; }");
+        Path src_m3 = src.resolve("m3");
+        tb.writeJavaFiles(src_m3,
+                          "module m3 { }",
+                          "package p3; class C3 { p1.C1 c1; }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        new JavacTask(tb)
+                .options("--module-source-path", src.toString(),
+                         "--add-reads", "m2=m1",
+                         "--add-reads", "m3=m1")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+    }
+
+    @Test
+    public void testMultipleAddReads_SameModule(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { exports p1; }",
+                          "package p1; public class C1 { }");
+        Path src_m2 = src.resolve("m2");
+        tb.writeJavaFiles(src_m2,
+                          "module m2 { exports p2; }",
+                          "package p2; public class C2 { }");
+        Path src_m3 = src.resolve("m3");
+        tb.writeJavaFiles(src_m3,
+                          "module m3 { }",
+                          "package p3; class C3 { p1.C1 c1; p2.C2 c2; }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        new JavacTask(tb)
+                .options("--module-source-path", src.toString(),
+                         "--add-reads", "m3=m1",
+                         "--add-reads", "m3=m2")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+    }
+
+    @Test
+    public void testDuplicateAddReads_SameOption(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { exports p1; }",
+                          "package p1; public class C1 { }");
+        Path src_m2 = src.resolve("m2");
+        tb.writeJavaFiles(src_m2,
+                          "module m2 { exports p2; }",
+                          "package p2; class C2 { p1.C1 c1; }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        new JavacTask(tb)
+                .options("--module-source-path", src.toString(),
+                         "--add-reads", "m2=m1,m1")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+    }
+
+    @Test
+    public void testDuplicateAddReads_MultipleOptions(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { exports p1; }",
+                          "package p1; public class C1 { }");
+        Path src_m2 = src.resolve("m2");
+        tb.writeJavaFiles(src_m2,
+                          "module m2 { }",
+                          "package p2; class C2 { p1.C1 c1; }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        new JavacTask(tb)
+                .options("--module-source-path", src.toString(),
+                         "--add-reads", "m2=m1",
+                         "--add-reads", "m2=m1")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+    }
+
+    @Test
+    public void testRepeatedAddReads(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { exports p1; }",
+                          "package p1; public class C1 { }");
+        Path src_m2 = src.resolve("m2");
+        tb.writeJavaFiles(src_m2,
+                          "module m2 { exports p2; }",
+                          "package p2; public class C2 { }");
+        Path src_m3 = src.resolve("m3");
+        tb.writeJavaFiles(src_m3,
+                          "module m3 { }",
+                          "package p3; class C3 { p1.C1 c1; p2.C2 c2; }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        new JavacTask(tb)
+                .options("--module-source-path", src.toString(),
+                         "--add-reads", "m3=m1",
+                         "--add-reads", "m3=m2")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+    }
+
+    @Test
+    public void testNoEquals(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "class Dummy { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        String log = new JavacTask(tb, Task.Mode.CMDLINE)
+                .options("-XDrawDiagnostics",
+                         "--add-reads", "m1:m2")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        checkOutputContains(log,
+            "javac: bad value for --add-reads option: 'm1:m2'");
+    }
+
+    @Test
+    public void testBadSourceName(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "class Dummy { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        String log = new JavacTask(tb)
+                .options("-XDrawDiagnostics",
+                         "--add-reads", "bad*Source=m2")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        checkOutputContains(log,
+            "- compiler.warn.bad.name.for.option: --add-reads, bad*Source");
+    }
+
+    @Test
+    public void testBadTargetName(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { }",
+                          "package p1; class C1 { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        String log = new JavacTask(tb)
+                .options("-XDrawDiagnostics",
+                         "--add-reads", "m1=badTarget!")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        checkOutputContains(log,
+            "- compiler.warn.bad.name.for.option: --add-reads, badTarget!");
+    }
+
+    @Test
+    public void testSourceNameNotFound(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { exports p1; }",
+                          "package p1; public class C1 { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        String log = new JavacTask(tb)
+                .options("-XDrawDiagnostics",
+                         "--add-reads", "missingSource=m1")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        checkOutputContains(log,
+            "- compiler.warn.module.for.option.not.found: --add-reads, missingSource");
+    }
+
+    @Test
+    public void testTargetNameNotFound(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { exports p1; }",
+                          "package p1; public class C1 { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        String log = new JavacTask(tb)
+                .options("-XDrawDiagnostics",
+                         "--add-reads", "m1=missingTarget")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        checkOutputContains(log,
+            "- compiler.warn.module.for.option.not.found: --add-reads, missingTarget");
+    }
 }
--- a/test/tools/javac/modules/AnnotationProcessorsInModulesTest.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/tools/javac/modules/AnnotationProcessorsInModulesTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -230,8 +230,7 @@
                 .run(Task.Expect.FAIL)
                 .writeAll()
                 .getOutputLines(Task.OutputKind.DIRECT);
-        if (!log.equals(Arrays.asList("- compiler.err.processorpath.no.processormodulepath",
-                                      "1 error"))) {
+        if (!log.equals(Arrays.asList("- compiler.err.processorpath.no.processormodulepath"))) {
             throw new AssertionError("Unexpected output: " + log);
         }
     }
--- a/test/tools/javac/modules/EdgeCases.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/tools/javac/modules/EdgeCases.java	Thu Nov 10 15:58:49 2016 -0800
@@ -71,21 +71,22 @@
     @Test
     public void testAddExportUndefinedModule(Path base) throws Exception {
         Path src = base.resolve("src");
-        tb.writeJavaFiles(src, "package test; import undef.Any; public class Test {}");
+        tb.writeJavaFiles(src, "package test; import undefPackage.Any; public class Test {}");
         Path classes = base.resolve("classes");
         tb.createDirectories(classes);
 
         List<String> log = new JavacTask(tb)
-                .options("--add-exports", "undef/undef=ALL-UNNAMED", "-XDrawDiagnostics")
+                .options("--add-exports", "undefModule/undefPackage=ALL-UNNAMED",
+                         "-XDrawDiagnostics")
                 .outdir(classes)
                 .files(findJavaFiles(src))
                 .run(Task.Expect.FAIL)
                 .writeAll()
                 .getOutputLines(Task.OutputKind.DIRECT);
 
-        List<String> expected = Arrays.asList("- compiler.err.cant.find.module: undef",
-                                              "Test.java:1:27: compiler.err.doesnt.exist: undef",
-                                              "2 errors");
+        List<String> expected = Arrays.asList("- compiler.warn.module.for.option.not.found: --add-exports, undefModule",
+                                              "Test.java:1:34: compiler.err.doesnt.exist: undefPackage",
+                                              "1 error", "1 warning");
 
         if (!expected.equals(log))
             throw new Exception("expected output not found: " + log);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/javac/modules/LimitModulesTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,188 @@
+/*
+ * Copyright (c) 2015, 2016, 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
+ * @summary Test the --limit-modules option
+ * @library /tools/lib
+ * @modules jdk.compiler/com.sun.tools.javac.api
+ *          jdk.compiler/com.sun.tools.javac.main
+ * @build toolbox.ToolBox toolbox.JavacTask ModuleTestBase
+ * @run main LimitModulesTest
+ */
+
+
+import java.nio.file.Path;
+
+import toolbox.JavacTask;
+import toolbox.Task;
+import toolbox.ToolBox;
+
+public class LimitModulesTest extends ModuleTestBase {
+    public static void main(String... args) throws Exception {
+        new LimitModulesTest().runTests();
+    }
+
+    @Test
+    public void testEmpty(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "class Dummy { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        String log = new JavacTask(tb, Task.Mode.CMDLINE)
+                .options("--module-source-path", src.toString(),
+                         "--limit-modules", "")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!log.contains("javac: no value for --limit-modules option"))
+            throw new Exception("expected output not found");
+
+        log = new JavacTask(tb, Task.Mode.CMDLINE)
+                .options("--module-source-path", src.toString(),
+                         "--limit-modules=")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!log.contains("javac: no value for --limit-modules option"))
+            throw new Exception("expected output not found");
+    }
+
+    @Test
+    public void testEmptyItem(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1,
+                          "module m1 { }");
+        Path src_m2 = src.resolve("m2");
+        tb.writeJavaFiles(src_m2,
+                          "module m2 { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        new JavacTask(tb)
+                .options("--module-source-path", src.toString(),
+                         "--limit-modules", ",m1")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+
+        new JavacTask(tb)
+                .options("--module-source-path", src.toString(),
+                         "--limit-modules", "m1,,m2")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+
+        new JavacTask(tb)
+                .options("--module-source-path", src.toString(),
+                         "--limit-modules", "m1,")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+    }
+
+    @Test
+    public void testEmptyList(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "class Dummy { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        String log = new JavacTask(tb, Task.Mode.CMDLINE)
+                .options("--module-source-path", src.toString(),
+                         "--limit-modules", ",")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!log.contains("javac: bad value for --limit-modules option"))
+            throw new Exception("expected output not found");
+    }
+
+    @Test
+    public void testInvalidName(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "class Dummy { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        String log = new JavacTask(tb)
+                .options("-XDrawDiagnostics",
+                         "--limit-modules", "BadModule!")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!log.contains("- compiler.warn.bad.name.for.option: --limit-modules, BadModule!"))
+            throw new Exception("expected output not found");
+    }
+
+    @Test
+    public void testLastOneWins(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src,
+                          "package p; class C { com.sun.tools.javac.Main main; }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        System.err.println("case 1:");
+        new JavacTask(tb)
+                .options("-XDrawDiagnostics",
+                         "--limit-modules", "java.base",
+                         "--limit-modules", "jdk.compiler")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+
+        System.err.println("case 2:");
+        String log = new JavacTask(tb)
+                .options("-XDrawDiagnostics",
+                         "--limit-modules", "jdk.compiler",
+                         "--limit-modules", "java.base")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!log.contains("C.java:1:41: compiler.err.doesnt.exist: com.sun.tools.javac"))
+            throw new Exception("expected output not found");
+    }
+}
+
--- a/test/tools/javac/modules/ModuleTestBase.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/tools/javac/modules/ModuleTestBase.java	Thu Nov 10 15:58:49 2016 -0800
@@ -53,4 +53,12 @@
     Path[] findJavaFiles(Path... paths) throws IOException {
         return tb.findJavaFiles(paths);
     }
+
+    void checkOutputContains(String log, String... expect) throws Exception {
+        for (String e : expect) {
+            if (!log.contains(e)) {
+                throw new Exception("expected output not found: " + e);
+            }
+        }
+    }
 }
--- a/test/tools/javac/modules/PatchModulesTest.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/tools/javac/modules/PatchModulesTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -91,12 +91,28 @@
     }
 
     @Test
-    public void testLastOneWins(Path base) throws Exception {
+    public void testDuplicates(Path base) throws Exception {
         test(asList("java.base=a", "java.compiler=b", "java.base=c"),
-            "{java.base=[c], java.compiler=[b]}");
+            false, "--patch-module specified more than once for java.base");
+    }
+
+    @Test
+    public void testEmpty(Path base) throws Exception {
+        test(asList(""),
+            false, "no value for --patch-module option");
+    }
+
+    @Test
+    public void testInvalid(Path base) throws Exception {
+        test(asList("java.base/java.lang=."),
+            false, "bad value for --patch-module option: 'java.base/java.lang=.'");
     }
 
     void test(List<String> patches, String expect) throws Exception {
+        test(patches, true, expect);
+    }
+
+    void test(List<String> patches, boolean expectOK, String expect) throws Exception {
         JavacTool tool = (JavacTool) ToolProvider.getSystemJavaCompiler();
         StringWriter sw = new StringWriter();
         try (PrintWriter pw = new PrintWriter(sw)) {
@@ -121,6 +137,17 @@
                 tb.out.println("Found:  " + found);
                 error("output not as expected");
             }
+        } catch (IllegalArgumentException e) {
+            if (expectOK) {
+                error("unexpected exception: " + e);
+                throw e;
+            }
+            String found = e.getMessage();
+            if (!found.equals(expect)) {
+                tb.out.println("Expect: " + expect);
+                tb.out.println("Found:  " + found);
+                error("output not as expected");
+            }
         }
     }
 }
--- a/test/tools/javac/modules/ProvidesTest.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/tools/javac/modules/ProvidesTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -24,6 +24,7 @@
 /**
  * @test
  * @summary simple tests of module provides
+ * @bug 8168854
  * @library /tools/lib
  * @modules
  *      jdk.compiler/com.sun.tools.javac.api
@@ -39,6 +40,7 @@
 
 import toolbox.JavacTask;
 import toolbox.Task;
+import toolbox.Task.Expect;
 
 public class ProvidesTest extends ModuleTestBase {
     public static void main(String... args) throws Exception {
@@ -414,25 +416,14 @@
         tb.writeJavaFiles(src,
                 "module m { provides p1.C1.InnerDefinition with p2.C2; }",
                 "package p1; public class C1 { public class InnerDefinition { } }",
-                "package p2; public class C2 extends p1.C1.InnerDefinition { }");
+                "package p2; public class C2 extends p1.C1.InnerDefinition { public C2() { new p1.C1().super(); } }");
 
-        List<String> output = new JavacTask(tb)
+        new JavacTask(tb)
                 .options("-XDrawDiagnostics")
                 .outdir(Files.createDirectories(base.resolve("classes")))
                 .files(findJavaFiles(src))
-                .run(Task.Expect.FAIL)
-                .writeAll()
-                .getOutputLines(Task.OutputKind.DIRECT);
-
-        List<String> expected = Arrays.asList(
-                "module-info.java:1:26: compiler.err.service.definition.is.inner: p1.C1.InnerDefinition",
-                "module-info.java:1:12: compiler.warn.service.provided.but.not.exported.or.used: p1.C1.InnerDefinition",
-                "C2.java:1:20: compiler.err.encl.class.required: p1.C1.InnerDefinition",
-                "2 errors",
-                "1 warning");
-        if (!output.containsAll(expected)) {
-            throw new Exception("Expected output not found");
-        }
+                .run(Expect.SUCCESS)
+                .writeAll();
     }
 
     @Test
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/javac/modules/T8168854/module-info.java	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,10 @@
+/*
+ * @test
+ * @bug 8168854
+ * @summary javac erroneously reject a a service interface inner class in a provides clause
+ * @compile module-info.java
+ */
+module mod {
+    exports pack1;
+    provides pack1.Outer.Inter with pack1.Outer1.Implem;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/javac/modules/T8168854/pack1/Outer.java	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2016, 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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.
+ */
+
+package pack1;
+
+public class Outer {
+    public class Inter {
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/javac/modules/T8168854/pack1/Outer1.java	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2016, 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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.
+ */
+
+package pack1;
+
+public class Outer1 {
+    public static class Implem extends Outer.Inter {
+        public Implem () {
+            new Outer().super();
+        }
+    }
+}
--- a/test/tools/javac/modules/XModuleTest.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/tools/javac/modules/XModuleTest.java	Thu Nov 10 15:58:49 2016 -0800
@@ -223,8 +223,7 @@
                 .writeAll()
                 .getOutputLines(Task.OutputKind.DIRECT);
 
-        List<String> expected = Arrays.asList("- compiler.err.xmodule.no.module.sourcepath",
-                                              "1 error");
+        List<String> expected = Arrays.asList("- compiler.err.xmodule.no.module.sourcepath");
 
         if (!expected.equals(log))
             throw new Exception("expected output not found: " + log);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/javac/processing/model/LocalClasses/LocalClassesModel.java	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2016, 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 8166700
+ * @summary Check that local classes originating in static initializer can be loaded properly.
+ * @modules jdk.compiler
+ * @build LocalTest$1Local LocalTest$2Local LocalTest$3Local LocalTest$4Local LocalTest$5Local LocalTest
+ * @compile LocalClassesModel.java
+ * @compile/process/ref=LocalClassesModel.out -processor LocalClassesModel LocalTest$1Local LocalTest$2Local LocalTest$3Local LocalTest$4Local LocalTest$5Local LocalTest
+ */
+
+import java.util.Set;
+
+import javax.annotation.processing.AbstractProcessor;
+import javax.annotation.processing.RoundEnvironment;
+import javax.annotation.processing.SupportedAnnotationTypes;
+import javax.lang.model.SourceVersion;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.element.VariableElement;
+import javax.lang.model.util.ElementFilter;
+
+@SupportedAnnotationTypes("*")
+public class LocalClassesModel extends AbstractProcessor {
+
+    @Override
+    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
+        for (TypeElement root : ElementFilter.typesIn(roundEnv.getRootElements())) {
+            System.out.println(processingEnv.getElementUtils().getBinaryName(root));
+            for (ExecutableElement constr : ElementFilter.constructorsIn(root.getEnclosedElements())) {
+                System.out.print("  (");
+                boolean first = true;
+                for (VariableElement param : constr.getParameters()) {
+                    if (!first) {
+                        System.out.print(", ");
+                    }
+                    first = false;
+                    System.out.print(param.asType().toString());
+                }
+                System.out.println(")");
+            }
+        }
+
+        return false;
+    }
+
+    @Override
+    public SourceVersion getSupportedSourceVersion() {
+        return SourceVersion.latestSupported();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/javac/processing/model/LocalClasses/LocalClassesModel.out	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,12 @@
+LocalTest$1Local
+  ()
+LocalTest$2Local
+  (LocalTest)
+LocalTest$3Local
+  ()
+LocalTest$4Local
+  (LocalTest)
+LocalTest$5Local
+  (LocalTest)
+LocalTest
+  ()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/javac/processing/model/LocalClasses/LocalTest$1Local.jcod	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,77 @@
+class LocalTest$1Local {
+  0xCAFEBABE;
+  0; // minor version
+  52; // version
+  [] { // Constant Pool
+    ; // first element is empty
+    Method #3 #12; // #1    
+    class #13; // #2    
+    class #16; // #3    
+    Utf8 "<init>"; // #4    
+    Utf8 "()V"; // #5    
+    Utf8 "Code"; // #6    
+    Utf8 "LineNumberTable"; // #7    
+    Utf8 "SourceFile"; // #8    
+    Utf8 "LocalTest.java"; // #9    
+    Utf8 "EnclosingMethod"; // #10    
+    class #17; // #11    
+    NameAndType #4 #5; // #12    
+    Utf8 "LocalTest$1Local"; // #13    
+    Utf8 "Local"; // #14    
+    Utf8 "InnerClasses"; // #15    
+    Utf8 "java/lang/Object"; // #16    
+    Utf8 "LocalTest"; // #17    
+  } // Constant Pool
+
+  0x0020; // access
+  #2;// this_cpx
+  #3;// super_cpx
+
+  [] { // Interfaces
+  } // Interfaces
+
+  [] { // fields
+  } // fields
+
+  [] { // methods
+    { // Member
+      0x0000; // access
+      #4; // name_cpx
+      #5; // sig_cpx
+      [] { // Attributes
+        Attr(#6) { // Code
+          1; // max_stack
+          1; // max_locals
+          Bytes[]{
+            0x2AB70001B1;
+          };
+          [] { // Traps
+          } // end Traps
+          [] { // Attributes
+            Attr(#7) { // LineNumberTable
+              [] { // LineNumberTable
+                0  3;
+              }
+            } // end LineNumberTable
+          } // Attributes
+        } // end Code
+      } // Attributes
+    } // Member
+  } // methods
+
+  [] { // Attributes
+    Attr(#8) { // SourceFile
+      #9;
+    } // end SourceFile
+    ;
+    Attr(#10) { // EnclosingMethod
+      #11 #0;
+    } // end EnclosingMethod
+    ;
+    Attr(#15) { // InnerClasses
+      [] { // InnerClasses
+        #2 #0 #14 0;
+      }
+    } // end InnerClasses
+  } // Attributes
+} // end class LocalTest$1Local
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/javac/processing/model/LocalClasses/LocalTest$2Local.jcod	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,90 @@
+class LocalTest$2Local {
+  0xCAFEBABE;
+  0; // minor version
+  52; // version
+  [] { // Constant Pool
+    ; // first element is empty
+    Field #3 #15; // #1    
+    Method #4 #16; // #2    
+    class #17; // #3    
+    class #20; // #4    
+    Utf8 "this$0"; // #5    
+    Utf8 "LLocalTest;"; // #6    
+    Utf8 "<init>"; // #7    
+    Utf8 "(LLocalTest;)V"; // #8    
+    Utf8 "Code"; // #9    
+    Utf8 "LineNumberTable"; // #10    
+    Utf8 "SourceFile"; // #11    
+    Utf8 "LocalTest.java"; // #12    
+    Utf8 "EnclosingMethod"; // #13    
+    class #21; // #14    
+    NameAndType #5 #6; // #15    
+    NameAndType #7 #22; // #16    
+    Utf8 "LocalTest$2Local"; // #17    
+    Utf8 "Local"; // #18    
+    Utf8 "InnerClasses"; // #19    
+    Utf8 "java/lang/Object"; // #20    
+    Utf8 "LocalTest"; // #21    
+    Utf8 "()V"; // #22    
+  } // Constant Pool
+
+  0x0020; // access
+  #3;// this_cpx
+  #4;// super_cpx
+
+  [] { // Interfaces
+  } // Interfaces
+
+  [] { // fields
+    { // Member
+      0x1010; // access
+      #5; // name_cpx
+      #6; // sig_cpx
+      [] { // Attributes
+      } // Attributes
+    } // Member
+  } // fields
+
+  [] { // methods
+    { // Member
+      0x0000; // access
+      #7; // name_cpx
+      #8; // sig_cpx
+      [] { // Attributes
+        Attr(#9) { // Code
+          2; // max_stack
+          2; // max_locals
+          Bytes[]{
+            0x2A2BB500012AB700;
+            0x02B1;
+          };
+          [] { // Traps
+          } // end Traps
+          [] { // Attributes
+            Attr(#10) { // LineNumberTable
+              [] { // LineNumberTable
+                0  6;
+              }
+            } // end LineNumberTable
+          } // Attributes
+        } // end Code
+      } // Attributes
+    } // Member
+  } // methods
+
+  [] { // Attributes
+    Attr(#11) { // SourceFile
+      #12;
+    } // end SourceFile
+    ;
+    Attr(#13) { // EnclosingMethod
+      #14 #0;
+    } // end EnclosingMethod
+    ;
+    Attr(#19) { // InnerClasses
+      [] { // InnerClasses
+        #3 #0 #18 0;
+      }
+    } // end InnerClasses
+  } // Attributes
+} // end class LocalTest$2Local
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/javac/processing/model/LocalClasses/LocalTest$3Local.jcod	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,79 @@
+class LocalTest$3Local {
+  0xCAFEBABE;
+  0; // minor version
+  52; // version
+  [] { // Constant Pool
+    ; // first element is empty
+    Method #3 #13; // #1    
+    class #14; // #2    
+    class #17; // #3    
+    Utf8 "<init>"; // #4    
+    Utf8 "()V"; // #5    
+    Utf8 "Code"; // #6    
+    Utf8 "LineNumberTable"; // #7    
+    Utf8 "SourceFile"; // #8    
+    Utf8 "LocalTest.java"; // #9    
+    Utf8 "EnclosingMethod"; // #10    
+    class #18; // #11    
+    NameAndType #19 #5; // #12    
+    NameAndType #4 #5; // #13    
+    Utf8 "LocalTest$3Local"; // #14    
+    Utf8 "Local"; // #15    
+    Utf8 "InnerClasses"; // #16    
+    Utf8 "java/lang/Object"; // #17    
+    Utf8 "LocalTest"; // #18    
+    Utf8 "test1"; // #19    
+  } // Constant Pool
+
+  0x0020; // access
+  #2;// this_cpx
+  #3;// super_cpx
+
+  [] { // Interfaces
+  } // Interfaces
+
+  [] { // fields
+  } // fields
+
+  [] { // methods
+    { // Member
+      0x0000; // access
+      #4; // name_cpx
+      #5; // sig_cpx
+      [] { // Attributes
+        Attr(#6) { // Code
+          1; // max_stack
+          1; // max_locals
+          Bytes[]{
+            0x2AB70001B1;
+          };
+          [] { // Traps
+          } // end Traps
+          [] { // Attributes
+            Attr(#7) { // LineNumberTable
+              [] { // LineNumberTable
+                0  9;
+              }
+            } // end LineNumberTable
+          } // Attributes
+        } // end Code
+      } // Attributes
+    } // Member
+  } // methods
+
+  [] { // Attributes
+    Attr(#8) { // SourceFile
+      #9;
+    } // end SourceFile
+    ;
+    Attr(#10) { // EnclosingMethod
+      #11 #12;
+    } // end EnclosingMethod
+    ;
+    Attr(#16) { // InnerClasses
+      [] { // InnerClasses
+        #2 #0 #15 0;
+      }
+    } // end InnerClasses
+  } // Attributes
+} // end class LocalTest$3Local
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/javac/processing/model/LocalClasses/LocalTest$4Local.jcod	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,92 @@
+class LocalTest$4Local {
+  0xCAFEBABE;
+  0; // minor version
+  52; // version
+  [] { // Constant Pool
+    ; // first element is empty
+    Field #3 #16; // #1    
+    Method #4 #17; // #2    
+    class #18; // #3    
+    class #21; // #4    
+    Utf8 "this$0"; // #5    
+    Utf8 "LLocalTest;"; // #6    
+    Utf8 "<init>"; // #7    
+    Utf8 "(LLocalTest;)V"; // #8    
+    Utf8 "Code"; // #9    
+    Utf8 "LineNumberTable"; // #10    
+    Utf8 "SourceFile"; // #11    
+    Utf8 "LocalTest.java"; // #12    
+    Utf8 "EnclosingMethod"; // #13    
+    class #22; // #14    
+    NameAndType #23 #24; // #15    
+    NameAndType #5 #6; // #16    
+    NameAndType #7 #24; // #17    
+    Utf8 "LocalTest$4Local"; // #18    
+    Utf8 "Local"; // #19    
+    Utf8 "InnerClasses"; // #20    
+    Utf8 "java/lang/Object"; // #21    
+    Utf8 "LocalTest"; // #22    
+    Utf8 "test2"; // #23    
+    Utf8 "()V"; // #24    
+  } // Constant Pool
+
+  0x0020; // access
+  #3;// this_cpx
+  #4;// super_cpx
+
+  [] { // Interfaces
+  } // Interfaces
+
+  [] { // fields
+    { // Member
+      0x1010; // access
+      #5; // name_cpx
+      #6; // sig_cpx
+      [] { // Attributes
+      } // Attributes
+    } // Member
+  } // fields
+
+  [] { // methods
+    { // Member
+      0x0000; // access
+      #7; // name_cpx
+      #8; // sig_cpx
+      [] { // Attributes
+        Attr(#9) { // Code
+          2; // max_stack
+          2; // max_locals
+          Bytes[]{
+            0x2A2BB500012AB700;
+            0x02B1;
+          };
+          [] { // Traps
+          } // end Traps
+          [] { // Attributes
+            Attr(#10) { // LineNumberTable
+              [] { // LineNumberTable
+                0  12;
+              }
+            } // end LineNumberTable
+          } // Attributes
+        } // end Code
+      } // Attributes
+    } // Member
+  } // methods
+
+  [] { // Attributes
+    Attr(#11) { // SourceFile
+      #12;
+    } // end SourceFile
+    ;
+    Attr(#13) { // EnclosingMethod
+      #14 #15;
+    } // end EnclosingMethod
+    ;
+    Attr(#20) { // InnerClasses
+      [] { // InnerClasses
+        #3 #0 #19 0;
+      }
+    } // end InnerClasses
+  } // Attributes
+} // end class LocalTest$4Local
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/javac/processing/model/LocalClasses/LocalTest$5Local.jcod	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,90 @@
+class LocalTest$5Local {
+  0xCAFEBABE;
+  0; // minor version
+  52; // version
+  [] { // Constant Pool
+    ; // first element is empty
+    Field #3 #16; // #1    
+    Method #4 #15; // #2    
+    class #17; // #3    
+    class #20; // #4    
+    Utf8 "this$0"; // #5    
+    Utf8 "LLocalTest;"; // #6    
+    Utf8 "<init>"; // #7    
+    Utf8 "(LLocalTest;)V"; // #8    
+    Utf8 "Code"; // #9    
+    Utf8 "LineNumberTable"; // #10    
+    Utf8 "SourceFile"; // #11    
+    Utf8 "LocalTest.java"; // #12    
+    Utf8 "EnclosingMethod"; // #13    
+    class #21; // #14    
+    NameAndType #7 #22; // #15    
+    NameAndType #5 #6; // #16    
+    Utf8 "LocalTest$5Local"; // #17    
+    Utf8 "Local"; // #18    
+    Utf8 "InnerClasses"; // #19    
+    Utf8 "java/lang/Object"; // #20    
+    Utf8 "LocalTest"; // #21    
+    Utf8 "()V"; // #22    
+  } // Constant Pool
+
+  0x0020; // access
+  #3;// this_cpx
+  #4;// super_cpx
+
+  [] { // Interfaces
+  } // Interfaces
+
+  [] { // fields
+    { // Member
+      0x1010; // access
+      #5; // name_cpx
+      #6; // sig_cpx
+      [] { // Attributes
+      } // Attributes
+    } // Member
+  } // fields
+
+  [] { // methods
+    { // Member
+      0x0000; // access
+      #7; // name_cpx
+      #8; // sig_cpx
+      [] { // Attributes
+        Attr(#9) { // Code
+          2; // max_stack
+          2; // max_locals
+          Bytes[]{
+            0x2A2BB500012AB700;
+            0x02B1;
+          };
+          [] { // Traps
+          } // end Traps
+          [] { // Attributes
+            Attr(#10) { // LineNumberTable
+              [] { // LineNumberTable
+                0  15;
+              }
+            } // end LineNumberTable
+          } // Attributes
+        } // end Code
+      } // Attributes
+    } // Member
+  } // methods
+
+  [] { // Attributes
+    Attr(#11) { // SourceFile
+      #12;
+    } // end SourceFile
+    ;
+    Attr(#13) { // EnclosingMethod
+      #14 #15;
+    } // end EnclosingMethod
+    ;
+    Attr(#19) { // InnerClasses
+      [] { // InnerClasses
+        #3 #0 #18 0;
+      }
+    } // end InnerClasses
+  } // Attributes
+} // end class LocalTest$5Local
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/javac/processing/model/LocalClasses/LocalTest.jcod	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,160 @@
+class LocalTest {
+  0xCAFEBABE;
+  0; // minor version
+  52; // version
+  [] { // Constant Pool
+    ; // first element is empty
+    Method #3 #20; // #1    
+    class #21; // #2    
+    class #22; // #3    
+    class #23; // #4    
+    Utf8 "Local"; // #5    
+    Utf8 "InnerClasses"; // #6    
+    class #24; // #7    
+    class #25; // #8    
+    class #26; // #9    
+    class #27; // #10    
+    Utf8 "test1"; // #11    
+    Utf8 "()V"; // #12    
+    Utf8 "Code"; // #13    
+    Utf8 "LineNumberTable"; // #14    
+    Utf8 "test2"; // #15    
+    Utf8 "<init>"; // #16    
+    Utf8 "<clinit>"; // #17    
+    Utf8 "SourceFile"; // #18    
+    Utf8 "LocalTest.java"; // #19    
+    NameAndType #16 #12; // #20    
+    Utf8 "LocalTest"; // #21    
+    Utf8 "java/lang/Object"; // #22    
+    Utf8 "LocalTest$5Local"; // #23    
+    Utf8 "LocalTest$4Local"; // #24    
+    Utf8 "LocalTest$3Local"; // #25    
+    Utf8 "LocalTest$2Local"; // #26    
+    Utf8 "LocalTest$1Local"; // #27    
+  } // Constant Pool
+
+  0x0021; // access
+  #2;// this_cpx
+  #3;// super_cpx
+
+  [] { // Interfaces
+  } // Interfaces
+
+  [] { // fields
+  } // fields
+
+  [] { // methods
+    { // Member
+      0x0008; // access
+      #11; // name_cpx
+      #12; // sig_cpx
+      [] { // Attributes
+        Attr(#13) { // Code
+          0; // max_stack
+          0; // max_locals
+          Bytes[]{
+            0xB1;
+          };
+          [] { // Traps
+          } // end Traps
+          [] { // Attributes
+            Attr(#14) { // LineNumberTable
+              [] { // LineNumberTable
+                0  10;
+              }
+            } // end LineNumberTable
+          } // Attributes
+        } // end Code
+      } // Attributes
+    } // Member
+    ;
+    { // Member
+      0x0000; // access
+      #15; // name_cpx
+      #12; // sig_cpx
+      [] { // Attributes
+        Attr(#13) { // Code
+          0; // max_stack
+          1; // max_locals
+          Bytes[]{
+            0xB1;
+          };
+          [] { // Traps
+          } // end Traps
+          [] { // Attributes
+            Attr(#14) { // LineNumberTable
+              [] { // LineNumberTable
+                0  13;
+              }
+            } // end LineNumberTable
+          } // Attributes
+        } // end Code
+      } // Attributes
+    } // Member
+    ;
+    { // Member
+      0x0000; // access
+      #16; // name_cpx
+      #12; // sig_cpx
+      [] { // Attributes
+        Attr(#13) { // Code
+          1; // max_stack
+          1; // max_locals
+          Bytes[]{
+            0x2AB70001B1;
+          };
+          [] { // Traps
+          } // end Traps
+          [] { // Attributes
+            Attr(#14) { // LineNumberTable
+              [] { // LineNumberTable
+                0  14;
+                4  16;
+              }
+            } // end LineNumberTable
+          } // Attributes
+        } // end Code
+      } // Attributes
+    } // Member
+    ;
+    { // Member
+      0x0008; // access
+      #17; // name_cpx
+      #12; // sig_cpx
+      [] { // Attributes
+        Attr(#13) { // Code
+          0; // max_stack
+          0; // max_locals
+          Bytes[]{
+            0xB1;
+          };
+          [] { // Traps
+          } // end Traps
+          [] { // Attributes
+            Attr(#14) { // LineNumberTable
+              [] { // LineNumberTable
+                0  4;
+              }
+            } // end LineNumberTable
+          } // Attributes
+        } // end Code
+      } // Attributes
+    } // Member
+  } // methods
+
+  [] { // Attributes
+    Attr(#18) { // SourceFile
+      #19;
+    } // end SourceFile
+    ;
+    Attr(#6) { // InnerClasses
+      [] { // InnerClasses
+        #4 #0 #5 0;
+        #7 #0 #5 0;
+        #8 #0 #5 0;
+        #9 #0 #5 0;
+        #10 #0 #5 0;
+      }
+    } // end InnerClasses
+  } // Attributes
+} // end class LocalTest
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/javac/processing/model/LocalClasses/LocalTest.orign	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2016, 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.
+ */
+
+/**The jcod files are generated from this file, compiled by JDK 8 javac.
+ */
+public class LocalTest {
+    static {
+        class Local { }
+    }
+    {
+        class Local { }
+    }
+    static void test1() {
+        class Local { }
+    }
+    void test2() {
+        class Local { }
+    }
+    LocalTest() {
+        class Local { }
+    }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/javac/processing/model/nestedTypeVars/NestedTypeVars.java	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2016, 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
+ * @modules jdk.compiler
+ * @build NestedTypeVars
+ * @compile/process/ref=NestedTypeVars.out -processor NestedTypeVars Test$1L1$L2$1L3$L4$L5 Test$1L1$CCheck Test$1L1 Test$1CCheck Test$CCheck Test
+ */
+
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import javax.annotation.processing.AbstractProcessor;
+import javax.annotation.processing.RoundEnvironment;
+import javax.annotation.processing.SupportedAnnotationTypes;
+import javax.lang.model.SourceVersion;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.element.TypeParameterElement;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.type.TypeVariable;
+import javax.lang.model.util.ElementFilter;
+
+@SupportedAnnotationTypes("*")
+public class NestedTypeVars extends AbstractProcessor{
+
+    @Override
+    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
+        for (TypeElement te : ElementFilter.typesIn(roundEnv.getRootElements())) {
+            System.out.print(processingEnv.getElementUtils().getBinaryName(te));
+            System.out.print("<");
+            String separator = "";
+            for (TypeParameterElement tp : te.getTypeParameters()) {
+                System.out.print(separator);
+                separator = ", ";
+                System.out.print(tp.getSimpleName());
+                System.out.print(" extends ");
+                System.out.print(tp.getBounds().stream().map(b -> toString(b)).collect(Collectors.joining("&")));
+            }
+            System.out.println(">");
+            for (ExecutableElement m : ElementFilter.methodsIn(te.getEnclosedElements())) {
+                System.out.print("  <");
+                separator = "";
+                for (TypeParameterElement tp : m.getTypeParameters()) {
+                    System.out.print(separator);
+                    separator = ", ";
+                    System.out.print(tp.getSimpleName());
+                    System.out.print(" extends ");
+                    System.out.print(tp.getBounds().
+                            stream().
+                            map(b -> toString(b)).
+                            collect(Collectors.joining("&")));
+                }
+                System.out.print(">");
+                System.out.println(m.getSimpleName());
+            }
+        }
+
+        return false;
+    }
+
+    String toString(TypeMirror bound) {
+        if (bound.getKind() == TypeKind.TYPEVAR) {
+            TypeVariable var = (TypeVariable) bound;
+            return toString(var.asElement());
+        }
+        return bound.toString();
+    }
+
+    String toString(Element el) {
+        switch (el.getKind()) {
+            case METHOD:
+                return toString(el.getEnclosingElement()) + "." + el.getSimpleName();
+            case CLASS:
+                return processingEnv.getElementUtils().getBinaryName((TypeElement) el).toString();
+            case TYPE_PARAMETER:
+                return toString(((TypeParameterElement) el).getGenericElement()) + "." + el.getSimpleName();
+            default:
+                throw new IllegalStateException("Unexpected element: " + el + "(" + el.getKind() + ")");
+        }
+    }
+    @Override
+    public SourceVersion getSupportedSourceVersion() {
+        return SourceVersion.latestSupported();
+    }
+
+
+}
+
+class Test<T1, C> {
+    <T2, C> void m() {
+        class L1<T3, C> {
+            class L2<T4, C> {
+                <T5, C> void m() {
+                    class L3<T6, C> {
+                        class L4<T7, C> {
+                            class L5<T1a extends T1,
+                                     T2a extends T2,
+                                     T3a extends T3,
+                                     T4a extends T4,
+                                     T5a extends T5,
+                                     T6a extends T6,
+                                     T7a extends T7> {}
+                        }
+                    }
+                }
+            }
+            class CCheck<T extends C> {}
+            <T extends C> void test() {}
+        }
+        class CCheck<T extends C> {}
+    }
+    class CCheck<T extends C> {}
+    <T extends C> void test() {}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/javac/processing/model/nestedTypeVars/NestedTypeVars.out	Thu Nov 10 15:58:49 2016 -0800
@@ -0,0 +1,9 @@
+Test$1L1$L2$1L3$L4$L5<T1a extends Test.T1, T2a extends Test.m.T2, T3a extends Test$1L1.T3, T4a extends Test$1L1$L2.T4, T5a extends Test$1L1$L2.m.T5, T6a extends Test$1L1$L2$1L3.T6, T7a extends Test$1L1$L2$1L3$L4.T7>
+Test$1L1$CCheck<T extends Test$1L1.C>
+Test$1L1<T3 extends java.lang.Object, C extends java.lang.Object>
+  <T extends Test$1L1.C>test
+Test$1CCheck<T extends Test.m.C>
+Test$CCheck<T extends Test.C>
+Test<T1 extends java.lang.Object, C extends java.lang.Object>
+  <T2 extends java.lang.Object, C extends java.lang.Object>m
+  <T extends Test.C>test
--- a/test/tools/jdeprscan/tests/jdk/jdeprscan/TestLoad.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/tools/jdeprscan/tests/jdk/jdeprscan/TestLoad.java	Thu Nov 10 15:58:49 2016 -0800
@@ -23,6 +23,7 @@
 
 /*
  * @test
+ * @bug 8145464 8164837
  * @summary Test of jdeprscan tool loading and printing to aCSV file.
  * @modules jdk.jdeps/com.sun.tools.jdeprscan
  * @library ../../../cases
--- a/test/tools/jdeprscan/tests/jdk/jdeprscan/TestScan.java	Wed Nov 09 21:20:20 2016 +0100
+++ b/test/tools/jdeprscan/tests/jdk/jdeprscan/TestScan.java	Thu Nov 10 15:58:49 2016 -0800
@@ -23,6 +23,7 @@
 
 /*
  * @test
+ * @bug 8145464 8164837 8165646
  * @summary Basic test of jdeprscan's scanning phase.
  * @modules jdk.jdeps/com.sun.tools.jdeprscan
  * @library ../../../cases