From 6c898b0d01623dd1d52ffca13762bcea71441932 Mon Sep 17 00:00:00 2001 From: Araozu Date: Sun, 19 May 2024 19:41:56 -0500 Subject: [PATCH] Manually highlight code using the lexer --- src/components/InteractiveCode.astro | 31 +++++++++++++++++++++----- src/pages/learn/basics/hello-world.mdx | 11 +++++++++ 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/src/components/InteractiveCode.astro b/src/components/InteractiveCode.astro index 2ccf905..d318ee8 100644 --- a/src/components/InteractiveCode.astro +++ b/src/components/InteractiveCode.astro @@ -1,15 +1,14 @@ --- +import { lex } from "../lexer/lexer"; const {code} = Astro.props; -let c = trimAndDedent(code); - /** * Performs the following: * - Removes the first & last line, if they are empty * - Picks the indentation level from the first non-white line * - Dedents the following lines */ -function trimAndDedent(input: string): string { +function trimAndDedent(input: string): Array { let lines = input.split("\n"); // Remove empty lines at the start @@ -70,16 +69,36 @@ function trimAndDedent(input: string): string { } } - return lines.join("\n"); + return lines; } -// TODO: Apply syntax highlighting +function highlightCode(lines: Array): string { + let outLines: Array = []; + for (const line of lines) { + const tokens = lex(line); + const lineArray = []; + + for (const token of tokens) { + if (token.token_type !== "") { + lineArray.push(`${token.v}`); + } else { + lineArray.push(token.v); + } + } + + outLines.push(lineArray.join("")); + } + + return outLines.join("\n"); +} + +const codeHtml = highlightCode(trimAndDedent(code)); ---
thp code -
{c}
+
stdout
diff --git a/src/pages/learn/basics/hello-world.mdx b/src/pages/learn/basics/hello-world.mdx index dd9b66c..19a5fae 100644 --- a/src/pages/learn/basics/hello-world.mdx +++ b/src/pages/learn/basics/hello-world.mdx @@ -16,6 +16,17 @@ Then run `thp hello.thp` ## Try +```thp +val x = 322 +val y = 322 + +fun f(Int x, Int y) { + print("gaaaa {x} {y}") +} + +f(x, y) +``` +