Last active
March 14, 2025 06:35
-
-
Save akingdom/47b19af9350cb35d12cf7825d6b97307 to your computer and use it in GitHub Desktop.
Example of printing a source code line at an error position (based on an index within the entire source code)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example of printing a source code line at an error position | |
// (based on an index within the entire source code) | |
// | |
// By Andrew Kingdom | |
// MIT license | |
// (and use at own risk) | |
// | |
// Example prints: | |
// | |
// DEFGH | |
// ..^ | |
// | |
var s='AB\nDEFGH\nJK'; // Dummy source code. | |
var errpos = 6; // Supposed index of the first character of the error within entire source string. | |
function printableError(s,errpos) { | |
let maxPrintable = 127; | |
var p=errpos-1; | |
if(p < 0 || p >= s.length) return "(out-of-range)\n"; | |
var extraindent = 0; | |
if(s[p] === '\n') { | |
if(p === 0) return "\n^"; | |
p -= 1; | |
if(s[p] === '\n') return "\n^"; | |
extraindent = 1; | |
} | |
var l0=s.lastIndexOf('\n',p); | |
var l1=s.indexOf('\n',l0+1); | |
var wholeline=s.substring(l0+1,l1); // only the line of source code for the specified position | |
var errindent='.'.repeat(p-l0-1 + extraindent); // | |
if (wholeline.length > maxPrintable) { | |
wholeline = wholeline.slice(-maxPrintable) | |
errindent = errindent.slice(-maxPrintable-extraindent+1); | |
} | |
return wholeline + '\n' + errindent + '^'; | |
} | |
console.log( printableError(s,errpos)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment