Capstone: a parser that reports
The exception part ends with the job exceptions are really for: a parser that reads text and reports where the text is wrong. The report has three parts, a message, a line and a column, and the caller prints them with the offending line and a caret under the position. A second parser collects every problem instead of stopping at the first.
A parser that throws
The format is one key=value per line. The exception carries the line and the column as fields, and its message already contains them, so a log line is readable without the fields and a program can use the fields for a caret:
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Parser {
static class ParseException extends Exception {
private static final long serialVersionUID = 1L;
private final int line;
private final int column;
ParseException(String message, int line, int column) {
super("line " + line + ", column " + column + ": " + message);
this.line = line;
this.column = column;
}
int line() {
return line;
}
int column() {
return column;
}
}
public static void main(String[] args) {
List<String> lines = List.of("name=Ada", "age=36", "broken", "city=London");
try {
Map<String, String> settings = parse(lines);
System.out.println(settings);
} catch (ParseException e) {
System.out.println(e.getMessage());
System.out.println("at " + lines.get(e.line() - 1));
System.out.println(" ".repeat(e.column() - 1) + "^");
}
}
static Map<String, String> parse(List<String> lines) throws ParseException {
Map<String, String> settings = new LinkedHashMap<>();
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
int equals = line.indexOf('=');
if (equals < 0) {
throw new ParseException("expected key=value", i + 1, line.length() + 1);
}
if (equals == 0) {
throw new ParseException("empty key", i + 1, 1);
}
settings.put(line.substring(0, equals), line.substring(equals + 1));
}
return settings;
}
}
javac -Xlint:all Parser.java
java Parser
line 3, column 7: expected key=value
at broken
^
The report the caller prints
The three lines are the report a person can act on: the position, the line, and the caret under the column. The column of a missing = is one past the end of the line, which is where the parser noticed the absence, and the caret line uses " ".repeat(e.column() - 1) to reach it.
The exception stops the parse at the first problem, and the settings that were collected before it are thrown away with the call. For a configuration file that is the right behaviour: a file with an error is not half applied. For a form, the caller wants every problem, which is the next program.
Collecting every problem
The validating parser returns a list of problems instead of throwing, and each problem is a record with the same three fields. It reports three kinds of mistake: a missing equals, an empty key and an empty value:
import java.util.ArrayList;
import java.util.List;
public class Collect {
record Problem(int line, int column, String message) {
@Override
public String toString() {
return "line " + line + ", column " + column + ": " + message;
}
}
public static void main(String[] args) {
List<String> lines = List.of("name=Ada", "=36", "broken", "city=", "ok=1");
List<Problem> problems = validate(lines);
for (Problem problem : problems) {
System.out.println(problem);
}
System.out.println(problems.size() + " problems in " + lines.size() + " lines");
System.out.println((lines.size() - problems.size()) + " of " + lines.size() + " lines are valid");
}
static List<Problem> validate(List<String> lines) {
List<Problem> problems = new ArrayList<>();
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
int equals = line.indexOf('=');
if (equals < 0) {
problems.add(new Problem(i + 1, line.length() + 1, "expected key=value"));
} else if (equals == 0) {
problems.add(new Problem(i + 1, 1, "empty key"));
} else if (equals == line.length() - 1) {
problems.add(new Problem(i + 1, equals + 2, "empty value"));
}
}
return problems;
}
}
javac -Xlint:all Collect.java
java Collect
line 2, column 1: empty key
line 3, column 7: expected key=value
line 4, column 6: empty value
3 problems in 5 lines
2 of 5 lines are valid
The two last lines check each other: three problems in five lines leaves two valid ones, and the count of valid lines is computed from the same two numbers rather than from a second pass. A problem is a value here and not an exception, because the parse continues; that is the same choice as the rule list of lesson 095.
The positions checked
A column that is off by one is the classic parser bug, so the third program states the expected position for each input and compares. It also strips the line before parsing, which the first two do not:
import java.util.List;
import java.util.Map;
public class Checks {
static class ParseException extends Exception {
private static final long serialVersionUID = 1L;
final int line;
final int column;
ParseException(String message, int line, int column) {
super(message);
this.line = line;
this.column = column;
}
}
public static void main(String[] args) {
check("name=Ada", true, 0, 0);
check("=Ada", false, 1, 1);
check("broken", false, 1, 7);
check(" name = Ada ", true, 0, 0);
}
static void check(String line, boolean shouldPass, int lineNo, int column) {
try {
Map<String, String> parsed = parse(List.of(line));
System.out.println(shouldPass
? "ok " + line + " -> " + parsed
: "FAIL " + line + " was accepted");
} catch (ParseException e) {
if (shouldPass) {
System.out.println("FAIL " + line + " was rejected: " + e.getMessage());
} else if (e.line == lineNo && e.column == column) {
System.out.println("ok " + line + " rejected at " + e.line + ":" + e.column);
} else {
System.out.println("FAIL " + line + " rejected at " + e.line + ":" + e.column
+ " instead of " + lineNo + ":" + column);
}
}
}
static Map<String, String> parse(List<String> lines) throws ParseException {
java.util.LinkedHashMap<String, String> settings = new java.util.LinkedHashMap<>();
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i).strip();
int equals = line.indexOf('=');
if (equals < 0) {
throw new ParseException("expected key=value", i + 1, line.length() + 1);
}
if (equals == 0) {
throw new ParseException("empty key", i + 1, 1);
}
settings.put(line.substring(0, equals).strip(), line.substring(equals + 1).strip());
}
return settings;
}
}
javac -Xlint:all Checks.java
java Checks
ok name=Ada -> {name=Ada}
ok =Ada rejected at 1:1
ok broken rejected at 1:7
ok name = Ada -> {name=Ada}
Four cases, four ok: an accepted pair, an empty key at column one, a line of six characters whose position is seven, and a pair with spaces that the strip removes. The last line shows the map with no spaces around the key and the value, which is the answer the strip is for.
Exercises
- Add a rule that rejects a key with a space in it, and a check for its position.
- Make the collecting parser return the valid settings as well as the problems.
- Add a third line to the report of the first program that shows the message without the position.
- Parse a number in the value and report a column where the digits stop.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What should a parse exception carry besides a message?
Answer
The line and the column where the text went wrong
A position is what a person needs to find the mistake in the text.
-
When is a list of problems better than an exception?
Answer
When the caller wants every mistake in one pass, as for a form
An exception stops at the first problem, and a list reports all of them.
-
Why is the column of a missing character one past the end of the line?
Answer
That is where the parser noticed that the character was absent
The position of an absence is the place the expected character should have been.
-
What does this program print?
import java.util.List; import java.util.Map; public class Q1 { static class E extends Exception { final int column; E(String message, int column) { super(message); this.column = column; } } static Map<String, String> parse(String line) throws E { int equals = line.indexOf("="); if (equals < 0) { throw new E("expected =", line.length() + 1); } return Map.of(line.substring(0, equals), line.substring(equals + 1)); } public static void main(String[] args) { try { parse("ab"); } catch (E e) { System.out.println(e.getMessage() + " at " + e.column); } } }Answer
expected = at 3
The line has two characters, so the missing equals would be at column three.
-
Why does the caret need the column and not only the line?
Answer
The column says where in the line the mistake is, which the message alone cannot show
A line of text has many positions, and the caret points at one of them.
-
What does the parser answer for a line with no equals sign?
Answer
An exception whose column is one past the end of the line
The expected character is absent at the end, which is the position the report names.
-
What is the difference between the validating parser and the throwing one?
Answer
The validating one returns a list of problems and keeps going
One answers the first failure as an exception, the other reports all of them as values.
-
What does this program print?
import java.util.ArrayList; import java.util.List; public class Q2 { record Problem(int line, String message) { } public static void main(String[] args) { List<String> lines = List.of("a=1", "bad", "b=2"); List<Problem> problems = new ArrayList<>(); for (int i = 0; i < lines.size(); i++) { if (!lines.get(i).contains("=")) { problems.add(new Problem(i + 1, "no equals")); } } System.out.println(problems.size()); System.out.println(problems.get(0)); } }Answer
1 / Problem[line=2, message=no equals]
Only the second line is missing the equals, and the record prints its components.
-
What does
String.repeatgive the report?Answer
A run of spaces as long as the column before the caret
The spaces move the caret to the column, and the caret is printed after them.
-
Why does the last program strip the line before parsing it?
Answer
So spaces around the key and the value do not reach the map
The strip is the normalisation of the last check, and the map it prints has no spaces.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev