From 50222849a78163170abe34774a2e3e10515dce2f Mon Sep 17 00:00:00 2001 From: uw4 Date: Thu, 14 Dec 2023 12:52:05 +0100 Subject: [PATCH] Show error details + hint. #12 --- .../java/com/dashjoin/jsonata/cli/Main.java | 83 ++++++++++++++++++- 1 file changed, 79 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/dashjoin/jsonata/cli/Main.java b/src/main/java/com/dashjoin/jsonata/cli/Main.java index 4b7e8ec..e2a23de 100644 --- a/src/main/java/com/dashjoin/jsonata/cli/Main.java +++ b/src/main/java/com/dashjoin/jsonata/cli/Main.java @@ -7,6 +7,8 @@ import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.StringWriter; import java.nio.file.Files; import java.util.Map; @@ -18,6 +20,7 @@ import org.apache.commons.cli.Options; import com.dashjoin.jsonata.Functions; +import com.dashjoin.jsonata.JException; import com.dashjoin.jsonata.Jsonata; import com.dashjoin.jsonata.json.Json; @@ -27,6 +30,8 @@ public class Main { Options options; + String expr; + String exprFile; Main() { initCli(); @@ -88,9 +93,9 @@ void run(String[] args) throws Throwable { printHelp(); return; } - String expr = cmd.getOptionValue("e"); - if (expr != null) - expr = readFile(expr); + exprFile = cmd.getOptionValue("e"); + if (exprFile != null) + expr = readFile(exprFile); else expr = cmd.getArgList().get(0); @@ -191,6 +196,65 @@ void printVersion() { System.out.println(Version.getVersion()); } + static class ErrorDetails { + /** + * Hint string showing the error location + */ + String hint; + /** + * Row of the error + */ + int row; + /** + * Column of the error + */ + int column; + } + + /** + * Returns the error details: row, column, + * and a hint that points to the error. + * Supports multi-line expressions + * + * @param location (character index) + * @return error details + */ + ErrorDetails getErrorDetails(int location) { + int lineStart = -1; + int line = 0; + + StringWriter sw = new StringWriter(); + PrintWriter err = new PrintWriter(sw); + + for (int i=0; i=location) + break; + if ("\n\r".contains(""+expr.charAt(i))) { + lineStart = i; + line++; + } + } + int col = location - lineStart - 1; + for (int i=lineStart+1; i