langtools/src/jdk.jshell/share/classes/jdk/jshell/Eval.java
changeset 46185 f4c981fc7818
parent 43586 cc7a4eb79b29
child 46926 25ac5da6502e
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/Eval.java	Tue Aug 15 13:16:32 2017 -0700
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/Eval.java	Wed Aug 16 18:42:11 2017 -0700
@@ -91,6 +91,9 @@
 
     private static final Pattern IMPORT_PATTERN = Pattern.compile("import\\p{javaWhitespace}+(?<static>static\\p{javaWhitespace}+)?(?<fullname>[\\p{L}\\p{N}_\\$\\.]+\\.(?<name>[\\p{L}\\p{N}_\\$]+|\\*))");
 
+    // for uses that should not change state -- non-evaluations
+    private boolean preserveState = false;
+
     private int varNumber = 0;
 
     private final JShell state;
@@ -145,6 +148,23 @@
     /**
      * Converts the user source of a snippet into a Snippet object (or list of
      * objects in the case of: int x, y, z;).  Does not install the Snippets
+     * or execute them.  Does not change any state.
+     *
+     * @param userSource the source of the snippet
+     * @return usually a singleton list of Snippet, but may be empty or multiple
+     */
+    List<Snippet> toScratchSnippets(String userSource) {
+        try {
+            preserveState = true;
+            return sourceToSnippets(userSource);
+        } finally {
+            preserveState = false;
+        }
+    }
+
+    /**
+     * Converts the user source of a snippet into a Snippet object (or list of
+     * objects in the case of: int x, y, z;).  Does not install the Snippets
      * or execute them.
      *
      * @param userSource the source of the snippet
@@ -316,11 +336,15 @@
                 subkind = SubKind.OTHER_EXPRESSION_SUBKIND;
             }
             if (shouldGenTempVar(subkind)) {
-                if (state.tempVariableNameGenerator != null) {
-                    name = state.tempVariableNameGenerator.get();
-                }
-                while (name == null || state.keyMap.doesVariableNameExist(name)) {
-                    name = "$" + ++varNumber;
+                if (preserveState) {
+                    name = "$$";
+                } else {
+                    if (state.tempVariableNameGenerator != null) {
+                        name = state.tempVariableNameGenerator.get();
+                    }
+                    while (name == null || state.keyMap.doesVariableNameExist(name)) {
+                        name = "$" + ++varNumber;
+                    }
                 }
                 guts = Wrap.tempVarWrap(compileSource, typeName, name);
                 Collection<String> declareReferences = null; //TODO