summaryrefslogtreecommitdiff
path: root/src/parser/utils/get_code_frame.ts
diff options
context:
space:
mode:
authorGravatar Fred K. Schott <fkschott@gmail.com> 2021-03-25 00:00:22 -0700
committerGravatar GitHub <noreply@github.com> 2021-03-25 00:00:22 -0700
commit30cccdf7154b6470e876464da9e412af10894dd5 (patch)
tree73ed40b30af23ba3e5b94070e478f3e2ca1670c0 /src/parser/utils/get_code_frame.ts
parenta72ab10c623022860691d6a095b74dea70cc6f69 (diff)
downloadastro-30cccdf7154b6470e876464da9e412af10894dd5.tar.gz
astro-30cccdf7154b6470e876464da9e412af10894dd5.tar.zst
astro-30cccdf7154b6470e876464da9e412af10894dd5.zip
add component state, top-level await support (#26)
Diffstat (limited to 'src/parser/utils/get_code_frame.ts')
-rw-r--r--src/parser/utils/get_code_frame.ts27
1 files changed, 27 insertions, 0 deletions
diff --git a/src/parser/utils/get_code_frame.ts b/src/parser/utils/get_code_frame.ts
new file mode 100644
index 000000000..a0c296672
--- /dev/null
+++ b/src/parser/utils/get_code_frame.ts
@@ -0,0 +1,27 @@
+function tabs_to_spaces(str: string) {
+ return str.replace(/^\t+/, (match) => match.split('\t').join(' '));
+}
+
+export default function get_code_frame(source: string, line: number, column: number) {
+ const lines = source.split('\n');
+
+ const frame_start = Math.max(0, line - 2);
+ const frame_end = Math.min(line + 3, lines.length);
+
+ const digits = String(frame_end + 1).length;
+
+ return lines
+ .slice(frame_start, frame_end)
+ .map((str, i) => {
+ const isErrorLine = frame_start + i === line;
+ const line_num = String(i + frame_start + 1).padStart(digits, ' ');
+
+ if (isErrorLine) {
+ const indicator = ' '.repeat(digits + 2 + tabs_to_spaces(str.slice(0, column)).length) + '^';
+ return `${line_num}: ${tabs_to_spaces(str)}\n${indicator}`;
+ }
+
+ return `${line_num}: ${tabs_to_spaces(str)}`;
+ })
+ .join('\n');
+}