« get me outta code hell

show line and column position in parse errors - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
diff options
context:
space:
mode:
author(quasar) nebula <towerofnix@gmail.com>2021-04-16 13:55:51 -0300
committer(quasar) nebula <towerofnix@gmail.com>2021-04-16 13:55:51 -0300
commit14eb1ea1e2aa92831794e599121663f4113361ed (patch)
tree9e2e6b980e29ac51271630d2c969881640c5bac2
parent094e5a621b80b21bbc03937e2b40e1c32df93315 (diff)
show line and column position in parse errors
-rwxr-xr-xupd8.js25
1 files changed, 23 insertions, 2 deletions
diff --git a/upd8.js b/upd8.js
index d2983e7..17b3f28 100755
--- a/upd8.js
+++ b/upd8.js
@@ -1210,8 +1210,29 @@ const replacerSpec = {
 
             const { i, data: { message } } = errorNode;
 
-            // TODO: Visual line/surrounding characters presentation!
-            throw new SyntaxError(`Parse error (at pos ${i}): ${message}`);
+            let lineStart = input.slice(0, i).lastIndexOf('\n');
+            if (lineStart >= 0) {
+                lineStart += 1;
+            } else {
+                lineStart = 0;
+            }
+
+            let lineEnd = input.slice(i).indexOf('\n');
+            if (lineEnd >= 0) {
+                lineEnd += i;
+            } else {
+                lineEnd = input.length;
+            }
+
+            const line = input.slice(lineStart, lineEnd);
+
+            const cursor = i - lineStart;
+
+            throw new SyntaxError(fixWS`
+                Parse error (at pos ${i}): ${message}
+                ${line}
+                ${'-'.repeat(cursor) + '^'}
+            `);
         }
     };
 }