Skip to content

Commit

Permalink
Refactoring: Changed Parser static methods to non static
Browse files Browse the repository at this point in the history
  • Loading branch information
mattirn committed Feb 11, 2020
1 parent 1354c23 commit bb952c5
Show file tree
Hide file tree
Showing 9 changed files with 174 additions and 53 deletions.
24 changes: 11 additions & 13 deletions builtins/src/main/java/org/jline/builtins/Completers.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
import org.jline.reader.Candidate;
import org.jline.reader.LineReader;
import org.jline.reader.LineReader.Option;
import org.jline.reader.Parser;
import org.jline.reader.impl.completer.AggregateCompleter;
import org.jline.reader.impl.completer.ArgumentCompleter;
import org.jline.reader.impl.completer.NullCompleter;
Expand Down Expand Up @@ -83,7 +82,6 @@ public void complete(LineReader reader, ParsedLine line, List<Candidate> candida
}
}

@SuppressWarnings("unchecked")
protected void tryCompleteArguments(LineReader reader, ParsedLine line, List<Candidate> candidates) {
String command = line.words().get(0);
String resolved = environment.resolveCommand(command);
Expand All @@ -96,7 +94,6 @@ protected void tryCompleteArguments(LineReader reader, ParsedLine line, List<Can
}
}

@SuppressWarnings("unchecked")
protected void completeCommandArguments(LineReader reader, ParsedLine line, List<Candidate> candidates, List<CompletionData> completions) {
for (CompletionData completion : completions) {
boolean isOption = line.word().startsWith("-");
Expand Down Expand Up @@ -131,7 +128,7 @@ protected void completeCommandArguments(LineReader reader, ParsedLine line, List
} else if (res instanceof String) {
candidates.add(new Candidate((String) res, (String) res, null, null, null, null, true));
} else if (res instanceof Collection) {
for (Object s : (Collection) res) {
for (Object s : (Collection<?>) res) {
if (s instanceof Candidate) {
candidates.add((Candidate) s);
} else if (s instanceof String) {
Expand Down Expand Up @@ -160,7 +157,7 @@ protected void completeCommandArguments(LineReader reader, ParsedLine line, List
} else if (res instanceof String) {
candidates.add(new Candidate((String) res, (String) res, null, completion.description, null, null, true));
} else if (res instanceof Collection) {
for (Object s : (Collection) res) {
for (Object s : (Collection<?>) res) {
if (s instanceof Candidate) {
candidates.add((Candidate) s);
} else if (s instanceof String) {
Expand All @@ -172,7 +169,6 @@ protected void completeCommandArguments(LineReader reader, ParsedLine line, List
}
}

@SuppressWarnings("unchecked")
protected void completeCommand(List<Candidate> candidates) {
Set<String> commands = environment.getCommands();
for (String command : commands) {
Expand Down Expand Up @@ -592,15 +588,15 @@ public void complete(LineReader reader, ParsedLine commandLine, List<Candidate>
int eq = buffer.indexOf('=');
if (eq < 0) {
commands.complete(reader, commandLine, candidates);
} else if (buffer.substring(0, eq).matches("[a-zA-Z]{1,}[a-zA-Z0-9]*")) {
} else if (reader.getParser().validVariableName(buffer.substring(0, eq))) {
String curBuf = buffer.substring(0, eq + 1);
for (String c: completers.keySet()) {
candidates.add(new Candidate(AttributedString.stripAnsi(curBuf+c)
, c, null, null, null, null, true));
}
}
} else {
String cmd = Parser.getCommand(commandLine.words().get(0));
String cmd = reader.getParser().getCommand(commandLine.words().get(0));
if (command(cmd) != null) {
completers.get(command(cmd)).get(0).complete(reader, commandLine, candidates);
}
Expand All @@ -614,10 +610,12 @@ public boolean isCompiled() {

private String command(String cmd) {
String out = null;
if (completers.containsKey(cmd)) {
out = cmd;
} else if (aliasCommand.containsKey(cmd)) {
out = aliasCommand.get(cmd);
if (cmd != null) {
if (completers.containsKey(cmd)) {
out = cmd;
} else if (aliasCommand.containsKey(cmd)) {
out = aliasCommand.get(cmd);
}
}
return out;
}
Expand Down Expand Up @@ -876,7 +874,7 @@ public void complete(LineReader reader, final ParsedLine commandLine, List<Candi
candidates.add(new Candidate(buffer, buffer, null, null, null, null, true));
return;
}
String command = Parser.getCommand(words.get(0));
String command = reader.getParser().getCommand(words.get(0));
if (buffer.startsWith("-")) {
boolean addbuff = true;
boolean valueCandidates = false;
Expand Down
40 changes: 24 additions & 16 deletions builtins/src/main/java/org/jline/builtins/ConsoleEngineImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -290,9 +290,9 @@ private boolean isCodeBlock(String line) {
}

private boolean isCommandLine(String line) {
String command = Parser.getCommand(line);
String command = parser().getCommand(line);
boolean out = false;
if (command.startsWith(":")) {
if (command != null && command.startsWith(":")) {
if (systemRegistry.hasCommand(command.substring(1))) {
out = true;
} else {
Expand Down Expand Up @@ -333,7 +333,7 @@ private class ScriptFile {

@SuppressWarnings("unchecked")
public ScriptFile(String command, String cmdLine, String[] args) {
if (!command.matches("[a-zA-Z0-9_-]+")) {
if (!parser().validCommandName(command)) {
return;
}
try {
Expand Down Expand Up @@ -540,14 +540,22 @@ public Object execute(String cmd, String line, String[] args) throws Exception {
return null;
}
Object out = null;
ScriptFile file = new ScriptFile(cmd, line, args);
if (file.execute()) {
ScriptFile file = null;
if (parser().validCommandName(cmd)) {
file = new ScriptFile(cmd, line, args);
} else {
File f = new File(line.split("\\s+")[0]);
if (f.exists()) {
file = new ScriptFile(f, line, args);
}
}
if (file != null && file.execute()) {
out = file.getResult();
} else {
line = line.trim();
if (isCodeBlock(line)) {
StringBuilder sb = new StringBuilder();
for (String s: line.split("\n|\n\r")) {
for (String s: line.split("\\r?\\n")) {
if (isCommandLine(s)) {
List<String> ws = parser().parse(s, 0, ParseContext.COMPLETE).words();
int idx = ws.get(0).lastIndexOf(":");
Expand Down Expand Up @@ -583,7 +591,7 @@ public Object execute(String cmd, String line, String[] args) throws Exception {
}
if (engine.hasVariable(line)) {
out = engine.get(line);
} else if (Parser.getVariable(line) == null) {
} else if (parser().getVariable(line) == null) {
out = engine.execute(line);
engine.put("_", out);
} else {
Expand Down Expand Up @@ -645,15 +653,15 @@ private boolean splitCommandOutput() {
@Override
public Object postProcess(String line, Object result, String output) {
Object out = result;
Object _output = output != null && splitCommandOutput() ? output.split("\n") : output;
if (Parser.getVariable(line) != null && result != null) {
Object _output = output != null && splitCommandOutput() ? output.split("\\r?\\n") : output;
if (parser().getVariable(line) != null && result != null) {
engine.put("output", _output);
}
if (systemRegistry.hasCommand(Parser.getCommand(line))) {
out = postProcess(line, Parser.getVariable(line) != null && result == null ? _output : result);
} else if (Parser.getVariable(line) != null) {
if (systemRegistry.hasCommand(parser().getCommand(line))) {
out = postProcess(line, parser().getVariable(line) != null && result == null ? _output : result);
} else if (parser().getVariable(line) != null) {
if (result == null) {
engine.put(Parser.getVariable(line), _output);
engine.put(parser().getVariable(line), _output);
}
out = null;
}
Expand All @@ -662,10 +670,10 @@ public Object postProcess(String line, Object result, String output) {

private Object postProcess(String line, Object result) {
Object out = result instanceof String && ((String)result).trim().length() == 0 ? null : result;
if (Parser.getVariable(line) != null) {
engine.put(Parser.getVariable(line), result);
if (parser().getVariable(line) != null) {
engine.put(parser().getVariable(line), result);
out = null;
} else if (!Parser.getCommand(line).equals("show") && result != null) {
} else if (!parser().getCommand(line).equals("show") && result != null) {
engine.put("_", result);
}
return out;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ public Widgets.CmdDesc commandDescription(Widgets.CmdLine line) {
Widgets.CmdDesc out = null;
switch (line.getDescriptionType()) {
case COMMAND:
String cmd = Parser.getCommand(line.getArgs().get(0));
String cmd = parser.getCommand(line.getArgs().get(0));
out = commandDescription(cmd);
break;
case METHOD:
Expand Down Expand Up @@ -515,12 +515,12 @@ private List<CommandData> compileCommandLine(String commandLine) {
String pipeResult = null;
do {
String variable = null;
String command = ConsoleEngine.plainCommand(Parser.getCommand(words.get(first)));
if (Parser.validCommandName(command) && consoleId != null) {
variable = Parser.getVariable(words.get(first));
String command = ConsoleEngine.plainCommand(parser.getCommand(words.get(first)));
if (parser.validCommandName(command) && consoleId != null) {
variable = parser.getVariable(words.get(first));
if (consoleEngine().hasAlias(command)) {
pl = parser.parse(nextRawLine.replaceFirst(command, consoleEngine().getAlias(command)), 0, ParseContext.ACCEPT_LINE);
command = ConsoleEngine.plainCommand(Parser.getCommand(pl.word()));
command = ConsoleEngine.plainCommand(parser.getCommand(pl.word()));
words = pl.words();
first = 0;
}
Expand Down Expand Up @@ -731,7 +731,7 @@ public Object execute(String line) throws Exception {
outputStream.open();
}
boolean consoleScript = false;
if (Parser.validCommandName(cmd.command())) {
if (parser.validCommandName(cmd.command())) {
if (isLocalCommand(cmd.command())) {
out = localExecute(cmd.command(), cmd.args());
} else {
Expand Down
8 changes: 6 additions & 2 deletions builtins/src/main/java/org/jline/builtins/Widgets.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2002-2019, the original author or authors.
* Copyright (c) 2002-2020, the original author or authors.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
Expand Down Expand Up @@ -118,6 +118,10 @@ private Widget widget(String name) {
return out;
}

public Parser parser() {
return reader.getParser();
}

public KeyMap<Binding> getKeyMap() {
return reader.getKeyMaps().get(LineReader.MAIN);
}
Expand Down Expand Up @@ -1036,7 +1040,7 @@ private Pair<String,Boolean> evaluateCommandLine(String line, List<String> args,
} else {
if (line.length() == curPos) {
cmd = args != null && (args.size() > 1 || (args.size() == 1
&& line.endsWith(" "))) ? Parser.getCommand(args.get(0)) : null;
&& line.endsWith(" "))) ? parser().getCommand(args.get(0)) : null;
descType = CmdLine.DescriptionType.COMMAND;
}
int brackets = 0;
Expand Down
10 changes: 8 additions & 2 deletions builtins/src/test/java/org/jline/example/Example.java
Original file line number Diff line number Diff line change
Expand Up @@ -135,11 +135,16 @@ private static Map<String,CmdDesc> compileTailTips() {

private static class MasterRegistry {
private final CommandRegistry[] commandRegistries;
private Parser parser;

public MasterRegistry(CommandRegistry... commandRegistries) {
this.commandRegistries = commandRegistries;
}

public void setParser(Parser parser) {
this.parser = parser;
}

public void help() {
System.out.println("List of available commands:");
for (CommandRegistry r : commandRegistries) {
Expand All @@ -166,7 +171,7 @@ public CmdDesc commandDescription(CmdLine line) {
CmdDesc out = null;
switch (line.getDescriptionType()) {
case COMMAND:
String cmd = Parser.getCommand(line.getArgs().get(0));
String cmd = parser.getCommand(line.getArgs().get(0));
for (CommandRegistry r : commandRegistries) {
if (r.hasCommand(cmd)) {
out = r.commandDescription(cmd);
Expand Down Expand Up @@ -643,6 +648,7 @@ public void complete(LineReader reader, ParsedLine line, List<Candidate> candida
builtins.alias("bindkey", "keymap");
ExampleCommands exampleCommands = new ExampleCommands();
MasterRegistry masterRegistry = new MasterRegistry(builtins, exampleCommands);
masterRegistry.setParser(parser);
//
// Command completers
//
Expand Down Expand Up @@ -748,7 +754,7 @@ public void complete(LineReader reader, ParsedLine line, List<Candidate> candida
}
ParsedLine pl = reader.getParser().parse(line, 0);
String[] argv = pl.words().subList(1, pl.words().size()).toArray(new String[0]);
String cmd = Parser.getCommand(pl.word());
String cmd = parser.getCommand(pl.word());
if ("help".equals(cmd) || "?".equals(cmd)) {
masterRegistry.help();
}
Expand Down
14 changes: 9 additions & 5 deletions groovy/src/main/java/org/jline/script/GroovyEngine.java
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ private List<AttributedString> internalHighlight(Map<String, Object> options, Ob
asb.append(header.get(i), AttributedStyle.DEFAULT.foreground(AttributedStyle.BLUE + AttributedStyle.BRIGHT));
asb.append("\t");
}
out.add(asb.subSequence(0, width));
out.add(truncate(asb, width));
Integer row = 0;
for (Object o : collection) {
AttributedStringBuilder asb2 = new AttributedStringBuilder().tabs(columns);
Expand Down Expand Up @@ -384,7 +384,7 @@ private List<AttributedString> internalHighlight(Map<String, Object> options, Ob
asb.append(Utils.toString(inner.get(i)));
asb.append("\t");
}
out.add(asb.subSequence(0, width));
out.add(truncate(asb, width));
}
} else {
Integer row = 0;
Expand All @@ -397,7 +397,7 @@ private List<AttributedString> internalHighlight(Map<String, Object> options, Ob
row++;
}
asb.append(Utils.toString(o));
out.add(asb.subSequence(0, width));
out.add(truncate(asb, width));
}
}
}
Expand All @@ -408,6 +408,10 @@ private List<AttributedString> internalHighlight(Map<String, Object> options, Ob
return out;
}

private AttributedString truncate(AttributedStringBuilder asb, int width) {
return asb.columnLength() > width ? asb.subSequence(0, width) : asb.toAttributedString();
}

private void toTabStops(List<Integer> columns, boolean rownum) {
if (rownum) {
columns.add(0, 5);
Expand All @@ -427,7 +431,7 @@ private List<AttributedString> highlightMap(Map<String, Object> map, int width)
for (String v : Utils.toString(entry.getValue()).split("\\r?\\n")) {
asb.append("\t");
asb.append(v, AttributedStyle.DEFAULT.foreground(AttributedStyle.YELLOW));
out.add(asb.subSequence(0, width));
out.add(truncate(asb, width));
asb = new AttributedStringBuilder().tabs(Arrays.asList(0, max + 1));
}
} else {
Expand All @@ -437,7 +441,7 @@ private List<AttributedString> highlightMap(Map<String, Object> map, int width)
}
asb.append("\t");
asb.append(v, AttributedStyle.DEFAULT.foreground(AttributedStyle.YELLOW));
out.add(asb.subSequence(0, width));
out.add(truncate(asb, width));
}
}
return out;
Expand Down
21 changes: 14 additions & 7 deletions reader/src/main/java/org/jline/reader/Parser.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import java.util.regex.Pattern;

public interface Parser {
static final String REGEX_VARIABLE = "[a-zA-Z_]{1,}[a-zA-Z0-9_-]*((.|\\['|\\[\\\")[a-zA-Z0-9_-]*(|'\\]|\\\"\\])){0,1}";
static final String REGEX_VARIABLE = "[a-zA-Z_]{1,}[a-zA-Z0-9_-]*";
static final String REGEX_COMMAND = "[:]{0,1}[a-zA-Z]{1,}[a-zA-Z0-9_-]*";

ParsedLine parse(String line, int cursor, ParseContext context) throws SyntaxError;
Expand All @@ -25,27 +25,34 @@ default boolean isEscapeChar(char ch) {
return ch == '\\';
}

public static boolean validCommandName(String name) {
return name.matches(REGEX_COMMAND);
default boolean validCommandName(String name) {
return name != null && name.matches(REGEX_COMMAND);
}

static String getCommand(final String line) {
String out = null;
default boolean validVariableName(String name) {
return name != null && name.matches(REGEX_VARIABLE);
}

default String getCommand(final String line) {
String out = "";
Pattern patternCommand = Pattern.compile("^\\s*" + REGEX_VARIABLE + "=(" + REGEX_COMMAND + ")(\\s+.*|$)");
Matcher matcher = patternCommand.matcher(line);
if (matcher.find()) {
out = matcher.group(4);
out = matcher.group(1);
} else {
out = line.trim().split("\\s+")[0];
int idx = out.indexOf("=");
if (idx > -1) {
out = out.substring(idx + 1);
}
if (!out.matches(REGEX_COMMAND)) {
out = "";
}
}
return out;
}

static String getVariable(final String line) {
default String getVariable(final String line) {
String out = null;
Pattern patternCommand = Pattern.compile("^\\s*(" + REGEX_VARIABLE + ")\\s*=[^=~].*");
Matcher matcher = patternCommand.matcher(line);
Expand Down

0 comments on commit bb952c5

Please sign in to comment.