author | jlahoda |
Mon, 30 Nov 2015 17:31:55 +0100 | |
changeset 34475 | 7af94fd75ede |
parent 33714 | 8064f484590e |
child 34477 | 64001b0533a2 |
permissions | -rw-r--r-- |
33362 | 1 |
/* |
2 |
* Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. |
|
3 |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. |
|
4 |
* |
|
5 |
* This code is free software; you can redistribute it and/or modify it |
|
6 |
* under the terms of the GNU General Public License version 2 only, as |
|
7 |
* published by the Free Software Foundation. Oracle designates this |
|
8 |
* particular file as subject to the "Classpath" exception as provided |
|
9 |
* by Oracle in the LICENSE file that accompanied this code. |
|
10 |
* |
|
11 |
* This code is distributed in the hope that it will be useful, but WITHOUT |
|
12 |
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
|
13 |
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
|
14 |
* version 2 for more details (a copy is included in the LICENSE file that |
|
15 |
* accompanied this code). |
|
16 |
* |
|
17 |
* You should have received a copy of the GNU General Public License version |
|
18 |
* 2 along with this work; if not, write to the Free Software Foundation, |
|
19 |
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
|
20 |
* |
|
21 |
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA |
|
22 |
* or visit www.oracle.com if you need additional information or have any |
|
23 |
* questions. |
|
24 |
*/ |
|
25 |
||
26 |
package jdk.internal.jshell.tool; |
|
27 |
||
28 |
import java.io.BufferedWriter; |
|
29 |
import java.io.ByteArrayInputStream; |
|
30 |
import java.io.File; |
|
31 |
import java.io.FileNotFoundException; |
|
32 |
import java.io.FileReader; |
|
33 |
import java.io.IOException; |
|
34 |
import java.io.InputStream; |
|
35 |
import java.io.PrintStream; |
|
36 |
import java.io.Reader; |
|
37 |
import java.io.StringReader; |
|
38 |
import java.nio.charset.Charset; |
|
39 |
import java.nio.file.AccessDeniedException; |
|
40 |
import java.nio.file.FileSystems; |
|
41 |
import java.nio.file.Files; |
|
42 |
import java.nio.file.NoSuchFileException; |
|
43 |
import java.nio.file.Path; |
|
44 |
import java.nio.file.Paths; |
|
45 |
import java.util.ArrayList; |
|
46 |
import java.util.Arrays; |
|
47 |
import java.util.Collections; |
|
48 |
import java.util.Iterator; |
|
49 |
import java.util.LinkedHashMap; |
|
50 |
import java.util.LinkedHashSet; |
|
51 |
import java.util.List; |
|
52 |
import java.util.Map; |
|
53 |
import java.util.Map.Entry; |
|
54 |
import java.util.Scanner; |
|
55 |
import java.util.Set; |
|
56 |
import java.util.function.Consumer; |
|
57 |
import java.util.function.Predicate; |
|
58 |
import java.util.prefs.Preferences; |
|
59 |
import java.util.regex.Matcher; |
|
60 |
import java.util.regex.Pattern; |
|
61 |
import java.util.stream.Collectors; |
|
62 |
import java.util.stream.Stream; |
|
63 |
import java.util.stream.StreamSupport; |
|
64 |
||
65 |
import jdk.internal.jshell.debug.InternalDebugControl; |
|
66 |
import jdk.internal.jshell.tool.IOContext.InputInterruptedException; |
|
67 |
import jdk.jshell.Diag; |
|
68 |
import jdk.jshell.EvalException; |
|
69 |
import jdk.jshell.JShell; |
|
70 |
import jdk.jshell.Snippet; |
|
71 |
import jdk.jshell.DeclarationSnippet; |
|
72 |
import jdk.jshell.TypeDeclSnippet; |
|
73 |
import jdk.jshell.MethodSnippet; |
|
74 |
import jdk.jshell.PersistentSnippet; |
|
75 |
import jdk.jshell.VarSnippet; |
|
76 |
import jdk.jshell.ExpressionSnippet; |
|
77 |
import jdk.jshell.Snippet.Status; |
|
78 |
import jdk.jshell.SourceCodeAnalysis; |
|
79 |
import jdk.jshell.SourceCodeAnalysis.CompletionInfo; |
|
80 |
import jdk.jshell.SourceCodeAnalysis.Suggestion; |
|
81 |
import jdk.jshell.SnippetEvent; |
|
82 |
import jdk.jshell.UnresolvedReferenceException; |
|
83 |
import jdk.jshell.Snippet.SubKind; |
|
84 |
import jdk.jshell.JShell.Subscription; |
|
85 |
||
86 |
import static java.nio.file.StandardOpenOption.CREATE; |
|
87 |
import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; |
|
88 |
import static java.nio.file.StandardOpenOption.WRITE; |
|
89 |
import java.util.MissingResourceException; |
|
90 |
import java.util.ResourceBundle; |
|
91 |
import static java.util.stream.Collectors.toList; |
|
92 |
||
93 |
/** |
|
94 |
* Command line REPL tool for Java using the JShell API. |
|
95 |
* @author Robert Field |
|
96 |
*/ |
|
97 |
public class JShellTool { |
|
98 |
||
99 |
private static final Pattern LINEBREAK = Pattern.compile("\\R"); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
100 |
private static final Pattern HISTORY_ALL_START_FILENAME = Pattern.compile( |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
101 |
"((?<cmd>(all|history|start))(\\z|\\p{javaWhitespace}+))?(?<filename>.*)"); |
33362 | 102 |
|
103 |
final InputStream cmdin; |
|
104 |
final PrintStream cmdout; |
|
105 |
final PrintStream cmderr; |
|
106 |
final PrintStream console; |
|
107 |
final InputStream userin; |
|
108 |
final PrintStream userout; |
|
109 |
final PrintStream usererr; |
|
110 |
||
111 |
/** |
|
112 |
* The constructor for the tool (used by tool launch via main and by test |
|
113 |
* harnesses to capture ins and outs. |
|
114 |
* @param cmdin command line input -- snippets and commands |
|
115 |
* @param cmdout command line output, feedback including errors |
|
116 |
* @param cmderr start-up errors and debugging info |
|
117 |
* @param console console control interaction |
|
118 |
* @param userin code execution input (not yet functional) |
|
119 |
* @param userout code execution output -- System.out.printf("hi") |
|
120 |
* @param usererr code execution error stream -- System.err.printf("Oops") |
|
121 |
*/ |
|
122 |
public JShellTool(InputStream cmdin, PrintStream cmdout, PrintStream cmderr, |
|
123 |
PrintStream console, |
|
124 |
InputStream userin, PrintStream userout, PrintStream usererr) { |
|
125 |
this.cmdin = cmdin; |
|
126 |
this.cmdout = cmdout; |
|
127 |
this.cmderr = cmderr; |
|
128 |
this.console = console; |
|
129 |
this.userin = userin; |
|
130 |
this.userout = userout; |
|
131 |
this.usererr = usererr; |
|
132 |
} |
|
133 |
||
134 |
private IOContext input = null; |
|
135 |
private boolean regenerateOnDeath = true; |
|
136 |
private boolean live = false; |
|
137 |
||
138 |
SourceCodeAnalysis analysis; |
|
139 |
JShell state = null; |
|
140 |
Subscription shutdownSubscription = null; |
|
141 |
||
142 |
private boolean debug = false; |
|
143 |
private boolean displayPrompt = true; |
|
144 |
public boolean testPrompt = false; |
|
145 |
private Feedback feedback = Feedback.Default; |
|
146 |
private String cmdlineClasspath = null; |
|
147 |
private String cmdlineStartup = null; |
|
148 |
private String editor = null; |
|
149 |
||
150 |
static final Preferences PREFS = Preferences.userRoot().node("tool/REPL"); |
|
151 |
||
152 |
static final String STARTUP_KEY = "STARTUP"; |
|
153 |
||
154 |
static final String DEFAULT_STARTUP = |
|
155 |
"\n" + |
|
156 |
"import java.util.*;\n" + |
|
157 |
"import java.io.*;\n" + |
|
158 |
"import java.math.*;\n" + |
|
159 |
"import java.net.*;\n" + |
|
160 |
"import java.util.concurrent.*;\n" + |
|
161 |
"import java.util.prefs.*;\n" + |
|
162 |
"import java.util.regex.*;\n" + |
|
163 |
"void printf(String format, Object... args) { System.out.printf(format, args); }\n"; |
|
164 |
||
165 |
// Tool id (tid) mapping |
|
166 |
NameSpace mainNamespace; |
|
167 |
NameSpace startNamespace; |
|
168 |
NameSpace errorNamespace; |
|
169 |
NameSpace currentNameSpace; |
|
170 |
Map<Snippet,SnippetInfo> mapSnippet; |
|
171 |
||
172 |
void debug(String format, Object... args) { |
|
173 |
if (debug) { |
|
174 |
cmderr.printf(format + "\n", args); |
|
175 |
} |
|
176 |
} |
|
177 |
||
178 |
/** |
|
179 |
* For more verbose feedback modes |
|
180 |
* @param format printf format |
|
181 |
* @param args printf args |
|
182 |
*/ |
|
183 |
void fluff(String format, Object... args) { |
|
184 |
if (feedback() != Feedback.Off && feedback() != Feedback.Concise) { |
|
185 |
hard(format, args); |
|
186 |
} |
|
187 |
} |
|
188 |
||
189 |
/** |
|
190 |
* For concise feedback mode only |
|
191 |
* @param format printf format |
|
192 |
* @param args printf args |
|
193 |
*/ |
|
194 |
void concise(String format, Object... args) { |
|
195 |
if (feedback() == Feedback.Concise) { |
|
196 |
hard(format, args); |
|
197 |
} |
|
198 |
} |
|
199 |
||
200 |
/** |
|
201 |
* For all feedback modes -- must show |
|
202 |
* @param format printf format |
|
203 |
* @param args printf args |
|
204 |
*/ |
|
205 |
void hard(String format, Object... args) { |
|
206 |
cmdout.printf("| " + format + "\n", args); |
|
207 |
} |
|
208 |
||
209 |
/** |
|
210 |
* Trim whitespace off end of string |
|
211 |
* @param s |
|
212 |
* @return |
|
213 |
*/ |
|
214 |
static String trimEnd(String s) { |
|
215 |
int last = s.length() - 1; |
|
216 |
int i = last; |
|
217 |
while (i >= 0 && Character.isWhitespace(s.charAt(i))) { |
|
218 |
--i; |
|
219 |
} |
|
220 |
if (i != last) { |
|
221 |
return s.substring(0, i + 1); |
|
222 |
} else { |
|
223 |
return s; |
|
224 |
} |
|
225 |
} |
|
226 |
||
227 |
/** |
|
228 |
* Normal start entry point |
|
229 |
* @param args |
|
230 |
* @throws Exception |
|
231 |
*/ |
|
232 |
public static void main(String[] args) throws Exception { |
|
233 |
new JShellTool(System.in, System.out, System.err, System.out, |
|
234 |
new ByteArrayInputStream(new byte[0]), System.out, System.err) |
|
235 |
.start(args); |
|
236 |
} |
|
237 |
||
238 |
public void start(String[] args) throws Exception { |
|
239 |
List<String> loadList = processCommandArgs(args); |
|
240 |
if (loadList == null) { |
|
241 |
// Abort |
|
242 |
return; |
|
243 |
} |
|
244 |
try (IOContext in = new ConsoleIOContext(this, cmdin, console)) { |
|
245 |
start(in, loadList); |
|
246 |
} |
|
247 |
} |
|
248 |
||
249 |
private void start(IOContext in, List<String> loadList) { |
|
250 |
resetState(); // Initialize |
|
251 |
||
252 |
for (String loadFile : loadList) { |
|
253 |
cmdOpen(loadFile); |
|
254 |
} |
|
255 |
||
256 |
if (regenerateOnDeath) { |
|
257 |
fluff("Welcome to JShell -- Version %s", version()); |
|
258 |
fluff("Type /help for help"); |
|
259 |
} |
|
260 |
||
261 |
try { |
|
262 |
while (regenerateOnDeath) { |
|
263 |
if (!live) { |
|
264 |
resetState(); |
|
265 |
} |
|
266 |
run(in); |
|
267 |
} |
|
268 |
} finally { |
|
269 |
closeState(); |
|
270 |
} |
|
271 |
} |
|
272 |
||
273 |
/** |
|
274 |
* Process the command line arguments. |
|
275 |
* Set options. |
|
276 |
* @param args the command line arguments |
|
277 |
* @return the list of files to be loaded |
|
278 |
*/ |
|
279 |
private List<String> processCommandArgs(String[] args) { |
|
280 |
List<String> loadList = new ArrayList<>(); |
|
281 |
Iterator<String> ai = Arrays.asList(args).iterator(); |
|
282 |
while (ai.hasNext()) { |
|
283 |
String arg = ai.next(); |
|
284 |
if (arg.startsWith("-")) { |
|
285 |
switch (arg) { |
|
286 |
case "-classpath": |
|
287 |
case "-cp": |
|
288 |
if (cmdlineClasspath != null) { |
|
289 |
cmderr.printf("Conflicting -classpath option.\n"); |
|
290 |
return null; |
|
291 |
} |
|
292 |
if (ai.hasNext()) { |
|
293 |
cmdlineClasspath = ai.next(); |
|
294 |
} else { |
|
295 |
cmderr.printf("Argument to -classpath missing.\n"); |
|
296 |
return null; |
|
297 |
} |
|
298 |
break; |
|
299 |
case "-help": |
|
300 |
printUsage(); |
|
301 |
return null; |
|
302 |
case "-version": |
|
303 |
cmdout.printf("jshell %s\n", version()); |
|
304 |
return null; |
|
305 |
case "-fullversion": |
|
306 |
cmdout.printf("jshell %s\n", fullVersion()); |
|
307 |
return null; |
|
308 |
case "-startup": |
|
309 |
if (cmdlineStartup != null) { |
|
310 |
cmderr.printf("Conflicting -startup or -nostartup option.\n"); |
|
311 |
return null; |
|
312 |
} |
|
313 |
if (ai.hasNext()) { |
|
314 |
String filename = ai.next(); |
|
315 |
try { |
|
316 |
byte[] encoded = Files.readAllBytes(Paths.get(filename)); |
|
317 |
cmdlineStartup = new String(encoded); |
|
318 |
} catch (AccessDeniedException e) { |
|
319 |
hard("File '%s' for start-up is not accessible.", filename); |
|
320 |
} catch (NoSuchFileException e) { |
|
321 |
hard("File '%s' for start-up is not found.", filename); |
|
322 |
} catch (Exception e) { |
|
323 |
hard("Exception while reading start-up file: %s", e); |
|
324 |
} |
|
325 |
} else { |
|
326 |
cmderr.printf("Argument to -startup missing.\n"); |
|
327 |
return null; |
|
328 |
} |
|
329 |
break; |
|
330 |
case "-nostartup": |
|
331 |
if (cmdlineStartup != null && !cmdlineStartup.isEmpty()) { |
|
332 |
cmderr.printf("Conflicting -startup option.\n"); |
|
333 |
return null; |
|
334 |
} |
|
335 |
cmdlineStartup = ""; |
|
336 |
break; |
|
337 |
default: |
|
338 |
cmderr.printf("Unknown option: %s\n", arg); |
|
339 |
printUsage(); |
|
340 |
return null; |
|
341 |
} |
|
342 |
} else { |
|
343 |
loadList.add(arg); |
|
344 |
} |
|
345 |
} |
|
346 |
return loadList; |
|
347 |
} |
|
348 |
||
349 |
private void printUsage() { |
|
350 |
cmdout.printf("Usage: jshell <options> <load files>\n"); |
|
351 |
cmdout.printf("where possible options include:\n"); |
|
352 |
cmdout.printf(" -classpath <path> Specify where to find user class files\n"); |
|
353 |
cmdout.printf(" -cp <path> Specify where to find user class files\n"); |
|
354 |
cmdout.printf(" -startup <file> One run replacement for the start-up definitions\n"); |
|
355 |
cmdout.printf(" -nostartup Do not run the start-up definitions\n"); |
|
356 |
cmdout.printf(" -help Print a synopsis of standard options\n"); |
|
357 |
cmdout.printf(" -version Version information\n"); |
|
358 |
} |
|
359 |
||
360 |
private void resetState() { |
|
361 |
closeState(); |
|
362 |
||
363 |
// Initialize tool id mapping |
|
364 |
mainNamespace = new NameSpace("main", ""); |
|
365 |
startNamespace = new NameSpace("start", "s"); |
|
366 |
errorNamespace = new NameSpace("error", "e"); |
|
367 |
mapSnippet = new LinkedHashMap<>(); |
|
368 |
currentNameSpace = startNamespace; |
|
369 |
||
370 |
state = JShell.builder() |
|
371 |
.in(userin) |
|
372 |
.out(userout) |
|
373 |
.err(usererr) |
|
374 |
.tempVariableNameGenerator(()-> "$" + currentNameSpace.tidNext()) |
|
375 |
.idGenerator((sn, i) -> (currentNameSpace == startNamespace || state.status(sn).isActive) |
|
376 |
? currentNameSpace.tid(sn) |
|
377 |
: errorNamespace.tid(sn)) |
|
378 |
.build(); |
|
379 |
analysis = state.sourceCodeAnalysis(); |
|
380 |
shutdownSubscription = state.onShutdown((JShell deadState) -> { |
|
381 |
if (deadState == state) { |
|
382 |
hard("State engine terminated. See /history"); |
|
383 |
live = false; |
|
384 |
} |
|
385 |
}); |
|
386 |
live = true; |
|
387 |
||
388 |
if (cmdlineClasspath != null) { |
|
389 |
state.addToClasspath(cmdlineClasspath); |
|
390 |
} |
|
391 |
||
392 |
||
393 |
String start; |
|
394 |
if (cmdlineStartup == null) { |
|
395 |
start = PREFS.get(STARTUP_KEY, "<nada>"); |
|
396 |
if (start.equals("<nada>")) { |
|
397 |
start = DEFAULT_STARTUP; |
|
398 |
PREFS.put(STARTUP_KEY, DEFAULT_STARTUP); |
|
399 |
} |
|
400 |
} else { |
|
401 |
start = cmdlineStartup; |
|
402 |
} |
|
403 |
try (IOContext suin = new FileScannerIOContext(new StringReader(start))) { |
|
404 |
run(suin); |
|
405 |
} catch (Exception ex) { |
|
406 |
hard("Unexpected exception reading start-up: %s\n", ex); |
|
407 |
} |
|
408 |
currentNameSpace = mainNamespace; |
|
409 |
} |
|
410 |
||
411 |
private void closeState() { |
|
412 |
live = false; |
|
413 |
JShell oldState = state; |
|
414 |
if (oldState != null) { |
|
415 |
oldState.unsubscribe(shutdownSubscription); // No notification |
|
416 |
oldState.close(); |
|
417 |
} |
|
418 |
} |
|
419 |
||
420 |
/** |
|
421 |
* Main loop |
|
422 |
* @param in the line input/editing context |
|
423 |
*/ |
|
424 |
private void run(IOContext in) { |
|
425 |
IOContext oldInput = input; |
|
426 |
input = in; |
|
427 |
try { |
|
428 |
String incomplete = ""; |
|
429 |
while (live) { |
|
430 |
String prompt; |
|
431 |
if (in.interactiveOutput() && displayPrompt) { |
|
432 |
prompt = testPrompt |
|
433 |
? incomplete.isEmpty() |
|
434 |
? "\u0005" //ENQ |
|
435 |
: "\u0006" //ACK |
|
436 |
: incomplete.isEmpty() |
|
437 |
? feedback() == Feedback.Concise |
|
438 |
? "-> " |
|
439 |
: "\n-> " |
|
440 |
: ">> " |
|
441 |
; |
|
442 |
} else { |
|
443 |
prompt = ""; |
|
444 |
} |
|
445 |
String raw; |
|
446 |
try { |
|
447 |
raw = in.readLine(prompt, incomplete); |
|
448 |
} catch (InputInterruptedException ex) { |
|
449 |
//input interrupted - clearing current state |
|
450 |
incomplete = ""; |
|
451 |
continue; |
|
452 |
} |
|
453 |
if (raw == null) { |
|
454 |
//EOF |
|
455 |
if (in.interactiveOutput()) { |
|
456 |
// End after user ctrl-D |
|
457 |
regenerateOnDeath = false; |
|
458 |
} |
|
459 |
break; |
|
460 |
} |
|
461 |
String trimmed = trimEnd(raw); |
|
462 |
if (!trimmed.isEmpty()) { |
|
463 |
String line = incomplete + trimmed; |
|
464 |
||
465 |
// No commands in the middle of unprocessed source |
|
466 |
if (incomplete.isEmpty() && line.startsWith("/") && !line.startsWith("//") && !line.startsWith("/*")) { |
|
467 |
processCommand(line.trim()); |
|
468 |
} else { |
|
469 |
incomplete = processSourceCatchingReset(line); |
|
470 |
} |
|
471 |
} |
|
472 |
} |
|
473 |
} catch (IOException ex) { |
|
474 |
hard("Unexpected exception: %s\n", ex); |
|
475 |
} finally { |
|
476 |
input = oldInput; |
|
477 |
} |
|
478 |
} |
|
479 |
||
480 |
private String processSourceCatchingReset(String src) { |
|
481 |
try { |
|
482 |
input.beforeUserCode(); |
|
483 |
return processSource(src); |
|
484 |
} catch (IllegalStateException ex) { |
|
485 |
hard("Resetting..."); |
|
486 |
live = false; // Make double sure |
|
487 |
return ""; |
|
488 |
} finally { |
|
489 |
input.afterUserCode(); |
|
490 |
} |
|
491 |
} |
|
492 |
||
493 |
private void processCommand(String cmd) { |
|
494 |
try { |
|
495 |
//handle "/[number]" |
|
496 |
cmdUseHistoryEntry(Integer.parseInt(cmd.substring(1))); |
|
497 |
return ; |
|
498 |
} catch (NumberFormatException ex) { |
|
499 |
//ignore |
|
500 |
} |
|
501 |
String arg = ""; |
|
502 |
int idx = cmd.indexOf(' '); |
|
503 |
if (idx > 0) { |
|
504 |
arg = cmd.substring(idx + 1).trim(); |
|
505 |
cmd = cmd.substring(0, idx); |
|
506 |
} |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
507 |
Command[] candidates = findCommand(cmd, c -> c.kind != CommandKind.HELP_ONLY); |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
508 |
if (candidates.length == 0) { |
33362 | 509 |
hard("No such command: %s", cmd); |
510 |
fluff("Type /help for help."); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
511 |
} else if (candidates.length == 1) { |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
512 |
candidates[0].run.accept(arg); |
33362 | 513 |
} else { |
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
514 |
hard("Command: %s is ambiguous: %s", cmd, Arrays.stream(candidates).map(c -> c.command).collect(Collectors.joining(", "))); |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
515 |
fluff("Type /help for help."); |
33362 | 516 |
} |
517 |
} |
|
518 |
||
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
519 |
private Command[] findCommand(String cmd, Predicate<Command> filter) { |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
520 |
Command exact = commands.get(cmd); |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
521 |
if (exact != null) |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
522 |
return new Command[] {exact}; |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
523 |
|
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
524 |
return commands.values() |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
525 |
.stream() |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
526 |
.filter(filter) |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
527 |
.filter(command -> command.command.startsWith(cmd)) |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
528 |
.toArray(size -> new Command[size]); |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
529 |
} |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
530 |
|
33362 | 531 |
private static Path toPathResolvingUserHome(String pathString) { |
532 |
if (pathString.replace(File.separatorChar, '/').startsWith("~/")) |
|
533 |
return Paths.get(System.getProperty("user.home"), pathString.substring(2)); |
|
534 |
else |
|
535 |
return Paths.get(pathString); |
|
536 |
} |
|
537 |
||
538 |
static final class Command { |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
539 |
public final String command; |
33362 | 540 |
public final String params; |
541 |
public final String description; |
|
542 |
public final Consumer<String> run; |
|
543 |
public final CompletionProvider completions; |
|
544 |
public final CommandKind kind; |
|
545 |
||
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
546 |
public Command(String command, String params, String description, Consumer<String> run, CompletionProvider completions) { |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
547 |
this(command, params, description, run, completions, CommandKind.NORMAL); |
33362 | 548 |
} |
549 |
||
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
550 |
public Command(String command, String params, String description, Consumer<String> run, CompletionProvider completions, CommandKind kind) { |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
551 |
this.command = command; |
33362 | 552 |
this.params = params; |
553 |
this.description = description; |
|
554 |
this.run = run; |
|
555 |
this.completions = completions; |
|
556 |
this.kind = kind; |
|
557 |
} |
|
558 |
||
559 |
} |
|
560 |
||
561 |
interface CompletionProvider { |
|
562 |
List<Suggestion> completionSuggestions(String input, int cursor, int[] anchor); |
|
563 |
} |
|
564 |
||
565 |
enum CommandKind { |
|
566 |
NORMAL, |
|
567 |
HIDDEN, |
|
568 |
HELP_ONLY; |
|
569 |
} |
|
570 |
||
571 |
static final class FixedCompletionProvider implements CompletionProvider { |
|
572 |
||
573 |
private final String[] alternatives; |
|
574 |
||
575 |
public FixedCompletionProvider(String... alternatives) { |
|
576 |
this.alternatives = alternatives; |
|
577 |
} |
|
578 |
||
579 |
@Override |
|
580 |
public List<Suggestion> completionSuggestions(String input, int cursor, int[] anchor) { |
|
581 |
List<Suggestion> result = new ArrayList<>(); |
|
582 |
||
583 |
for (String alternative : alternatives) { |
|
584 |
if (alternative.startsWith(input)) { |
|
585 |
result.add(new Suggestion(alternative, false)); |
|
586 |
} |
|
587 |
} |
|
588 |
||
589 |
anchor[0] = 0; |
|
590 |
||
591 |
return result; |
|
592 |
} |
|
593 |
||
594 |
} |
|
595 |
||
596 |
private static final CompletionProvider EMPTY_COMPLETION_PROVIDER = new FixedCompletionProvider(); |
|
597 |
private static final CompletionProvider FILE_COMPLETION_PROVIDER = fileCompletions(p -> true); |
|
598 |
private final Map<String, Command> commands = new LinkedHashMap<>(); |
|
599 |
private void registerCommand(Command cmd) { |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
600 |
commands.put(cmd.command, cmd); |
33362 | 601 |
} |
602 |
private static CompletionProvider fileCompletions(Predicate<Path> accept) { |
|
603 |
return (code, cursor, anchor) -> { |
|
604 |
int lastSlash = code.lastIndexOf('/'); |
|
605 |
String path = code.substring(0, lastSlash + 1); |
|
606 |
String prefix = lastSlash != (-1) ? code.substring(lastSlash + 1) : code; |
|
607 |
Path current = toPathResolvingUserHome(path); |
|
608 |
List<Suggestion> result = new ArrayList<>(); |
|
609 |
try (Stream<Path> dir = Files.list(current)) { |
|
610 |
dir.filter(f -> accept.test(f) && f.getFileName().toString().startsWith(prefix)) |
|
611 |
.map(f -> new Suggestion(f.getFileName() + (Files.isDirectory(f) ? "/" : ""), false)) |
|
612 |
.forEach(result::add); |
|
613 |
} catch (IOException ex) { |
|
614 |
//ignore... |
|
615 |
} |
|
616 |
if (path.isEmpty()) { |
|
617 |
StreamSupport.stream(FileSystems.getDefault().getRootDirectories().spliterator(), false) |
|
618 |
.filter(root -> accept.test(root) && root.toString().startsWith(prefix)) |
|
619 |
.map(root -> new Suggestion(root.toString(), false)) |
|
620 |
.forEach(result::add); |
|
621 |
} |
|
622 |
anchor[0] = path.length(); |
|
623 |
return result; |
|
624 |
}; |
|
625 |
} |
|
626 |
||
627 |
private static CompletionProvider classPathCompletion() { |
|
628 |
return fileCompletions(p -> Files.isDirectory(p) || |
|
629 |
p.getFileName().toString().endsWith(".zip") || |
|
630 |
p.getFileName().toString().endsWith(".jar")); |
|
631 |
} |
|
632 |
||
633 |
private CompletionProvider editCompletion() { |
|
634 |
return (prefix, cursor, anchor) -> { |
|
635 |
anchor[0] = 0; |
|
636 |
return state.snippets() |
|
637 |
.stream() |
|
638 |
.flatMap(k -> (k instanceof DeclarationSnippet) |
|
639 |
? Stream.of(String.valueOf(k.id()), ((DeclarationSnippet) k).name()) |
|
640 |
: Stream.of(String.valueOf(k.id()))) |
|
641 |
.filter(k -> k.startsWith(prefix)) |
|
642 |
.map(k -> new Suggestion(k, false)) |
|
643 |
.collect(Collectors.toList()); |
|
644 |
}; |
|
645 |
} |
|
646 |
||
647 |
private static CompletionProvider saveCompletion() { |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
648 |
CompletionProvider keyCompletion = new FixedCompletionProvider("all ", "history ", "start "); |
33362 | 649 |
return (code, cursor, anchor) -> { |
650 |
List<Suggestion> result = new ArrayList<>(); |
|
651 |
int space = code.indexOf(' '); |
|
652 |
if (space == (-1)) { |
|
653 |
result.addAll(keyCompletion.completionSuggestions(code, cursor, anchor)); |
|
654 |
} |
|
655 |
result.addAll(FILE_COMPLETION_PROVIDER.completionSuggestions(code.substring(space + 1), cursor - space - 1, anchor)); |
|
656 |
anchor[0] += space + 1; |
|
657 |
return result; |
|
658 |
}; |
|
659 |
} |
|
660 |
||
661 |
// Table of commands -- with command forms, argument kinds, help message, implementation, ... |
|
662 |
||
663 |
{ |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
664 |
registerCommand(new Command("/list", "[all]", "list the source you have typed", |
33362 | 665 |
arg -> cmdList(arg), |
666 |
new FixedCompletionProvider("all"))); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
667 |
registerCommand(new Command("/seteditor", "<executable>", "set the external editor command to use", |
33362 | 668 |
arg -> cmdSetEditor(arg), |
669 |
EMPTY_COMPLETION_PROVIDER)); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
670 |
registerCommand(new Command("/edit", "<name or id>", "edit a source entry referenced by name or id", |
33362 | 671 |
arg -> cmdEdit(arg), |
672 |
editCompletion())); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
673 |
registerCommand(new Command("/drop", "<name or id>", "delete a source entry referenced by name or id", |
33362 | 674 |
arg -> cmdDrop(arg), |
675 |
editCompletion())); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
676 |
registerCommand(new Command("/save", "[all|history|start] <file>", "save: <none> - current source;\n" + |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
677 |
" all - source including overwritten, failed, and start-up code;\n" + |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
678 |
" history - editing history;\n" + |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
679 |
" start - default start-up definitions", |
33362 | 680 |
arg -> cmdSave(arg), |
681 |
saveCompletion())); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
682 |
registerCommand(new Command("/open", "<file>", "open a file as source input", |
33362 | 683 |
arg -> cmdOpen(arg), |
684 |
FILE_COMPLETION_PROVIDER)); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
685 |
registerCommand(new Command("/vars", null, "list the declared variables and their values", |
33362 | 686 |
arg -> cmdVars(), |
687 |
EMPTY_COMPLETION_PROVIDER)); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
688 |
registerCommand(new Command("/methods", null, "list the declared methods and their signatures", |
33362 | 689 |
arg -> cmdMethods(), |
690 |
EMPTY_COMPLETION_PROVIDER)); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
691 |
registerCommand(new Command("/classes", null, "list the declared classes", |
33362 | 692 |
arg -> cmdClasses(), |
693 |
EMPTY_COMPLETION_PROVIDER)); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
694 |
registerCommand(new Command("/imports", null, "list the imported items", |
33714
8064f484590e
8142384: JShell tool: New command: /imports, /i which show the list of imported packages or classes, etc...
shinyafox
parents:
33362
diff
changeset
|
695 |
arg -> cmdImports(), |
8064f484590e
8142384: JShell tool: New command: /imports, /i which show the list of imported packages or classes, etc...
shinyafox
parents:
33362
diff
changeset
|
696 |
EMPTY_COMPLETION_PROVIDER)); |
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
697 |
registerCommand(new Command("/exit", null, "exit the REPL", |
33362 | 698 |
arg -> cmdExit(), |
699 |
EMPTY_COMPLETION_PROVIDER)); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
700 |
registerCommand(new Command("/reset", null, "reset everything in the REPL", |
33362 | 701 |
arg -> cmdReset(), |
702 |
EMPTY_COMPLETION_PROVIDER)); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
703 |
registerCommand(new Command("/feedback", "<level>", "feedback information: off, concise, normal, verbose, default, or ?", |
33362 | 704 |
arg -> cmdFeedback(arg), |
705 |
new FixedCompletionProvider("off", "concise", "normal", "verbose", "default", "?"))); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
706 |
registerCommand(new Command("/prompt", null, "toggle display of a prompt", |
33362 | 707 |
arg -> cmdPrompt(), |
708 |
EMPTY_COMPLETION_PROVIDER)); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
709 |
registerCommand(new Command("/classpath", "<path>", "add a path to the classpath", |
33362 | 710 |
arg -> cmdClasspath(arg), |
711 |
classPathCompletion())); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
712 |
registerCommand(new Command("/history", null, "history of what you have typed", |
33362 | 713 |
arg -> cmdHistory(), |
714 |
EMPTY_COMPLETION_PROVIDER)); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
715 |
registerCommand(new Command("/setstart", "<file>", "read file and set as the new start-up definitions", |
33362 | 716 |
arg -> cmdSetStart(arg), |
717 |
FILE_COMPLETION_PROVIDER)); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
718 |
registerCommand(new Command("/debug", "", "toggle debugging of the REPL", |
33362 | 719 |
arg -> cmdDebug(arg), |
720 |
EMPTY_COMPLETION_PROVIDER, |
|
721 |
CommandKind.HIDDEN)); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
722 |
registerCommand(new Command("/help", "", "this help message", |
33362 | 723 |
arg -> cmdHelp(), |
724 |
EMPTY_COMPLETION_PROVIDER)); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
725 |
registerCommand(new Command("/?", "", "this help message", |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
726 |
arg -> cmdHelp(), |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
727 |
EMPTY_COMPLETION_PROVIDER)); |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
728 |
registerCommand(new Command("/!", "", "re-run last snippet", |
33362 | 729 |
arg -> cmdUseHistoryEntry(-1), |
730 |
EMPTY_COMPLETION_PROVIDER)); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
731 |
registerCommand(new Command("/<n>", "", "re-run n-th snippet", |
33362 | 732 |
arg -> { throw new IllegalStateException(); }, |
733 |
EMPTY_COMPLETION_PROVIDER, |
|
734 |
CommandKind.HELP_ONLY)); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
735 |
registerCommand(new Command("/-<n>", "", "re-run n-th previous snippet", |
33362 | 736 |
arg -> { throw new IllegalStateException(); }, |
737 |
EMPTY_COMPLETION_PROVIDER, |
|
738 |
CommandKind.HELP_ONLY)); |
|
739 |
} |
|
740 |
||
741 |
public List<Suggestion> commandCompletionSuggestions(String code, int cursor, int[] anchor) { |
|
742 |
String prefix = code.substring(0, cursor); |
|
743 |
int space = prefix.indexOf(' '); |
|
744 |
Stream<Suggestion> result; |
|
745 |
||
746 |
if (space == (-1)) { |
|
747 |
result = commands.values() |
|
748 |
.stream() |
|
749 |
.distinct() |
|
750 |
.filter(cmd -> cmd.kind != CommandKind.HIDDEN && cmd.kind != CommandKind.HELP_ONLY) |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
751 |
.map(cmd -> cmd.command) |
33362 | 752 |
.filter(key -> key.startsWith(prefix)) |
753 |
.map(key -> new Suggestion(key + " ", false)); |
|
754 |
anchor[0] = 0; |
|
755 |
} else { |
|
756 |
String arg = prefix.substring(space + 1); |
|
757 |
String cmd = prefix.substring(0, space); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
758 |
Command[] candidates = findCommand(cmd, c -> true); |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
759 |
if (candidates.length == 1) { |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
760 |
result = candidates[0].completions.completionSuggestions(arg, cursor - space, anchor).stream(); |
33362 | 761 |
anchor[0] += space + 1; |
762 |
} else { |
|
763 |
result = Stream.empty(); |
|
764 |
} |
|
765 |
} |
|
766 |
||
767 |
return result.sorted((s1, s2) -> s1.continuation.compareTo(s2.continuation)) |
|
768 |
.collect(Collectors.toList()); |
|
769 |
} |
|
770 |
||
771 |
public String commandDocumentation(String code, int cursor) { |
|
772 |
code = code.substring(0, cursor); |
|
773 |
int space = code.indexOf(' '); |
|
774 |
||
775 |
if (space != (-1)) { |
|
776 |
String cmd = code.substring(0, space); |
|
777 |
Command command = commands.get(cmd); |
|
778 |
if (command != null) { |
|
779 |
return command.description; |
|
780 |
} |
|
781 |
} |
|
782 |
||
783 |
return null; |
|
784 |
} |
|
785 |
||
786 |
// --- Command implementations --- |
|
787 |
||
788 |
void cmdSetEditor(String arg) { |
|
789 |
if (arg.isEmpty()) { |
|
790 |
hard("/seteditor requires a path argument"); |
|
791 |
} else { |
|
792 |
editor = arg; |
|
793 |
fluff("Editor set to: %s", arg); |
|
794 |
} |
|
795 |
} |
|
796 |
||
797 |
void cmdClasspath(String arg) { |
|
798 |
if (arg.isEmpty()) { |
|
799 |
hard("/classpath requires a path argument"); |
|
800 |
} else { |
|
801 |
state.addToClasspath(toPathResolvingUserHome(arg).toString()); |
|
802 |
fluff("Path %s added to classpath", arg); |
|
803 |
} |
|
804 |
} |
|
805 |
||
806 |
void cmdDebug(String arg) { |
|
807 |
if (arg.isEmpty()) { |
|
808 |
debug = !debug; |
|
809 |
InternalDebugControl.setDebugFlags(state, debug ? InternalDebugControl.DBG_GEN : 0); |
|
810 |
fluff("Debugging %s", debug ? "on" : "off"); |
|
811 |
} else { |
|
812 |
int flags = 0; |
|
813 |
for (char ch : arg.toCharArray()) { |
|
814 |
switch (ch) { |
|
815 |
case '0': |
|
816 |
flags = 0; |
|
817 |
debug = false; |
|
818 |
fluff("Debugging off"); |
|
819 |
break; |
|
820 |
case 'r': |
|
821 |
debug = true; |
|
822 |
fluff("REPL tool debugging on"); |
|
823 |
break; |
|
824 |
case 'g': |
|
825 |
flags |= InternalDebugControl.DBG_GEN; |
|
826 |
fluff("General debugging on"); |
|
827 |
break; |
|
828 |
case 'f': |
|
829 |
flags |= InternalDebugControl.DBG_FMGR; |
|
830 |
fluff("File manager debugging on"); |
|
831 |
break; |
|
832 |
case 'c': |
|
833 |
flags |= InternalDebugControl.DBG_COMPA; |
|
834 |
fluff("Completion analysis debugging on"); |
|
835 |
break; |
|
836 |
case 'd': |
|
837 |
flags |= InternalDebugControl.DBG_DEP; |
|
838 |
fluff("Dependency debugging on"); |
|
839 |
break; |
|
840 |
case 'e': |
|
841 |
flags |= InternalDebugControl.DBG_EVNT; |
|
842 |
fluff("Event debugging on"); |
|
843 |
break; |
|
844 |
default: |
|
845 |
hard("Unknown debugging option: %c", ch); |
|
846 |
fluff("Use: 0 r g f c d"); |
|
847 |
break; |
|
848 |
} |
|
849 |
} |
|
850 |
InternalDebugControl.setDebugFlags(state, flags); |
|
851 |
} |
|
852 |
} |
|
853 |
||
854 |
private void cmdExit() { |
|
855 |
regenerateOnDeath = false; |
|
856 |
live = false; |
|
857 |
fluff("Goodbye\n"); |
|
858 |
} |
|
859 |
||
860 |
private void cmdFeedback(String arg) { |
|
861 |
switch (arg) { |
|
862 |
case "": |
|
863 |
case "d": |
|
864 |
case "default": |
|
865 |
feedback = Feedback.Default; |
|
866 |
break; |
|
867 |
case "o": |
|
868 |
case "off": |
|
869 |
feedback = Feedback.Off; |
|
870 |
break; |
|
871 |
case "c": |
|
872 |
case "concise": |
|
873 |
feedback = Feedback.Concise; |
|
874 |
break; |
|
875 |
case "n": |
|
876 |
case "normal": |
|
877 |
feedback = Feedback.Normal; |
|
878 |
break; |
|
879 |
case "v": |
|
880 |
case "verbose": |
|
881 |
feedback = Feedback.Verbose; |
|
882 |
break; |
|
883 |
default: |
|
884 |
hard("Follow /feedback with of the following:"); |
|
885 |
hard(" off (errors and critical output only)"); |
|
886 |
hard(" concise"); |
|
887 |
hard(" normal"); |
|
888 |
hard(" verbose"); |
|
889 |
hard(" default"); |
|
890 |
hard("You may also use just the first letter, for example: /f c"); |
|
891 |
hard("In interactive mode 'default' is the same as 'normal', from a file it is the same as 'off'"); |
|
892 |
return; |
|
893 |
} |
|
894 |
fluff("Feedback mode: %s", feedback.name().toLowerCase()); |
|
895 |
} |
|
896 |
||
897 |
void cmdHelp() { |
|
898 |
int synopsisLen = 0; |
|
899 |
Map<String, String> synopsis2Description = new LinkedHashMap<>(); |
|
900 |
for (Command cmd : new LinkedHashSet<>(commands.values())) { |
|
901 |
if (cmd.kind == CommandKind.HIDDEN) |
|
902 |
continue; |
|
903 |
StringBuilder synopsis = new StringBuilder(); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
904 |
synopsis.append(cmd.command); |
33362 | 905 |
if (cmd.params != null) |
906 |
synopsis.append(" ").append(cmd.params); |
|
907 |
synopsis2Description.put(synopsis.toString(), cmd.description); |
|
908 |
synopsisLen = Math.max(synopsisLen, synopsis.length()); |
|
909 |
} |
|
910 |
cmdout.println("Type a Java language expression, statement, or declaration."); |
|
911 |
cmdout.println("Or type one of the following commands:\n"); |
|
912 |
for (Entry<String, String> e : synopsis2Description.entrySet()) { |
|
913 |
cmdout.print(String.format("%-" + synopsisLen + "s", e.getKey())); |
|
914 |
cmdout.print(" -- "); |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
915 |
String indentedNewLine = System.getProperty("line.separator") + |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
916 |
String.format("%-" + (synopsisLen + 4) + "s", ""); |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
917 |
cmdout.println(e.getValue().replace("\n", indentedNewLine)); |
33362 | 918 |
} |
919 |
cmdout.println(); |
|
920 |
cmdout.println("Supported shortcuts include:"); |
|
921 |
cmdout.println("<tab> -- show possible completions for the current text"); |
|
922 |
cmdout.println("Shift-<tab> -- for current method or constructor invocation, show a synopsis of the method/constructor"); |
|
923 |
} |
|
924 |
||
925 |
private void cmdHistory() { |
|
926 |
cmdout.println(); |
|
927 |
for (String s : input.currentSessionHistory()) { |
|
928 |
// No number prefix, confusing with snippet ids |
|
929 |
cmdout.printf("%s\n", s); |
|
930 |
} |
|
931 |
} |
|
932 |
||
933 |
/** |
|
934 |
* Convert a user argument to a list of snippets referenced by that |
|
935 |
* argument (or lack of argument). |
|
936 |
* @param arg The user's argument to the command |
|
937 |
* @return a list of referenced snippets |
|
938 |
*/ |
|
939 |
private List<Snippet> argToSnippets(String arg) { |
|
940 |
List<Snippet> snippets = new ArrayList<>(); |
|
941 |
if (arg.isEmpty()) { |
|
942 |
// Default is all user snippets |
|
943 |
for (Snippet sn : state.snippets()) { |
|
944 |
if (notInStartUp(sn)) { |
|
945 |
snippets.add(sn); |
|
946 |
} |
|
947 |
} |
|
948 |
} else { |
|
949 |
// Look for all declarations with matching names |
|
950 |
for (Snippet key : state.snippets()) { |
|
951 |
switch (key.kind()) { |
|
952 |
case METHOD: |
|
953 |
case VAR: |
|
954 |
case TYPE_DECL: |
|
955 |
if (((DeclarationSnippet) key).name().equals(arg)) { |
|
956 |
snippets.add(key); |
|
957 |
} |
|
958 |
break; |
|
959 |
} |
|
960 |
} |
|
961 |
// If no declarations found, look for an id of this name |
|
962 |
if (snippets.isEmpty()) { |
|
963 |
for (Snippet sn : state.snippets()) { |
|
964 |
if (sn.id().equals(arg)) { |
|
965 |
snippets.add(sn); |
|
966 |
break; |
|
967 |
} |
|
968 |
} |
|
969 |
} |
|
970 |
// If still no matches found, give an error |
|
971 |
if (snippets.isEmpty()) { |
|
972 |
hard("No definition or id named %s found. See /classes /methods /vars or /list", arg); |
|
973 |
return null; |
|
974 |
} |
|
975 |
} |
|
976 |
return snippets; |
|
977 |
} |
|
978 |
||
979 |
private void cmdDrop(String arg) { |
|
980 |
if (arg.isEmpty()) { |
|
981 |
hard("In the /drop argument, please specify an import, variable, method, or class to drop."); |
|
982 |
hard("Specify by id or name. Use /list to see ids. Use /reset to reset all state."); |
|
983 |
return; |
|
984 |
} |
|
985 |
List<Snippet> snippetSet = argToSnippets(arg); |
|
986 |
if (snippetSet == null) { |
|
987 |
return; |
|
988 |
} |
|
989 |
snippetSet = snippetSet.stream() |
|
990 |
.filter(sn -> state.status(sn).isActive) |
|
991 |
.collect(toList()); |
|
992 |
snippetSet.removeIf(sn -> !(sn instanceof PersistentSnippet)); |
|
993 |
if (snippetSet.isEmpty()) { |
|
994 |
hard("The argument did not specify an import, variable, method, or class to drop."); |
|
995 |
return; |
|
996 |
} |
|
997 |
if (snippetSet.size() > 1) { |
|
998 |
hard("The argument references more than one import, variable, method, or class."); |
|
999 |
hard("Try again with one of the ids below:"); |
|
1000 |
for (Snippet sn : snippetSet) { |
|
1001 |
cmdout.printf("%4s : %s\n", sn.id(), sn.source().replace("\n", "\n ")); |
|
1002 |
} |
|
1003 |
return; |
|
1004 |
} |
|
1005 |
PersistentSnippet psn = (PersistentSnippet) snippetSet.iterator().next(); |
|
1006 |
state.drop(psn).forEach(this::handleEvent); |
|
1007 |
} |
|
1008 |
||
1009 |
private void cmdEdit(String arg) { |
|
1010 |
List<Snippet> snippetSet = argToSnippets(arg); |
|
1011 |
if (snippetSet == null) { |
|
1012 |
return; |
|
1013 |
} |
|
1014 |
Set<String> srcSet = new LinkedHashSet<>(); |
|
1015 |
for (Snippet key : snippetSet) { |
|
1016 |
String src = key.source(); |
|
1017 |
switch (key.subKind()) { |
|
1018 |
case VAR_VALUE_SUBKIND: |
|
1019 |
break; |
|
1020 |
case ASSIGNMENT_SUBKIND: |
|
1021 |
case OTHER_EXPRESSION_SUBKIND: |
|
1022 |
case TEMP_VAR_EXPRESSION_SUBKIND: |
|
1023 |
if (!src.endsWith(";")) { |
|
1024 |
src = src + ";"; |
|
1025 |
} |
|
1026 |
srcSet.add(src); |
|
1027 |
break; |
|
1028 |
default: |
|
1029 |
srcSet.add(src); |
|
1030 |
break; |
|
1031 |
} |
|
1032 |
} |
|
1033 |
StringBuilder sb = new StringBuilder(); |
|
1034 |
for (String s : srcSet) { |
|
1035 |
sb.append(s); |
|
1036 |
sb.append('\n'); |
|
1037 |
} |
|
1038 |
String src = sb.toString(); |
|
1039 |
Consumer<String> saveHandler = new SaveHandler(src, srcSet); |
|
1040 |
Consumer<String> errorHandler = s -> hard("Edit Error: %s", s); |
|
1041 |
if (editor == null) { |
|
1042 |
EditPad.edit(errorHandler, src, saveHandler); |
|
1043 |
} else { |
|
1044 |
ExternalEditor.edit(editor, errorHandler, src, saveHandler, input); |
|
1045 |
} |
|
1046 |
} |
|
1047 |
//where |
|
1048 |
// receives editor requests to save |
|
1049 |
private class SaveHandler implements Consumer<String> { |
|
1050 |
||
1051 |
String src; |
|
1052 |
Set<String> currSrcs; |
|
1053 |
||
1054 |
SaveHandler(String src, Set<String> ss) { |
|
1055 |
this.src = src; |
|
1056 |
this.currSrcs = ss; |
|
1057 |
} |
|
1058 |
||
1059 |
@Override |
|
1060 |
public void accept(String s) { |
|
1061 |
if (!s.equals(src)) { // quick check first |
|
1062 |
src = s; |
|
1063 |
try { |
|
1064 |
Set<String> nextSrcs = new LinkedHashSet<>(); |
|
1065 |
boolean failed = false; |
|
1066 |
while (true) { |
|
1067 |
CompletionInfo an = analysis.analyzeCompletion(s); |
|
1068 |
if (!an.completeness.isComplete) { |
|
1069 |
break; |
|
1070 |
} |
|
1071 |
String tsrc = trimNewlines(an.source); |
|
1072 |
if (!failed && !currSrcs.contains(tsrc)) { |
|
1073 |
failed = processCompleteSource(tsrc); |
|
1074 |
} |
|
1075 |
nextSrcs.add(tsrc); |
|
1076 |
if (an.remaining.isEmpty()) { |
|
1077 |
break; |
|
1078 |
} |
|
1079 |
s = an.remaining; |
|
1080 |
} |
|
1081 |
currSrcs = nextSrcs; |
|
1082 |
} catch (IllegalStateException ex) { |
|
1083 |
hard("Resetting..."); |
|
1084 |
resetState(); |
|
1085 |
currSrcs = new LinkedHashSet<>(); // re-process everything |
|
1086 |
} |
|
1087 |
} |
|
1088 |
} |
|
1089 |
||
1090 |
private String trimNewlines(String s) { |
|
1091 |
int b = 0; |
|
1092 |
while (b < s.length() && s.charAt(b) == '\n') { |
|
1093 |
++b; |
|
1094 |
} |
|
1095 |
int e = s.length() -1; |
|
1096 |
while (e >= 0 && s.charAt(e) == '\n') { |
|
1097 |
--e; |
|
1098 |
} |
|
1099 |
return s.substring(b, e + 1); |
|
1100 |
} |
|
1101 |
} |
|
1102 |
||
1103 |
private void cmdList(String arg) { |
|
1104 |
boolean all = false; |
|
1105 |
switch (arg) { |
|
1106 |
case "all": |
|
1107 |
all = true; |
|
1108 |
break; |
|
1109 |
case "history": |
|
1110 |
cmdHistory(); |
|
1111 |
return; |
|
1112 |
case "": |
|
1113 |
break; |
|
1114 |
default: |
|
1115 |
hard("Invalid /list argument: %s", arg); |
|
1116 |
return; |
|
1117 |
} |
|
1118 |
boolean hasOutput = false; |
|
1119 |
for (Snippet sn : state.snippets()) { |
|
1120 |
if (all || (notInStartUp(sn) && state.status(sn).isActive)) { |
|
1121 |
if (!hasOutput) { |
|
1122 |
cmdout.println(); |
|
1123 |
hasOutput = true; |
|
1124 |
} |
|
1125 |
cmdout.printf("%4s : %s\n", sn.id(), sn.source().replace("\n", "\n ")); |
|
1126 |
||
1127 |
} |
|
1128 |
} |
|
1129 |
} |
|
1130 |
||
1131 |
private void cmdOpen(String filename) { |
|
1132 |
if (filename.isEmpty()) { |
|
1133 |
hard("The /open command requires a filename argument."); |
|
1134 |
} else { |
|
1135 |
try { |
|
1136 |
run(new FileScannerIOContext(toPathResolvingUserHome(filename).toString())); |
|
1137 |
} catch (FileNotFoundException e) { |
|
1138 |
hard("File '%s' is not found: %s", filename, e.getMessage()); |
|
1139 |
} catch (Exception e) { |
|
1140 |
hard("Exception while reading file: %s", e); |
|
1141 |
} |
|
1142 |
} |
|
1143 |
} |
|
1144 |
||
1145 |
private void cmdPrompt() { |
|
1146 |
displayPrompt = !displayPrompt; |
|
1147 |
fluff("Prompt will %sdisplay. Use /prompt to toggle.", displayPrompt ? "" : "NOT "); |
|
1148 |
concise("Prompt: %s", displayPrompt ? "on" : "off"); |
|
1149 |
} |
|
1150 |
||
1151 |
private void cmdReset() { |
|
1152 |
live = false; |
|
1153 |
fluff("Resetting state."); |
|
1154 |
} |
|
1155 |
||
1156 |
private void cmdSave(String arg_filename) { |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
1157 |
Matcher mat = HISTORY_ALL_START_FILENAME.matcher(arg_filename); |
33362 | 1158 |
if (!mat.find()) { |
1159 |
hard("Malformed argument to the /save command: %s", arg_filename); |
|
1160 |
return; |
|
1161 |
} |
|
1162 |
boolean useHistory = false; |
|
1163 |
boolean saveAll = false; |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
1164 |
boolean saveStart = false; |
33362 | 1165 |
String cmd = mat.group("cmd"); |
1166 |
if (cmd != null) switch (cmd) { |
|
1167 |
case "all": |
|
1168 |
saveAll = true; |
|
1169 |
break; |
|
1170 |
case "history": |
|
1171 |
useHistory = true; |
|
1172 |
break; |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
1173 |
case "start": |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
1174 |
saveStart = true; |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
1175 |
break; |
33362 | 1176 |
} |
1177 |
String filename = mat.group("filename"); |
|
1178 |
if (filename == null ||filename.isEmpty()) { |
|
1179 |
hard("The /save command requires a filename argument."); |
|
1180 |
return; |
|
1181 |
} |
|
1182 |
try (BufferedWriter writer = Files.newBufferedWriter(toPathResolvingUserHome(filename), |
|
1183 |
Charset.defaultCharset(), |
|
1184 |
CREATE, TRUNCATE_EXISTING, WRITE)) { |
|
1185 |
if (useHistory) { |
|
1186 |
for (String s : input.currentSessionHistory()) { |
|
1187 |
writer.write(s); |
|
1188 |
writer.write("\n"); |
|
1189 |
} |
|
34475
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
1190 |
} else if (saveStart) { |
7af94fd75ede
8143037: JShell should determine commands by prefix
jlahoda
parents:
33714
diff
changeset
|
1191 |
writer.append(DEFAULT_STARTUP); |
33362 | 1192 |
} else { |
1193 |
for (Snippet sn : state.snippets()) { |
|
1194 |
if (saveAll || notInStartUp(sn)) { |
|
1195 |
writer.write(sn.source()); |
|
1196 |
writer.write("\n"); |
|
1197 |
} |
|
1198 |
} |
|
1199 |
} |
|
1200 |
} catch (FileNotFoundException e) { |
|
1201 |
hard("File '%s' for save is not accessible: %s", filename, e.getMessage()); |
|
1202 |
} catch (Exception e) { |
|
1203 |
hard("Exception while saving: %s", e); |
|
1204 |
} |
|
1205 |
} |
|
1206 |
||
1207 |
private void cmdSetStart(String filename) { |
|
1208 |
if (filename.isEmpty()) { |
|
1209 |
hard("The /setstart command requires a filename argument."); |
|
1210 |
} else { |
|
1211 |
try { |
|
1212 |
byte[] encoded = Files.readAllBytes(toPathResolvingUserHome(filename)); |
|
1213 |
String init = new String(encoded); |
|
1214 |
PREFS.put(STARTUP_KEY, init); |
|
1215 |
} catch (AccessDeniedException e) { |
|
1216 |
hard("File '%s' for /setstart is not accessible.", filename); |
|
1217 |
} catch (NoSuchFileException e) { |
|
1218 |
hard("File '%s' for /setstart is not found.", filename); |
|
1219 |
} catch (Exception e) { |
|
1220 |
hard("Exception while reading start set file: %s", e); |
|
1221 |
} |
|
1222 |
} |
|
1223 |
} |
|
1224 |
||
1225 |
private void cmdVars() { |
|
1226 |
for (VarSnippet vk : state.variables()) { |
|
1227 |
String val = state.status(vk) == Status.VALID |
|
1228 |
? state.varValue(vk) |
|
1229 |
: "(not-active)"; |
|
1230 |
hard(" %s %s = %s", vk.typeName(), vk.name(), val); |
|
1231 |
} |
|
1232 |
} |
|
1233 |
||
1234 |
private void cmdMethods() { |
|
1235 |
for (MethodSnippet mk : state.methods()) { |
|
1236 |
hard(" %s %s", mk.name(), mk.signature()); |
|
1237 |
} |
|
1238 |
} |
|
1239 |
||
1240 |
private void cmdClasses() { |
|
1241 |
for (TypeDeclSnippet ck : state.types()) { |
|
1242 |
String kind; |
|
1243 |
switch (ck.subKind()) { |
|
1244 |
case INTERFACE_SUBKIND: |
|
1245 |
kind = "interface"; |
|
1246 |
break; |
|
1247 |
case CLASS_SUBKIND: |
|
1248 |
kind = "class"; |
|
1249 |
break; |
|
1250 |
case ENUM_SUBKIND: |
|
1251 |
kind = "enum"; |
|
1252 |
break; |
|
1253 |
case ANNOTATION_TYPE_SUBKIND: |
|
1254 |
kind = "@interface"; |
|
1255 |
break; |
|
1256 |
default: |
|
1257 |
assert false : "Wrong kind" + ck.subKind(); |
|
1258 |
kind = "class"; |
|
1259 |
break; |
|
1260 |
} |
|
1261 |
hard(" %s %s", kind, ck.name()); |
|
1262 |
} |
|
1263 |
} |
|
1264 |
||
33714
8064f484590e
8142384: JShell tool: New command: /imports, /i which show the list of imported packages or classes, etc...
shinyafox
parents:
33362
diff
changeset
|
1265 |
private void cmdImports() { |
8064f484590e
8142384: JShell tool: New command: /imports, /i which show the list of imported packages or classes, etc...
shinyafox
parents:
33362
diff
changeset
|
1266 |
state.imports().forEach(ik -> { |
8064f484590e
8142384: JShell tool: New command: /imports, /i which show the list of imported packages or classes, etc...
shinyafox
parents:
33362
diff
changeset
|
1267 |
hard(" import %s%s", ik.isStatic() ? "static " : "", ik.fullname()); |
8064f484590e
8142384: JShell tool: New command: /imports, /i which show the list of imported packages or classes, etc...
shinyafox
parents:
33362
diff
changeset
|
1268 |
}); |
8064f484590e
8142384: JShell tool: New command: /imports, /i which show the list of imported packages or classes, etc...
shinyafox
parents:
33362
diff
changeset
|
1269 |
} |
8064f484590e
8142384: JShell tool: New command: /imports, /i which show the list of imported packages or classes, etc...
shinyafox
parents:
33362
diff
changeset
|
1270 |
|
33362 | 1271 |
private void cmdUseHistoryEntry(int index) { |
1272 |
List<Snippet> keys = state.snippets(); |
|
1273 |
if (index < 0) |
|
1274 |
index += keys.size(); |
|
1275 |
else |
|
1276 |
index--; |
|
1277 |
if (index >= 0 && index < keys.size()) { |
|
1278 |
String source = keys.get(index).source(); |
|
1279 |
cmdout.printf("%s\n", source); |
|
1280 |
input.replaceLastHistoryEntry(source); |
|
1281 |
processSourceCatchingReset(source); |
|
1282 |
} else { |
|
1283 |
hard("Cannot find snippet %d", index + 1); |
|
1284 |
} |
|
1285 |
} |
|
1286 |
||
1287 |
/** |
|
1288 |
* Filter diagnostics for only errors (no warnings, ...) |
|
1289 |
* @param diagnostics input list |
|
1290 |
* @return filtered list |
|
1291 |
*/ |
|
1292 |
List<Diag> errorsOnly(List<Diag> diagnostics) { |
|
1293 |
return diagnostics.stream() |
|
1294 |
.filter(d -> d.isError()) |
|
1295 |
.collect(toList()); |
|
1296 |
} |
|
1297 |
||
1298 |
void printDiagnostics(String source, List<Diag> diagnostics, boolean embed) { |
|
1299 |
String padding = embed? " " : ""; |
|
1300 |
for (Diag diag : diagnostics) { |
|
1301 |
//assert diag.getSource().equals(source); |
|
1302 |
||
1303 |
if (!embed) { |
|
1304 |
if (diag.isError()) { |
|
1305 |
hard("Error:"); |
|
1306 |
} else { |
|
1307 |
hard("Warning:"); |
|
1308 |
} |
|
1309 |
} |
|
1310 |
||
1311 |
for (String line : diag.getMessage(null).split("\\r?\\n")) { |
|
1312 |
if (!line.trim().startsWith("location:")) { |
|
1313 |
hard("%s%s", padding, line); |
|
1314 |
} |
|
1315 |
} |
|
1316 |
||
1317 |
int pstart = (int) diag.getStartPosition(); |
|
1318 |
int pend = (int) diag.getEndPosition(); |
|
1319 |
Matcher m = LINEBREAK.matcher(source); |
|
1320 |
int pstartl = 0; |
|
1321 |
int pendl = -2; |
|
1322 |
while (m.find(pstartl)) { |
|
1323 |
pendl = m.start(); |
|
1324 |
if (pendl >= pstart) { |
|
1325 |
break; |
|
1326 |
} else { |
|
1327 |
pstartl = m.end(); |
|
1328 |
} |
|
1329 |
} |
|
1330 |
if (pendl < pstart) { |
|
1331 |
pendl = source.length(); |
|
1332 |
} |
|
1333 |
fluff("%s%s", padding, source.substring(pstartl, pendl)); |
|
1334 |
||
1335 |
StringBuilder sb = new StringBuilder(); |
|
1336 |
int start = pstart - pstartl; |
|
1337 |
for (int i = 0; i < start; ++i) { |
|
1338 |
sb.append(' '); |
|
1339 |
} |
|
1340 |
sb.append('^'); |
|
1341 |
boolean multiline = pend > pendl; |
|
1342 |
int end = (multiline ? pendl : pend) - pstartl - 1; |
|
1343 |
if (end > start) { |
|
1344 |
for (int i = start + 1; i < end; ++i) { |
|
1345 |
sb.append('-'); |
|
1346 |
} |
|
1347 |
if (multiline) { |
|
1348 |
sb.append("-..."); |
|
1349 |
} else { |
|
1350 |
sb.append('^'); |
|
1351 |
} |
|
1352 |
} |
|
1353 |
fluff("%s%s", padding, sb.toString()); |
|
1354 |
||
1355 |
debug("printDiagnostics start-pos = %d ==> %d -- wrap = %s", diag.getStartPosition(), start, this); |
|
1356 |
debug("Code: %s", diag.getCode()); |
|
1357 |
debug("Pos: %d (%d - %d)", diag.getPosition(), |
|
1358 |
diag.getStartPosition(), diag.getEndPosition()); |
|
1359 |
} |
|
1360 |
} |
|
1361 |
||
1362 |
private String processSource(String srcInput) throws IllegalStateException { |
|
1363 |
while (true) { |
|
1364 |
CompletionInfo an = analysis.analyzeCompletion(srcInput); |
|
1365 |
if (!an.completeness.isComplete) { |
|
1366 |
return an.remaining; |
|
1367 |
} |
|
1368 |
boolean failed = processCompleteSource(an.source); |
|
1369 |
if (failed || an.remaining.isEmpty()) { |
|
1370 |
return ""; |
|
1371 |
} |
|
1372 |
srcInput = an.remaining; |
|
1373 |
} |
|
1374 |
} |
|
1375 |
//where |
|
1376 |
private boolean processCompleteSource(String source) throws IllegalStateException { |
|
1377 |
debug("Compiling: %s", source); |
|
1378 |
boolean failed = false; |
|
1379 |
List<SnippetEvent> events = state.eval(source); |
|
1380 |
for (SnippetEvent e : events) { |
|
1381 |
failed |= handleEvent(e); |
|
1382 |
} |
|
1383 |
return failed; |
|
1384 |
} |
|
1385 |
||
1386 |
private boolean handleEvent(SnippetEvent ste) { |
|
1387 |
Snippet sn = ste.snippet(); |
|
1388 |
if (sn == null) { |
|
1389 |
debug("Event with null key: %s", ste); |
|
1390 |
return false; |
|
1391 |
} |
|
1392 |
List<Diag> diagnostics = state.diagnostics(sn); |
|
1393 |
String source = sn.source(); |
|
1394 |
if (ste.causeSnippet() == null) { |
|
1395 |
// main event |
|
1396 |
printDiagnostics(source, diagnostics, false); |
|
1397 |
if (ste.status().isActive) { |
|
1398 |
if (ste.exception() != null) { |
|
1399 |
if (ste.exception() instanceof EvalException) { |
|
1400 |
printEvalException((EvalException) ste.exception()); |
|
1401 |
return true; |
|
1402 |
} else if (ste.exception() instanceof UnresolvedReferenceException) { |
|
1403 |
printUnresolved((UnresolvedReferenceException) ste.exception()); |
|
1404 |
} else { |
|
1405 |
hard("Unexpected execution exception: %s", ste.exception()); |
|
1406 |
return true; |
|
1407 |
} |
|
1408 |
} else { |
|
1409 |
displayDeclarationAndValue(ste, false, ste.value()); |
|
1410 |
} |
|
1411 |
} else if (ste.status() == Status.REJECTED) { |
|
1412 |
if (diagnostics.isEmpty()) { |
|
1413 |
hard("Failed."); |
|
1414 |
} |
|
1415 |
return true; |
|
1416 |
} |
|
1417 |
} else if (ste.status() == Status.REJECTED) { |
|
1418 |
//TODO -- I don't believe updates can cause failures any more |
|
1419 |
hard("Caused failure of dependent %s --", ((DeclarationSnippet) sn).name()); |
|
1420 |
printDiagnostics(source, diagnostics, true); |
|
1421 |
} else { |
|
1422 |
// Update |
|
1423 |
SubKind subkind = sn.subKind(); |
|
1424 |
if (sn instanceof DeclarationSnippet |
|
1425 |
&& (feedback() == Feedback.Verbose |
|
1426 |
|| ste.status() == Status.OVERWRITTEN |
|
1427 |
|| subkind == SubKind.VAR_DECLARATION_SUBKIND |
|
1428 |
|| subkind == SubKind.VAR_DECLARATION_WITH_INITIALIZER_SUBKIND)) { |
|
1429 |
// Under the conditions, display update information |
|
1430 |
displayDeclarationAndValue(ste, true, null); |
|
1431 |
List<Diag> other = errorsOnly(diagnostics); |
|
1432 |
if (other.size() > 0) { |
|
1433 |
printDiagnostics(source, other, true); |
|
1434 |
} |
|
1435 |
} |
|
1436 |
} |
|
1437 |
return false; |
|
1438 |
} |
|
1439 |
||
1440 |
@SuppressWarnings("fallthrough") |
|
1441 |
private void displayDeclarationAndValue(SnippetEvent ste, boolean update, String value) { |
|
1442 |
Snippet key = ste.snippet(); |
|
1443 |
String declared; |
|
1444 |
Status status = ste.status(); |
|
1445 |
switch (status) { |
|
1446 |
case VALID: |
|
1447 |
case RECOVERABLE_DEFINED: |
|
1448 |
case RECOVERABLE_NOT_DEFINED: |
|
1449 |
if (ste.previousStatus().isActive) { |
|
1450 |
declared = ste.isSignatureChange() |
|
1451 |
? "Replaced" |
|
1452 |
: "Modified"; |
|
1453 |
} else { |
|
1454 |
declared = "Added"; |
|
1455 |
} |
|
1456 |
break; |
|
1457 |
case OVERWRITTEN: |
|
1458 |
declared = "Overwrote"; |
|
1459 |
break; |
|
1460 |
case DROPPED: |
|
1461 |
declared = "Dropped"; |
|
1462 |
break; |
|
1463 |
case REJECTED: |
|
1464 |
declared = "Rejected"; |
|
1465 |
break; |
|
1466 |
case NONEXISTENT: |
|
1467 |
default: |
|
1468 |
// Should not occur |
|
1469 |
declared = ste.previousStatus().toString() + "=>" + status.toString(); |
|
1470 |
} |
|
1471 |
if (update) { |
|
1472 |
declared = " Update " + declared.toLowerCase(); |
|
1473 |
} |
|
1474 |
String however; |
|
1475 |
if (key instanceof DeclarationSnippet && (status == Status.RECOVERABLE_DEFINED || status == Status.RECOVERABLE_NOT_DEFINED)) { |
|
1476 |
String cannotUntil = (status == Status.RECOVERABLE_NOT_DEFINED) |
|
1477 |
? " cannot be referenced until" |
|
1478 |
: " cannot be invoked until"; |
|
1479 |
however = (update? " which" : ", however, it") + cannotUntil + unresolved((DeclarationSnippet) key); |
|
1480 |
} else { |
|
1481 |
however = ""; |
|
1482 |
} |
|
1483 |
switch (key.subKind()) { |
|
1484 |
case CLASS_SUBKIND: |
|
1485 |
fluff("%s class %s%s", declared, ((TypeDeclSnippet) key).name(), however); |
|
1486 |
break; |
|
1487 |
case INTERFACE_SUBKIND: |
|
1488 |
fluff("%s interface %s%s", declared, ((TypeDeclSnippet) key).name(), however); |
|
1489 |
break; |
|
1490 |
case ENUM_SUBKIND: |
|
1491 |
fluff("%s enum %s%s", declared, ((TypeDeclSnippet) key).name(), however); |
|
1492 |
break; |
|
1493 |
case ANNOTATION_TYPE_SUBKIND: |
|
1494 |
fluff("%s annotation interface %s%s", declared, ((TypeDeclSnippet) key).name(), however); |
|
1495 |
break; |
|
1496 |
case METHOD_SUBKIND: |
|
1497 |
fluff("%s method %s(%s)%s", declared, ((MethodSnippet) key).name(), |
|
1498 |
((MethodSnippet) key).parameterTypes(), however); |
|
1499 |
break; |
|
1500 |
case VAR_DECLARATION_SUBKIND: |
|
1501 |
if (!update) { |
|
1502 |
VarSnippet vk = (VarSnippet) key; |
|
1503 |
if (status == Status.RECOVERABLE_NOT_DEFINED) { |
|
1504 |
fluff("%s variable %s%s", declared, vk.name(), however); |
|
1505 |
} else { |
|
1506 |
fluff("%s variable %s of type %s%s", declared, vk.name(), vk.typeName(), however); |
|
1507 |
} |
|
1508 |
break; |
|
1509 |
} |
|
1510 |
// Fall through |
|
1511 |
case VAR_DECLARATION_WITH_INITIALIZER_SUBKIND: { |
|
1512 |
VarSnippet vk = (VarSnippet) key; |
|
1513 |
if (status == Status.RECOVERABLE_NOT_DEFINED) { |
|
1514 |
if (!update) { |
|
1515 |
fluff("%s variable %s%s", declared, vk.name(), however); |
|
1516 |
break; |
|
1517 |
} |
|
1518 |
} else if (update) { |
|
1519 |
if (ste.isSignatureChange()) { |
|
1520 |
hard("%s variable %s, reset to null", declared, vk.name()); |
|
1521 |
} |
|
1522 |
} else { |
|
1523 |
fluff("%s variable %s of type %s with initial value %s", |
|
1524 |
declared, vk.name(), vk.typeName(), value); |
|
1525 |
concise("%s : %s", vk.name(), value); |
|
1526 |
} |
|
1527 |
break; |
|
1528 |
} |
|
1529 |
case TEMP_VAR_EXPRESSION_SUBKIND: { |
|
1530 |
VarSnippet vk = (VarSnippet) key; |
|
1531 |
if (update) { |
|
1532 |
hard("%s temporary variable %s, reset to null", declared, vk.name()); |
|
1533 |
} else { |
|
1534 |
fluff("Expression value is: %s", (value)); |
|
1535 |
fluff(" assigned to temporary variable %s of type %s", vk.name(), vk.typeName()); |
|
1536 |
concise("%s : %s", vk.name(), value); |
|
1537 |
} |
|
1538 |
break; |
|
1539 |
} |
|
1540 |
case OTHER_EXPRESSION_SUBKIND: |
|
1541 |
fluff("Expression value is: %s", (value)); |
|
1542 |
break; |
|
1543 |
case VAR_VALUE_SUBKIND: { |
|
1544 |
ExpressionSnippet ek = (ExpressionSnippet) key; |
|
1545 |
fluff("Variable %s of type %s has value %s", ek.name(), ek.typeName(), (value)); |
|
1546 |
concise("%s : %s", ek.name(), value); |
|
1547 |
break; |
|
1548 |
} |
|
1549 |
case ASSIGNMENT_SUBKIND: { |
|
1550 |
ExpressionSnippet ek = (ExpressionSnippet) key; |
|
1551 |
fluff("Variable %s has been assigned the value %s", ek.name(), (value)); |
|
1552 |
concise("%s : %s", ek.name(), value); |
|
1553 |
break; |
|
1554 |
} |
|
1555 |
} |
|
1556 |
} |
|
1557 |
//where |
|
1558 |
void printStackTrace(StackTraceElement[] stes) { |
|
1559 |
for (StackTraceElement ste : stes) { |
|
1560 |
StringBuilder sb = new StringBuilder(); |
|
1561 |
String cn = ste.getClassName(); |
|
1562 |
if (!cn.isEmpty()) { |
|
1563 |
int dot = cn.lastIndexOf('.'); |
|
1564 |
if (dot > 0) { |
|
1565 |
sb.append(cn.substring(dot + 1)); |
|
1566 |
} else { |
|
1567 |
sb.append(cn); |
|
1568 |
} |
|
1569 |
sb.append("."); |
|
1570 |
} |
|
1571 |
if (!ste.getMethodName().isEmpty()) { |
|
1572 |
sb.append(ste.getMethodName()); |
|
1573 |
sb.append(" "); |
|
1574 |
} |
|
1575 |
String fileName = ste.getFileName(); |
|
1576 |
int lineNumber = ste.getLineNumber(); |
|
1577 |
String loc = ste.isNativeMethod() |
|
1578 |
? "Native Method" |
|
1579 |
: fileName == null |
|
1580 |
? "Unknown Source" |
|
1581 |
: lineNumber >= 0 |
|
1582 |
? fileName + ":" + lineNumber |
|
1583 |
: fileName; |
|
1584 |
hard(" at %s(%s)", sb, loc); |
|
1585 |
||
1586 |
} |
|
1587 |
} |
|
1588 |
//where |
|
1589 |
void printUnresolved(UnresolvedReferenceException ex) { |
|
1590 |
MethodSnippet corralled = ex.getMethodSnippet(); |
|
1591 |
List<Diag> otherErrors = errorsOnly(state.diagnostics(corralled)); |
|
1592 |
StringBuilder sb = new StringBuilder(); |
|
1593 |
if (otherErrors.size() > 0) { |
|
1594 |
if (state.unresolvedDependencies(corralled).size() > 0) { |
|
1595 |
sb.append(" and"); |
|
1596 |
} |
|
1597 |
if (otherErrors.size() == 1) { |
|
1598 |
sb.append(" this error is addressed --"); |
|
1599 |
} else { |
|
1600 |
sb.append(" these errors are addressed --"); |
|
1601 |
} |
|
1602 |
} else { |
|
1603 |
sb.append("."); |
|
1604 |
} |
|
1605 |
||
1606 |
hard("Attempted to call %s which cannot be invoked until%s", corralled.name(), |
|
1607 |
unresolved(corralled), sb.toString()); |
|
1608 |
if (otherErrors.size() > 0) { |
|
1609 |
printDiagnostics(corralled.source(), otherErrors, true); |
|
1610 |
} |
|
1611 |
} |
|
1612 |
//where |
|
1613 |
void printEvalException(EvalException ex) { |
|
1614 |
if (ex.getMessage() == null) { |
|
1615 |
hard("%s thrown", ex.getExceptionClassName()); |
|
1616 |
} else { |
|
1617 |
hard("%s thrown: %s", ex.getExceptionClassName(), ex.getMessage()); |
|
1618 |
} |
|
1619 |
printStackTrace(ex.getStackTrace()); |
|
1620 |
} |
|
1621 |
//where |
|
1622 |
String unresolved(DeclarationSnippet key) { |
|
1623 |
List<String> unr = state.unresolvedDependencies(key); |
|
1624 |
StringBuilder sb = new StringBuilder(); |
|
1625 |
int fromLast = unr.size(); |
|
1626 |
if (fromLast > 0) { |
|
1627 |
sb.append(" "); |
|
1628 |
} |
|
1629 |
for (String u : unr) { |
|
1630 |
--fromLast; |
|
1631 |
sb.append(u); |
|
1632 |
if (fromLast == 0) { |
|
1633 |
// No suffix |
|
1634 |
} else if (fromLast == 1) { |
|
1635 |
sb.append(", and "); |
|
1636 |
} else { |
|
1637 |
sb.append(", "); |
|
1638 |
} |
|
1639 |
} |
|
1640 |
switch (unr.size()) { |
|
1641 |
case 0: |
|
1642 |
break; |
|
1643 |
case 1: |
|
1644 |
sb.append(" is declared"); |
|
1645 |
break; |
|
1646 |
default: |
|
1647 |
sb.append(" are declared"); |
|
1648 |
break; |
|
1649 |
} |
|
1650 |
return sb.toString(); |
|
1651 |
} |
|
1652 |
||
1653 |
enum Feedback { |
|
1654 |
Default, |
|
1655 |
Off, |
|
1656 |
Concise, |
|
1657 |
Normal, |
|
1658 |
Verbose |
|
1659 |
} |
|
1660 |
||
1661 |
Feedback feedback() { |
|
1662 |
if (feedback == Feedback.Default) { |
|
1663 |
return input == null || input.interactiveOutput() ? Feedback.Normal : Feedback.Off; |
|
1664 |
} |
|
1665 |
return feedback; |
|
1666 |
} |
|
1667 |
||
1668 |
boolean notInStartUp(Snippet sn) { |
|
1669 |
return mapSnippet.get(sn).space != startNamespace; |
|
1670 |
} |
|
1671 |
||
1672 |
/** The current version number as a string. |
|
1673 |
*/ |
|
1674 |
static String version() { |
|
1675 |
return version("release"); // mm.nn.oo[-milestone] |
|
1676 |
} |
|
1677 |
||
1678 |
/** The current full version number as a string. |
|
1679 |
*/ |
|
1680 |
static String fullVersion() { |
|
1681 |
return version("full"); // mm.mm.oo[-milestone]-build |
|
1682 |
} |
|
1683 |
||
1684 |
private static final String versionRBName = "jdk.internal.jshell.tool.resources.version"; |
|
1685 |
private static ResourceBundle versionRB; |
|
1686 |
||
1687 |
private static String version(String key) { |
|
1688 |
if (versionRB == null) { |
|
1689 |
try { |
|
1690 |
versionRB = ResourceBundle.getBundle(versionRBName); |
|
1691 |
} catch (MissingResourceException e) { |
|
1692 |
return "(version info not available)"; |
|
1693 |
} |
|
1694 |
} |
|
1695 |
try { |
|
1696 |
return versionRB.getString(key); |
|
1697 |
} |
|
1698 |
catch (MissingResourceException e) { |
|
1699 |
return "(version info not available)"; |
|
1700 |
} |
|
1701 |
} |
|
1702 |
||
1703 |
class NameSpace { |
|
1704 |
final String spaceName; |
|
1705 |
final String prefix; |
|
1706 |
private int nextNum; |
|
1707 |
||
1708 |
NameSpace(String spaceName, String prefix) { |
|
1709 |
this.spaceName = spaceName; |
|
1710 |
this.prefix = prefix; |
|
1711 |
this.nextNum = 1; |
|
1712 |
} |
|
1713 |
||
1714 |
String tid(Snippet sn) { |
|
1715 |
String tid = prefix + nextNum++; |
|
1716 |
mapSnippet.put(sn, new SnippetInfo(sn, this, tid)); |
|
1717 |
return tid; |
|
1718 |
} |
|
1719 |
||
1720 |
String tidNext() { |
|
1721 |
return prefix + nextNum; |
|
1722 |
} |
|
1723 |
} |
|
1724 |
||
1725 |
static class SnippetInfo { |
|
1726 |
final Snippet snippet; |
|
1727 |
final NameSpace space; |
|
1728 |
final String tid; |
|
1729 |
||
1730 |
SnippetInfo(Snippet snippet, NameSpace space, String tid) { |
|
1731 |
this.snippet = snippet; |
|
1732 |
this.space = space; |
|
1733 |
this.tid = tid; |
|
1734 |
} |
|
1735 |
} |
|
1736 |
} |
|
1737 |
||
1738 |
class ScannerIOContext extends IOContext { |
|
1739 |
||
1740 |
private final Scanner scannerIn; |
|
1741 |
private final PrintStream pStream; |
|
1742 |
||
1743 |
public ScannerIOContext(Scanner scannerIn, PrintStream pStream) { |
|
1744 |
this.scannerIn = scannerIn; |
|
1745 |
this.pStream = pStream; |
|
1746 |
} |
|
1747 |
||
1748 |
@Override |
|
1749 |
public String readLine(String prompt, String prefix) { |
|
1750 |
if (pStream != null && prompt != null) { |
|
1751 |
pStream.print(prompt); |
|
1752 |
} |
|
1753 |
if (scannerIn.hasNextLine()) { |
|
1754 |
return scannerIn.nextLine(); |
|
1755 |
} else { |
|
1756 |
return null; |
|
1757 |
} |
|
1758 |
} |
|
1759 |
||
1760 |
@Override |
|
1761 |
public boolean interactiveOutput() { |
|
1762 |
return true; |
|
1763 |
} |
|
1764 |
||
1765 |
@Override |
|
1766 |
public Iterable<String> currentSessionHistory() { |
|
1767 |
return Collections.emptyList(); |
|
1768 |
} |
|
1769 |
||
1770 |
@Override |
|
1771 |
public void close() { |
|
1772 |
scannerIn.close(); |
|
1773 |
} |
|
1774 |
||
1775 |
@Override |
|
1776 |
public boolean terminalEditorRunning() { |
|
1777 |
return false; |
|
1778 |
} |
|
1779 |
||
1780 |
@Override |
|
1781 |
public void suspend() { |
|
1782 |
} |
|
1783 |
||
1784 |
@Override |
|
1785 |
public void resume() { |
|
1786 |
} |
|
1787 |
||
1788 |
@Override |
|
1789 |
public void beforeUserCode() { |
|
1790 |
} |
|
1791 |
||
1792 |
@Override |
|
1793 |
public void afterUserCode() { |
|
1794 |
} |
|
1795 |
||
1796 |
@Override |
|
1797 |
public void replaceLastHistoryEntry(String source) { |
|
1798 |
} |
|
1799 |
} |
|
1800 |
||
1801 |
class FileScannerIOContext extends ScannerIOContext { |
|
1802 |
||
1803 |
public FileScannerIOContext(String fn) throws FileNotFoundException { |
|
1804 |
this(new FileReader(fn)); |
|
1805 |
} |
|
1806 |
||
1807 |
public FileScannerIOContext(Reader rdr) throws FileNotFoundException { |
|
1808 |
super(new Scanner(rdr), null); |
|
1809 |
} |
|
1810 |
||
1811 |
@Override |
|
1812 |
public boolean interactiveOutput() { |
|
1813 |
return false; |
|
1814 |
} |
|
1815 |
} |
|
1816 |